hash
stringlengths
40
40
date
stringdate
2020-04-14 18:04:14
2025-03-25 16:48:49
author
stringclasses
154 values
commit_message
stringlengths
15
172
is_merge
bool
1 class
masked_commit_message
stringlengths
11
165
type
stringclasses
7 values
git_diff
stringlengths
32
8.56M
f17ce968e74b587e06eabbd89ee8176fdae51315
2021-11-08 20:49:33
Aswath K
fix: toast width to fit-content (#8955)
false
toast width to fit-content (#8955)
fix
diff --git a/app/client/src/components/ads/Toast.tsx b/app/client/src/components/ads/Toast.tsx index 0662fc436e79..dda574a89806 100644 --- a/app/client/src/components/ads/Toast.tsx +++ b/app/client/src/components/ads/Toast.tsx @@ -59,7 +59,8 @@ const ToastBody = styled.div<{ dispatchableAction?: { type: ReduxActionType; payload: any }; width?: string; }>` - width: ${(props) => props.width || "264px"}; + width: ${(props) => props.width || "fit-content"}; + margin-left: auto; background: ${(props) => props.theme.colors.toast.bg}; padding: ${(props) => props.theme.spaces[4]}px ${(props) => props.theme.spaces[5]}px; @@ -130,6 +131,7 @@ const StyledDebugButton = styled(DebugButton)` const StyledActionText = styled(Text)` color: ${(props) => props.theme.colors.toast.undoRedoColor} !important; cursor: pointer; + margin-left: ${(props) => props.theme.spaces[3]}px; `; export function ToastComponent( diff --git a/app/client/src/index.css b/app/client/src/index.css index 7b5aa6b5ac2a..016901fb71ca 100755 --- a/app/client/src/index.css +++ b/app/client/src/index.css @@ -46,6 +46,7 @@ div.bp3-popover-arrow { .Toastify__toast { padding: 0 !important; border-radius: 4px !important; + box-shadow: none !important; } .Toastify__toast-body { margin: 0 !important;
c0c75905bcb8bfb67e548efa6c15d9ce3804aff2
2023-06-27 10:52:50
Parthvi
test: Remove 3rd party api from cypress tests (#24815)
false
Remove 3rd party api from cypress tests (#24815)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/Omnibar_spec.js b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/Omnibar_spec.js index db604e7566d7..24fa70bca5bf 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/Omnibar_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/Omnibar_spec.js @@ -179,6 +179,8 @@ describe("Omnibar functionality test cases", () => { cy.get(omnibar.categoryTitle) .contains("Search documentation") .click({ force: true }); + cy.get(omnibar.globalSearchInput).type("Connecting to datasources"); + cy.wait(2000); // for value to register cy.url().then(($urlBeforeDocu) => { cy.get(omnibar.openDocumentationLink) .invoke("removeAttr", "target") @@ -186,7 +188,7 @@ describe("Omnibar functionality test cases", () => { .wait(3000); cy.url().should( "contain", - "https://docs.appsmith.com/core-concepts/connecting-to-data-sources", + "https://docs.appsmith.com/learning-and-resources/tutorials/review-moderator-dashboard/connecting-to-data-source-and-binding-queries", ); // => true cy.wait(2000); //cy.go(-1); diff --git a/app/client/cypress/e2e/Regression/ServerSide/Postgres_DataTypes/UUID_Spec.ts b/app/client/cypress/e2e/Regression/ServerSide/Postgres_DataTypes/UUID_Spec.ts index a52d14ef0b1d..2d7ba0e9cc35 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/Postgres_DataTypes/UUID_Spec.ts +++ b/app/client/cypress/e2e/Regression/ServerSide/Postgres_DataTypes/UUID_Spec.ts @@ -28,24 +28,15 @@ describe("UUID Datatype tests", function () { it("1. Creating supporting api's for generating random UUID's", () => { entityExplorer.NavigateToSwitcher("Explorer"); - apiPage.CreateAndFillApi( - //"https://www.uuidgenerator.net/api/version1", - "https://www.uuidtools.com/api/generate/v1", - "version1", - ); - apiPage.CreateAndFillApi( - "https://www.uuidgenerator.net/api/version4", - "version4", - ); - apiPage.CreateAndFillApi("https://www.uuidgenerator.net/api/guid", "guid"); - apiPage.CreateAndFillApi( - "https://www.uuidgenerator.net/api/version-nil", - "nill", - ); + cy.fixture("datasources").then((datasourceFormData) => { + apiPage.CreateAndFillApi(datasourceFormData.uuid1Api, "version1"); + apiPage.CreateAndFillApi(datasourceFormData.uuid4Api, "version4"); + apiPage.CreateAndFillApi(datasourceFormData.nillApi, "nill"); + }); }); it("2. Creating table query - uuidtype", () => { - query = `CREATE table uuidtype (serialid SERIAL primary key, v1 uuid, v4 uuid, guid uuid, nil uuid);`; + query = `CREATE table uuidtype (serialid SERIAL primary key, v1 uuid, v4 uuid, nil uuid);`; dataSources.NavigateFromActiveDS(dsName, true); dataSources.EnterQuery(query); agHelper.RenameWithInPane("createTable"); @@ -70,12 +61,12 @@ describe("UUID Datatype tests", function () { }); it("4. Creating all queries - uuidtype", () => { - query = `INSERT INTO public."uuidtype" ("v1", "v4", "guid", "nil") VALUES ('{{version1.data[0]}}', '{{version4.data}}', '{{guid.data}}', '{{nill.data}}');`; + query = `INSERT INTO public."uuidtype" ("v1", "v4", "nil") VALUES ('{{version1.data}}', '{{version4.data}}', '{{nill.data}}');`; entityExplorer.CreateNewDsQuery(dsName); dataSources.EnterQuery(query); agHelper.RenameWithInPane("insertRecord"); - query = `UPDATE public."uuidtype" SET "v1" ='{{version1.data[0] ? version1.data[0] : Table1.selectedRow.v1}}', "v4" ='{{version4.data ? version4.data : Table1.selectedRow.v4}}', "guid" ='{{guid.data ? guid.data : Table1.selectedRow.guid}}', "nil" ='{{nill.data ? nill.data : Table1.selectedRow.nil}}' WHERE serialid = {{Table1.selectedRow.serialid}};`; + query = `UPDATE public."uuidtype" SET "v1" ='{{version1.data ? version1.data : Table1.selectedRow.v1}}', "v4" ='{{version4.data ? version4.data : Table1.selectedRow.v4}}', "nil" ='{{nill.data ? nill.data : Table1.selectedRow.nil}}' WHERE serialid = {{Table1.selectedRow.serialid}};`; entityExplorer.CreateNewDsQuery(dsName); dataSources.EnterQuery(query); agHelper.RenameWithInPane("updateRecord"); @@ -108,7 +99,7 @@ describe("UUID Datatype tests", function () { agHelper.ClickButton("Generate UUID's"); agHelper.AssertContains("All UUIDs generated & available"); - + cy.pause(); agHelper.ClickButton("Insert"); agHelper.AssertElementAbsence(locators._specificToast("failed to execute")); //Assert that Insert did not fail agHelper.AssertElementVisible(locators._spanButton("Run InsertQuery")); @@ -122,10 +113,7 @@ describe("UUID Datatype tests", function () { table.ReadTableRowColumnData(0, 2, "v1", 200).then(($v4) => { expect($v4).not.empty; }); - table.ReadTableRowColumnData(0, 3, "v1", 200).then(($guid) => { - expect($guid).not.empty; - }); - table.ReadTableRowColumnData(0, 4, "v1", 200).then(($nil) => { + table.ReadTableRowColumnData(0, 3, "v1", 200).then(($nil) => { expect($nil).not.empty; }); }); @@ -151,10 +139,7 @@ describe("UUID Datatype tests", function () { table.ReadTableRowColumnData(1, 2, "v1", 200).then(($v4) => { expect($v4).not.empty; }); - table.ReadTableRowColumnData(1, 3, "v1", 200).then(($guid) => { - expect($guid).not.empty; - }); - table.ReadTableRowColumnData(1, 4, "v1", 200).then(($nil) => { + table.ReadTableRowColumnData(1, 3, "v1", 200).then(($nil) => { expect($nil).not.empty; }); }); @@ -180,10 +165,7 @@ describe("UUID Datatype tests", function () { table.ReadTableRowColumnData(2, 2, "v1", 200).then(($v4) => { expect($v4).not.empty; }); - table.ReadTableRowColumnData(2, 3, "v1", 200).then(($guid) => { - expect($guid).not.empty; - }); - table.ReadTableRowColumnData(2, 4, "v1", 200).then(($nil) => { + table.ReadTableRowColumnData(2, 3, "v1", 200).then(($nil) => { expect($nil).not.empty; }); }); @@ -219,41 +201,35 @@ describe("UUID Datatype tests", function () { }); }); - it("9. Updating record - uuidtype - updating v4, guid", () => { + it("9. Updating record - uuidtype - updating v4 ", () => { //table.SelectTableRow(2); //As Table Selected row has issues due to fast selction table.ReadTableRowColumnData(2, 1, "v1", 200).then(($oldV1) => { table.ReadTableRowColumnData(2, 2, "v1", 200).then(($oldV4) => { - table.ReadTableRowColumnData(2, 3, "v1", 200).then(($oldguid) => { - agHelper.ClickButton("Run UpdateQuery"); - agHelper.AssertElementVisible(locators._modal); - - agHelper.ClickButton("Generate new v4"); - agHelper.AssertContains("New V4 UUID available!"); - - agHelper.ClickButton("Generate new GUID"); - agHelper.AssertContains("New GUID available!"); - - agHelper.ClickButton("Update"); - agHelper.AssertElementAbsence( - locators._specificToast("failed to execute"), - ); //Assert that Insert did not fail - agHelper.AssertElementVisible( - locators._spanButton("Run UpdateQuery"), - ); - table.WaitUntilTableLoad(); - table.ReadTableRowColumnData(2, 0).then(($cellData) => { - expect($cellData).to.eq("3"); //asserting serial column is inserting fine in sequence - }); - table.ReadTableRowColumnData(2, 1, "v1", 200).then(($newV1) => { - expect($oldV1).to.eq($newV1); //making sure v1 is same - }); - table.ReadTableRowColumnData(2, 2, "v1", 200).then(($newV4) => { - expect($oldV4).to.not.eq($newV4); //making sure new v4 is updated - }); - table.ReadTableRowColumnData(2, 3, "v1", 200).then(($newguid) => { - expect($oldguid).to.not.eq($newguid); //making sure new guid is updated - }); + //table.ReadTableRowColumnData(2, 3, "v1", 200).then(($oldguid) => { + agHelper.ClickButton("Run UpdateQuery"); + agHelper.AssertElementVisible(locators._modal); + + agHelper.ClickButton("Generate new v4"); + agHelper.AssertContains("New V4 UUID available!"); + + agHelper.ClickButton("Update"); + agHelper.AssertElementAbsence( + locators._specificToast("failed to execute"), + ); //Assert that Insert did not fail + agHelper.AssertElementVisible(locators._spanButton("Run UpdateQuery")); + table.WaitUntilTableLoad(); + table.ReadTableRowColumnData(2, 0).then(($cellData) => { + expect($cellData).to.eq("3"); //asserting serial column is inserting fine in sequence }); + table.ReadTableRowColumnData(2, 1, "v1", 200).then(($newV1) => { + expect($oldV1).to.eq($newV1); //making sure v1 is same + }); + table.ReadTableRowColumnData(2, 2, "v1", 200).then(($newV4) => { + expect($oldV4).to.not.eq($newV4); //making sure new v4 is updated + }); + /*table.ReadTableRowColumnData(2, 3, "v1", 200).then(($newguid) => { + expect($oldguid).to.not.eq($newguid); //making sure new guid is updated + }); */ }); }); }); @@ -313,28 +289,21 @@ describe("UUID Datatype tests", function () { }); deployMode.DeployApp(); table.WaitUntilTableLoad(); - table.ReadTableRowColumnData(1, 5).then(($newFormedguid1) => { - expect($newFormedguid1).not.to.be.empty; //making sure new guid is set for row - - deployMode.NavigateBacktoEditor(); - table.WaitUntilTableLoad(); - entityExplorer.ExpandCollapseEntity("Queries/JS"); - entityExplorer.SelectEntityByName("verifyUUIDFunctions"); - - //Validating altering the new column default value to generate id from pgcrypto package - query = `ALTER TABLE uuidtype ALTER COLUMN newUUID SET DEFAULT gen_random_uuid();`; - dataSources.EnterQuery(query); - dataSources.RunQueryNVerifyResponseViews(1); - dataSources.AssertQueryResponseHeaders(["affectedRows"]); - dataSources.ReadQueryTableResponse(0).then(($cellData) => { - expect($cellData).to.eq("0"); - }); - deployMode.DeployApp(); - table.WaitUntilTableLoad(); - table.ReadTableRowColumnData(1, 5, "v1", 200).then(($newFormedguid2) => { - expect($newFormedguid1).to.eq($newFormedguid2); - }); + deployMode.NavigateBacktoEditor(); + table.WaitUntilTableLoad(); + entityExplorer.ExpandCollapseEntity("Queries/JS"); + entityExplorer.SelectEntityByName("verifyUUIDFunctions"); + + //Validating altering the new column default value to generate id from pgcrypto package + query = `ALTER TABLE uuidtype ALTER COLUMN newUUID SET DEFAULT gen_random_uuid();`; + dataSources.EnterQuery(query); + dataSources.RunQueryNVerifyResponseViews(1); + dataSources.AssertQueryResponseHeaders(["affectedRows"]); + dataSources.ReadQueryTableResponse(0).then(($cellData) => { + expect($cellData).to.eq("0"); }); + deployMode.DeployApp(); + table.WaitUntilTableLoad(); deployMode.NavigateBacktoEditor(); table.WaitUntilTableLoad(); @@ -387,13 +356,10 @@ describe("UUID Datatype tests", function () { table.ReadTableRowColumnData(0, 2, "v1", 200).then(($v4) => { expect($v4).not.empty; }); - table.ReadTableRowColumnData(0, 3, "v1", 200).then(($guid) => { - expect($guid).not.empty; - }); - table.ReadTableRowColumnData(0, 4, "v1", 200).then(($nil) => { + table.ReadTableRowColumnData(0, 3, "v1", 200).then(($nil) => { expect($nil).not.empty; }); - table.ReadTableRowColumnData(0, 5, "v1", 200).then(($newGenUUID) => { + table.ReadTableRowColumnData(0, 4, "v1", 200).then(($newGenUUID) => { expect($newGenUUID).not.empty; }); }); diff --git a/app/client/cypress/fixtures/Datatypes/UUIDDTdsl.json b/app/client/cypress/fixtures/Datatypes/UUIDDTdsl.json index 779c7699c22d..db65a3665a0c 100644 --- a/app/client/cypress/fixtures/Datatypes/UUIDDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/UUIDDTdsl.json @@ -996,7 +996,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "CallGenerateapis", - "onClick": "{{\nversion1.run();\nversion4.run();\nguid.run();\nnill.run(() => showAlert(\"All UUIDs generated & available\", \"success\"), () => {})\n}}", + "onClick": "{{\nversion1.run();\nversion4.run();\nnill.run(() => showAlert(\"All UUIDs generated & available\", \"success\"), () => {})\n}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { diff --git a/app/client/cypress/fixtures/datasources.json b/app/client/cypress/fixtures/datasources.json index c42fc8387042..3cfa9433914f 100644 --- a/app/client/cypress/fixtures/datasources.json +++ b/app/client/cypress/fixtures/datasources.json @@ -68,7 +68,10 @@ "echoApiUrl": "http://host.docker.internal:5001/v1/mock-api/echo", "randomCatfactUrl": "http://host.docker.internal:5001/v1/catfact/random", "multipartAPI": "http://host.docker.internal:5001/v1/mock-api/echo-multipart", - "randomTrumpApi":"http://host.docker.internal:5001/v1/whatdoestrumpthink/random", + "randomTrumpApi": "http://host.docker.internal:5001/v1/whatdoestrumpthink/random", + "uuid1Api": "http://host.docker.internal:5001/v1/mock-api/uuid1", + "uuid4Api": "http://host.docker.internal:5001/v1/mock-api/uuid4", + "nillApi": "http://host.docker.internal:5001/v1/mock-api/nill", "firestore-database-url": "https://appsmith-22e8b.firebaseio.com", "firestore-projectID": "appsmith-22e8b",
0a3492ff9647d30c7f6e8edd50481689eac6c867
2024-08-27 09:27:03
Ankita Kinger
feat: Action redesign: Updating Mongo plugin form config (#35883)
false
Action redesign: Updating Mongo plugin form config (#35883)
feat
diff --git a/app/client/src/components/formControls/DynamicInputTextControl.tsx b/app/client/src/components/formControls/DynamicInputTextControl.tsx index 874a8c9e9e32..752dbede4233 100644 --- a/app/client/src/components/formControls/DynamicInputTextControl.tsx +++ b/app/client/src/components/formControls/DynamicInputTextControl.tsx @@ -84,7 +84,10 @@ export function InputText(props: { } } return ( - <div className={`t--${props?.name}`} style={customStyle}> + <div + className={`t--${props?.name} uqi-dynamic-input-text`} + style={customStyle} + > {/* <div style={customStyle}> */} <StyledDynamicTextField dataTreePath={dataTreePath} diff --git a/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css b/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css index 6b04213740de..4daaaddf8341 100644 --- a/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css +++ b/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css @@ -47,6 +47,11 @@ } } } + /* DynamicInputTextControl min height and width removed */ + & :global(.uqi-dynamic-input-text) { + width: unset !important; + min-height: unset !important; + } /* Removable section ends here */ } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/aggregate.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/aggregate.json deleted file mode 100644 index 323f7f760c4b..000000000000 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/aggregate.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "identifier": "AGGREGATE", - "controlType": "SECTION", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'AGGREGATE'}}" - }, - "children": [ - { - "controlType": "SECTION", - "label": "Select collection to query", - "children": [ - { - "label": "Collection", - "configProperty": "actionConfiguration.formData.collection.data", - "controlType": "DROP_DOWN", - "evaluationSubstitutionType": "TEMPLATE", - "propertyName": "get_collections", - "fetchOptionsConditionally": true, - "alternateViewTypes": ["json"], - "conditionals": { - "fetchDynamicValues": { - "condition": "{{true}}", - "config": { - "params": { - "requestType": "_GET_STRUCTURE", - "displayType": "DROP_DOWN" - } - } - } - } - } - ] - }, - { - "controlType": "SECTION", - "label": "Query", - "description": "Optional", - "children": [ - { - "label": "Array of pipelines", - "configProperty": "actionConfiguration.formData.aggregate.arrayPipelines.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "[{ $project: { tags: 1 } }, { $unwind: \"$tags\" }, { $group: { _id: \"$tags\", count: { $sum : 1 } } } ]" - } - ] - }, - { - "label": "Limit", - "configProperty": "actionConfiguration.formData.aggregate.limit.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "initialValue": "10" - } - ] -} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/count.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/count.json deleted file mode 100644 index 70a9ddc79895..000000000000 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/count.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "identifier": "COUNT", - "controlType": "SECTION", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'COUNT'}}" - }, - "children": [ - { - "controlType": "SECTION", - "label": "Select collection to query", - "children": [ - { - "label": "Collection", - "configProperty": "actionConfiguration.formData.collection.data", - "controlType": "DROP_DOWN", - "evaluationSubstitutionType": "TEMPLATE", - "propertyName": "get_collections", - "fetchOptionsConditionally": true, - "alternateViewTypes": ["json"], - "conditionals": { - "fetchDynamicValues": { - "condition": "{{true}}", - "config": { - "params": { - "requestType": "_GET_STRUCTURE", - "displayType": "DROP_DOWN" - } - } - } - } - } - ] - }, - { - "controlType": "SECTION", - "label": "Query", - "description": "Optional", - "children": [ - { - "label": "Query", - "configProperty": "actionConfiguration.formData.count.query.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{rating : {$gte : 9}}" - } - ] - } - ] -} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/delete.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/delete.json deleted file mode 100644 index d5fce44dbbe1..000000000000 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/delete.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "identifier": "DELETE", - "controlType": "SECTION", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'DELETE'}}" - }, - "children": [ - { - "controlType": "SECTION", - "label": "Select collection to query", - "children": [ - { - "label": "Collection", - "configProperty": "actionConfiguration.formData.collection.data", - "controlType": "DROP_DOWN", - "evaluationSubstitutionType": "TEMPLATE", - "propertyName": "get_collections", - "fetchOptionsConditionally": true, - "alternateViewTypes": ["json"], - "conditionals": { - "fetchDynamicValues": { - "condition": "{{true}}", - "config": { - "params": { - "requestType": "_GET_STRUCTURE", - "displayType": "DROP_DOWN" - } - } - } - } - } - ] - }, - { - "controlType": "SECTION", - "label": "Query", - "description": "Optional", - "children": [ - { - "label": "Query", - "configProperty": "actionConfiguration.formData.delete.query.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{rating : {$gte : 9}}" - }, - { - "label": "Limit", - "configProperty": "actionConfiguration.formData.delete.limit.data", - "controlType": "DROP_DOWN", - "-subtitle": "Allowed values: SINGLE, ALL", - "-tooltipText": "Allowed values: SINGLE, ALL", - "-alternateViewTypes": ["json"], - "initialValue": "SINGLE", - "options": [ - { - "label": "Single document", - "value": "SINGLE" - }, - { - "label": "All matching documents", - "value": "ALL" - } - ] - } - ] - } - ] -} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/distinct.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/distinct.json deleted file mode 100644 index ab4bfc4fb0d0..000000000000 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/distinct.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "identifier": "DISTINCT", - "controlType": "SECTION", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'DISTINCT'}}" - }, - "children": [ - { - "controlType": "SECTION", - "label": "Select collection to query", - "children": [ - { - "label": "Collection", - "configProperty": "actionConfiguration.formData.collection.data", - "controlType": "DROP_DOWN", - "evaluationSubstitutionType": "TEMPLATE", - "propertyName": "get_collections", - "fetchOptionsConditionally": true, - "alternateViewTypes": ["json"], - "conditionals": { - "fetchDynamicValues": { - "condition": "{{true}}", - "config": { - "params": { - "requestType": "_GET_STRUCTURE", - "displayType": "DROP_DOWN" - } - } - } - } - } - ] - }, - { - "controlType": "SECTION", - "label": "Query", - "description": "Optional", - "children": [ - { - "label": "Query", - "configProperty": "actionConfiguration.formData.distinct.query.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{rating : {$gte : 9}}" - }, - { - "label": "Key", - "configProperty": "actionConfiguration.formData.distinct.key.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "name" - } - ] - } - ] -} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/find.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/find.json deleted file mode 100644 index 741a77885283..000000000000 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/find.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "identifier": "FIND", - "controlType": "SECTION", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'FIND'}}" - }, - "children": [ - { - "controlType": "SECTION", - "label": "Select collection to query", - "children": [ - { - "label": "Collection", - "configProperty": "actionConfiguration.formData.collection.data", - "controlType": "DROP_DOWN", - "evaluationSubstitutionType": "TEMPLATE", - "propertyName": "get_collections", - "fetchOptionsConditionally": true, - "alternateViewTypes": ["json"], - "conditionals": { - "fetchDynamicValues": { - "condition": "{{true}}", - "config": { - "params": { - "requestType": "_GET_STRUCTURE", - "displayType": "DROP_DOWN" - } - } - } - } - } - ] - }, - { - "controlType": "SECTION", - "label": "Query", - "description": "Optional", - "children": [ - { - "label": "Query", - "configProperty": "actionConfiguration.formData.find.query.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{rating : {$gte : 9}}" - }, - { - "label": "Sort", - "configProperty": "actionConfiguration.formData.find.sort.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{name : 1}" - }, - { - "label": "Projection", - "configProperty": "actionConfiguration.formData.find.projection.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{name : 1}" - }, - { - "label": "Limit", - "configProperty": "actionConfiguration.formData.find.limit.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "10" - }, - { - "label": "Skip", - "configProperty": "actionConfiguration.formData.find.skip.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "0" - } - ] - } - ] -} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/insert.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/insert.json deleted file mode 100644 index e70f7f903bc9..000000000000 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/insert.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "identifier": "INSERT", - "controlType": "SECTION", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'INSERT'}}" - }, - "children": [ - { - "controlType": "SECTION", - "label": "Select collection to query", - "children": [ - { - "label": "Collection", - "configProperty": "actionConfiguration.formData.collection.data", - "controlType": "DROP_DOWN", - "evaluationSubstitutionType": "TEMPLATE", - "propertyName": "get_collections", - "fetchOptionsConditionally": true, - "alternateViewTypes": ["json"], - "conditionals": { - "fetchDynamicValues": { - "condition": "{{true}}", - "config": { - "params": { - "requestType": "_GET_STRUCTURE", - "displayType": "DROP_DOWN" - } - } - } - } - } - ] - }, - { - "controlType": "SECTION", - "label": "Query", - "description": "Optional", - "children": [ - { - "label": "Documents", - "configProperty": "actionConfiguration.formData.insert.documents.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "[ { _id: 1, user: \"abc123\", status: \"A\" } ]" - } - ] - } - ] -} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/raw.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/raw.json deleted file mode 100644 index 6829311c3817..000000000000 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/raw.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "identifier": "RAW", - "controlType": "SECTION", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'RAW'}}" - }, - "children": [ - { - "controlType": "SECTION", - "label": "Query", - "description": "Optional", - "children": [ - { - "label": "", - "propertyName": "rawWithSmartSubstitute", - "configProperty": "actionConfiguration.formData.body.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "evaluationSubstitutionType": "SMART_SUBSTITUTE", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'RAW' && actionConfiguration.formData.smartSubstitution.data === true}}" - } - }, - { - "label": "", - "configProperty": "actionConfiguration.formData.body.data", - "propertyName": "rawWithTemplateSubstitute", - "controlType": "QUERY_DYNAMIC_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'RAW' && actionConfiguration.formData.smartSubstitution.data === false}}" - } - } - ] - } - ] -} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/root.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/root.json index 7d1c79dc8ef9..badb0936ff6a 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/root.json +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/root.json @@ -1,61 +1,394 @@ { "editor": [ { - "controlType": "SECTION", - "identifier": "SELECTOR", + "controlType": "SECTION_V2", + "identifier": "SECTION-ONE", "children": [ { - "label": "Command", - "description": "Choose method you would like to use to query the database", - "configProperty": "actionConfiguration.formData.command.data", - "controlType": "DROP_DOWN", - "initialValue": "FIND", - "options": [ + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SO-Z1", + "children": [ { - "label": "Find document(s)", - "value": "FIND" + "label": "Command", + "description": "Choose method you would like to use to query the database", + "configProperty": "actionConfiguration.formData.command.data", + "controlType": "DROP_DOWN", + "initialValue": "FIND", + "options": [ + { + "label": "Find document(s)", + "value": "FIND" + }, + { + "label": "Insert document(s)", + "value": "INSERT" + }, + { + "label": "Update document(s)", + "value": "UPDATE" + }, + { + "label": "Delete document(s)", + "value": "DELETE" + }, + { + "label": "Count", + "value": "COUNT" + }, + { + "label": "Distinct", + "value": "DISTINCT" + }, + { + "label": "Aggregate", + "value": "AGGREGATE" + }, + { + "label": "Raw", + "value": "RAW" + } + ] }, { - "label": "Insert document(s)", - "value": "INSERT" - }, + "label": "Collection", + "configProperty": "actionConfiguration.formData.collection.data", + "controlType": "DROP_DOWN", + "evaluationSubstitutionType": "TEMPLATE", + "propertyName": "get_collections", + "fetchOptionsConditionally": true, + "alternateViewTypes": ["json"], + "conditionals": { + "show": "{{actionConfiguration.formData.command.data !== 'RAW'}}", + "fetchDynamicValues": { + "condition": "{{true}}", + "config": { + "params": { + "requestType": "_GET_STRUCTURE", + "displayType": "DROP_DOWN" + } + } + } + } + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z2", + "label": "Query", + "description": "Optional", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'AGGREGATE'}}" + }, + "children": [ { - "label": "Update document(s)", - "value": "UPDATE" - }, + "label": "Array of pipelines", + "configProperty": "actionConfiguration.formData.aggregate.arrayPipelines.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "[{ $project: { tags: 1 } }, { $unwind: \"$tags\" }, { $group: { _id: \"$tags\", count: { $sum : 1 } } } ]" + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SO-Z3", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'AGGREGATE'}}" + }, + "children": [ { - "label": "Delete document(s)", - "value": "DELETE" - }, + "label": "Limit", + "configProperty": "actionConfiguration.formData.aggregate.limit.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "initialValue": "10" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z4", + "label": "Query", + "description": "Optional", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'COUNT'}}" + }, + "children": [ + { + "label": "Query", + "configProperty": "actionConfiguration.formData.count.query.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{rating : {$gte : 9}}" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z5", + "label": "Query", + "description": "Optional", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'DELETE'}}" + }, + "children": [ + { + "label": "Query", + "configProperty": "actionConfiguration.formData.delete.query.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{rating : {$gte : 9}}" + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SO-Z6", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'DELETE'}}" + }, + "children": [ + { + "label": "Limit", + "configProperty": "actionConfiguration.formData.delete.limit.data", + "controlType": "DROP_DOWN", + "-subtitle": "Allowed values: SINGLE, ALL", + "-tooltipText": "Allowed values: SINGLE, ALL", + "-alternateViewTypes": ["json"], + "initialValue": "SINGLE", + "options": [ + { + "label": "Single document", + "value": "SINGLE" + }, + { + "label": "All matching documents", + "value": "ALL" + } + ] + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z7", + "label": "Query", + "description": "Optional", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'DISTINCT'}}" + }, + "children": [ + { + "label": "Query", + "configProperty": "actionConfiguration.formData.distinct.query.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{rating : {$gte : 9}}" + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SO-Z8", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'DISTINCT'}}" + }, + "children": [ + { + "label": "Key", + "configProperty": "actionConfiguration.formData.distinct.key.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "name" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z9", + "label": "Query", + "description": "Optional", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'FIND'}}" + }, + "children": [ + { + "label": "Query", + "configProperty": "actionConfiguration.formData.find.query.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{rating : {$gte : 9}}" + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SO-Z10", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'FIND'}}" + }, + "children": [ { - "label": "Count", - "value": "COUNT" + "label": "Sort", + "configProperty": "actionConfiguration.formData.find.sort.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{name : 1}" }, { - "label": "Distinct", - "value": "DISTINCT" + "label": "Projection", + "configProperty": "actionConfiguration.formData.find.projection.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{name : 1}" + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SO-Z11", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'FIND'}}" + }, + "children": [ + { + "label": "Limit", + "configProperty": "actionConfiguration.formData.find.limit.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "10" }, { - "label": "Aggregate", - "value": "AGGREGATE" + "label": "Skip", + "configProperty": "actionConfiguration.formData.find.skip.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "0" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z12", + "label": "Query", + "description": "Optional", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'INSERT'}}" + }, + "children": [ + { + "label": "Documents", + "configProperty": "actionConfiguration.formData.insert.documents.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "[ { _id: 1, user: \"abc123\", status: \"A\" } ]" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z13", + "label": "Query", + "description": "Optional", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'UPDATE'}}" + }, + "children": [ + { + "label": "Query", + "configProperty": "actionConfiguration.formData.updateMany.query.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{rating : {$gte : 9}}" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z14", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'UPDATE'}}" + }, + "children": [ + { + "label": "Update", + "configProperty": "actionConfiguration.formData.updateMany.update.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "inputType": "JSON", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{ $inc: { score: 1 } }" + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SO-Z15", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'UPDATE'}}" + }, + "children": [ + { + "label": "Limit", + "configProperty": "actionConfiguration.formData.updateMany.limit.data", + "controlType": "DROP_DOWN", + "-subtitle": "Allowed values: SINGLE, ALL", + "-tooltipText": "Allowed values: SINGLE, ALL", + "-alternateViewTypes": ["json"], + "initialValue": "SINGLE", + "options": [ + { + "label": "Single document", + "value": "SINGLE" + }, + { + "label": "All matching documents", + "value": "ALL" + } + ] + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SO-Z16", + "label": "Query", + "description": "Optional", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'RAW'}}" + }, + "children": [ + { + "label": "", + "propertyName": "rawWithSmartSubstitute", + "configProperty": "actionConfiguration.formData.body.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "evaluationSubstitutionType": "SMART_SUBSTITUTE", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'RAW' && actionConfiguration.formData.smartSubstitution.data === true}}" + } }, { - "label": "Raw", - "value": "RAW" + "label": "", + "configProperty": "actionConfiguration.formData.body.data", + "propertyName": "rawWithTemplateSubstitute", + "controlType": "QUERY_DYNAMIC_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "conditionals": { + "show": "{{actionConfiguration.formData.command.data === 'RAW' && actionConfiguration.formData.smartSubstitution.data === false}}" + } } ] } ] } - ], - "files": [ - "aggregate.json", - "count.json", - "delete.json", - "distinct.json", - "find.json", - "insert.json", - "update.json", - "raw.json" ] } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/update.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/update.json deleted file mode 100644 index bcd4aae93c70..000000000000 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/editor/update.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "identifier": "UPDATE", - "controlType": "SECTION", - "conditionals": { - "show": "{{actionConfiguration.formData.command.data === 'UPDATE'}}" - }, - "children": [ - { - "controlType": "SECTION", - "label": "Select collection to query", - "children": [ - { - "label": "Collection", - "configProperty": "actionConfiguration.formData.collection.data", - "controlType": "DROP_DOWN", - "evaluationSubstitutionType": "TEMPLATE", - "propertyName": "get_collections", - "fetchOptionsConditionally": true, - "alternateViewTypes": ["json"], - "conditionals": { - "fetchDynamicValues": { - "condition": "{{true}}", - "config": { - "params": { - "requestType": "_GET_STRUCTURE", - "displayType": "DROP_DOWN" - } - } - } - } - } - ] - }, - { - "controlType": "SECTION", - "label": "Query", - "description": "Optional", - "children": [ - { - "label": "Query", - "configProperty": "actionConfiguration.formData.updateMany.query.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{rating : {$gte : 9}}" - }, - { - "label": "Update", - "configProperty": "actionConfiguration.formData.updateMany.update.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "inputType": "JSON", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{ $inc: { score: 1 } }" - }, - { - "label": "Limit", - "configProperty": "actionConfiguration.formData.updateMany.limit.data", - "controlType": "DROP_DOWN", - "-subtitle": "Allowed values: SINGLE, ALL", - "-tooltipText": "Allowed values: SINGLE, ALL", - "-alternateViewTypes": ["json"], - "initialValue": "SINGLE", - "options": [ - { - "label": "Single document", - "value": "SINGLE" - }, - { - "label": "All matching documents", - "value": "ALL" - } - ] - } - ] - } - ] -}
e7343d12ac62b817ba35ecc2dcb7554f3266043b
2023-03-29 15:12:29
Aishwarya-U-R
test: Cypress - Flaky fix (#21860)
false
Cypress - Flaky fix (#21860)
test
diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js index 2966156af0e8..526cab75097c 100644 --- a/app/client/cypress/support/commands.js +++ b/app/client/cypress/support/commands.js @@ -1260,9 +1260,9 @@ Cypress.Commands.add("createSuperUser", () => { //cy.get(welcomePage.dataCollection).trigger("mouseover").click(); //cy.wait(1000); //for toggles to settle cy.get(welcomePage.createButton).should("be.visible"); - cy.get(welcomePage.createButton).trigger("mouseover").click(); - //if seeing issue with above also, to try multiple click as below - //cy.get(welcomePage.createButton).click({ multiple: true }); + //cy.get(welcomePage.createButton).trigger("mouseover").click(); + //Seeing issue with above also, trying multiple click as below + cy.get(welcomePage.createButton).click({ multiple: true }); cy.wait("@createSuperUser").then((interception) => { expect(interception.request.body).contains( "allowCollectingAnonymousData=true",
f68bdaa453480a1098d1e7699b00424f6eeeb65e
2022-03-25 12:04:23
Aishwarya-U-R
test: Skip Git flaky test to unblock CI (#12238)
false
Skip Git flaky test to unblock CI (#12238)
test
diff --git a/app/client/cypress/fixtures/listwidgetdsl.json b/app/client/cypress/fixtures/listwidgetdsl.json index 00ce42b5cf5b..f34952103fc8 100644 --- a/app/client/cypress/fixtures/listwidgetdsl.json +++ b/app/client/cypress/fixtures/listwidgetdsl.json @@ -104,7 +104,7 @@ }, { "isVisible": true, - "text": "{{currentItem.num}}", + "text": "{{currentItem.email}}", "fontSize": "PARAGRAPH", "fontStyle": "BOLD", "textAlign": "LEFT", @@ -241,7 +241,7 @@ }, "Text2": { "isVisible": true, - "text": "{{List1.listData.map((currentItem) => currentItem.num)}}", + "text": "{{List1.listData.map((currentItem) => currentItem.email)}}", "fontSize": "PARAGRAPH", "fontStyle": "BOLD", "textAlign": "LEFT", diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Bind_API_with_List_Widget_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Bind_API_with_List_Widget_spec.js index f27344fd8da6..079fc24989c4 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Bind_API_with_List_Widget_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Bind_API_with_List_Widget_spec.js @@ -32,7 +32,7 @@ describe("Test Create Api and Bind to Table widget", function() { it("Test_Validate the Api data is updated on List widget", function() { cy.SearchEntityandOpen("List1"); cy.testJsontext("items", "{{Api1.data.users}}"); - cy.get(".t--draggable-textwidget span").should("have.length.gte", 8); + cy.get(".t--draggable-textwidget span").should("have.length", 8); cy.get(".t--draggable-textwidget span") .first() .invoke("text") @@ -50,7 +50,7 @@ describe("Test Create Api and Bind to Table widget", function() { }, ).then(() => cy.wait(500)); - cy.get(".t--widget-textwidget span").should("have.length.gte", 8); + cy.get(".t--widget-textwidget span").should("have.length", 8); cy.get(".t--widget-textwidget span") .first() .invoke("text") @@ -63,7 +63,7 @@ describe("Test Create Api and Bind to Table widget", function() { cy.get(publishPage.backToEditor).click({ force: true }); cy.SearchEntityandOpen("List1"); cy.testJsontext("itemspacing\\(px\\)", "50"); - cy.get(".t--draggable-textwidget span").should("have.length.gte", 6); + cy.get(".t--draggable-textwidget span").should("have.length", 6); cy.get(".t--draggable-textwidget span") .first() .invoke("text") @@ -79,7 +79,7 @@ describe("Test Create Api and Bind to Table widget", function() { interval: 1000, }, ).then(() => cy.wait(500)); - cy.get(".t--widget-textwidget span").should("have.length.gte", 6); + cy.get(".t--widget-textwidget span").should("have.length", 6); cy.get(".t--widget-textwidget span") .first() .invoke("text") diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Switchgroup_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Switchgroup_spec.js index 1783fb1604d4..dd8cfac37d03 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Switchgroup_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Switchgroup_spec.js @@ -4,9 +4,10 @@ const explorer = require("../../../../locators/explorerlocators.json"); describe("Switchgroup Widget Functionality", function() { before(() => { cy.addDsl(dsl); + cy.wait(5000); }); - it("Add a new switch group widget with others", () => { + it("1. Add a new switch group widget with others", () => { cy.get(explorer.addWidget).click(); cy.dragAndDropToCanvas("switchgroupwidget", { x: 300, y: 300 }); cy.get(".t--widget-switchgroupwidget").should("exist"); @@ -20,7 +21,7 @@ describe("Switchgroup Widget Functionality", function() { ); }); - it("should check that empty value is allowed in options", () => { + it("2. Should check that empty value is allowed in options", () => { cy.openPropertyPane("switchgroupwidget"); cy.updateCodeInput( ".t--property-control-options", @@ -44,7 +45,7 @@ describe("Switchgroup Widget Functionality", function() { ); }); - it("should check that more thatn empty value is not allowed in options", () => { + it("3. Should check that more thatn empty value is not allowed in options", () => { cy.openPropertyPane("switchgroupwidget"); cy.updateCodeInput( ".t--property-control-options", @@ -68,7 +69,7 @@ describe("Switchgroup Widget Functionality", function() { ); }); - it("setting selectedValues to undefined does not crash the app", () => { + it("4. Setting selectedValues to undefined does not crash the app", () => { // Reset options for switch group cy.openPropertyPane("switchgroupwidget"); cy.updateCodeInput( @@ -99,11 +100,12 @@ describe("Switchgroup Widget Functionality", function() { .find(".t--js-toggle") .click(); // wait for a cyclic dependency error to occur - cy.wait(2000); + cy.validateToastMessage("Cyclic dependency found while evaluating"); // check if a crash messsge is appeared cy.get(".t--widget-switchgroupwidget") .contains("Oops, Something went wrong.") .should("not.exist"); + cy.wait(1000); // check if the evaluation is disabled cy.get(".t--widget-textwidget").should( "contain", diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/GitSync/Git_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/GitSync/Git_spec.js index b0f88703fbc2..10e298e09e0b 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/GitSync/Git_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/GitSync/Git_spec.js @@ -201,29 +201,29 @@ describe("Git sync:", function() { cy.get(gitSyncLocators.closeGitSyncModal).click({ force: true }); }); - after(() => { - cy.deleteTestGithubRepo(repoName); - - // TODO remove when app deletion with conflicts is fixed - cy.get(homePage.homeIcon).click({ force: true }); - cy.get(homePage.createNew) - .first() - .click({ force: true }); - cy.wait("@createNewApplication").should( - "have.nested.property", - "response.body.responseMeta.status", - 201, - ); - cy.get("#loading").should("not.exist"); - // eslint-disable-next-line cypress/no-unnecessary-waiting - cy.wait(2000); - - cy.AppSetupForRename(); - cy.get(homePage.applicationName).type(repoName + "{enter}"); - cy.wait("@updateApplication").should( - "have.nested.property", - "response.body.responseMeta.status", - 200, - ); - }); + // after(() => { + // cy.deleteTestGithubRepo(repoName); + + // // TODO remove when app deletion with conflicts is fixed + // cy.get(homePage.homeIcon).click({ force: true }); + // cy.get(homePage.createNew) + // .first() + // .click({ force: true }); + // cy.wait("@createNewApplication").should( + // "have.nested.property", + // "response.body.responseMeta.status", + // 201, + // ); + // cy.get("#loading").should("not.exist"); + // // eslint-disable-next-line cypress/no-unnecessary-waiting + // cy.wait(2000); + + // cy.AppSetupForRename(); + // cy.get(homePage.applicationName).type(repoName + "{enter}"); + // cy.wait("@updateApplication").should( + // "have.nested.property", + // "response.body.responseMeta.status", + // 200, + // ); + // }); }); diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js index 3d3d3c79b4a5..4ae88d7e2260 100644 --- a/app/client/cypress/support/commands.js +++ b/app/client/cypress/support/commands.js @@ -3177,7 +3177,7 @@ Cypress.Commands.add("assertEvaluatedValuePopup", (expectedType) => { }); Cypress.Commands.add("validateToastMessage", (value) => { - cy.get(commonlocators.toastMsg).should("have.text", value); + cy.get(commonlocators.toastMsg).should("contain.text", value); }); Cypress.Commands.add("NavigateToPaginationTab", () => {
0eb707ba5e1354873ad67e2acc0feb5d94310c54
2023-06-28 10:03:19
Rudraprasad Das
fix: adding theme and settings to git status messages (#24045)
false
adding theme and settings to git status messages (#24045)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/GitBugs_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/GitBugs_Spec.ts index 83dcf0ed4ee8..a8967e55ee46 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/GitBugs_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/GitBugs_Spec.ts @@ -2,6 +2,7 @@ import * as _ from "../../../../support/Objects/ObjectsCore"; let repoName: any; let tempBranch: any; +let statusBranch: any; describe("Git Bugs", function () { before(() => { @@ -69,7 +70,42 @@ describe("Git Bugs", function () { _.agHelper.AssertURL("testQP=Yes"); //Validate we also ve the Query Params from Page1 }); - it("4. Bug 24206 : Open repository button is not functional in git sync modal", function () { + it("4. Bug 24045 : Theme and app settings message in git status", function () { + _.gitSync.SwitchGitBranch("master"); + _.gitSync.CreateGitBranch(`st`, true); + cy.get("@gitbranchName").then((branchName) => { + statusBranch = branchName; + _.agHelper.GetNClick(_.locators._appEditMenuBtn); + // cy.wait(_.locators._appEditMenu); + _.agHelper.GetNClick(_.locators._appEditMenuSettings); + _.agHelper.GetNClick(_.locators._appThemeSettings); + _.agHelper.GetNClick(_.locators._appChangeThemeBtn, 0, true); + _.agHelper.GetNClick(_.locators._appThemeCard, 2); + _.agHelper.GetNClick(_.locators._publishButton); + _.agHelper.WaitUntilEleAppear(_.locators._gitStatusChanges); + _.agHelper.AssertContains( + "Theme modified", + "exist", + _.locators._gitStatusChanges, + ); + _.agHelper.GetNClick(_.locators._dialogCloseButton); + _.agHelper.GetNClick(_.locators._appEditMenuBtn); + // cy.wait(_.locators._appEditMenu); + _.agHelper.GetNClick(_.locators._appEditMenuSettings); + _.agHelper.GetNClick(_.locators._appNavigationSettings); + _.agHelper.GetNClick(_.locators._appNavigationSettingsShowTitle); + _.agHelper.GetNClick(_.locators._publishButton); + _.agHelper.WaitUntilEleAppear(_.locators._gitStatusChanges); + _.agHelper.AssertContains( + "Application settings modified", + "exist", + _.locators._gitStatusChanges, + ); + _.agHelper.GetNClick(_.locators._dialogCloseButton); + }); + }); + + it("5. Bug 24206 : Open repository button is not functional in git sync modal", function () { _.gitSync.SwitchGitBranch("master"); _.entityExplorer.DragDropWidgetNVerify("modalwidget", 50, 50); _.gitSync.CommitAndPush(); diff --git a/app/client/cypress/support/Objects/CommonLocators.ts b/app/client/cypress/support/Objects/CommonLocators.ts index 1d2ba1dc0e77..e9ef02530278 100644 --- a/app/client/cypress/support/Objects/CommonLocators.ts +++ b/app/client/cypress/support/Objects/CommonLocators.ts @@ -225,4 +225,13 @@ export class CommonLocators { _selectionCanvas = (canvasId: string) => `#div-selection-${canvasId}`; _sqlKeyword = ".cm-m-sql.cm-keyword"; _appLeveltooltip = (toolTip: string) => `span:contains('${toolTip}')`; + _appEditMenu = "[data-testid='t--application-edit-menu']"; + _appEditMenuBtn = "[data-testid='t--application-edit-menu-cta']"; + _appEditMenuSettings = "[data-testid='t--application-edit-menu-settings']"; + _appThemeSettings = "#t--theme-settings-header"; + _appChangeThemeBtn = ".t--change-theme-btn"; + _appThemeCard = ".t--theme-card"; + _gitStatusChanges = "[data-testid='t--git-change-statuses']"; + _appNavigationSettings = "#t--navigation-settings-header"; + _appNavigationSettingsShowTitle = "#t--navigation-settings-application-title"; } diff --git a/app/client/src/pages/Editor/EditorAppName/NavigationMenuItem.tsx b/app/client/src/pages/Editor/EditorAppName/NavigationMenuItem.tsx index a68307290481..b84ea2bb8758 100644 --- a/app/client/src/pages/Editor/EditorAppName/NavigationMenuItem.tsx +++ b/app/client/src/pages/Editor/EditorAppName/NavigationMenuItem.tsx @@ -1,4 +1,5 @@ import React, { useState } from "react"; +import { kebabCase } from "lodash"; import { MenuItem, @@ -94,13 +95,16 @@ export function NavigationMenuItem({ switch (menuItemData.type) { case MenuTypes.MENU: return ( - <MenuItem onClick={(e) => handleClick(e, menuItemData)}> + <MenuItem + data-testid={`t--application-edit-menu-${kebabCase(text)}`} + onClick={(e) => handleClick(e, menuItemData)} + > {menuItemData.text} </MenuItem> ); case MenuTypes.PARENT: return ( - <MenuSub> + <MenuSub data-testid={`t--application-edit-menu-${kebabCase(text)}`}> <MenuSubTrigger>{menuItemData.text}</MenuSubTrigger> <MenuSubContent width="214px"> {menuItemData?.children?.map((subitem, idx) => ( @@ -122,6 +126,7 @@ export function NavigationMenuItem({ return ( <ReconfirmMenuItem className="error-menuitem" + data-testid={`t--application-edit-menu-${kebabCase(text)}`} onClick={(e) => handleReconfirmClick(e, menuItemData)} > {confirm.text} diff --git a/app/client/src/pages/Editor/EditorAppName/index.tsx b/app/client/src/pages/Editor/EditorAppName/index.tsx index 0ac421a19cd8..4271f44ff7f7 100644 --- a/app/client/src/pages/Editor/EditorAppName/index.tsx +++ b/app/client/src/pages/Editor/EditorAppName/index.tsx @@ -137,7 +137,10 @@ export function EditorAppName(props: EditorAppNameProps) { open={isPopoverOpen} > <MenuTrigger disabled={isEditing}> - <Container onClick={handleAppNameClick}> + <Container + data-testid="t--application-edit-menu-cta" + onClick={handleAppNameClick} + > <EditableAppName className={props.className} defaultSavingState={defaultSavingState} diff --git a/app/client/src/pages/Editor/gitSync/components/GitChangesList.tsx b/app/client/src/pages/Editor/gitSync/components/GitChangesList.tsx index b25489faa16f..f240ea91ec58 100644 --- a/app/client/src/pages/Editor/gitSync/components/GitChangesList.tsx +++ b/app/client/src/pages/Editor/gitSync/components/GitChangesList.tsx @@ -49,6 +49,8 @@ export enum Kind { PAGE = "PAGE", QUERY = "QUERY", JS_LIB = "JS_LIB", + THEME = "THEME", + SETTINGS = "SETTINGS", } type GitStatusProps = { @@ -72,6 +74,16 @@ const STATUS_MAP: GitStatusMap = { iconName: "git-commit", hasValue: (status?.behindCount || 0) > 0, }), + [Kind.SETTINGS]: (status: GitStatusData) => ({ + message: `Application settings modified`, + iconName: "settings-2-line", + hasValue: (status?.modified || []).includes("application.json"), + }), + [Kind.THEME]: (status: GitStatusData) => ({ + message: `Theme modified`, + iconName: "sip-line", + hasValue: (status?.modified || []).includes("theme.json"), + }), [Kind.DATA_SOURCE]: (status: GitStatusData) => ({ message: `${status?.modifiedDatasources || 0} ${ status?.modifiedDatasources || 0 ? "datasource" : "datasources" @@ -168,6 +180,8 @@ export function gitChangeListData( status: GitStatusData = defaultStatus, ): JSX.Element[] { const changeKind = [ + Kind.SETTINGS, + Kind.THEME, Kind.PAGE, Kind.QUERY, Kind.JS_OBJECT,
79c5042e34d45cd18c17f9a1423ed282b9fe2448
2021-11-12 15:03:47
Tolulope Adetula
fix: null check in Table widget (#8979)
false
null check in Table widget (#8979)
fix
diff --git a/app/client/src/utils/migrations/TableWidget.test.ts b/app/client/src/utils/migrations/TableWidget.test.ts index d1ab4a82e31c..5010f6e89ff1 100644 --- a/app/client/src/utils/migrations/TableWidget.test.ts +++ b/app/client/src/utils/migrations/TableWidget.test.ts @@ -1487,8 +1487,182 @@ describe("Table Widget Migration - #migrateTableSanitizeColumnKeys", () => { ], }; + const badDsl = ({ + widgetName: "MainContainer", + backgroundColor: "none", + rightColumn: 1080, + snapColumns: 64, + detachFromLayout: true, + widgetId: "0", + topRow: 0, + bottomRow: 980, + containerStyle: "none", + snapRows: 125, + parentRowSpace: 1, + type: "CANVAS_WIDGET", + canExtend: true, + version: 34, + minHeight: 860, + parentColumnSpace: 1, + dynamicTriggerPathList: [], + dynamicBindingPathList: [], + leftColumn: 0, + children: [ + { + widgetName: "Table1", + defaultPageSize: 0, + columnOrder: ["Employee.id"], + isVisibleDownload: true, + dynamicPropertyPathList: [], + topRow: 8, + bottomRow: 53, + parentRowSpace: 10, + type: "TABLE_WIDGET", + parentColumnSpace: 14.62421875, + dynamicTriggerPathList: [], + dynamicBindingPathList: [ + { key: "tableData" }, + { key: "primaryColumns.Employee.id.computedValue" }, + ], + leftColumn: 1, + primaryColumns: { + "Employee.id": { + "": { + index: 20, + width: 150, + id: "Employee.id", + horizontalAlignment: "LEFT", + verticalAlignment: "CENTER", + columnType: "text", + textSize: "PARAGRAPH", + enableFilter: true, + enableSort: true, + isVisible: true, + isDerived: false, + label: "Employee.id", + computedValue: + "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.Employee.id))}}", + }, + }, + }, + delimiter: ",", + derivedColumns: {}, + rightColumn: 63, + textSize: "PARAGRAPH", + widgetId: "oclzovhzgx", + isVisibleFilters: true, + tableData: '{{users.data.concat({ "\'random header": 100})}}', + isVisible: true, + label: "Data", + searchKey: "", + version: 1, + parentId: "0", + totalRecordCount: 0, + isLoading: false, + isVisibleCompactMode: true, + horizontalAlignment: "LEFT", + isVisibleSearch: true, + isVisiblePagination: true, + verticalAlignment: "CENTER", + columnSizeMap: { + task: 245, + step: 62, + status: 75, + email: 261, + }, + }, + ], + } as unknown) as DSLWidget; + + const fixedDsl = { + widgetName: "MainContainer", + backgroundColor: "none", + rightColumn: 1080, + snapColumns: 64, + detachFromLayout: true, + widgetId: "0", + topRow: 0, + bottomRow: 980, + containerStyle: "none", + snapRows: 125, + parentRowSpace: 1, + type: "CANVAS_WIDGET", + canExtend: true, + version: 34, + minHeight: 860, + parentColumnSpace: 1, + dynamicTriggerPathList: [], + dynamicBindingPathList: [], + leftColumn: 0, + children: [ + { + widgetName: "Table1", + defaultPageSize: 0, + columnOrder: ["Employee_id"], + isVisibleDownload: true, + dynamicPropertyPathList: [], + topRow: 8, + bottomRow: 53, + parentRowSpace: 10, + type: "TABLE_WIDGET", + parentColumnSpace: 14.62421875, + dynamicTriggerPathList: [], + dynamicBindingPathList: [ + { key: "tableData" }, + { key: "primaryColumns.Employee_id.computedValue" }, + ], + leftColumn: 1, + primaryColumns: { + Employee_id: { + index: 20, + width: 150, + id: "Employee_id", + horizontalAlignment: "LEFT", + verticalAlignment: "CENTER", + columnType: "text", + textSize: "PARAGRAPH", + enableFilter: true, + enableSort: true, + isVisible: true, + isDerived: false, + label: "Employee.id", + computedValue: + "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.Employee_id))}}", + }, + }, + delimiter: ",", + derivedColumns: {}, + rightColumn: 63, + textSize: "PARAGRAPH", + widgetId: "oclzovhzgx", + isVisibleFilters: true, + tableData: '{{users.data.concat({ "\'random header": 100})}}', + isVisible: true, + label: "Data", + searchKey: "", + version: 1, + parentId: "0", + totalRecordCount: 0, + isLoading: false, + isVisibleCompactMode: true, + horizontalAlignment: "LEFT", + isVisibleSearch: true, + isVisiblePagination: true, + verticalAlignment: "CENTER", + columnSizeMap: { + task: 245, + step: 62, + status: 75, + email: 261, + }, + }, + ], + }; + const newDsl = migrateTableSanitizeColumnKeys(inputDsl); + const correctedDsl = migrateTableSanitizeColumnKeys(badDsl); expect(newDsl).toStrictEqual(outputDsl); + expect(correctedDsl).toStrictEqual(fixedDsl); }); }); diff --git a/app/client/src/utils/migrations/TableWidget.ts b/app/client/src/utils/migrations/TableWidget.ts index c41e01e7326b..5f9f5b8dd114 100644 --- a/app/client/src/utils/migrations/TableWidget.ts +++ b/app/client/src/utils/migrations/TableWidget.ts @@ -383,9 +383,25 @@ export const migrateTableSanitizeColumnKeys = (currentDSL: DSLWidget) => { const newPrimaryColumns: Record<string, ColumnProperties> = {}; if (primaryColumnEntries.length) { - for (const [key, value] of primaryColumnEntries) { + for (const [, primaryColumnEntry] of primaryColumnEntries.entries()) { + // Value is reassigned when its invalid(Faulty DSL https://github.com/appsmithorg/appsmith/issues/8979) + const [key] = primaryColumnEntry; + let [, value] = primaryColumnEntry; const sanitizedKey = removeSpecialChars(key, 200); - const id = removeSpecialChars(value.id, 200); + let id = ""; + if (value.id) { + id = removeSpecialChars(value.id, 200); + } + // When id is undefined it's likely value isn't correct and needs fixing + else if (Object.keys(value)) { + const onlyKey = Object.keys(value)[0] as keyof ColumnProperties; + const obj: ColumnProperties = value[onlyKey] as any; + if (!obj.id && !obj.columnType) { + continue; + } + value = obj; + id = removeSpecialChars(value.id, 200); + } // Sanitizes "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.$$$random_header))}}" // to "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._random_header))}}"
03abcfe4ef2acb08184fab60bdf58b46df42137c
2024-10-02 13:28:32
vadim
chore: WDS Refinement inner spacing (#36505)
false
WDS Refinement inner spacing (#36505)
chore
diff --git a/app/client/packages/design-system/theming/src/token/src/tokensConfigs.json b/app/client/packages/design-system/theming/src/token/src/tokensConfigs.json index 2c6f2ec9a379..ae7264c82474 100644 --- a/app/client/packages/design-system/theming/src/token/src/tokensConfigs.json +++ b/app/client/packages/design-system/theming/src/token/src/tokensConfigs.json @@ -18,12 +18,12 @@ "userDensityRatio": 2.25 }, "innerSpacing": { - "V": 1.4, + "V": 1.2, "R": 2.25, "N": 2, "stepsUp": 8, "stepsDown": 0, - "userSizingRatio": 0.5, + "userSizingRatio": 1.35, "userDensityRatio": 2.5 }, "typography": {
d8ce162c60bd93724efb8714d2676a7192c9e665
2023-03-13 15:24:48
Anagh Hegde
fix: Added fix for the status API (#21321)
false
Added fix for the status API (#21321)
fix
diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java index 908b622ff53c..1a1bedefe9bd 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java @@ -484,6 +484,8 @@ public Mono<GitStatusDTO> getStatus(Path repoPath, String branchName) { response.setAdded(status.getAdded()); response.setRemoved(status.getRemoved()); + Set<String> queriesModified = new HashSet<>(); + Set<String> jsObjectsModified = new HashSet<>(); int modifiedPages = 0; int modifiedQueries = 0; int modifiedJSObjects = 0; @@ -492,10 +494,20 @@ public Mono<GitStatusDTO> getStatus(Path repoPath, String branchName) { for (String x : modifiedAssets) { if (x.contains(CommonConstants.CANVAS)) { modifiedPages++; - } else if (x.contains(GitDirectories.ACTION_DIRECTORY + "/")) { - modifiedQueries++; - } else if (x.contains(GitDirectories.ACTION_COLLECTION_DIRECTORY + "/")) { - modifiedJSObjects++; + } else if (x.contains(GitDirectories.ACTION_DIRECTORY + "/") && !x.endsWith(".json")) { + String queryName = x.substring(x.lastIndexOf("/") + 1); + String pageName = x.split("/")[1]; + if (!queriesModified.contains(pageName + queryName)) { + queriesModified.add(pageName + queryName); + modifiedQueries++; + } + } else if (x.contains(GitDirectories.ACTION_COLLECTION_DIRECTORY + "/") && !x.endsWith(".json")) { + String queryName = x.substring(x.lastIndexOf("/") + 1); + String pageName = x.split("/")[1]; + if (!jsObjectsModified.contains(pageName + queryName)) { + jsObjectsModified.add(pageName + queryName); + modifiedJSObjects++; + } } else if (x.contains(GitDirectories.DATASOURCE_DIRECTORY + "/")) { modifiedDatasources++; } else if (x.contains(GitDirectories.JS_LIB_DIRECTORY + "/")) { @@ -540,6 +552,16 @@ public Mono<GitStatusDTO> getStatus(Path repoPath, String branchName) { .subscribeOn(scheduler); } + private int getModifiedQueryCount(Set<String> jsObjectsModified, int modifiedCount, String filePath) { + String queryName = filePath.substring(filePath.lastIndexOf("/") + 1); + String pageName = filePath.split("/")[1]; + if (!jsObjectsModified.contains(pageName + queryName)) { + jsObjectsModified.add(pageName + queryName); + modifiedCount++; + } + return modifiedCount; + } + @Override public Mono<String> mergeBranch(Path repoSuffix, String sourceBranch, String destinationBranch) { return Mono.fromCallable(() -> {
5dc5cff722eae0e621bcadcff8dd4e2c236d2522
2022-02-23 20:48:58
balajisoundar
fix: Update date ISO string validations (#11399)
false
Update date ISO string validations (#11399)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/DatePicker_2_Default_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/DatePicker_2_Default_spec.js index 99a3283c3948..662207e07f14 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/DatePicker_2_Default_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/DatePicker_2_Default_spec.js @@ -105,6 +105,16 @@ describe("DatePicker Widget Property pane tests with js bindings", function() { cy.closePropertyPane(); cy.assertDateFormat(); }); + + it("Datepicker default date validation with js binding and default date with moment object", function() { + cy.openPropertyPane("datepickerwidget2"); + cy.testJsontext("defaultdate", `{{moment("1/1/2012")}}`); + cy.get(".t--widget-datepickerwidget2 .bp3-input").should( + "contain.value", + "01/01/2012 00:00", + ); + }); + it("Datepicker default date validation with js binding", function() { cy.PublishtheApp(); // eslint-disable-next-line cypress/no-unnecessary-waiting diff --git a/app/client/src/workers/validations.ts b/app/client/src/workers/validations.ts index 32511f6d4601..e83239052a36 100644 --- a/app/client/src/workers/validations.ts +++ b/app/client/src/workers/validations.ts @@ -778,32 +778,25 @@ export const VALIDATORS: Record<ValidationTypes, Validator> = { value: unknown, props: Record<string, unknown>, ): ValidationResponse => { - const invalidResponse = { - isValid: false, - parsed: config.params?.default, - messages: [`Value does not match: ${getExpectedType(config)}`], - }; - if (value === undefined || value === null || !isString(value)) { - if (!config.params?.required) { - return { - isValid: true, - parsed: value, - }; - } - return invalidResponse; - } - if (isString(value)) { - if (value === "" && !config.params?.required) { - return { - isValid: true, - parsed: config.params?.default, - }; - } else if (value === "" && config.params?.required) { - return invalidResponse; - } + let isValid = false; + let parsed = value; + let message = ""; - if (!moment(value).isValid()) return invalidResponse; + if (_.isNil(value) || value === "") { + parsed = config.params?.default; + if (config.params?.required) { + isValid = false; + message = `Value does not match: ${getExpectedType(config)}`; + } else { + isValid = true; + } + } else if (typeof value === "object" && moment(value).isValid()) { + //Date and moment object + isValid = true; + parsed = moment(value).toISOString(true); + } else if (isString(value)) { + //Date string if ( value === moment(value).toISOString() || value === moment(value).toISOString(true) @@ -812,11 +805,29 @@ export const VALIDATORS: Record<ValidationTypes, Validator> = { isValid: true, parsed: value, }; + } else if (moment(value).isValid()) { + isValid = true; + parsed = moment(value).toISOString(true); + } else { + isValid = false; + message = `Value does not match: ${getExpectedType(config)}`; + parsed = config.params?.default; } - if (moment(value).isValid()) - return { isValid: true, parsed: moment(value).toISOString(true) }; + } else { + isValid = false; + message = `Value does not match: ${getExpectedType(config)}`; } - return invalidResponse; + + const result: ValidationResponse = { + isValid, + parsed, + }; + + if (message) { + result.messages = [message]; + } + + return result; }, [ValidationTypes.FUNCTION]: ( config: ValidationConfig,
a08b525007d111b4b6589f4cb7c344aa1a43e130
2023-05-31 15:27:12
Shrikant Sharat Kandula
fix: Re-gzip html files after env variables substitution (#23546)
false
Re-gzip html files after env variables substitution (#23546)
fix
diff --git a/deploy/docker/scripts/run-nginx.sh b/deploy/docker/scripts/run-nginx.sh index 3bfaf06cb6af..f19f2497a430 100755 --- a/deploy/docker/scripts/run-nginx.sh +++ b/deploy/docker/scripts/run-nginx.sh @@ -84,6 +84,9 @@ apply-env-vars() { ) fs.writeFileSync("'"$served"'", content) ' + pushd "$(dirname "$served")" + gzip --keep --force "$(basename "$served")" + popd } apply-env-vars /opt/appsmith/index.html.original /opt/appsmith/editor/index.html
92a00e590e2988fa4dabb8c2322f3d28aecdcdcc
2022-08-18 09:31:54
Satish Gandham
ci: Remove directory listing command from perf tests (#16117)
false
Remove directory listing command from perf tests (#16117)
ci
diff --git a/.github/workflows/integration-tests-command.yml b/.github/workflows/integration-tests-command.yml index c73264f2d238..de0a14d52936 100644 --- a/.github/workflows/integration-tests-command.yml +++ b/.github/workflows/integration-tests-command.yml @@ -1500,9 +1500,6 @@ jobs: token: ${{ secrets.APPSMITH_PERF_INFRA_REPO_PAT }} ref: main path: app/client/perf - - - name: List files - run: find . -maxdepth 2 -type d -exec ls -ld "{}" \; - name: Installing performance tests dependencies if: steps.run_result.outputs.run_result != 'success'
d6305bad825d2a4a9d73afb6cc9db1c46c51dd4a
2024-10-29 16:21:54
Pawan Kumar
chore: chat widget polish fixes (#37124)
false
chat widget polish fixes (#37124)
chore
diff --git a/app/client/packages/design-system/ads/src/SegmentedControl/SegmentedControl.styles.tsx b/app/client/packages/design-system/ads/src/SegmentedControl/SegmentedControl.styles.tsx index 9ab6f42ab00f..d3578c22ba7c 100644 --- a/app/client/packages/design-system/ads/src/SegmentedControl/SegmentedControl.styles.tsx +++ b/app/client/packages/design-system/ads/src/SegmentedControl/SegmentedControl.styles.tsx @@ -77,7 +77,9 @@ export const StyledControlContainer = styled.div` /* Select all segments which is not a selected and last child */ /* seperator */ - &:not(:last-child):not([data-selected="true"]):after { + &:not(:last-child):not([data-selected="true"]):not( + :has(+ [data-selected="true"]) + ):after { content: ""; position: absolute; right: 0; diff --git a/app/client/packages/design-system/widgets/src/components/Input/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/Input/src/styles.module.css index 317b00c820ba..95c1532aedfb 100644 --- a/app/client/packages/design-system/widgets/src/components/Input/src/styles.module.css +++ b/app/client/packages/design-system/widgets/src/components/Input/src/styles.module.css @@ -101,7 +101,7 @@ ); --icon-offset: calc((var(--input-height) - var(--icon-size)) / 2); - bottom: var(--icon-offset); + bottom: round(up, var(--icon-offset), 0.5px); right: var(--icon-offset); } diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Code.tsx b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Code.tsx index b5683b1e4164..e4f4fb3c3775 100644 --- a/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Code.tsx +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Code.tsx @@ -1,5 +1,5 @@ -import { Button, Flex, Text } from "@appsmith/wds"; import type { ExtraProps } from "react-markdown"; +import { Button, Flex, Text } from "@appsmith/wds"; import React, { useState, useCallback } from "react"; import { useThemeContext } from "@appsmith/wds-theming"; import { @@ -13,7 +13,7 @@ type CodeProps = React.ClassAttributes<HTMLElement> & ExtraProps; export const Code = (props: CodeProps) => { - const { children, className, ...rest } = props; + const { children, className } = props; const match = /language-(\w+)/.exec(className ?? ""); const theme = useThemeContext(); const [copied, setCopied] = useState(false); @@ -50,9 +50,7 @@ export const Code = (props: CodeProps) => { </SyntaxHighlighter> </div> ) : ( - <code {...rest} className={className}> - {children} - </code> + <code className={className}>{children}</code> ); }; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/Markdown/src/styles.module.css index 9d930398df89..ba0ff15e28f0 100644 --- a/app/client/packages/design-system/widgets/src/components/Markdown/src/styles.module.css +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/styles.module.css @@ -95,6 +95,12 @@ overflow: auto; } + code:not(pre code) { + padding-inline: var(--inner-spacing-1); + background: var(--color-bg-accent-subtle); + border-radius: var(--border-radius-elevation-3); + } + pre { margin-top: var(--inner-spacing-4); margin-bottom: var(--inner-spacing-4); diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/stories/Markdown.stories.ts b/app/client/packages/design-system/widgets/src/components/Markdown/stories/Markdown.stories.ts index 08eec4fe8bba..4f00c9834fb4 100644 --- a/app/client/packages/design-system/widgets/src/components/Markdown/stories/Markdown.stories.ts +++ b/app/client/packages/design-system/widgets/src/components/Markdown/stories/Markdown.stories.ts @@ -13,7 +13,7 @@ export const Default: Story = { args: { children: `# Hello, Markdown! -This is a paragraph with **bold** and *italic* text. +This is a \`paragraph\` with **bold** and *italic* text. ## Code Example diff --git a/app/client/src/components/propertyControls/IconTabControl.tsx b/app/client/src/components/propertyControls/IconTabControl.tsx index 9facf3e4cc92..e253941d5234 100644 --- a/app/client/src/components/propertyControls/IconTabControl.tsx +++ b/app/client/src/components/propertyControls/IconTabControl.tsx @@ -12,8 +12,16 @@ import { } from "utils/AppsmithUtils"; const StyledSegmentedControl = styled(SegmentedControl)` + &.ads-v2-segmented-control { + gap: 0; + } + > .ads-v2-segmented-control__segments-container { - flex: 1 1 0%; + flex: 1 1 auto; + } + + > .ads-v2-segmented-control__segments-container:has(.ads-v2-text) span { + padding: 0; } `; diff --git a/app/client/src/layoutSystems/anvil/common/styles.module.css b/app/client/src/layoutSystems/anvil/common/styles.module.css index 7a39ba004975..17cb02727103 100644 --- a/app/client/src/layoutSystems/anvil/common/styles.module.css +++ b/app/client/src/layoutSystems/anvil/common/styles.module.css @@ -7,15 +7,15 @@ */ .anvilWidgetWrapper { /** If a section,zone and card have elevation, then add padding */ - [data-elevation="true"][elevation="1"], - [data-elevation="true"][elevation="2"], - [data-elevation="true"][elevation="3"], + [data-elevation="true"][elevation="1"]:not([data-no-padding]), + [data-elevation="true"][elevation="2"]:not([data-no-padding]), + [data-elevation="true"][elevation="3"]:not([data-no-padding]), /** If a section has any zone with elevation, then add padding to all the zones that don't have elevation */ - [elevation="1"]:has([elevation="2"][data-elevation="true"]) [elevation="2"][data-elevation="false"], + [elevation="1"]:has([elevation="2"][data-elevation="true"]) [elevation="2"][data-elevation="false"]:not([data-no-padding]), /** If a section has any card with elevation, then add padding to all the cards that don't have elevation */ - [elevation="1"]:has([elevation="3"][data-elevation="true"]) [elevation="3"][data-elevation="false"], + [elevation="1"]:has([elevation="3"][data-elevation="true"]) [elevation="3"][data-elevation="false"]:not([data-no-padding]), /** If a zone has any card with elevation, then add padding to all the cards that don't have elevation,*/ - [elevation="2"]:has([elevation="3"][data-elevation="true"]) [elevation="3"][data-elevation="false"] { + [elevation="2"]:has([elevation="3"][data-elevation="true"]) [elevation="3"][data-elevation="false"]:not([data-no-padding]) { padding-block: var(--outer-spacing-3); padding-inline: var(--outer-spacing-3); } diff --git a/app/client/src/modules/ui-builder/ui/wds/Container.tsx b/app/client/src/modules/ui-builder/ui/wds/Container.tsx index 67132176fd4c..5cc6af34e545 100644 --- a/app/client/src/modules/ui-builder/ui/wds/Container.tsx +++ b/app/client/src/modules/ui-builder/ui/wds/Container.tsx @@ -29,6 +29,7 @@ export function ContainerComponent(props: ContainerComponentProps) { <StyledContainerComponent className={`${generateClassName(props.widgetId)}`} data-elevation={props.elevatedBackground} + data-no-padding={props.noPadding} elevatedBackground={props.elevatedBackground} elevation={props.elevation} > @@ -42,4 +43,5 @@ export interface ContainerComponentProps { children?: ReactNode; elevation: Elevations; elevatedBackground: boolean; + noPadding?: boolean; }
b69b1191cf6b464910383befd4f0e3049045d125
2022-04-15 11:10:56
arunvjn
fix: widgets from other apps shown in omnibar (#12890)
false
widgets from other apps shown in omnibar (#12890)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Migration_Spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Migration_Spec.js index c306af7306c3..8e2e09f31eb5 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Migration_Spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Migration_Spec.js @@ -35,9 +35,8 @@ describe("Migration Validate", function() { const uuid = () => Cypress._.random(0, 1e4); const name = uuid(); cy.wait(2000); - cy.get(homePage.applicationName) - .clear() - .type(`app${name}`); + cy.AppSetupForRename(); + cy.get(homePage.applicationName).type(`app${name}`); cy.wrap(`app${name}`).as("appname"); cy.wait(2000); diff --git a/app/client/cypress/support/Pages/HomePage.ts b/app/client/cypress/support/Pages/HomePage.ts index a0e2845e2c1d..2d6e34e0e1eb 100644 --- a/app/client/cypress/support/Pages/HomePage.ts +++ b/app/client/cypress/support/Pages/HomePage.ts @@ -156,7 +156,7 @@ export class HomePage { if (!$appName.hasClass(this._editAppName)) { cy.get(this._applicationName).click(); cy.get(this._appMenu) - .contains("Rename", { matchCase: false }) + .contains("Edit Name", { matchCase: false }) .click(); } }); diff --git a/app/client/src/actions/pageActions.tsx b/app/client/src/actions/pageActions.tsx index 6874e5fe143f..8ab6d5c11bab 100644 --- a/app/client/src/actions/pageActions.tsx +++ b/app/client/src/actions/pageActions.tsx @@ -462,3 +462,11 @@ export const setPageOrder = ( }, }; }; + +export const resetPageList = () => ({ + type: ReduxActionTypes.RESET_PAGE_LIST, +}); + +export const resetApplicationWidgets = () => ({ + type: ReduxActionTypes.RESET_APPLICATION_WIDGET_STATE_REQUEST, +}); diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index 974b1dfeb9e1..9de195d40d68 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -698,6 +698,7 @@ export const ReduxActionTypes = { GET_TEMPLATE_INIT: "GET_TEMPLATES_INIT", GET_TEMPLATE_SUCCESS: "GET_TEMPLATES_SUCCESS", START_EXECUTE_JS_FUNCTION: "START_EXECUTE_JS_FUNCTION", + RESET_PAGE_LIST: "RESET_PAGE_LIST", }; export type ReduxActionType = typeof ReduxActionTypes[keyof typeof ReduxActionTypes]; diff --git a/app/client/src/reducers/entityReducers/pageListReducer.tsx b/app/client/src/reducers/entityReducers/pageListReducer.tsx index 0dcdaf4fc17b..d789d4868a62 100644 --- a/app/client/src/reducers/entityReducers/pageListReducer.tsx +++ b/app/client/src/reducers/entityReducers/pageListReducer.tsx @@ -45,6 +45,7 @@ export const pageListReducer = createReducer(initialState, { action.payload.pages[0].pageId, }; }, + [ReduxActionTypes.RESET_PAGE_LIST]: () => initialState, [ReduxActionTypes.CREATE_PAGE_SUCCESS]: ( state: PageListReduxState, action: ReduxAction<{ diff --git a/app/client/src/reducers/uiReducers/pageCanvasStructureReducer.ts b/app/client/src/reducers/uiReducers/pageCanvasStructureReducer.ts index 98b44758ef19..ad5b7dddd1ed 100644 --- a/app/client/src/reducers/uiReducers/pageCanvasStructureReducer.ts +++ b/app/client/src/reducers/uiReducers/pageCanvasStructureReducer.ts @@ -60,6 +60,11 @@ const pageCanvasStructureReducer = createImmerReducer(initialState, { ) => { return { ...state, [action.payload.pageId]: false }; }, + [ReduxActionTypes.RESET_APPLICATION_WIDGET_STATE_REQUEST]: ( + state: PageCanvasStructureReduxState, + ) => { + Object.keys(state).forEach((key) => delete state[key]); + }, }); export default pageCanvasStructureReducer; diff --git a/app/client/src/reducers/uiReducers/pageWidgetsReducer.ts b/app/client/src/reducers/uiReducers/pageWidgetsReducer.ts index 008495bb447a..9417530a0365 100644 --- a/app/client/src/reducers/uiReducers/pageWidgetsReducer.ts +++ b/app/client/src/reducers/uiReducers/pageWidgetsReducer.ts @@ -13,9 +13,9 @@ export interface PageWidgetsReduxState { }; } -const initalState: PageWidgetsReduxState = {}; +const initialState: PageWidgetsReduxState = {}; -const pageWidgetsReducer = createImmerReducer(initalState, { +const pageWidgetsReducer = createImmerReducer(initialState, { // Reducer to clear all pageWidgets before finishing creating // a new application [ReduxActionTypes.RESET_APPLICATION_WIDGET_STATE_REQUEST]: () => ({}), diff --git a/app/client/src/sagas/ApplicationSagas.tsx b/app/client/src/sagas/ApplicationSagas.tsx index 7ebf36ed1e84..4d5baef9acd4 100644 --- a/app/client/src/sagas/ApplicationSagas.tsx +++ b/app/client/src/sagas/ApplicationSagas.tsx @@ -97,6 +97,7 @@ import { getConfigInitialValues } from "components/formControls/utils"; import { merge } from "lodash"; import DatasourcesApi from "api/DatasourcesApi"; import { AppState } from "reducers"; +import { resetApplicationWidgets } from "actions/pageActions"; export const getDefaultPageId = ( pages?: ApplicationPagePayload[], @@ -530,9 +531,7 @@ export function* createApplicationSaga( // This sets ui.pageWidgets = {} to ensure that // widgets are cleaned up from state before // finishing creating a new application - yield put({ - type: ReduxActionTypes.RESET_APPLICATION_WIDGET_STATE_REQUEST, - }); + yield put(resetApplicationWidgets()); yield put({ type: ReduxActionTypes.CREATE_APPLICATION_SUCCESS, payload: { diff --git a/app/client/src/sagas/InitSagas.ts b/app/client/src/sagas/InitSagas.ts index 06e2044067f8..a9fb56deb89c 100644 --- a/app/client/src/sagas/InitSagas.ts +++ b/app/client/src/sagas/InitSagas.ts @@ -21,6 +21,8 @@ import { ERROR_CODES } from "@appsmith/constants/ApiConstants"; import { fetchPage, fetchPublishedPage, + resetApplicationWidgets, + resetPageList, setAppMode, updateAppPersistentStore, } from "actions/pageActions"; @@ -38,6 +40,7 @@ import { import { ApplicationVersion, fetchApplication, + resetCurrentApplication, } from "actions/applicationActions"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { getCurrentApplication } from "selectors/applicationSelectors"; @@ -441,6 +444,9 @@ export function* initializeAppViewerSaga( } function* resetEditorSaga() { + yield put(resetCurrentApplication()); + yield put(resetPageList()); + yield put(resetApplicationWidgets()); yield put(resetRecentEntities()); // End guided tour once user exits editor yield put(enableGuidedTour(false));
2b77da799189ff9bb13a86db683c2b8c2db435af
2025-01-30 17:40:34
Apeksha Bhosale
chore: added buckets for 2s, 5s, 10s and 20s to be measured on grafana (#38910)
false
added buckets for 2s, 5s, 10s and 20s to be measured on grafana (#38910)
chore
diff --git a/app/server/appsmith-server/src/main/resources/application.properties b/app/server/appsmith-server/src/main/resources/application.properties index 37a09c3ed519..9a5be44783a5 100644 --- a/app/server/appsmith-server/src/main/resources/application.properties +++ b/app/server/appsmith-server/src/main/resources/application.properties @@ -95,7 +95,7 @@ management.opentelemetry.resource-attributes.service.instance.id=${HOSTNAME:apps management.opentelemetry.resource-attributes.deployment.name=${APPSMITH_DEPLOYMENT_NAME:self-hosted} management.tracing.sampling.probability=${APPSMITH_SAMPLING_PROBABILITY:0.1} management.prometheus.metrics.export.descriptions=true -management.metrics.distribution.slo.http.server.requests=100,200,500,1000,30000 +management.metrics.distribution.slo.http.server.requests=100,200,500,1000,2000,5000,10000,20000,30000 # Observability and Micrometer related configs # Keeping this license key around, until later
0695bb37c9573da962aa02b0e6d056366aae677e
2025-03-19 13:48:03
Nilesh Sarupriya
chore: add post publish hooks for application (#39793)
false
add post publish hooks for application (#39793)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/postpublishhooks/NewActionPostApplicationPublishServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/postpublishhooks/NewActionPostApplicationPublishServiceCEImpl.java new file mode 100644 index 000000000000..931e407dd7cc --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/postpublishhooks/NewActionPostApplicationPublishServiceCEImpl.java @@ -0,0 +1,22 @@ +package com.appsmith.server.newactions.postpublishhooks; + +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.NewAction; +import com.appsmith.server.postpublishhooks.base.PostPublishHookableCE; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RequiredArgsConstructor +public class NewActionPostApplicationPublishServiceCEImpl implements PostPublishHookableCE<Application, NewAction> { + + @Override + public Class<NewAction> getEntityType() { + return NewAction.class; + } + + @Override + public Class<Application> getArtifactType() { + return Application.class; + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/postpublishhooks/NewActionPostApplicationPublishServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/postpublishhooks/NewActionPostApplicationPublishServiceImpl.java new file mode 100644 index 000000000000..81184b66dc21 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/postpublishhooks/NewActionPostApplicationPublishServiceImpl.java @@ -0,0 +1,15 @@ +package com.appsmith.server.newactions.postpublishhooks; + +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.NewAction; +import com.appsmith.server.postpublishhooks.base.PostPublishHookable; +import org.springframework.stereotype.Service; + +@Service +public class NewActionPostApplicationPublishServiceImpl extends NewActionPostApplicationPublishServiceCEImpl + implements PostPublishHookable<Application, NewAction> { + + public NewActionPostApplicationPublishServiceImpl() { + super(); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/ApplicationPostPublishHookCoordinatorServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/ApplicationPostPublishHookCoordinatorServiceCEImpl.java new file mode 100644 index 000000000000..019549469552 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/ApplicationPostPublishHookCoordinatorServiceCEImpl.java @@ -0,0 +1,55 @@ +package com.appsmith.server.postpublishhooks; + +import com.appsmith.server.domains.Application; +import com.appsmith.server.postpublishhooks.base.PostPublishHookCoordinatorServiceCE; +import com.appsmith.server.postpublishhooks.base.PostPublishHookable; +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; + +/** + * Service responsible for coordinating post-publish hooks for different entity types. + * This service delegates to the appropriate specialized services based on entity type. + */ +@Slf4j +public class ApplicationPostPublishHookCoordinatorServiceCEImpl + implements PostPublishHookCoordinatorServiceCE<Application> { + + protected final List<PostPublishHookable<Application, ?>> postPublishHookables; + + public ApplicationPostPublishHookCoordinatorServiceCEImpl( + List<PostPublishHookable<Application, ?>> postPublishHookables) { + this.postPublishHookables = postPublishHookables; + } + + /** + * Executes all post-publish hooks for all entity types in an application. + * This is done asynchronously to not block the publish operation. + * + * @param applicationId The ID of the application that was published + * @return Void Mono when all hooks have been executed + */ + @Override + public void executePostPublishHooks(String applicationId) { + log.debug("Executing post-publish hooks for application: {}", applicationId); + + Flux.fromIterable(postPublishHookables) + .flatMap(hookable -> { + log.debug( + "Executing post-publish hook for entity type: {}", + hookable.getEntityType().getSimpleName()); + return hookable.postPublishHookForArtifactEntities(applicationId) + .onErrorResume(error -> { + log.error( + "Error executing post-publish hook for entity type {}: {}", + hookable.getEntityType().getSimpleName(), + error.getMessage()); + return Mono.empty(); + }); + }) + .then() + .subscribe(); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/ApplicationPostPublishHookCoordinatorServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/ApplicationPostPublishHookCoordinatorServiceImpl.java new file mode 100644 index 000000000000..aa4b2b821af4 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/ApplicationPostPublishHookCoordinatorServiceImpl.java @@ -0,0 +1,24 @@ +package com.appsmith.server.postpublishhooks; + +import com.appsmith.server.domains.Application; +import com.appsmith.server.postpublishhooks.base.PostPublishHookCoordinatorService; +import com.appsmith.server.postpublishhooks.base.PostPublishHookable; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Service responsible for coordinating post-publish hooks for different entity types. + * This service delegates to the appropriate specialized services based on entity type. + */ +@Slf4j +@Service +public class ApplicationPostPublishHookCoordinatorServiceImpl extends ApplicationPostPublishHookCoordinatorServiceCEImpl + implements PostPublishHookCoordinatorService<Application> { + + public ApplicationPostPublishHookCoordinatorServiceImpl( + List<PostPublishHookable<Application, ?>> postPublishHookables) { + super(postPublishHookables); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookCoordinatorService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookCoordinatorService.java new file mode 100644 index 000000000000..0a1c30e28de5 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookCoordinatorService.java @@ -0,0 +1,6 @@ +package com.appsmith.server.postpublishhooks.base; + +/** + * Interface defining operations for coordinating post-publish hooks across different entity types. + */ +public interface PostPublishHookCoordinatorService<T> extends PostPublishHookCoordinatorServiceCE<T> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookCoordinatorServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookCoordinatorServiceCE.java new file mode 100644 index 000000000000..9689ebd4a04b --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookCoordinatorServiceCE.java @@ -0,0 +1,15 @@ +package com.appsmith.server.postpublishhooks.base; + +/** + * Interface defining operations for coordinating post-publish hooks across different entity types. + */ +public interface PostPublishHookCoordinatorServiceCE<T> { + + /** + * Executes all post-publish hooks for all entity types in an artifact. + * + * @param artifactId The ID of the artifact that was published + * @return Void Mono when all hooks have been executed + */ + void executePostPublishHooks(String artifactId); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookable.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookable.java new file mode 100644 index 000000000000..79d979ae2fc3 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookable.java @@ -0,0 +1,3 @@ +package com.appsmith.server.postpublishhooks.base; + +public interface PostPublishHookable<ARTEFACT, ENTITY> extends PostPublishHookableCE<ARTEFACT, ENTITY> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookableCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookableCE.java new file mode 100644 index 000000000000..726e86ac2ac1 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/postpublishhooks/base/PostPublishHookableCE.java @@ -0,0 +1,36 @@ +package com.appsmith.server.postpublishhooks.base; + +import reactor.core.publisher.Mono; + +/** + * Interface defining the post-publish hook capability. + * This is implemented by services that need to perform operations after an artifact is published. + * + * @param <T> The entity type that this hook operates on + */ +public interface PostPublishHookableCE<ARTEFACT, ENTITY> { + + /** + * Executes post-publish operations for all entities of a specific type in an artifact. + * + * @param artifactId The artifact ID + * @return Void Mono when processing is complete + */ + default Mono<Void> postPublishHookForArtifactEntities(String artifactId) { + return Mono.empty(); + } + + /** + * Returns the entity class type this service handles. + * + * @return The class of the entity type + */ + Class<ENTITY> getEntityType(); + + /** + * Returns the artifact class type this service handles. + * + * @return The class of the artifact type + */ + Class<ARTEFACT> getArtifactType(); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java index f31d8f50c3a4..7b4ed4daf6fd 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java @@ -5,12 +5,14 @@ import com.appsmith.server.applications.base.ApplicationService; import com.appsmith.server.clonepage.ClonePageService; import com.appsmith.server.domains.ActionCollection; +import com.appsmith.server.domains.Application; import com.appsmith.server.domains.NewAction; import com.appsmith.server.helpers.CommonGitFileUtils; import com.appsmith.server.helpers.DSLMigrationUtils; import com.appsmith.server.layouts.UpdateLayoutService; import com.appsmith.server.newactions.base.NewActionService; import com.appsmith.server.newpages.base.NewPageService; +import com.appsmith.server.postpublishhooks.base.PostPublishHookCoordinatorService; import com.appsmith.server.repositories.ActionCollectionRepository; import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.CacheableRepositoryHelper; @@ -62,7 +64,8 @@ public ApplicationPageServiceImpl( ClonePageService<NewAction> actionClonePageService, ClonePageService<ActionCollection> actionCollectionClonePageService, ObservationRegistry observationRegistry, - CacheableRepositoryHelper cacheableRepositoryHelper) { + CacheableRepositoryHelper cacheableRepositoryHelper, + PostPublishHookCoordinatorService<Application> postApplicationPublishHookCoordinatorService) { super( workspaceService, applicationService, @@ -92,6 +95,7 @@ public ApplicationPageServiceImpl( actionClonePageService, actionCollectionClonePageService, observationRegistry, - cacheableRepositoryHelper); + cacheableRepositoryHelper, + postApplicationPublishHookCoordinatorService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java index d3d715620ff5..51da794866fa 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java @@ -42,6 +42,7 @@ import com.appsmith.server.migrations.ApplicationVersion; import com.appsmith.server.newactions.base.NewActionService; import com.appsmith.server.newpages.base.NewPageService; +import com.appsmith.server.postpublishhooks.base.PostPublishHookCoordinatorService; import com.appsmith.server.repositories.ActionCollectionRepository; import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.CacheableRepositoryHelper; @@ -132,6 +133,8 @@ public class ApplicationPageServiceCEImpl implements ApplicationPageServiceCE { private final ObservationRegistry observationRegistry; private final CacheableRepositoryHelper cacheableRepositoryHelper; + private final PostPublishHookCoordinatorService<Application> postApplicationPublishHookCoordinatorService; + @Override public Mono<PageDTO> createPage(PageDTO page) { if (page.getId() != null) { @@ -1042,6 +1045,8 @@ public Mono<Application> publishWithoutPermissionChecks(String applicationId, bo ApplicationPublishingMetaDTO metaDTO = tuple2.getT2(); return sendApplicationPublishedEvent(metaDTO); }) + .doOnNext(application -> + postApplicationPublishHookCoordinatorService.executePostPublishHooks(applicationId)) .elapsed() .map(objects -> { log.debug(
a715c0eefad6dadc78fa7caa74cfd4f1751011e8
2022-05-09 14:59:53
ashit-rath
fix: JSONForm Phone number field required validation (#13525)
false
JSONForm Phone number field required validation (#13525)
fix
diff --git a/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.test.ts b/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.test.ts index 3f15e958564e..e9665194d28c 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.test.ts +++ b/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.test.ts @@ -1,5 +1,5 @@ import { FieldType } from "../constants"; -import { InputFieldProps, isValid } from "./InputField"; +import { isValid, PhoneInputFieldProps } from "./PhoneInputField"; describe("Phone Input Field", () => { it("return validity when not required", () => { @@ -18,7 +18,7 @@ describe("Phone Input Field", () => { const schemaItem = { isRequired: false, fieldType: FieldType.TEXT_INPUT, - } as InputFieldProps["schemaItem"]; + } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); @@ -42,7 +42,7 @@ describe("Phone Input Field", () => { const schemaItem = { isRequired: true, fieldType: FieldType.TEXT_INPUT, - } as InputFieldProps["schemaItem"]; + } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); @@ -66,7 +66,7 @@ describe("Phone Input Field", () => { const schemaItem = { validation: true, fieldType: FieldType.TEXT_INPUT, - } as InputFieldProps["schemaItem"]; + } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); @@ -90,7 +90,7 @@ describe("Phone Input Field", () => { const schemaItem = { validation: false, fieldType: FieldType.TEXT_INPUT, - } as InputFieldProps["schemaItem"]; + } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); @@ -115,7 +115,7 @@ describe("Phone Input Field", () => { validation: false, isRequired: true, fieldType: FieldType.TEXT_INPUT, - } as InputFieldProps["schemaItem"]; + } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); diff --git a/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.tsx b/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.tsx index 8f38b2e863ea..b6fda8ec4707 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.tsx @@ -48,7 +48,7 @@ export const isValid = ( schemaItem: PhoneInputFieldProps["schemaItem"], inputValue?: string | null, ) => { - const isEmptyValue = !isEmpty(inputValue); + const isEmptyValue = isEmpty(inputValue); if (schemaItem.isRequired && isEmptyValue) { return false; @@ -64,7 +64,7 @@ export const isValid = ( const parsedRegex = parseRegex(schemaItem.regex); - return parsedRegex ? parsedRegex.test(inputValue) : isEmptyValue; + return !parsedRegex || parsedRegex.test(inputValue); }; const transformValue = (value: string) => {
c460154c4322445c731558993f09c9adbcd36999
2022-12-09 15:29:35
sneha122
fix: datasource discard popup issue fixed (#18761)
false
datasource discard popup issue fixed (#18761)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Bug18664_spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Bug18664_spec.ts new file mode 100644 index 000000000000..d74008366960 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Bug18664_spec.ts @@ -0,0 +1,24 @@ +import { ObjectsRegistry } from "../../../../support/Objects/Registry"; + +let dsName: any; + +const agHelper = ObjectsRegistry.AggregateHelper, + dataSources = ObjectsRegistry.DataSources; + +describe("Bug 18664: datasource unsaved changes popup shows even without changes", function() { + it("1. Create postgres datasource, save it and edit it and go back, now unsaved changes popup should not be shown", () => { + dataSources.NavigateToDSCreateNew(); + agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + dataSources.CreatePlugIn("PostgreSQL"); + dsName = "Postgres" + uid; + agHelper.RenameWithInPane(dsName, false); + dataSources.SaveDatasource(); + cy.wait(1000); + dataSources.EditDatasource(); + agHelper.GoBack(); + agHelper.AssertElementVisible(dataSources._activeDS); + dataSources.DeleteDatasouceFromActiveTab(dsName); + }); + }); +}); diff --git a/app/client/src/pages/Editor/DataSourceEditor/index.tsx b/app/client/src/pages/Editor/DataSourceEditor/index.tsx index a5c949a2eac2..064ffb959377 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/index.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/index.tsx @@ -208,8 +208,20 @@ const mapStateToProps = (state: AppState, props: any): ReduxStateProps => { const { applicationSlug, pageSlug } = selectURLSlugs(state); const formName = plugin?.type === "API" ? DATASOURCE_REST_API_FORM : DATASOURCE_DB_FORM; + // for plugins, where 1 default endpoint is initialized, + // added this check so that form isnt considered dirty with default endpoint + const defaultEndpoints: Array<{ + host: string; + port: string; + }> = (formData?.datasourceConfiguration as any)?.endpoints || []; + const isDefaultEndpoint = + defaultEndpoints.length === 1 && + defaultEndpoints[0].host === "" && + defaultEndpoints[0].port === ""; const isFormDirty = - datasourceId === TEMP_DATASOURCE_ID ? true : isDirty(formName)(state); + datasourceId === TEMP_DATASOURCE_ID + ? true + : isDirty(formName)(state) && !isDefaultEndpoint; return { datasourceId,
0ad0989a556b79b50f6f2e26bc7639acd78b1ba8
2024-09-20 19:37:10
Ankita Kinger
chore: Adding a new hook to set `settingsConfig` for an action based on IDE type (#36442)
false
Adding a new hook to set `settingsConfig` for an action based on IDE type (#36442)
chore
diff --git a/app/client/src/PluginActionEditor/PluginActionEditor.tsx b/app/client/src/PluginActionEditor/PluginActionEditor.tsx index 40470b7bd837..5ffa8a4d777e 100644 --- a/app/client/src/PluginActionEditor/PluginActionEditor.tsx +++ b/app/client/src/PluginActionEditor/PluginActionEditor.tsx @@ -7,7 +7,6 @@ import { getDatasource, getEditorConfig, getPlugin, - getPluginSettingConfigs, } from "ee/selectors/entitiesSelector"; import { PluginActionContextProvider } from "./PluginActionContext"; import { get } from "lodash"; @@ -16,6 +15,7 @@ import Spinner from "components/editorComponents/Spinner"; import CenteredWrapper from "components/designSystems/appsmith/CenteredWrapper"; import { Text } from "@appsmith/ads"; import { useIsEditorInitialised } from "IDE/hooks"; +import { useActionSettingsConfig } from "./hooks"; interface ChildrenProps { children: React.ReactNode | React.ReactNode[]; @@ -35,9 +35,7 @@ const PluginActionEditor = (props: ChildrenProps) => { const datasourceId = get(action, "datasource.id", ""); const datasource = useSelector((state) => getDatasource(state, datasourceId)); - const settingsConfig = useSelector((state) => - getPluginSettingConfigs(state, pluginId), - ); + const settingsConfig = useActionSettingsConfig(action); const editorConfig = useSelector((state) => getEditorConfig(state, pluginId)); diff --git a/app/client/src/PluginActionEditor/hooks/index.ts b/app/client/src/PluginActionEditor/hooks/index.ts new file mode 100644 index 000000000000..5af0c9060d3a --- /dev/null +++ b/app/client/src/PluginActionEditor/hooks/index.ts @@ -0,0 +1 @@ +export { useActionSettingsConfig } from "ee/PluginActionEditor/hooks/useActionSettingsConfig"; diff --git a/app/client/src/ce/PluginActionEditor/hooks/useActionSettingsConfig.ts b/app/client/src/ce/PluginActionEditor/hooks/useActionSettingsConfig.ts new file mode 100644 index 000000000000..22ade9d6c371 --- /dev/null +++ b/app/client/src/ce/PluginActionEditor/hooks/useActionSettingsConfig.ts @@ -0,0 +1,11 @@ +import { useSelector } from "react-redux"; +import { getPluginSettingConfigs } from "ee/selectors/entitiesSelector"; +import type { Action } from "entities/Action"; + +function useActionSettingsConfig(action?: Action) { + return useSelector((state) => + getPluginSettingConfigs(state, action?.pluginId || ""), + ); +} + +export { useActionSettingsConfig }; diff --git a/app/client/src/ee/PluginActionEditor/hooks/useActionSettingsConfig.ts b/app/client/src/ee/PluginActionEditor/hooks/useActionSettingsConfig.ts new file mode 100644 index 000000000000..23112ff41e01 --- /dev/null +++ b/app/client/src/ee/PluginActionEditor/hooks/useActionSettingsConfig.ts @@ -0,0 +1 @@ +export * from "ce/PluginActionEditor/hooks/useActionSettingsConfig";
1c7cca908ca7d515b3d975286f21beff75e87684
2023-09-19 11:54:43
Ankita Kinger
chore: Updating instance admin emails input field to tag input field for better UX (#27410)
false
Updating instance admin emails input field to tag input field for better UX (#27410)
chore
diff --git a/app/client/src/ce/constants/SocialLogin.tsx b/app/client/src/ce/constants/SocialLogin.tsx index 70ede20a8436..70aaf033137b 100644 --- a/app/client/src/ce/constants/SocialLogin.tsx +++ b/app/client/src/ce/constants/SocialLogin.tsx @@ -1,4 +1,7 @@ -import { GoogleOAuthURL, GithubOAuthURL } from "./ApiConstants"; +import { + GoogleOAuthURL, + GithubOAuthURL, +} from "@appsmith/constants/ApiConstants"; import GithubLogo from "assets/images/Github.png"; import GoogleLogo from "assets/images/Google.png"; diff --git a/app/client/src/ce/pages/AdminSettings/config/general.tsx b/app/client/src/ce/pages/AdminSettings/config/general.tsx index 02700c4e8635..4a4417e94408 100644 --- a/app/client/src/ce/pages/AdminSettings/config/general.tsx +++ b/app/client/src/ce/pages/AdminSettings/config/general.tsx @@ -31,11 +31,10 @@ export const APPSMITH_INSTANCE_NAME_SETTING_SETTING: Setting = { export const APPSMITH__ADMIN_EMAILS_SETTING: Setting = { id: "APPSMITH_ADMIN_EMAILS", category: SettingCategories.GENERAL, - controlType: SettingTypes.TEXTINPUT, + controlType: SettingTypes.TAGINPUT, controlSubType: SettingSubtype.EMAIL, label: "Admin email", - subText: - "* Emails of the users who can modify instance settings (comma separated)", + subText: "* Emails of the users who can modify instance settings", placeholder: "[email protected]", validate: (value: string) => { if ( diff --git a/app/client/src/ce/pages/Applications/index.tsx b/app/client/src/ce/pages/Applications/index.tsx index 393a0fc12f53..ec5c7da24845 100644 --- a/app/client/src/ce/pages/Applications/index.tsx +++ b/app/client/src/ce/pages/Applications/index.tsx @@ -93,8 +93,8 @@ import { import { getTenantPermissions } from "@appsmith/selectors/tenantSelectors"; import { getAppsmithConfigs } from "@appsmith/configs"; import FormDialogComponent from "components/editorComponents/form/FormDialogComponent"; -import WorkspaceMenu from "./WorkspaceMenu"; -import ApplicationCardList from "./ApplicationCardList"; +import WorkspaceMenu from "@appsmith/pages/Applications/WorkspaceMenu"; +import ApplicationCardList from "@appsmith/pages/Applications/ApplicationCardList"; import { usePackage } from "@appsmith/pages/Applications/helpers"; import PackageCardList from "@appsmith/pages/Applications/PackageCardList"; import WorkspaceAction from "@appsmith/pages/Applications/WorkspaceAction"; diff --git a/app/client/src/ce/pages/workspace/Members.tsx b/app/client/src/ce/pages/workspace/Members.tsx index 6560d20c71bf..5d072db4e2fc 100644 --- a/app/client/src/ce/pages/workspace/Members.tsx +++ b/app/client/src/ce/pages/workspace/Members.tsx @@ -37,7 +37,7 @@ import { PERMISSION_TYPE, } from "@appsmith/utils/permissionHelpers"; import { getInitials } from "utils/AppsmithUtils"; -import { CustomRolesRamp } from "./WorkspaceInviteUsersForm"; +import { CustomRolesRamp } from "@appsmith/pages/workspace/WorkspaceInviteUsersForm"; import { showProductRamps } from "@appsmith/selectors/rampSelectors"; import { RAMP_NAME } from "utils/ProductRamps/RampsControlList"; diff --git a/app/client/src/ce/reducers/settingsReducer.ts b/app/client/src/ce/reducers/settingsReducer.ts index 6c33f543247d..19d4e084a3fb 100644 --- a/app/client/src/ce/reducers/settingsReducer.ts +++ b/app/client/src/ce/reducers/settingsReducer.ts @@ -4,7 +4,7 @@ import { ReduxActionTypes, } from "@appsmith/constants/ReduxActionConstants"; import { createReducer } from "utils/ReducerUtils"; -import type { TenantReduxState } from "./tenantReducer"; +import type { TenantReduxState } from "@appsmith/reducers/tenantReducer"; import { tenantConfigConnection } from "@appsmith/constants/tenantConstants"; export const initialState: SettingsReduxState = { diff --git a/app/client/src/ce/sagas/JSFunctionExecutionSaga.ts b/app/client/src/ce/sagas/JSFunctionExecutionSaga.ts index 0f2fb867472d..393aa788a2a9 100644 --- a/app/client/src/ce/sagas/JSFunctionExecutionSaga.ts +++ b/app/client/src/ce/sagas/JSFunctionExecutionSaga.ts @@ -2,7 +2,7 @@ import { TriggerKind } from "constants/AppsmithActionConstants/ActionConstants"; import type { TriggerSource } from "constants/AppsmithActionConstants/ActionConstants"; import { call } from "redux-saga/effects"; import type { TMessage } from "utils/MessageUtil"; -import { logJSActionExecution } from "./analyticsSaga"; +import { logJSActionExecution } from "@appsmith/sagas/analyticsSaga"; export function* logJSFunctionExecution( data: TMessage<{ diff --git a/app/client/src/ce/sagas/WorkspaceSagas.ts b/app/client/src/ce/sagas/WorkspaceSagas.ts index c207532cd748..12efda80a14c 100644 --- a/app/client/src/ce/sagas/WorkspaceSagas.ts +++ b/app/client/src/ce/sagas/WorkspaceSagas.ts @@ -41,7 +41,7 @@ import { DELETE_WORKSPACE_SUCCESSFUL, } from "@appsmith/constants/messages"; import { toast } from "design-system"; -import { resetCurrentWorkspace } from "../actions/workspaceActions"; +import { resetCurrentWorkspace } from "@appsmith/actions/workspaceActions"; export function* fetchRolesSaga() { try { diff --git a/app/client/src/ee/pages/Applications/ApplicationCardList.tsx b/app/client/src/ee/pages/Applications/ApplicationCardList.tsx new file mode 100644 index 000000000000..f4e061c07450 --- /dev/null +++ b/app/client/src/ee/pages/Applications/ApplicationCardList.tsx @@ -0,0 +1,3 @@ +export * from "ce/pages/Applications/ApplicationCardList"; +import { default as CE_ApplicationCardList } from "ce/pages/Applications/ApplicationCardList"; +export default CE_ApplicationCardList; diff --git a/app/client/src/ee/pages/Applications/WorkspaceMenu.tsx b/app/client/src/ee/pages/Applications/WorkspaceMenu.tsx new file mode 100644 index 000000000000..d771d3d37e2c --- /dev/null +++ b/app/client/src/ee/pages/Applications/WorkspaceMenu.tsx @@ -0,0 +1,3 @@ +export * from "ce/pages/Applications/WorkspaceMenu"; +import { default as CE_WorkspaceMenu } from "ce/pages/Applications/WorkspaceMenu"; +export default CE_WorkspaceMenu; diff --git a/app/client/src/pages/AdminSettings/FormGroup/TagInputField.tsx b/app/client/src/pages/AdminSettings/FormGroup/TagInputField.tsx index 8f4cdedf6d5d..8bee64affcb5 100644 --- a/app/client/src/pages/AdminSettings/FormGroup/TagInputField.tsx +++ b/app/client/src/pages/AdminSettings/FormGroup/TagInputField.tsx @@ -5,6 +5,19 @@ import { TagInput } from "design-system-old"; import { FormGroup } from "./Common"; import type { Intent } from "constants/DefaultTheme"; import type { Setting } from "@appsmith/pages/AdminSettings/config/types"; +import styled from "styled-components"; + +const StyledTagInput = styled(TagInput)` + .bp3-tag-input-values { + flex-wrap: nowrap; + width: 100%; + overflow: auto; + + &::-webkit-scrollbar { + height: 0px; + } + } +`; const renderComponent = ( componentProps: TagListFieldProps & { @@ -20,7 +33,7 @@ const renderComponent = ( }`} setting={setting} > - <TagInput {...componentProps} /> + <StyledTagInput {...componentProps} /> </FormGroup> ); };
1f0c38bbf498e6638728ab82caad442acb9c0376
2022-06-09 14:11:16
Tolulope Adetula
fix: remove template literals
false
remove template literals
fix
diff --git a/app/client/src/widgets/MultiSelectWidget/component/index.tsx b/app/client/src/widgets/MultiSelectWidget/component/index.tsx index b514cfe05120..e0106a85c565 100644 --- a/app/client/src/widgets/MultiSelectWidget/component/index.tsx +++ b/app/client/src/widgets/MultiSelectWidget/component/index.tsx @@ -109,7 +109,7 @@ function MultiSelectComponent({ `.${MODAL_PORTAL_CLASSNAME}`, ) as HTMLElement; } - return document.querySelector(`.${CANVAS_SELECTOR}`) as HTMLElement; + return document.querySelector(CANVAS_SELECTOR) as HTMLElement; }, []); const handleSelectAll = () => {
819d43b5d0e04d1b060dcf44a01b78a316e7d5a9
2022-08-04 16:00:36
Tanvi Bhakta
feat: import changes for button tab component (#15507)
false
import changes for button tab component (#15507)
feat
diff --git a/app/client/package.json b/app/client/package.json index 95cf55d3fd54..adfa94a118ba 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -45,7 +45,7 @@ "cypress-log-to-output": "^1.1.2", "dayjs": "^1.10.6", "deep-diff": "^1.0.2", - "design-system": "npm:@appsmithorg/[email protected]", + "design-system": "npm:@appsmithorg/[email protected]", "downloadjs": "^1.4.7", "draft-js": "^0.11.7", "emoji-mart": "^3.0.1", @@ -292,4 +292,4 @@ "json-schema": "0.4.0", "node-fetch": "2.6.7" } -} \ No newline at end of file +} diff --git a/app/client/src/components/ads/ButtonTabComponent.test.tsx b/app/client/src/components/ads/ButtonTabComponent.test.tsx deleted file mode 100644 index dadef363d6fa..000000000000 --- a/app/client/src/components/ads/ButtonTabComponent.test.tsx +++ /dev/null @@ -1,123 +0,0 @@ -import React from "react"; -import "@testing-library/jest-dom"; -import { render, screen } from "@testing-library/react"; -import { ThemeProvider } from "constants/DefaultTheme"; -import ButtonTabComponent from "./ButtonTabComponent"; -import { lightTheme } from "selectors/themeSelectors"; -import userEvent from "@testing-library/user-event"; -import { noop } from "lodash"; - -const options = [ - { - icon: "BOLD_FONT", - value: "BOLD", - }, - { - icon: "ITALICS_FONT", - value: "ITALICS", - }, - { - icon: "UNDERLINE", - value: "UNDERLINE", - }, -]; - -describe("<ButtonTabComponent />", () => { - const getTestComponent = ( - handleOnSelect: any = undefined, - values: Array<string> = [], - ) => ( - <ThemeProvider theme={lightTheme}> - <ButtonTabComponent - options={options} - selectButton={handleOnSelect} - values={values} - /> - </ThemeProvider> - ); - - it("passed value should be selected", () => { - const firstItem = options[0]; - render(getTestComponent(noop, [firstItem.value])); - - expect(screen.getByRole("tab", { selected: true })).toHaveClass( - `t--button-tab-${firstItem.value}`, - ); - }); -}); - -describe("<ButtonTabComponent /> - Keyboard Navigation", () => { - const getTestComponent = (handleOnSelect: any = undefined) => ( - <ThemeProvider theme={lightTheme}> - <ButtonTabComponent - options={options} - selectButton={handleOnSelect} - values={[]} - /> - </ThemeProvider> - ); - - it("Pressing tab should focus the component", () => { - render(getTestComponent()); - userEvent.tab(); - expect(screen.getByRole("tablist")).toHaveFocus(); - - // Should focus first Item - screen.getAllByRole("tab").forEach((tab, i) => { - if (i === 0) expect(tab).toHaveClass("focused"); - else expect(tab).not.toHaveClass("focused"); - }); - }); - - it("{ArrowRight} should focus the next item", () => { - render(getTestComponent()); - userEvent.tab(); - - userEvent.keyboard("{ArrowRight}"); - screen.getAllByRole("tab").forEach((tab, i) => { - if (i === 1) expect(tab).toHaveClass("focused"); - else expect(tab).not.toHaveClass("focused"); - }); - - // ArrowRight after the last item should focus the first item again - userEvent.keyboard("{ArrowRight}"); - userEvent.keyboard("{ArrowRight}"); - screen.getAllByRole("tab").forEach((tab, i) => { - if (i === 0) expect(tab).toHaveClass("focused"); - else expect(tab).not.toHaveClass("focused"); - }); - }); - - it("{ArrowLeft} should focus the previous item", () => { - render(getTestComponent()); - userEvent.tab(); - - userEvent.keyboard("{ArrowLeft}"); - screen.getAllByRole("tab").forEach((tab, i) => { - if (i === 2) expect(tab).toHaveClass("focused"); - else expect(tab).not.toHaveClass("focused"); - }); - - userEvent.keyboard("{ArrowLeft}"); - screen.getAllByRole("tab").forEach((tab, i) => { - if (i === 1) expect(tab).toHaveClass("focused"); - else expect(tab).not.toHaveClass("focused"); - }); - }); - - it("{Enter} or ' ' should trigger click event for the focused item", () => { - const handleClick = jest.fn(); - render(getTestComponent(handleClick)); - userEvent.tab(); - - userEvent.keyboard("{ArrowRight}"); - userEvent.keyboard("{Enter}"); - expect(handleClick).toHaveBeenCalledTimes(1); - expect(handleClick).toHaveBeenLastCalledWith(options[1].value, true); - - userEvent.keyboard("{ArrowRight}"); - userEvent.keyboard("{Enter}"); - expect(handleClick).toHaveBeenCalledTimes(2); - expect(handleClick).toHaveBeenLastCalledWith(options[2].value, true); - }); -}); diff --git a/app/client/src/components/ads/ButtonTabComponent.tsx b/app/client/src/components/ads/ButtonTabComponent.tsx deleted file mode 100644 index 16707667a3aa..000000000000 --- a/app/client/src/components/ads/ButtonTabComponent.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import React, { useCallback, useState } from "react"; -import styled from "styled-components"; -import { Colors } from "constants/Colors"; -import { ControlIcons } from "icons/ControlIcons"; -import _ from "lodash"; -import { DSEventTypes } from "utils/AppsmithUtils"; -import useDSEvent from "utils/hooks/useDSEvent"; - -const ItemWrapper = styled.div<{ selected: boolean }>` - min-width: 32px; - height: 32px; - padding: 0 2px; - display: flex; - align-items: center; - justify-content: center; - border: 1px solid - ${(props) => (props.selected ? Colors.GREY_10 : Colors.GREY_5)}; - - &.focused { - background: ${Colors.GREY_3}; - } - - cursor: pointer; - & { - margin-right: 4px; - } - & > div { - cursor: pointer; - } - &:hover { - background: ${Colors.GREY_3}; - } - &&& svg { - path { - fill: ${Colors.GREY_7} !important; - } - } -`; - -const FlexWrapper = styled.div` - display: inline-flex; -`; - -export interface ButtonTabOption { - icon: string | JSX.Element; - value: string; - width?: number; -} - -interface ButtonTabComponentProps { - options: ButtonTabOption[]; - values: Array<string>; - selectButton: (value: string, isUpdatedViaKeyboard: boolean) => void; -} - -const ButtonTabComponent = React.forwardRef( - (props: ButtonTabComponentProps, ref: any) => { - const valueSet = new Set(props.values); - let firstValueIndex = 0; - for (const [i, x] of props.options.entries()) { - if (valueSet.has(x.value)) { - firstValueIndex = i; - break; - } - } - - const { emitDSEvent, eventEmitterRef } = useDSEvent<HTMLDivElement>( - false, - ref, - ); - - const emitKeyPressEvent = useCallback( - (key: string) => { - emitDSEvent({ - component: "ButtonTab", - event: DSEventTypes.KEYPRESS, - meta: { - key, - }, - }); - }, - [emitDSEvent], - ); - - const [focusedIndex, setFocusedIndex] = useState<number>(-1); - - const handleKeyDown = (e: React.KeyboardEvent) => { - switch (e.key) { - case "ArrowRight": - case "Right": - emitKeyPressEvent(e.key); - setFocusedIndex((prev) => - prev === props.options.length - 1 ? 0 : prev + 1, - ); - break; - case "ArrowLeft": - case "Left": - emitKeyPressEvent(e.key); - setFocusedIndex((prev) => - prev === 0 ? props.options.length - 1 : prev - 1, - ); - break; - case "Enter": - case " ": - emitKeyPressEvent(e.key); - props.selectButton(props.options[focusedIndex].value, true); - e.preventDefault(); - break; - case "Tab": - emitKeyPressEvent(`${e.shiftKey ? "Shift+" : ""}${e.key}`); - break; - } - }; - - return ( - <FlexWrapper - onBlur={() => setFocusedIndex(-1)} - onFocus={() => setFocusedIndex(firstValueIndex)} - onKeyDown={handleKeyDown} - ref={eventEmitterRef} - role="tablist" - tabIndex={0} - > - {props.options.map( - ({ icon, value, width = 24 }: ButtonTabOption, index: number) => { - let ControlIcon; - if (_.isString(icon)) { - const Icon = ControlIcons[icon]; - ControlIcon = <Icon height={24} width={width} />; - } else { - ControlIcon = icon; - } - const isSelected = valueSet.has(value); - return ( - <ItemWrapper - aria-selected={isSelected} - className={`t--button-tab-${value} ${ - index === focusedIndex ? "focused" : "" - }`} - key={index} - onClick={() => { - props.selectButton(value, false); - setFocusedIndex(index); - }} - role="tab" - selected={isSelected} - > - {ControlIcon} - </ItemWrapper> - ); - }, - )} - </FlexWrapper> - ); - }, -); - -export default ButtonTabComponent; diff --git a/app/client/src/components/ads/index.ts b/app/client/src/components/ads/index.ts index 5b46ab867061..fcf5ce4730a4 100644 --- a/app/client/src/components/ads/index.ts +++ b/app/client/src/components/ads/index.ts @@ -4,9 +4,6 @@ export * from "./AppIcon"; export { default as Button } from "./Button"; export * from "./Button"; -export { default as ButtonTabComponent } from "./ButtonTabComponent"; -export * from "./ButtonTabComponent"; - export { default as Callout } from "./Callout"; export * from "./Callout"; diff --git a/app/client/src/components/propertyControls/BorderRadiusOptionsControl.tsx b/app/client/src/components/propertyControls/BorderRadiusOptionsControl.tsx index 851519bb6788..d6adaf15897f 100644 --- a/app/client/src/components/propertyControls/BorderRadiusOptionsControl.tsx +++ b/app/client/src/components/propertyControls/BorderRadiusOptionsControl.tsx @@ -3,7 +3,7 @@ import * as React from "react"; import { TooltipComponent } from "design-system"; import BaseControl, { ControlData, ControlProps } from "./BaseControl"; import { borderRadiusOptions } from "constants/ThemeConstants"; -import { ButtonTabComponent } from "components/ads"; +import { ButtonTab } from "design-system"; import { DSEventDetail, DSEventTypes, @@ -86,7 +86,7 @@ class BorderRadiusOptionsControl extends BaseControl< public render() { return ( - <ButtonTabComponent + <ButtonTab options={options} ref={this.componentRef} selectButton={(value, isUpdatedViaKeyboard = false) => { diff --git a/app/client/src/components/propertyControls/BoxShadowOptionsControl.tsx b/app/client/src/components/propertyControls/BoxShadowOptionsControl.tsx index 336b870db8dd..2935eab0c796 100644 --- a/app/client/src/components/propertyControls/BoxShadowOptionsControl.tsx +++ b/app/client/src/components/propertyControls/BoxShadowOptionsControl.tsx @@ -4,7 +4,7 @@ import BaseControl, { ControlData, ControlProps } from "./BaseControl"; import { TooltipComponent } from "design-system"; import { boxShadowOptions } from "constants/ThemeConstants"; import CloseLineIcon from "remixicon-react/CloseLineIcon"; -import { ButtonTabComponent } from "components/ads"; +import { ButtonTab } from "design-system"; import { DSEventDetail, DSEventTypes, @@ -80,7 +80,7 @@ class BoxShadowOptionsControl extends BaseControl< public render() { return ( - <ButtonTabComponent + <ButtonTab options={options} ref={this.componentRef} selectButton={(value, isUpdatedViaKeyboard = false) => { diff --git a/app/client/src/components/propertyControls/ButtonTabControl.tsx b/app/client/src/components/propertyControls/ButtonTabControl.tsx index 81c3c380db53..8b5020647e45 100644 --- a/app/client/src/components/propertyControls/ButtonTabControl.tsx +++ b/app/client/src/components/propertyControls/ButtonTabControl.tsx @@ -1,8 +1,6 @@ import React from "react"; import BaseControl, { ControlData, ControlProps } from "./BaseControl"; -import ButtonTabComponent, { - ButtonTabOption, -} from "components/ads/ButtonTabComponent"; +import { ButtonTab, ButtonTabOption } from "design-system"; import produce from "immer"; import { DSEventDetail, @@ -69,7 +67,7 @@ class ButtonTabControl extends BaseControl<ButtonTabControlProps> { render() { const { options, propertyValue } = this.props; return ( - <ButtonTabComponent + <ButtonTab options={options} ref={this.componentRef} selectButton={this.selectButton} diff --git a/app/client/src/components/propertyControls/IconTabControl.tsx b/app/client/src/components/propertyControls/IconTabControl.tsx index ba2bf163a2b3..4c4a2c7b6cbb 100644 --- a/app/client/src/components/propertyControls/IconTabControl.tsx +++ b/app/client/src/components/propertyControls/IconTabControl.tsx @@ -1,8 +1,6 @@ import React from "react"; import BaseControl, { ControlData, ControlProps } from "./BaseControl"; -import ButtonTabComponent, { - ButtonTabOption, -} from "components/ads/ButtonTabComponent"; +import { ButtonTab, ButtonTabOption } from "design-system"; import { DSEventDetail, DSEventTypes, @@ -54,7 +52,7 @@ class IconTabControl extends BaseControl<IconTabControlProps> { render() { const { options, propertyValue } = this.props; return ( - <ButtonTabComponent + <ButtonTab options={options} ref={this.componentRef} selectButton={this.selectOption} diff --git a/app/client/src/components/propertyControls/LabelAlignmentOptionsControl.tsx b/app/client/src/components/propertyControls/LabelAlignmentOptionsControl.tsx index 9ba268a713aa..ffd8cfd6c599 100644 --- a/app/client/src/components/propertyControls/LabelAlignmentOptionsControl.tsx +++ b/app/client/src/components/propertyControls/LabelAlignmentOptionsControl.tsx @@ -3,9 +3,7 @@ import styled from "styled-components"; import { Alignment } from "@blueprintjs/core"; import BaseControl, { ControlProps } from "./BaseControl"; -import ButtonTabComponent, { - ButtonTabOption, -} from "components/ads/ButtonTabComponent"; +import { ButtonTab, ButtonTabOption } from "design-system"; import { DSEventDetail, DSEventTypes, @@ -72,7 +70,7 @@ class LabelAlignmentOptionsControl extends BaseControl< const { options, propertyValue } = this.props; return ( <ControlContainer> - <ButtonTabComponent + <ButtonTab options={options} ref={this.componentRef} selectButton={this.handleAlign} diff --git a/app/client/yarn.lock b/app/client/yarn.lock index 85082d2ae17a..fca5977196f7 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -1255,6 +1255,13 @@ dependencies: regenerator-runtime "^0.13.4" +"@babel/runtime@^7.2.0", "@babel/runtime@^7.7.6": + version "7.18.9" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.18.9.tgz#b4fcfce55db3d2e5e080d2490f608a3b9f407f4a" + integrity sha512-lkqXDcvlFT5rvEjiu6+QYO+1GXrEHRo2LOtS7E4GtX5ESIZOgepqsZBVIj6Pv+a6zqsya9VCgiK1KAK4BvJDAw== + dependencies: + regenerator-runtime "^0.13.4" + "@babel/runtime@^7.3.4": version "7.13.17" resolved "https://registry.npmjs.org/@babel/runtime/-/runtime-7.13.17.tgz" @@ -1408,7 +1415,7 @@ resize-observer-polyfill "^1.5.1" tslib "~1.13.0" -"@blueprintjs/datetime@^3.23.6": +"@blueprintjs/[email protected]", "@blueprintjs/datetime@^3.23.6": version "3.23.6" resolved "https://registry.npmjs.org/@blueprintjs/datetime/-/datetime-3.23.6.tgz" dependencies: @@ -3328,9 +3335,10 @@ "@types/scheduler" "*" csstype "^3.0.2" -"@types/redux-form@^8.1.9": +"@types/[email protected]", "@types/redux-form@^8.1.9": version "8.3.0" - resolved "https://registry.npmjs.org/@types/redux-form/-/redux-form-8.3.0.tgz" + resolved "https://registry.yarnpkg.com/@types/redux-form/-/redux-form-8.3.0.tgz#d253e0078a4940187b946459e0bb4d6a355018b1" + integrity sha512-LUOpffXkPpY7n9pQvaAy9TifMgQFVqQF0LmJLLiZGWpDmDmvgEbNbQ6h2tSJ7CVNIVo45wPPVdWw5Mi91ZPvfQ== dependencies: "@types/react" "*" redux "^3.6.0 || ^4.0.0" @@ -6119,10 +6127,21 @@ depd@~1.1.2: version "1.1.2" resolved "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz" -"design-system@npm:@appsmithorg/[email protected]": - version "1.0.4-beta.1" - resolved "https://registry.yarnpkg.com/@appsmithorg/design-system/-/design-system-1.0.4-beta.1.tgz#752383f3f25921c57de7618046d9c56589ecd2ec" - integrity sha512-AZUhobfOFOwtRushfElbqt+RKhkd5r8QKPtnjwbuxVQM7vPpI0m9mu8dEbUI7f5HWZlBz2dxg9CSnyNh2ULZ5w== +"design-system@npm:@appsmithorg/[email protected]": + version "1.0.7" + resolved "https://registry.yarnpkg.com/@appsmithorg/design-system/-/design-system-1.0.7.tgz#f698649435b9976e32ca54c42ac07fa7a867b239" + integrity sha512-irwuAb7+nVYkCBrlPLWlxp2p8QDNNeB7dJYlX+AM/2lu+qIQIEw+9+ymZaYAARTm3XVsgQc5vHYga2MS5a/lPA== + dependencies: + "@blueprintjs/datetime" "3.23.6" + "@types/redux-form" "8.3.0" + copy-to-clipboard "^3.3.1" + emoji-mart "3.0.1" + react-redux "^7.2.4" + react-router-dom "^6.3.0" + react-tabs "3.1.1" + redux-form "8.2.6" + remixicon-react "^1.0.0" + tinycolor2 "^1.4.2" [email protected]: version "1.2.0" @@ -6445,9 +6464,10 @@ emittery@^0.8.1: resolved "https://registry.npmjs.org/emittery/-/emittery-0.8.1.tgz" integrity sha512-uDfvUjVrfGJJhymx/kz6prltenw1u7WrCg1oa94zYY8xxVpLLUu045LAT0dhDZdXG58/EpPL/5kA180fQ/qudg== -emoji-mart@^3.0.1: [email protected], emoji-mart@^3.0.1: version "3.0.1" - resolved "https://registry.npmjs.org/emoji-mart/-/emoji-mart-3.0.1.tgz" + resolved "https://registry.yarnpkg.com/emoji-mart/-/emoji-mart-3.0.1.tgz#9ce86706e02aea0506345f98464814a662ca54c6" + integrity sha512-sxpmMKxqLvcscu6mFn9ITHeZNkGzIvD0BSNFE/LJESPbCA8s1jM6bCDPjWbV31xHq7JXaxgpHxLB54RCbBZSlg== dependencies: "@babel/runtime" "^7.0.0" prop-types "^15.6.0" @@ -8144,6 +8164,13 @@ history@^4.10.1, history@^4.9.0: tiny-warning "^1.0.0" value-equal "^1.0.1" +history@^5.2.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/history/-/history-5.3.0.tgz#1548abaa245ba47992f063a0783db91ef201c73b" + integrity sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ== + dependencies: + "@babel/runtime" "^7.7.6" + hogan.js@^3.0.2: version "3.0.2" resolved "https://registry.npmjs.org/hogan.js/-/hogan.js-3.0.2.tgz" @@ -8155,7 +8182,7 @@ hoist-non-react-statics@^2.3.1: version "2.5.5" resolved "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz" -hoist-non-react-statics@^3.0.0, hoist-non-react-statics@^3.1.0, hoist-non-react-statics@^3.3.0, hoist-non-react-statics@^3.3.2: +hoist-non-react-statics@^3.0.0, hoist-non-react-statics@^3.1.0, hoist-non-react-statics@^3.2.1, hoist-non-react-statics@^3.3.0, hoist-non-react-statics@^3.3.2: version "3.3.2" resolved "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz" dependencies: @@ -8429,6 +8456,11 @@ immer@^9.0.7: resolved "https://registry.npmjs.org/immer/-/immer-9.0.14.tgz" integrity sha512-ubBeqQutOSLIFCUBN03jGeOS6a3DoYlSYwYJTa+gSKEZKU5redJIqkIdZ3JVv/4RZpfcXdAWH5zCNLWPRv2WDw== [email protected]: + version "3.8.2" + resolved "https://registry.yarnpkg.com/immutable/-/immutable-3.8.2.tgz#c2439951455bb39913daf281376f1530e104adf3" + integrity sha512-15gZoQ38eYjEjxkorfbcgBKBL6R7T459OuK+CpcWt7O3KF4uPCx2tD0uFETlUDIyo+1789crbMhTvQBSR5yBMg== + immutable@~3.7.4: version "3.7.6" resolved "https://registry.npmjs.org/immutable/-/immutable-3.7.6.tgz" @@ -9951,7 +9983,7 @@ locate-path@^6.0.0: dependencies: p-locate "^5.0.0" [email protected], lodash-es@^4.17.21: [email protected], lodash-es@^4.17.15, lodash-es@^4.17.21: version "4.17.21" resolved "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz" @@ -12798,6 +12830,14 @@ react-router-dom@^5.1.2: tiny-invariant "^1.0.2" tiny-warning "^1.0.0" +react-router-dom@^6.3.0: + version "6.3.0" + resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.3.0.tgz#a0216da813454e521905b5fa55e0e5176123f43d" + integrity sha512-uaJj7LKytRxZNQV8+RbzJWnJ8K2nPsOOEuX7aQstlMZKQT0164C+X2w6bnkqU3sjtLvpd5ojrezAyfZ1+0sStw== + dependencies: + history "^5.2.0" + react-router "6.3.0" + [email protected], react-router@^5.1.2: version "5.2.0" resolved "https://registry.npmjs.org/react-router/-/react-router-5.2.0.tgz" @@ -12813,6 +12853,13 @@ [email protected], react-router@^5.1.2: tiny-invariant "^1.0.2" tiny-warning "^1.0.0" [email protected]: + version "6.3.0" + resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.3.0.tgz#3970cc64b4cb4eae0c1ea5203a80334fdd175557" + integrity sha512-7Wh1DzVQ+tlFjkeo+ujvjSqSJmkt1+8JO+T5xklPlgrh70y7ogx75ODRW0ThWhY7S+6yEDks8TYrtQe/aoboBQ== + dependencies: + history "^5.2.0" + react-scripts@^5.0.1: version "5.0.1" resolved "https://registry.npmjs.org/react-scripts/-/react-scripts-5.0.1.tgz" @@ -12913,9 +12960,10 @@ react-table@^7.0.0: version "7.6.0" resolved "https://registry.npmjs.org/react-table/-/react-table-7.6.0.tgz" -react-tabs@^3.0.0: [email protected], react-tabs@^3.0.0: version "3.1.1" - resolved "https://registry.npmjs.org/react-tabs/-/react-tabs-3.1.1.tgz" + resolved "https://registry.yarnpkg.com/react-tabs/-/react-tabs-3.1.1.tgz#b363a239f76046bb2158875a1e5921b11064052f" + integrity sha512-HpySC29NN1BkzBAnOC+ajfzPbTaVZcSWzMSjk56uAhPC/rBGtli8lTysR4CfPAyEE/hfweIzagOIoJ7nu80yng== dependencies: clsx "^1.1.0" prop-types "^15.5.0" @@ -13115,6 +13163,24 @@ redux-devtools@^3.5.0: prop-types "^15.7.2" redux-devtools-instrument "^1.10.0" [email protected]: + version "8.2.6" + resolved "https://registry.yarnpkg.com/redux-form/-/redux-form-8.2.6.tgz#6840bbe9ed5b2aaef9dd82e6db3e5efcfddd69b1" + integrity sha512-krmF7wl1C753BYpEpWIVJ5NM4lUJZFZc5GFUVgblT+jprB99VVBDyBcgrZM3gWWLOcncFyNsHcKNQQcFg8Uanw== + dependencies: + "@babel/runtime" "^7.2.0" + es6-error "^4.1.1" + hoist-non-react-statics "^3.2.1" + invariant "^2.2.4" + is-promise "^2.1.0" + lodash "^4.17.15" + lodash-es "^4.17.15" + prop-types "^15.6.1" + react-is "^16.7.0" + react-lifecycles-compat "^3.0.4" + optionalDependencies: + immutable "3.8.2" + redux-form@^8.2.6: version "8.3.6" resolved "https://registry.npmjs.org/redux-form/-/redux-form-8.3.6.tgz"
610799f7a78d2d7f75ff347fa3fb0ee870ebd253
2022-04-12 15:46:27
Arpit Mohan
chore: Migrating Github release workflow to use Buildjet for client build (#12847)
false
Migrating Github release workflow to use Buildjet for client build (#12847)
chore
diff --git a/.github/workflows/github-release.yml b/.github/workflows/github-release.yml index 6e664335208f..4c2b9c13daa0 100644 --- a/.github/workflows/github-release.yml +++ b/.github/workflows/github-release.yml @@ -44,7 +44,7 @@ jobs: needs: - prelude - runs-on: ubuntu-latest + runs-on: buildjet-8vcpu-ubuntu-2004 defaults: run:
a3e99674b711c8797bea672c8c247293ec45e7d1
2024-12-17 00:07:20
Nidhi
test: CGS commit and detach negative tests (#38173)
false
CGS commit and detach negative tests (#38173)
test
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitCommitTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitCommitTests.java new file mode 100644 index 000000000000..7b8b377c6428 --- /dev/null +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitCommitTests.java @@ -0,0 +1,237 @@ +package com.appsmith.server.git.ops; + +import com.appsmith.external.git.handler.FSGitHandler; +import com.appsmith.git.dto.CommitDTO; +import com.appsmith.server.applications.base.ApplicationService; +import com.appsmith.server.constants.ArtifactType; +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.GitArtifactMetadata; +import com.appsmith.server.domains.GitAuth; +import com.appsmith.server.domains.GitProfile; +import com.appsmith.server.domains.User; +import com.appsmith.server.domains.Workspace; +import com.appsmith.server.dtos.GitConnectDTO; +import com.appsmith.server.dtos.PageDTO; +import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.git.central.CentralGitService; +import com.appsmith.server.git.central.GitType; +import com.appsmith.server.helpers.CommonGitFileUtils; +import com.appsmith.server.services.ApplicationPageService; +import com.appsmith.server.services.UserService; +import com.appsmith.server.services.WorkspaceService; +import org.apache.commons.lang.StringUtils; +import org.eclipse.jgit.api.errors.EmptyCommitException; +import org.eclipse.jgit.errors.RepositoryNotFoundException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.security.test.context.support.WithUserDetails; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.UUID; + +import static com.appsmith.external.git.constants.GitConstants.EMPTY_COMMIT_ERROR_MESSAGE; +import static com.appsmith.external.git.constants.GitConstants.GIT_CONFIG_ERROR; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; + +@SpringBootTest +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GitCommitTests { + + @Autowired + CentralGitService centralGitService; + + @Autowired + ApplicationPageService applicationPageService; + + @Autowired + ApplicationService applicationService; + + @Autowired + WorkspaceService workspaceService; + + @Autowired + UserService userService; + + @SpyBean + FSGitHandler fsGitHandler; + + @SpyBean + CommonGitFileUtils commonGitFileUtils; + + @Test + @WithUserDetails(value = "api_user") + public void commitArtifact_whenNoChangesInLocal_returnsWithEmptyCommitMessage() throws IOException { + + CommitDTO commitDTO = new CommitDTO(); + commitDTO.setMessage("empty commit"); + + User apiUser = userService.findByEmail("api_user").block(); + Workspace toCreate = new Workspace(); + toCreate.setName("Workspace_" + UUID.randomUUID()); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + assertThat(workspace).isNotNull(); + + Application application = + createApplicationConnectedToGit("Application_" + UUID.randomUUID(), "foo", workspace.getId()); + + Mockito.doReturn(Mono.just(Paths.get(""))) + .when(commonGitFileUtils) + .saveArtifactToLocalRepoWithAnalytics(any(Path.class), any(), Mockito.anyString()); + Mockito.doReturn(Mono.error(new EmptyCommitException("nothing to commit"))) + .when(fsGitHandler) + .commitArtifact( + any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean()); + + Mono<String> commitMono = centralGitService.commitArtifact( + commitDTO, application.getId(), ArtifactType.APPLICATION, GitType.FILE_SYSTEM); + + StepVerifier.create(commitMono) + .assertNext(commitMsg -> { + assertThat(commitMsg).contains(EMPTY_COMMIT_ERROR_MESSAGE); + }) + .verifyComplete(); + } + + private Application createApplicationConnectedToGit(String name, String branchName, String workspaceId) + throws IOException { + + if (StringUtils.isEmpty(branchName)) { + branchName = "foo"; + } + Mockito.doReturn(Mono.just(branchName)) + .when(fsGitHandler) + .cloneRemoteIntoArtifactRepo(any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(Mono.just("commit")) + .when(fsGitHandler) + .commitArtifact( + any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean()); + Mockito.doReturn(Mono.just(true)).when(fsGitHandler).checkoutToBranch(any(Path.class), Mockito.anyString()); + Mockito.doReturn(Mono.just("success")) + .when(fsGitHandler) + .pushApplication(any(Path.class), any(), any(), any(), any()); + Mockito.doReturn(Mono.just(true)).when(commonGitFileUtils).checkIfDirectoryIsEmpty(any(Path.class)); + Mockito.doReturn(Mono.just(Paths.get("textPath"))) + .when(commonGitFileUtils) + .initializeReadme(any(Path.class), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(Mono.just(Paths.get("path"))) + .when(commonGitFileUtils) + .saveArtifactToLocalRepoWithAnalytics(any(Path.class), any(), Mockito.anyString()); + + Application testApplication = new Application(); + testApplication.setName(name); + testApplication.setWorkspaceId(workspaceId); + Application application1 = + applicationPageService.createApplication(testApplication).block(); + + GitArtifactMetadata gitArtifactMetadata = new GitArtifactMetadata(); + GitAuth gitAuth = new GitAuth(); + gitAuth.setPublicKey("testkey"); + gitAuth.setPrivateKey("privatekey"); + gitArtifactMetadata.setGitAuth(gitAuth); + gitArtifactMetadata.setDefaultApplicationId(application1.getId()); + gitArtifactMetadata.setRepoName("testRepo"); + application1.setGitApplicationMetadata(gitArtifactMetadata); + application1 = applicationService.save(application1).block(); + + PageDTO page = new PageDTO(); + page.setName("New Page"); + page.setApplicationId(application1.getId()); + applicationPageService.createPage(page).block(); + + GitProfile gitProfile = new GitProfile(); + gitProfile.setAuthorEmail("[email protected]"); + gitProfile.setAuthorName("testUser"); + GitConnectDTO gitConnectDTO = new GitConnectDTO(); + gitConnectDTO.setRemoteUrl("[email protected]:test/testRepo.git"); + gitConnectDTO.setGitProfile(gitProfile); + return centralGitService + .connectArtifactToGit( + application1.getId(), gitConnectDTO, "baseUrl", ArtifactType.APPLICATION, GitType.FILE_SYSTEM) + .map(artifact -> (Application) artifact) + .block(); + } + + @Test + @WithUserDetails(value = "api_user") + public void commitArtifact_whenApplicationNotConnectedToGit_throwsInvalidGitConfigException() { + + User apiUser = userService.findByEmail("api_user").block(); + Workspace toCreate = new Workspace(); + toCreate.setName("Workspace_" + UUID.randomUUID()); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + assertThat(workspace).isNotNull(); + + Application application = new Application(); + application.setName("sampleAppNotConnectedToGit"); + application.setWorkspaceId(workspace.getId()); + application.setId(null); + application = applicationPageService.createApplication(application).block(); + + CommitDTO commitDTO = new CommitDTO(); + commitDTO.setMessage("empty commit"); + + Mono<String> commitMono = centralGitService.commitArtifact( + commitDTO, application.getId(), ArtifactType.APPLICATION, GitType.FILE_SYSTEM); + + StepVerifier.create(commitMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR))) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void commitArtifact_whenLocalRepoNotAvailable_throwsRepoNotFoundException() throws IOException { + + CommitDTO commitDTO = new CommitDTO(); + commitDTO.setMessage("empty commit"); + + User apiUser = userService.findByEmail("api_user").block(); + Workspace toCreate = new Workspace(); + toCreate.setName("Workspace_" + UUID.randomUUID()); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + assertThat(workspace).isNotNull(); + + Application application = + createApplicationConnectedToGit("Application_" + UUID.randomUUID(), "foo", workspace.getId()); + + Mono<String> commitMono = centralGitService.commitArtifact( + commitDTO, application.getId(), ArtifactType.APPLICATION, GitType.FILE_SYSTEM); + + Mockito.doReturn(Mono.error(new RepositoryNotFoundException(AppsmithError.REPOSITORY_NOT_FOUND.getMessage()))) + .when(commonGitFileUtils) + .saveArtifactToLocalRepoWithAnalytics(any(Path.class), any(), Mockito.anyString()); + + StepVerifier.create(commitMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .contains(AppsmithError.REPOSITORY_NOT_FOUND.getMessage(application.getId()))) + .verify(); + } +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDetachTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDetachTests.java new file mode 100644 index 000000000000..422bfccd82f5 --- /dev/null +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDetachTests.java @@ -0,0 +1,131 @@ +package com.appsmith.server.git.ops; + +import com.appsmith.external.git.handler.FSGitHandler; +import com.appsmith.server.acl.AclPermission; +import com.appsmith.server.constants.ArtifactType; +import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.User; +import com.appsmith.server.domains.Workspace; +import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.git.central.CentralGitService; +import com.appsmith.server.git.central.GitType; +import com.appsmith.server.helpers.CommonGitFileUtils; +import com.appsmith.server.repositories.ApplicationRepository; +import com.appsmith.server.services.ApplicationPageService; +import com.appsmith.server.services.UserService; +import com.appsmith.server.services.WorkspaceService; +import com.appsmith.server.solutions.ApplicationPermission; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.security.test.context.support.WithUserDetails; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GitDetachTests { + + @Autowired + CentralGitService centralGitService; + + @Autowired + ApplicationPageService applicationPageService; + + @Autowired + WorkspaceService workspaceService; + + @Autowired + UserService userService; + + @Autowired + ApplicationPermission applicationPermission; + + @Autowired + ApplicationRepository applicationRepository; + + @SpyBean + FSGitHandler fsGitHandler; + + @SpyBean + CommonGitFileUtils commonGitFileUtils; + + @Test + @WithUserDetails(value = "api_user") + public void detachRemote_withEmptyGitData_hasNoChangeOnArtifact() { + User apiUser = userService.findByEmail("api_user").block(); + Workspace toCreate = new Workspace(); + toCreate.setName("Workspace_" + UUID.randomUUID()); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + assertThat(workspace).isNotNull(); + + Application testApplication = new Application(); + testApplication.setGitApplicationMetadata(null); + testApplication.setName("detachRemote_withEmptyGitData"); + testApplication.setWorkspaceId(workspace.getId()); + Application application1 = + applicationPageService.createApplication(testApplication).block(); + + Mono<Application> applicationMono = centralGitService + .detachRemote(application1.getId(), ArtifactType.APPLICATION, GitType.FILE_SYSTEM) + .map(artifact -> (Application) artifact); + + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + & throwable.getMessage().contains("Git configuration is invalid")) + .verify(); + } + + @WithUserDetails("api_user") + @Test + public void detachRemote_whenUserDoesNotHaveRequiredPermission_throwsException() { + Application application = + createApplicationAndRemovePermissionFromApplication(applicationPermission.getGitConnectPermission()); + Mono<Application> applicationMono = centralGitService + .detachRemote(application.getId(), ArtifactType.APPLICATION, GitType.FILE_SYSTEM) + .map(artifact -> (Application) artifact); + + StepVerifier.create(applicationMono) + .expectErrorMessage( + AppsmithError.ACL_NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, application.getId())) + .verify(); + } + + /** + * This method creates a workspace, creates an application in the workspace and removes the + * create application permission from the workspace for the api_user. + * + * @return Created Application + */ + private Application createApplicationAndRemovePermissionFromApplication(AclPermission permission) { + User apiUser = userService.findByEmail("api_user").block(); + + Workspace toCreate = new Workspace(); + toCreate.setName("Workspace_" + UUID.randomUUID()); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + assertThat(workspace).isNotNull(); + + Application testApplication = new Application(); + testApplication.setWorkspaceId(workspace.getId()); + testApplication.setName("Test App"); + Application application1 = + applicationPageService.createApplication(testApplication).block(); + + assertThat(application1).isNotNull(); + + // remove permission from the application for the api user + application1.getPolicyMap().remove(permission.getValue()); + + return applicationRepository.save(application1).block(); + } +}
769719ccfe667f059fe0b107a19ec9feb90f2e40
2022-09-19 12:41:57
Shrikant Sharat Kandula
fix: Better support for disallowed hosts (#16842)
false
Better support for disallowed hosts (#16842)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/TriggerUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/TriggerUtils.java index 99987e1ce405..2f3556d864de 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/TriggerUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/TriggerUtils.java @@ -35,10 +35,8 @@ import javax.crypto.SecretKey; import java.io.IOException; -import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; -import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; @@ -46,7 +44,6 @@ import java.util.List; import java.util.Set; -import static com.appsmith.external.helpers.restApiUtils.helpers.URIUtils.DISALLOWED_HOSTS; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @NoArgsConstructor @@ -204,14 +201,10 @@ protected Mono<ClientResponse> httpCall(WebClient webClient, HttpMethod httpMeth * It redirects to partial URI : /api/character/ * In this scenario we should convert the partial URI to complete URI */ - URI redirectUri; + final URI redirectUri; try { redirectUri = new URI(redirectUrl); - if (DISALLOWED_HOSTS.contains(redirectUri.getHost()) - || DISALLOWED_HOSTS.contains(InetAddress.getByName(redirectUri.getHost()).getHostAddress())) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Host not allowed.")); - } - } catch (URISyntaxException | UnknownHostException e) { + } catch (URISyntaxException e) { return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, e)); } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/URIUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/URIUtils.java index cc3c761b1332..70c9b5af9777 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/URIUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/URIUtils.java @@ -3,30 +3,21 @@ import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.Property; -import lombok.AccessLevel; import lombok.NoArgsConstructor; -import org.apache.commons.lang3.StringUtils; import org.springframework.web.util.UriComponentsBuilder; -import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; -import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.Set; import static org.apache.commons.collections.CollectionUtils.isEmpty; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @NoArgsConstructor public class URIUtils { - public static final Set<String> DISALLOWED_HOSTS = Set.of( - "169.254.169.254", - "metadata.google.internal" - ); public URI createUriWithQueryParams(ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration, String url, @@ -53,7 +44,7 @@ public URI addQueryParamsToURI(URI uri, List<Property> allQueryParams, boolean e for (Property queryParam : allQueryParams) { String key = queryParam.getKey(); if (isNotEmpty(key)) { - if (encodeParamsToggle == true) { + if (encodeParamsToggle) { uriBuilder.queryParam( URLEncoder.encode(key, StandardCharsets.UTF_8), URLEncoder.encode((String) queryParam.getValue(), StandardCharsets.UTF_8) @@ -78,9 +69,4 @@ protected String addHttpToUrlWhenPrefixNotPresent(String url) { return "http://" + url; } - public boolean isHostDisallowed(URI uri) throws UnknownHostException { - String host = uri.getHost(); - return StringUtils.isEmpty(host) || DISALLOWED_HOSTS.contains(host) - || DISALLOWED_HOSTS.contains(InetAddress.getByName(host).getHostAddress()); - } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java index 8861dd16e58f..f87b62fa3095 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java @@ -1,11 +1,31 @@ package com.appsmith.util; +import io.netty.resolver.AddressResolver; +import io.netty.resolver.AddressResolverGroup; +import io.netty.resolver.InetNameResolver; +import io.netty.resolver.InetSocketAddressResolver; +import io.netty.util.concurrent.EventExecutor; +import io.netty.util.concurrent.Promise; +import io.netty.util.internal.SocketUtils; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; import reactor.netty.http.client.HttpClient; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + public class WebClientUtils { + private static final Set<String> DISALLOWED_HOSTS = Set.of( + "169.254.169.254", + "metadata.google.internal" + ); + private WebClientUtils() { } @@ -31,15 +51,86 @@ public static WebClient.Builder builder() { public static WebClient.Builder builder(HttpClient httpClient) { return WebClient.builder() - .clientConnector(new ReactorClientHttpConnector(applyProxyIfConfigured(httpClient))); + .clientConnector(new ReactorClientHttpConnector(makeSafeHttpClient(httpClient))); } - private static HttpClient applyProxyIfConfigured(HttpClient httpClient) { + private static HttpClient makeSafeHttpClient(HttpClient httpClient) { if (shouldUseSystemProxy()) { httpClient = httpClient.proxyWithSystemProperties(); } - return httpClient; + return httpClient.resolver(ResolverGroup.INSTANCE); + } + + private static class ResolverGroup extends AddressResolverGroup<InetSocketAddress> { + public static final ResolverGroup INSTANCE = new ResolverGroup(); + + @Override + protected AddressResolver<InetSocketAddress> newResolver(EventExecutor executor) { + return new InetSocketAddressResolver(executor, new NameResolver(executor)); + } + } + + @Slf4j + private static class NameResolver extends InetNameResolver { + + public NameResolver(EventExecutor executor) { + super(executor); + } + + private static boolean isDisallowedAndFail(String host, Promise<?> promise) { + if (DISALLOWED_HOSTS.contains(host)) { + log.warn("Host {} is disallowed. Failing the request.", host); + promise.setFailure(new UnknownHostException("Host not allowed.")); + return true; + } + return false; + } + + @Override + protected void doResolve(String inetHost, Promise<InetAddress> promise) { + if (isDisallowedAndFail(inetHost, promise)) { + return; + } + + final InetAddress address; + try { + address = SocketUtils.addressByName(inetHost); + } catch (UnknownHostException e) { + promise.setFailure(e); + return; + } + + if (isDisallowedAndFail(address.getHostAddress(), promise)) { + return; + } + + promise.setSuccess(address); + } + + @Override + protected void doResolveAll(String inetHost, Promise<List<InetAddress>> promise) { + if (isDisallowedAndFail(inetHost, promise)) { + return; + } + + final List<InetAddress> addresses; + try { + addresses = Arrays.asList(SocketUtils.allAddressesByName(inetHost)); + } catch (UnknownHostException e) { + promise.setFailure(e); + return; + } + + // Even if _one_ of the addresses is disallowed, we fail the request. + for (InetAddress address : addresses) { + if (isDisallowedAndFail(address.getHostAddress(), promise)) { + return; + } + } + + promise.setSuccess(addresses); + } } } diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java index 8cda9bd1840e..8453494cce3a 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java @@ -27,7 +27,6 @@ import java.net.URI; import java.net.URISyntaxException; -import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -37,12 +36,12 @@ import static com.appsmith.external.helpers.PluginUtils.getValueSafelyFromPropertyList; import static com.appsmith.external.helpers.PluginUtils.setValueSafelyInPropertyList; import static com.external.utils.GraphQLBodyUtils.PAGINATION_DATA_INDEX; -import static com.external.utils.GraphQLDataTypeUtils.smartlyReplaceGraphQLQueryBodyPlaceholderWithValue; -import static com.external.utils.GraphQLPaginationUtils.updateVariablesWithPaginationValues; import static com.external.utils.GraphQLBodyUtils.QUERY_VARIABLES_INDEX; import static com.external.utils.GraphQLBodyUtils.convertToGraphQLPOSTBodyFormat; import static com.external.utils.GraphQLBodyUtils.getGraphQLQueryParamsForBodyAndVariables; import static com.external.utils.GraphQLBodyUtils.validateBodyAndVariablesSyntax; +import static com.external.utils.GraphQLDataTypeUtils.smartlyReplaceGraphQLQueryBodyPlaceholderWithValue; +import static com.external.utils.GraphQLPaginationUtils.updateVariablesWithPaginationValues; import static java.lang.Boolean.TRUE; import static org.apache.commons.lang3.StringUtils.isBlank; @@ -186,18 +185,6 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, ActionExecutionRequest actionExecutionRequest = RequestCaptureFilter.populateRequestFields(actionConfiguration, uri, insertedParams, objectMapper); - try { - if (uriUtils.isHostDisallowed(uri)) { - errorResult.setBody(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getMessage("Host not allowed.")); - errorResult.setRequest(actionExecutionRequest); - return Mono.just(errorResult); - } - } catch (UnknownHostException e) { - errorResult.setBody(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getMessage("Unknown host.")); - errorResult.setRequest(actionExecutionRequest); - return Mono.just(errorResult); - } - WebClient.Builder webClientBuilder = triggerUtils.getWebClientBuilder(actionConfiguration, datasourceConfiguration); @@ -282,7 +269,7 @@ else if (HttpMethod.GET.equals(httpMethod)) { EXCHANGE_STRATEGIES, requestCaptureFilter); /* Triggering the actual REST API call */ - Set<String> hintMessages = new HashSet<String>(); + Set<String> hintMessages = new HashSet<>(); return triggerUtils.triggerApiCall(client, httpMethod, uri, requestBodyObj, actionExecutionRequest, objectMapper, hintMessages, errorResult, requestCaptureFilter); diff --git a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java index ec1ae5b91023..86f9101cca0f 100644 --- a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java +++ b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java @@ -5,6 +5,8 @@ import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.helpers.DataTypeStringUtils; import com.appsmith.external.helpers.MustacheHelper; +import com.appsmith.external.helpers.restApiUtils.connections.APIConnection; +import com.appsmith.external.helpers.restApiUtils.helpers.RequestCaptureFilter; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionRequest; import com.appsmith.external.models.ActionExecutionResult; @@ -15,18 +17,16 @@ import com.appsmith.external.plugins.BasePlugin; import com.appsmith.external.plugins.BaseRestApiPluginExecutor; import com.appsmith.external.services.SharedConfig; -import com.appsmith.external.helpers.restApiUtils.connections.APIConnection; -import com.appsmith.external.helpers.restApiUtils.helpers.RequestCaptureFilter; import lombok.extern.slf4j.Slf4j; import org.pf4j.Extension; import org.pf4j.PluginWrapper; import org.springframework.http.HttpMethod; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; + import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; -import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashSet; @@ -125,7 +125,7 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, initUtils.initializeResponseWithError(errorResult); // Set of hint messages that can be returned to the user. - Set<String> hintMessages = new HashSet(); + Set<String> hintMessages = new HashSet<>(); // Initializing request URL String url = initUtils.initializeRequestUrl(actionConfiguration, datasourceConfiguration); @@ -148,18 +148,6 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, ActionExecutionRequest actionExecutionRequest = RequestCaptureFilter.populateRequestFields(actionConfiguration, uri, insertedParams, objectMapper); - try { - if (uriUtils.isHostDisallowed(uri)) { - errorResult.setBody(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getMessage("Host not allowed.")); - errorResult.setRequest(actionExecutionRequest); - return Mono.just(errorResult); - } - } catch (UnknownHostException e) { - errorResult.setBody(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getMessage("Unknown host.")); - errorResult.setRequest(actionExecutionRequest); - return Mono.just(errorResult); - } - WebClient.Builder webClientBuilder = triggerUtils.getWebClientBuilder(actionConfiguration, datasourceConfiguration); String reqContentType = headerUtils.getRequestContentType(actionConfiguration, datasourceConfiguration);
82c033c7859732dda1490c0daf51ac460c8906f0
2021-10-14 18:38:24
Pranav Kanade
fix: allow api error interceptor to handle api call failure (#8513)
false
allow api error interceptor to handle api call failure (#8513)
fix
diff --git a/app/client/src/api/ApiResponses.tsx b/app/client/src/api/ApiResponses.tsx index 43c781e9190b..5935f5913b8f 100644 --- a/app/client/src/api/ApiResponses.tsx +++ b/app/client/src/api/ApiResponses.tsx @@ -12,6 +12,7 @@ export type ResponseMeta = { export type ApiResponse = { responseMeta: ResponseMeta; data: any; + code?: string; }; export type GenericApiResponse<T> = { diff --git a/app/client/src/sagas/ErrorSagas.tsx b/app/client/src/sagas/ErrorSagas.tsx index 50983f4853c8..85f650316059 100644 --- a/app/client/src/sagas/ErrorSagas.tsx +++ b/app/client/src/sagas/ErrorSagas.tsx @@ -25,6 +25,7 @@ import { } from "constants/messages"; import * as Sentry from "@sentry/react"; +import { axiosConnectionAbortedCode } from "../api/ApiUtils"; /** * making with error message with action name @@ -70,6 +71,12 @@ export function* validateResponse(response: ApiResponse | any, show = true) { if (!response) { throw Error(""); } + + // letting `apiFailureResponseInterceptor` handle it this case + if (response?.code === axiosConnectionAbortedCode) { + return false; + } + if (!response.responseMeta && !response.status) { throw Error(getErrorMessage(0)); }
244b089771a2db52efd4e762a466695ca20493cb
2021-12-23 19:47:08
Bhavin K
fix: added support for timePrecision (#9423)
false
added support for timePrecision (#9423)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/DatePicker_2_Default_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/DatePicker_2_Default_spec.js index 3116ffd550d9..99a3283c3948 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/DatePicker_2_Default_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/DatePicker_2_Default_spec.js @@ -19,6 +19,76 @@ describe("DatePicker Widget Property pane tests with js bindings", function() { ); }); + it("Datepicker default time picker validation by Time precision", function() { + // default value in property pane + cy.openPropertyPane("datepickerwidget2"); + cy.get(".t--property-control-timeprecision span[type='p1']").should( + "have.text", + "Minute", + ); + + // default in date picker + cy.get(".t--widget-datepickerwidget2 input").click(); + cy.wait(200); + // datepicker is open + cy.get(".bp3-popover .bp3-datepicker").should("exist"); + // checking timepicker + cy.get(".bp3-datepicker-timepicker-wrapper .bp3-timepicker-input-row") + .children() + .should("have.length", 3); + cy.closePropertyPane(); + }); + + it("Hide Time picker from Datepicker", function() { + // default value in property pane + cy.openPropertyPane("datepickerwidget2"); + + cy.get(".t--property-control-timeprecision .bp3-popover-target") + .last() + .click(); + cy.get(".t--dropdown-option") + .children() + .contains("None") + .click(); + cy.wait("@updateLayout"); + // default in date picker + + cy.get(".t--widget-datepickerwidget2 input").click(); + cy.wait(200); + // datepicker is open + cy.get(".bp3-popover .bp3-datepicker").should("exist"); + // checking timepicker not showing + cy.get( + ".bp3-datepicker-timepicker-wrapper .bp3-timepicker-input-row", + ).should("not.exist"); + cy.closePropertyPane(); + }); + + it("set second field in time picker for Datepicker", function() { + // default value in property pane + cy.openPropertyPane("datepickerwidget2"); + + cy.get(".t--property-control-timeprecision .bp3-popover-target") + .last() + .click(); + cy.get(".t--dropdown-option") + .children() + .contains("Second") + .click(); + cy.wait("@updateLayout"); + // default in date picker + + cy.get(".t--widget-datepickerwidget2 input").click(); + cy.wait(200); + // datepicker is open + cy.get(".bp3-popover .bp3-datepicker").should("exist"); + // checking timepicker + cy.get(".bp3-datepicker-timepicker-wrapper .bp3-timepicker-input-row") + .children() + .should("have.length", 5); + cy.closePropertyPane(); + }); + it("Text widgets binding with datepicker", function() { cy.SearchEntityandOpen("Text1"); cy.testJsontext("text", "{{DatePicker1.formattedDate}}"); diff --git a/app/client/src/widgets/DatePickerWidget2/component/index.tsx b/app/client/src/widgets/DatePickerWidget2/component/index.tsx index fda72289d323..7a20c3f71222 100644 --- a/app/client/src/widgets/DatePickerWidget2/component/index.tsx +++ b/app/client/src/widgets/DatePickerWidget2/component/index.tsx @@ -10,9 +10,8 @@ import { ComponentProps } from "widgets/BaseComponent"; import { DateInput } from "@blueprintjs/datetime"; import moment from "moment-timezone"; import "../../../../node_modules/@blueprintjs/datetime/lib/css/blueprint-datetime.css"; -import { DatePickerType } from "../constants"; +import { DatePickerType, TimePrecision } from "../constants"; import { WIDGET_PADDING } from "constants/WidgetConstants"; -import { TimePrecision } from "@blueprintjs/datetime"; import { Colors } from "constants/Colors"; import { ISO_DATE_FORMAT } from "constants/WidgetValidation"; import ErrorTooltip from "components/editorComponents/ErrorTooltip"; @@ -169,7 +168,11 @@ class DatePickerComponent extends React.Component< }} shortcuts={this.props.shortcuts} showActionsBar - timePrecision={TimePrecision.MINUTE} + timePrecision={ + this.props.timePrecision === TimePrecision.NONE + ? undefined + : this.props.timePrecision + } value={value} /> </ErrorTooltip> @@ -258,6 +261,7 @@ interface DatePickerComponentProps extends ComponentProps { withoutPortal?: boolean; closeOnSelection: boolean; shortcuts: boolean; + timePrecision: TimePrecision; } interface DatePickerComponentState { diff --git a/app/client/src/widgets/DatePickerWidget2/constants.ts b/app/client/src/widgets/DatePickerWidget2/constants.ts index 369ec00d6ca0..1ee9f5599138 100644 --- a/app/client/src/widgets/DatePickerWidget2/constants.ts +++ b/app/client/src/widgets/DatePickerWidget2/constants.ts @@ -1 +1,8 @@ export type DatePickerType = "DATE_PICKER" | "DATE_RANGE_PICKER"; + +export enum TimePrecision { + NONE = "None", + MILLISECOND = "millisecond", + MINUTE = "minute", + SECOND = "second", +} diff --git a/app/client/src/widgets/DatePickerWidget2/index.ts b/app/client/src/widgets/DatePickerWidget2/index.ts index c063bdd2e02a..451527bab760 100644 --- a/app/client/src/widgets/DatePickerWidget2/index.ts +++ b/app/client/src/widgets/DatePickerWidget2/index.ts @@ -2,6 +2,7 @@ import Widget from "./widget"; import IconSVG from "./icon.svg"; import moment from "moment"; import { GRID_DENSITY_MIGRATION_V1 } from "widgets/constants"; +import { TimePrecision } from "./constants"; export const CONFIG = { type: Widget.getWidgetType(), @@ -23,6 +24,7 @@ export const CONFIG = { isRequired: false, closeOnSelection: false, shortcuts: false, + timePrecision: TimePrecision.MINUTE, animateLoading: true, }, properties: { diff --git a/app/client/src/widgets/DatePickerWidget2/widget/index.tsx b/app/client/src/widgets/DatePickerWidget2/widget/index.tsx index 530db63fc1f7..75cb3863c18c 100644 --- a/app/client/src/widgets/DatePickerWidget2/widget/index.tsx +++ b/app/client/src/widgets/DatePickerWidget2/widget/index.tsx @@ -8,7 +8,7 @@ import { ValidationTypes } from "constants/WidgetValidation"; import { DerivedPropertiesMap } from "utils/WidgetFactory"; import moment from "moment"; -import { DatePickerType } from "../constants"; +import { DatePickerType, TimePrecision } from "../constants"; class DatePickerWidget extends BaseWidget<DatePickerWidget2Props, WidgetState> { static getPropertyPaneConfig() { @@ -123,6 +123,41 @@ class DatePickerWidget extends BaseWidget<DatePickerWidget2Props, WidgetState> { validation: { type: ValidationTypes.TEXT }, hideSubText: true, }, + { + propertyName: "timePrecision", + label: "Time precision", + controlType: "DROP_DOWN", + helpText: "Sets the different time picker or hide.", + defaultValue: TimePrecision.MINUTE, + options: [ + { + label: "None", + value: TimePrecision.NONE, + }, + { + label: "Minute", + value: TimePrecision.MINUTE, + }, + { + label: "Second", + value: TimePrecision.SECOND, + }, + ], + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.TEXT, + params: { + allowedValues: [ + TimePrecision.NONE, + TimePrecision.MINUTE, + TimePrecision.SECOND, + ], + default: TimePrecision.MINUTE, + }, + }, + }, { propertyName: "isRequired", label: "Required", @@ -258,6 +293,7 @@ class DatePickerWidget extends BaseWidget<DatePickerWidget2Props, WidgetState> { onDateSelected={this.onDateSelected} selectedDate={this.props.value} shortcuts={this.props.shortcuts} + timePrecision={this.props.timePrecision} widgetId={this.props.widgetId} /> ); @@ -293,6 +329,7 @@ export interface DatePickerWidget2Props extends WidgetProps { isRequired?: boolean; closeOnSelection: boolean; shortcuts: boolean; + timePrecision: TimePrecision; } export default DatePickerWidget; diff --git a/app/client/src/widgets/TableWidget/component/CascadeFields.tsx b/app/client/src/widgets/TableWidget/component/CascadeFields.tsx index 532dfd1a891e..4c97c17d9467 100644 --- a/app/client/src/widgets/TableWidget/component/CascadeFields.tsx +++ b/app/client/src/widgets/TableWidget/component/CascadeFields.tsx @@ -22,6 +22,7 @@ import { RenderOptionWrapper } from "./TableStyledWrappers"; //TODO(abhinav): Fix this cross import between widgets import DatePickerComponent from "widgets/DatePickerWidget2/component"; +import { TimePrecision } from "widgets/DatePickerWidget2/constants"; const StyledRemoveIcon = styled( ControlIcons.CLOSE_CIRCLE_CONTROL as AnyStyledComponent, @@ -572,6 +573,7 @@ function Fields(props: CascadeFieldProps & { state: CascadeFieldState }) { onDateSelected={onDateSelected} selectedDate={value} shortcuts={false} + timePrecision={TimePrecision.MINUTE} widgetId="" withoutPortal />
5978a96e76d7d191207a8f4ba8339318de9ae481
2025-01-09 00:24:58
devin-ai-integration[bot]
chore: update map defaults to NYC coords (#38545)
false
update map defaults to NYC coords (#38545)
chore
diff --git a/app/client/src/constants/WidgetConstants.tsx b/app/client/src/constants/WidgetConstants.tsx index f5ff85758468..bd19d2645048 100644 --- a/app/client/src/constants/WidgetConstants.tsx +++ b/app/client/src/constants/WidgetConstants.tsx @@ -117,7 +117,7 @@ export const MODAL_PORTAL_CLASSNAME = "bp3-modal-widget"; export const MODAL_PORTAL_OVERLAY_CLASSNAME = "bp3-overlay-zindex"; export const CANVAS_SELECTOR = "canvas"; -export const DEFAULT_CENTER = { lat: -34.397, lng: 150.644 }; +export const DEFAULT_CENTER = { lat: 40.7128, lng: -74.006 }; export enum FontStyleTypes { BOLD = "BOLD", diff --git a/app/client/src/widgets/MapWidget/widget/index.tsx b/app/client/src/widgets/MapWidget/widget/index.tsx index 40457a6216ae..4ea6674c395a 100644 --- a/app/client/src/widgets/MapWidget/widget/index.tsx +++ b/app/client/src/widgets/MapWidget/widget/index.tsx @@ -90,8 +90,8 @@ class MapWidget extends BaseWidget<MapWidgetProps, WidgetState> { zoomLevel: 50, enablePickLocation: true, allowZoom: true, - mapCenter: { lat: 25.122, long: 50.132 }, - defaultMarkers: [{ lat: 25.122, long: 50.132, title: "Location1" }], + mapCenter: { lat: 40.7128, long: -74.006 }, + defaultMarkers: [{ lat: 40.7128, long: -74.006, title: "New York" }], isClickedMarkerCentered: true, version: 1, animateLoading: true,
07888cff2c8056111c0d4eab6700ca614838dfdc
2021-08-31 09:22:02
Hetu Nandu
ci: Update issue state check only critical issues (#6972)
false
Update issue state check only critical issues (#6972)
ci
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 661be10f2e76..a5a05a70f89d 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -18,12 +18,12 @@ jobs: with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-pr-stale: 7 - days-before-issue-stale: 90 + days-before-issue-stale: 7 stale-issue-message: 'This issue has not seen activity for a while. It will be closed in 7 days unless further activity is detected.' stale-pr-message: 'This PR has not seen activitiy for a while. It will be closed in 7 days unless further activity is detected.' close-issue-message: 'This issue has been closed because of inactivity.' close-pr-message: 'This PR has been closed because of inactivity.' - exempt-issue-labels: 'Low' + only-issue-labels: 'Critical' exempt-pr-labels: 'Dont merge,WIP'
091dcab60d1379f84545d7e43be66105358c61a0
2023-02-12 09:45:34
arunvjn
chore: Add missing imports errors for ee repo sync (#20575)
false
Add missing imports errors for ee repo sync (#20575)
chore
diff --git a/app/client/src/ce/entities/DataTree/actionTriggers.ts b/app/client/src/ce/entities/DataTree/actionTriggers.ts new file mode 100644 index 000000000000..62d4ecd8eec7 --- /dev/null +++ b/app/client/src/ce/entities/DataTree/actionTriggers.ts @@ -0,0 +1,226 @@ +import { NavigationTargetType_Dep } from "sagas/ActionExecution/NavigateActionSaga"; +import { TypeOptions } from "react-toastify"; + +export type ActionTriggerKeys = + | "RUN_PLUGIN_ACTION" + | "CLEAR_PLUGIN_ACTION" + | "NAVIGATE_TO" + | "SHOW_ALERT" + | "SHOW_MODAL_BY_NAME" + | "CLOSE_MODAL" + | "STORE_VALUE" + | "REMOVE_VALUE" + | "CLEAR_STORE" + | "DOWNLOAD" + | "COPY_TO_CLIPBOARD" + | "RESET_WIDGET_META_RECURSIVE_BY_NAME" + | "SET_INTERVAL" + | "CLEAR_INTERVAL" + | "GET_CURRENT_LOCATION" + | "WATCH_CURRENT_LOCATION" + | "STOP_WATCHING_CURRENT_LOCATION" + | "CONFIRMATION_MODAL" + | "POST_MESSAGE" + | "SET_TIMEOUT" + | "CLEAR_TIMEOUT"; + +export const ActionTriggerFunctionNames: Record<ActionTriggerKeys, string> = { + CLEAR_INTERVAL: "clearInterval", + CLEAR_PLUGIN_ACTION: "action.clear", + CLOSE_MODAL: "closeModal", + COPY_TO_CLIPBOARD: "copyToClipboard", + DOWNLOAD: "download", + NAVIGATE_TO: "navigateTo", + RESET_WIDGET_META_RECURSIVE_BY_NAME: "resetWidget", + RUN_PLUGIN_ACTION: "action.run", + SET_INTERVAL: "setInterval", + SHOW_ALERT: "showAlert", + SHOW_MODAL_BY_NAME: "showModal", + STORE_VALUE: "storeValue", + REMOVE_VALUE: "removeValue", + CLEAR_STORE: "clearStore", + GET_CURRENT_LOCATION: "getCurrentLocation", + WATCH_CURRENT_LOCATION: "watchLocation", + STOP_WATCHING_CURRENT_LOCATION: "stopWatch", + CONFIRMATION_MODAL: "ConfirmationModal", + POST_MESSAGE: "postWindowMessage", + SET_TIMEOUT: "setTimeout", + CLEAR_TIMEOUT: "clearTimeout", +}; + +export interface ActionDescriptionInterface<T, Type extends ActionTriggerKeys> { + type: Type; + payload: T; +} + +export type RunPluginActionDescription = ActionDescriptionInterface< + { + actionId: string; + params?: Record<string, unknown>; + onSuccess?: string; + onError?: string; + }, + "RUN_PLUGIN_ACTION" +>; + +export type ClearPluginActionDescription = ActionDescriptionInterface< + { + actionId: string; + }, + "CLEAR_PLUGIN_ACTION" +>; + +export type NavigateActionDescription = ActionDescriptionInterface< + { + pageNameOrUrl: string; + params?: Record<string, string>; + target?: NavigationTargetType_Dep; + }, + "NAVIGATE_TO" +>; + +export type ShowAlertActionDescription = ActionDescriptionInterface< + { + message: string | unknown; + style?: TypeOptions; + }, + "SHOW_ALERT" +>; + +export type ShowModalActionDescription = ActionDescriptionInterface< + { + modalName: string; + }, + "SHOW_MODAL_BY_NAME" +>; + +export type CloseModalActionDescription = ActionDescriptionInterface< + { + modalName: string; + }, + "CLOSE_MODAL" +>; + +export type StoreValueActionDescription = ActionDescriptionInterface< + { + key: string; + value: string; + persist: boolean; + }, + "STORE_VALUE" +>; + +export type RemoveValueActionDescription = ActionDescriptionInterface< + { + key: string; + }, + "REMOVE_VALUE" +>; + +export type ClearStoreActionDescription = ActionDescriptionInterface< + null, + "CLEAR_STORE" +>; + +export type DownloadActionDescription = ActionDescriptionInterface< + { + data: any; + name: string; + type: string; + }, + "DOWNLOAD" +>; + +export type CopyToClipboardDescription = ActionDescriptionInterface< + { + data: string; + options: { debug?: boolean; format?: string }; + }, + "COPY_TO_CLIPBOARD" +>; + +export type ResetWidgetDescription = ActionDescriptionInterface< + { + widgetName: string; + resetChildren: boolean; + }, + "RESET_WIDGET_META_RECURSIVE_BY_NAME" +>; + +export type SetIntervalDescription = ActionDescriptionInterface< + { + callback: string; + interval: number; + id?: string; + }, + "SET_INTERVAL" +>; + +export type ClearIntervalDescription = ActionDescriptionInterface< + { + id: string; + }, + "CLEAR_INTERVAL" +>; + +type GeolocationOptions = { + maximumAge?: number; + timeout?: number; + enableHighAccuracy?: boolean; +}; + +type GeolocationPayload = { + onSuccess?: string; + onError?: string; + options?: GeolocationOptions; +}; + +export type GetCurrentLocationDescription = ActionDescriptionInterface< + GeolocationPayload, + "GET_CURRENT_LOCATION" +>; + +export type WatchCurrentLocationDescription = ActionDescriptionInterface< + GeolocationPayload, + "WATCH_CURRENT_LOCATION" +>; + +export type StopWatchingCurrentLocationDescription = ActionDescriptionInterface< + Record<string, never> | undefined, + "STOP_WATCHING_CURRENT_LOCATION" +>; + +export type ConfirmationModalDescription = ActionDescriptionInterface< + Record<string, any> | undefined, + "CONFIRMATION_MODAL" +>; + +export type PostMessageDescription = ActionDescriptionInterface< + { + message: unknown; + source: string; + targetOrigin: string; + }, + "POST_MESSAGE" +>; + +export type ActionDescription = + | RunPluginActionDescription + | ClearPluginActionDescription + | NavigateActionDescription + | ShowAlertActionDescription + | ShowModalActionDescription + | CloseModalActionDescription + | StoreValueActionDescription + | RemoveValueActionDescription + | ClearStoreActionDescription + | DownloadActionDescription + | CopyToClipboardDescription + | ResetWidgetDescription + | SetIntervalDescription + | ClearIntervalDescription + | GetCurrentLocationDescription + | WatchCurrentLocationDescription + | StopWatchingCurrentLocationDescription + | ConfirmationModalDescription + | PostMessageDescription; diff --git a/app/client/src/ce/workers/Evaluation/Actions.ts b/app/client/src/ce/workers/Evaluation/Actions.ts index f96a6c8d6f21..6fd76677892d 100644 --- a/app/client/src/ce/workers/Evaluation/Actions.ts +++ b/app/client/src/ce/workers/Evaluation/Actions.ts @@ -18,6 +18,11 @@ declare global { } } +export enum ExecutionType { + PROMISE = "PROMISE", + TRIGGER = "TRIGGER", +} + /** * This method returns new dataTree with entity function and platform function */ diff --git a/app/client/src/ce/workers/Evaluation/PlatformFunctions.ts b/app/client/src/ce/workers/Evaluation/PlatformFunctions.ts new file mode 100644 index 000000000000..f75ae13231d5 --- /dev/null +++ b/app/client/src/ce/workers/Evaluation/PlatformFunctions.ts @@ -0,0 +1,145 @@ +/* eslint-disable @typescript-eslint/ban-types */ +import { ActionDescription } from "@appsmith/entities/DataTree/actionTriggers"; +import { ExecutionType } from "@appsmith/workers/Evaluation/Actions"; +import _ from "lodash"; +import uniqueId from "lodash/uniqueId"; +import { NavigationTargetType_Dep } from "sagas/ActionExecution/NavigateActionSaga"; + +export type ActionDescriptionWithExecutionType = ActionDescription & { + executionType: ExecutionType; +}; + +export type ActionDispatcherWithExecutionType = ( + ...args: any[] +) => ActionDescriptionWithExecutionType; + +export const PLATFORM_FUNCTIONS: Record< + string, + ActionDispatcherWithExecutionType +> = { + navigateTo: function( + pageNameOrUrl: string, + params: Record<string, string>, + target?: NavigationTargetType_Dep, + ) { + return { + type: "NAVIGATE_TO", + payload: { pageNameOrUrl, params, target }, + executionType: ExecutionType.PROMISE, + }; + }, + showAlert: function( + message: string, + style: "info" | "success" | "warning" | "error" | "default", + ) { + return { + type: "SHOW_ALERT", + payload: { message, style }, + executionType: ExecutionType.PROMISE, + }; + }, + showModal: function(modalName: string) { + return { + type: "SHOW_MODAL_BY_NAME", + payload: { modalName }, + executionType: ExecutionType.PROMISE, + }; + }, + closeModal: function(modalName: string) { + return { + type: "CLOSE_MODAL", + payload: { modalName }, + executionType: ExecutionType.PROMISE, + }; + }, + storeValue: function(key: string, value: string, persist = true) { + // momentarily store this value in local state to support loops + _.set(self, ["appsmith", "store", key], value); + return { + type: "STORE_VALUE", + payload: { + key, + value, + persist, + uniqueActionRequestId: uniqueId("store_value_id_"), + }, + executionType: ExecutionType.PROMISE, + }; + }, + removeValue: function(key: string) { + return { + type: "REMOVE_VALUE", + payload: { key }, + executionType: ExecutionType.PROMISE, + }; + }, + clearStore: function() { + return { + type: "CLEAR_STORE", + executionType: ExecutionType.PROMISE, + payload: null, + }; + }, + download: function(data: string, name: string, type: string) { + return { + type: "DOWNLOAD", + payload: { data, name, type }, + executionType: ExecutionType.PROMISE, + }; + }, + copyToClipboard: function( + data: string, + options?: { debug?: boolean; format?: string }, + ) { + return { + type: "COPY_TO_CLIPBOARD", + payload: { + data, + options: { debug: options?.debug, format: options?.format }, + }, + executionType: ExecutionType.PROMISE, + }; + }, + resetWidget: function(widgetName: string, resetChildren = true) { + return { + type: "RESET_WIDGET_META_RECURSIVE_BY_NAME", + payload: { widgetName, resetChildren }, + executionType: ExecutionType.PROMISE, + }; + }, + setInterval: function(callback: Function, interval: number, id?: string) { + return { + type: "SET_INTERVAL", + payload: { + callback: callback?.toString(), + interval, + id, + }, + executionType: ExecutionType.TRIGGER, + }; + }, + clearInterval: function(id: string) { + return { + type: "CLEAR_INTERVAL", + payload: { + id, + }, + executionType: ExecutionType.TRIGGER, + }; + }, + postWindowMessage: function( + message: unknown, + source: string, + targetOrigin: string, + ) { + return { + type: "POST_MESSAGE", + payload: { + message, + source, + targetOrigin, + }, + executionType: ExecutionType.TRIGGER, + }; + }, +}; diff --git a/app/client/src/ee/entities/DataTree/actionTriggers.ts b/app/client/src/ee/entities/DataTree/actionTriggers.ts new file mode 100644 index 000000000000..ab8d4cf88318 --- /dev/null +++ b/app/client/src/ee/entities/DataTree/actionTriggers.ts @@ -0,0 +1 @@ +export * from "ce/entities/DataTree/actionTriggers"; diff --git a/app/client/src/ee/workers/Evaluation/PlatformFunctions.ts b/app/client/src/ee/workers/Evaluation/PlatformFunctions.ts new file mode 100644 index 000000000000..db2755dfa48f --- /dev/null +++ b/app/client/src/ee/workers/Evaluation/PlatformFunctions.ts @@ -0,0 +1 @@ +export * from "ce/workers/Evaluation/PlatformFunctions"; diff --git a/app/client/src/sagas/ActionExecution/NavigateActionSaga.ts b/app/client/src/sagas/ActionExecution/NavigateActionSaga.ts index 1fb968c76f9e..3ca897a4e39b 100644 --- a/app/client/src/sagas/ActionExecution/NavigateActionSaga.ts +++ b/app/client/src/sagas/ActionExecution/NavigateActionSaga.ts @@ -17,6 +17,11 @@ import { TNavigateToDescription, } from "workers/Evaluation/fns/navigateTo"; +export enum NavigationTargetType_Dep { + SAME_WINDOW = "SAME_WINDOW", + NEW_WINDOW = "NEW_WINDOW", +} + const isValidUrlScheme = (url: string): boolean => { return ( // Standard http call
ada8f3ee12a40ac8757805bb76e7ea7ab00e1111
2023-05-10 18:08:18
PiyushPushkar02
fix: Redis Error Message Fix (#23067)
false
Redis Error Message Fix (#23067)
fix
diff --git a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java index 8d19fab6b34c..a0606442ecfa 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java +++ b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java @@ -50,7 +50,6 @@ public class RedisPlugin extends BasePlugin { private static final int CONNECTION_TIMEOUT = 60; private static final String CMD_KEY = "cmd"; private static final String ARGS_KEY = "args"; - public RedisPlugin(PluginWrapper wrapper) { super(wrapper); } @@ -321,9 +320,10 @@ private boolean isEndpointMissing(List<Endpoint> endpoints) { return false; } - private Mono<Void> verifyPing(Jedis jedis) { + private Mono<Void> verifyPing(JedisPool connectionPool) { String pingResponse; try { + Jedis jedis = connectionPool.getResource(); pingResponse = jedis.ping(); } catch (Exception exc) { return Mono.error(exc); @@ -338,12 +338,13 @@ private Mono<Void> verifyPing(Jedis jedis) { } @Override - public Mono<DatasourceTestResult> testDatasource(JedisPool connection) { - return Mono.fromCallable(() -> { - Jedis jedis = connection.getResource(); - return verifyPing(jedis); - }) - .thenReturn(new DatasourceTestResult()); + public Mono<DatasourceTestResult> testDatasource(JedisPool connectionPool) { + + return Mono.just(connectionPool) + .flatMap(c -> verifyPing(connectionPool)) + .then(Mono.just(new DatasourceTestResult())) + .onErrorResume(error -> Mono.just(new DatasourceTestResult(error.getCause().getMessage()))); + } } diff --git a/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java b/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java index c96e78dbc9d1..aed1208bc6a7 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java +++ b/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java @@ -121,7 +121,6 @@ public void itShouldValidateDatasourceWithInvalidAuth() { pluginExecutor.validateDatasource(invalidDatasourceConfiguration) ); } - @Test public void itShouldValidateDatasource() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); @@ -153,6 +152,28 @@ public void itShouldTestDatasource() { .verifyComplete(); } + @Test + public void itShouldThrowErrorIfHostnameIsInvalid() { + + String invalidHost = "invalidHost"; + String errorMessage = "Failed connecting to " + invalidHost + ":" + port; + + DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); + Endpoint endpoint = new Endpoint(); + endpoint.setHost(invalidHost); + endpoint.setPort(Long.valueOf(port)); + + datasourceConfiguration.setEndpoints(Collections.singletonList(endpoint)); + Mono<DatasourceTestResult> datasourceTestResultMono = pluginExecutor.testDatasource(datasourceConfiguration); + + StepVerifier.create(datasourceTestResultMono) + .assertNext(datasourceTestResult -> { + assertNotNull(datasourceTestResult); + assertFalse(datasourceTestResult.isSuccess()); + assertTrue(datasourceTestResult.getInvalids().contains(errorMessage)); + }) + .verifyComplete(); + } @Test public void itShouldThrowErrorIfEmptyBody() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration();
a25e02b6211fdf5c231a59385316327875009ef8
2023-06-09 10:24:43
Goutham Pratapa
chore: update entrypoint to deploy appsmith on cloudrun (#23829)
false
update entrypoint to deploy appsmith on cloudrun (#23829)
chore
diff --git a/Dockerfile b/Dockerfile index 12db1b452f8c..0b9588307007 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ ENV LC_ALL C.UTF-8 RUN apt-get update \ && apt-get upgrade --yes \ && DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends --yes \ - supervisor curl cron certbot nginx gnupg wget netcat openssh-client \ + supervisor curl cron nfs-common certbot nginx gnupg wget netcat openssh-client \ software-properties-common gettext \ python3-pip python3-requests python-setuptools git ca-certificates-java \ && wget -O - https://packages.adoptium.net/artifactory/api/gpg/key/public | apt-key add - \ diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh index 291d7e779777..697188bda6d7 100644 --- a/deploy/docker/entrypoint.sh +++ b/deploy/docker/entrypoint.sh @@ -21,6 +21,20 @@ if [[ -n ${APPSMITH_SEGMENT_CE_KEY-} ]]; then || true fi +if [[ -n "${FILESTORE_IP_ADDRESS-}" ]]; then + + ## Trim APPSMITH_FILESTORE_IP and FILE_SHARE_NAME + FILESTORE_IP_ADDRESS="$(echo "$FILESTORE_IP_ADDRESS" | xargs)" + FILE_SHARE_NAME="$(echo "$FILE_SHARE_NAME" | xargs)" + + echo "Running appsmith for cloudRun" + echo "Mounting File Sytem" + mount -t nfs -o nolock "$FILESTORE_IP_ADDRESS:/$FILE_SHARE_NAME" /appsmith-stacks + echo "Mounted File Sytem" + echo "Setting HOSTNAME for Cloudrun" + export HOSTNAME="cloudrun" +fi + stacks_path=/appsmith-stacks function get_maximum_heap() {
b456bad1e3191927eaa68ad0f1826c6128c7702f
2023-02-17 10:03:02
Shrikant Sharat Kandula
fix: Issue with filter not working with IPs (#20688)
false
Issue with filter not working with IPs (#20688)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RequestCaptureFilter.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RequestCaptureFilter.java index 63e7c031c347..fa8672f1c2f0 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RequestCaptureFilter.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RequestCaptureFilter.java @@ -52,8 +52,14 @@ public Mono<ClientResponse> filter(@NonNull ClientRequest request, ExchangeFunct } public ActionExecutionRequest populateRequestFields(ActionExecutionRequest existing) { - final ActionExecutionRequest actionExecutionRequest = new ActionExecutionRequest(); + + if (request == null) { + // The `request` can be null, if there's another filter function before `this.filter`, + // which returns a `Mono.error` instead of the request object. + return actionExecutionRequest; + } + actionExecutionRequest.setUrl(request.url().toString()); actionExecutionRequest.setHttpMethod(request.method()); MultiValueMap<String, String> headers = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java index 9046d4ee6cef..d96492e87a2b 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java @@ -9,7 +9,9 @@ import io.netty.util.internal.SocketUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; import reactor.netty.http.client.HttpClient; import reactor.netty.resources.ConnectionProvider; @@ -28,6 +30,14 @@ public class WebClientUtils { "metadata.google.internal" ); + public static final String HOST_NOT_ALLOWED = "Host not allowed."; + + public static final ExchangeFilterFunction IP_CHECK_FILTER = ExchangeFilterFunction.ofRequestProcessor(request -> + DISALLOWED_HOSTS.contains(request.url().getHost()) + ? Mono.error(new UnknownHostException(HOST_NOT_ALLOWED)) + : Mono.just(request) + ); + private WebClientUtils() { } @@ -68,6 +78,7 @@ public static WebClient.Builder builder(ConnectionProvider provider) { public static WebClient.Builder builder(HttpClient httpClient) { return WebClient.builder() + .filter(IP_CHECK_FILTER) .clientConnector(new ReactorClientHttpConnector(makeSafeHttpClient(httpClient))); } @@ -92,7 +103,7 @@ public static boolean isDisallowedAndFail(String host, Promise<?> promise) { if (DISALLOWED_HOSTS.contains(host)) { log.warn("Host {} is disallowed. Failing the request.", host); if (promise != null) { - promise.setFailure(new UnknownHostException("Host not allowed.")); + promise.setFailure(new UnknownHostException(HOST_NOT_ALLOWED)); } return true; } diff --git a/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java b/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java index f2491b5b7cef..8b0e2bfaa998 100644 --- a/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java +++ b/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java @@ -1330,7 +1330,14 @@ public void testDenyInstanceMetadataAws() { Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) - .assertNext(result -> assertFalse(result.getIsExecutionSuccess())) + .assertNext(result -> { + assertFalse(result.getIsExecutionSuccess()); + assertEquals( + "Host not allowed.", + result.getBody(), + "Unexpected error message. Did this fail for a different reason?" + ); + }) .verifyComplete(); } @@ -1344,7 +1351,10 @@ public void testDenyInstanceMetadataAwsViaCname() { Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) - .assertNext(result -> assertFalse(result.getIsExecutionSuccess())) + .assertNext(result -> { + assertFalse(result.getIsExecutionSuccess()); + assertEquals("Host not allowed.", result.getBody()); + }) .verifyComplete(); }
8474c206960c950cd802d409f1defaf3730931d2
2024-09-17 11:01:08
Aman Agarwal
fix: mongo uri spec flakiness (#36249)
false
mongo uri spec flakiness (#36249)
fix
diff --git a/app/client/cypress/e2e/Regression/ServerSide/GenerateCRUD/MongoURI_Spec.ts b/app/client/cypress/e2e/Regression/ServerSide/GenerateCRUD/MongoURI_Spec.ts index 9eab077782bd..4b1d780a9ec5 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/GenerateCRUD/MongoURI_Spec.ts +++ b/app/client/cypress/e2e/Regression/ServerSide/GenerateCRUD/MongoURI_Spec.ts @@ -15,12 +15,14 @@ import EditorNavigation, { AppSidebar, } from "../../../../support/Pages/EditorNavigation"; import PageList from "../../../../support/Pages/PageList"; +import data from "../../../../fixtures/mongouri_data_spec.json"; describe( "Validate Mongo URI CRUD with JSON Form", { tags: ["@tag.Datasource"] }, () => { let dsName: any; + let importDataCollectionName: string; it("1. Create DS & Generate CRUD template", () => { dataSources.NavigateToDSCreateNew(); @@ -32,13 +34,38 @@ describe( dataSources.FillMongoDatasourceFormWithURI(); dataSources.TestSaveDatasource(); AppSidebar.navigate(AppSidebarButton.Editor); + + importDataCollectionName = dsName + "_Import_data"; + + // Create data dump in new collection + dataSources.CreateQueryForDS(dsName, "", importDataCollectionName); + dataSources.ValidateNSelectDropdown( + "Command", + "Find document(s)", + "Insert document(s)", + ); + dataSources.EnterJSContext({ + fieldLabel: "Collection", + fieldValue: importDataCollectionName, + }); + agHelper.EnterValue(JSON.stringify(data), { + propFieldName: "", + directInput: false, + inputFieldName: "Documents", + }); + + dataSources.RunQuery(); + PageList.AddNewPage("Generate page with data"); agHelper.GetNClick(dataSources._selectDatasourceDropdown); agHelper.GetNClickByContains(dataSources._dropdownOption, dsName); assertHelper.AssertNetworkStatus("@getDatasourceStructure"); //Making sure table dropdown is populated agHelper.GetNClick(dataSources._selectTableDropdown, 0, true); - agHelper.GetNClickByContains(dataSources._dropdownOption, "mongomart"); + agHelper.GetNClickByContains( + dataSources._dropdownOption, + importDataCollectionName, + ); GenerateCRUDNValidateDeployPage( "/img/products/mug.jpg", "Coffee Mug", @@ -56,6 +83,13 @@ describe( it("2. Verify Update data from Deploy page - on mongomart - existing record", () => { //Update documents query to handle the int _id data + EditorNavigation.SelectEntityByName("DeleteQuery", EntityType.Query); + agHelper.EnterValue(`{ _id: {{data_table.triggeredRow._id}}}`, { + propFieldName: "", + directInput: false, + inputFieldName: "Query", + }); + EditorNavigation.SelectEntityByName("UpdateQuery", EntityType.Query); agHelper.EnterValue(`{ _id: {{data_table.selectedRow._id}}}`, { propFieldName: "", @@ -65,7 +99,7 @@ describe( deployMode.DeployApp(locators._widgetInDeployed(draggableWidgets.TABLE)); agHelper.GetNAssertElementText( locators._textWidgetInDeployed, - "mongomart Data", + `${importDataCollectionName} Data`, ); //Validating loaded table table.SelectTableRow(2, 0, true, "v2"); @@ -132,7 +166,7 @@ describe( } }); - it("4. Verify Delete from Deploy page - on MongoMart - newly added record", () => { + it("4. Verify Delete from Deploy page - on mongo mart data - newly added record", () => { agHelper.ClickButton("Delete", 0); agHelper.AssertElementVisibility(locators._modal); agHelper.AssertElementVisibility( @@ -141,7 +175,7 @@ describe( ), ); agHelper.ClickButton("Confirm"); - assertHelper.AssertNetworkStatus("@postExecute", 200); + assertHelper.AssertNetworkExecutionSuccess("@postExecute"); assertHelper.AssertNetworkStatus("@postExecute", 200); table.ReadTableRowColumnData(0, 6, "v2", 200).then(($cellData) => { expect($cellData).to.eq("Coffee Mug"); @@ -151,7 +185,7 @@ describe( }); }); - it("5 Verify Filter & Search & Download from Deploy page - on MongoMart - existing record", () => { + it("5 Verify Filter & Search & Download from Deploy page - on mongo mart data - existing record", () => { table.SearchTable("Swag"); agHelper.Sleep(2500); //for search to load for (let i = 0; i <= 1; i++) { @@ -198,7 +232,11 @@ describe( table.WaitUntilTableLoad(0, 0, "v2"); PageList.AddNewPage(); dataSources.CreateQueryForDS(dsName); - dataSources.ValidateNSelectDropdown("Collection", "", "mongomart"); + dataSources.ValidateNSelectDropdown( + "Collection", + "", + importDataCollectionName, + ); dataSources.RunQuery({ toValidateResponse: false }); dataSources.AddSuggestedWidget(Widgets.Table); table.ReadTableRowColumnData(0, 3, "v2").then((cellData) => { @@ -223,7 +261,6 @@ function GenerateCRUDNValidateDeployPage( assertHelper.AssertNetworkStatus("@updateLayout", 200); appSettings.OpenPaneAndChangeTheme("Pacific"); deployMode.DeployApp(locators._widgetInDeployed(draggableWidgets.TABLE)); - //Validating loaded table agHelper.AssertElementExist(dataSources._selectedRow); table.ReadTableRowColumnData(0, 1, "v2", 2000).then(($cellData) => { diff --git a/app/client/cypress/fixtures/mongouri_data_spec.json b/app/client/cypress/fixtures/mongouri_data_spec.json new file mode 100644 index 000000000000..7687106464f8 --- /dev/null +++ b/app/client/cypress/fixtures/mongouri_data_spec.json @@ -0,0 +1 @@ +[ { "_id": { "$numberInt": "1" }, "title": "Gray Hooded Sweatshirt", "slogan": "The top hooded sweatshirt we offer", "description": "Unless you live in a nudist colony, there are moments when the chill you feel demands that you put on something warm, and for those times, there's nothing better than this sharp MongoDB hoodie. Made of 100% cotton, this machine washable, mid-weight hoodie is all you need to stay comfortable when the temperature drops. And, since being able to keep your vital stuff with you is important, the hoodie features two roomy kangaroo pockets to ensure nothing you need ever gets lost.", "stars": { "$numberInt": "0" }, "category": "Apparel", "img_url": "/img/products/hoodie.jpg", "price": { "$numberDouble": "29.99" } }, { "_id": { "$numberInt": "5" }, "title": "Women's T-shirt", "slogan": "MongoDB shirt in-style", "description": "Crafted from ultra-soft combed cotton, this essential t-shirt features sporty contrast tipping and MongoDB's signature leaf.", "stars": { "$numberInt": "0" }, "category": "Apparel", "img_url": "/img/products/white-mongo.jpg", "price": { "$numberDouble": "45.0" } }, { "_id": { "$numberInt": "3" }, "title": "Stress Ball", "slogan": "Squeeze your stress away", "description": "The moment life piles more onto your already heaping plate and you start feeling hopelessly overwhelmed, take a stress ball in hand and squeeze as hard as you can. Take a deep breath and just let that tension go. Repeat as needed. It will all be OK! Having something small, portable and close at hand is a must for stress management.", "stars": { "$numberInt": "0" }, "category": "Swag", "img_url": "/img/products/stress-ball.jpg", "price": { "$numberDouble": "5.0" } }, { "_id": { "$numberInt": "6" }, "title": "Brown Carry-all Bag", "slogan": "Keep extra items here", "description": "Let your style speak for itself with this chic brown carry-all bag. Featuring a nylon exterior with solid contrast trim, brown in color, and MongoDB logo", "stars": { "$numberInt": "0" }, "category": "Swag", "img_url": "/img/products/brown-bag.jpg", "price": { "$numberDouble": "5.0" } }, { "_id": { "$numberInt": "7" }, "title": "Brown Tumbler", "slogan": "Bring your coffee to go", "description": "The MongoDB Insulated Travel Tumbler is smartly designed to maintain temperatures and go anywhere. Dual wall construction will keep your beverages hot or cold for hours and a slide lock lid helps minimize spills.", "stars": { "$numberInt": "0" }, "category": "Kitchen", "img_url": "/img/products/brown-tumbler.jpg", "price": { "$numberDouble": "9.0" } }, { "_id": { "$numberInt": "8" }, "title": "Pen (Green)", "slogan": "The only pen you'll ever need", "description": "Erase and rewrite repeatedly without damaging documents. The needlepoint tip creates clear precise lines and the thermo-sensitive gel ink formula disappears with erasing friction.", "stars": { "$numberInt": "0" }, "category": "Office", "img_url": "/img/products/green-pen.jpg", "price": { "$numberDouble": "2.0" } }, { "_id": { "$numberInt": "10" }, "title": "Green T-shirt", "slogan": "MongoDB community shirt", "description": "Crafted from ultra-soft combed cotton, this essential t-shirt features sporty contrast tipping and MongoDB's signature leaf.", "stars": { "$numberInt": "0" }, "category": "Apparel", "img_url": "/img/products/green-tshirt.jpg", "price": { "$numberDouble": "20.0" } }, { "_id": { "$numberInt": "11" }, "title": "MongoDB The Definitive Guide", "slogan": "2nd Edition", "description": "Manage the huMONGOus amount of data collected through your web application with MongoDB. This authoritative introduction—written by a core contributor to the project—shows you the many advantages of using document-oriented databases, and demonstrates how this reliable, high-performance system allows for almost infinite horizontal scalability.", "stars": { "$numberInt": "0" }, "category": "Books", "img_url": "/img/products/guide-book.jpg", "price": { "$numberDouble": "20.0" } }, { "_id": { "$numberInt": "2" }, "title": "Coffee Mug", "slogan": "Keep your coffee hot!", "description": "A mug is a type of cup used for drinking hot beverages, such as coffee, tea, hot chocolate or soup. Mugs usually have handles, and hold a larger amount of fluid than other types of cup. Usually a mug holds approximately 12 US fluid ounces (350 ml) of liquid; double a tea cup. A mug is a less formal style of drink container and is not usually used in formal place settings, where a teacup or coffee cup is preferred.", "stars": { "$numberInt": "0" }, "category": "Kitchen", "img_url": "/img/products/mug.jpg", "price": { "$numberDouble": "12.5" }, "reviews": [ { "name": "", "comment": "", "stars": { "$numberInt": "5" }, "date": { "$numberDouble": "1.456067725049E+12" } }, { "name": "", "comment": "When I drank coffee from this mug the coffee seemed somehow unstructured, as if the molecules weren't following a specific chemical structure. When I drink coffee from my Oracle mug it tastes like all the caffeine has the same atomic formula. Plus the leaf makes it taste funny. ", "stars": { "$numberInt": "1" }, "date": { "$numberDouble": "1.471519691157E+12" } }, { "name": "", "comment": "Much better than a datastax mug!!!!! And all my hipster web developer friends now think I'm terribly cool ", "stars": { "$numberInt": "5" }, "date": { "$numberDouble": "1.471519744173E+12" } } ] }, { "_id": { "$numberInt": "12" }, "title": "Leaf Sticker", "slogan": "Add to your sticker collection", "description": "Waterproof vinyl, will last 18 months outdoors. Ideal for smooth flat surfaces like laptops, journals, windows etc. Easy to remove. 50% discounts on all orders of any 6+", "stars": { "$numberInt": "0" }, "category": "Stickers", "img_url": "/img/products/leaf-sticker.jpg", "price": { "$numberDouble": "1.0" }, "reviews": [ { "name": "r1", "comment": "My First Review", "stars": { "$numberInt": "5" }, "date": { "$numberDouble": "1.468800807077E+12" } }, { "name": "r 2", "comment": "My Second review", "stars": { "$numberInt": "2" }, "date": { "$numberDouble": "1.468800824493E+12" } } ] }, { "_id": { "$numberInt": "4" }, "title": "Track Jacket", "slogan": "Go to the track in style!", "description": "Crafted from ultra-soft combed cotton, this essential jacket features sporty contrast tipping and MongoDB's signature embroidered leaf.", "stars": { "$numberInt": "0" }, "category": "Apparel", "img_url": "/img/products/track-jacket.jpg", "price": { "$numberDouble": "45.0" }, "reviews": [ { "name": "Shannon", "comment": "This is so warm and comfortable.", "stars": { "$numberInt": "2" }, "date": { "$numberDouble": "1.455800194995E+12" } }, { "name": "Bob", "comment": "Love this.", "stars": { "$numberInt": "5" }, "date": { "$numberDouble": "1.455804800769E+12" } }, { "name": "Jorge", "comment": "Brown. It's brown.", "stars": { "$numberInt": "4" }, "date": { "$numberDouble": "1.455804825509E+12" } }, { "name": "Guy", "comment": "My five star review", "stars": { "$numberInt": "5" }, "date": { "$numberDouble": "1.46880086461E+12" } } ] }, { "_id": { "$numberInt": "14" }, "title": "USB Stick (Leaf)", "slogan": "1GB of space", "description": "MongoDB's Turbo USB 3.0 features lightning fast transfer speeds of up to 10X faster than standard MongoDB USB 2.0 drives. This ultra-fast USB allows for fast transfer of larger files such as movies and videos.", "stars": { "$numberInt": "0" }, "category": "Electronics", "img_url": "/img/products/leaf-usb.jpg", "price": { "$numberDouble": "20.0" } }, { "_id": { "$numberInt": "16" }, "title": "Powered by MongoDB Sticker", "slogan": "Add to your sticker collection", "description": "Waterproof vinyl, will last 18 months outdoors. Ideal for smooth flat surfaces like laptops, journals, windows etc. Easy to remove. 50% discounts on all orders of any 6+", "stars": { "$numberInt": "0" }, "category": "Stickers", "img_url": "/img/products/sticker.jpg", "price": { "$numberDouble": "1.0" } }, { "_id": { "$numberInt": "15" }, "title": "Scaling MongoDB", "slogan": "2nd Edition", "description": "Create a MongoDB cluster that will grow to meet the needs of your application. With this short and concise book, you'll get guidelines for setting up and using clusters to store a large volume of data, and learn how to access the data efficiently. In the process, you'll understand how to make your application work with a distributed database system.", "stars": { "$numberInt": "0" }, "category": "Books", "img_url": "/img/products/scaling-book.jpg", "price": { "$numberDouble": "29.0" }, "reviews": [ { "name": "Horatio", "comment": "This is a pretty good book", "stars": { "$numberInt": "4" }, "date": { "$numberDouble": "1.456086633854E+12" } } ] }, { "_id": { "$numberInt": "9" }, "title": "Pen (Black)", "slogan": "The only pen you'll ever need", "description": "Erase and rewrite repeatedly without damaging documents. The needlepoint tip creates clear precise lines and the thermo-sensitive gel ink formula disappears with erasing friction.", "stars": { "$numberInt": "0" }, "category": "Office", "img_url": "/img/products/pen.jpg", "price": { "$numberDouble": "2.0" } }, { "_id": { "$numberInt": "18" }, "title": "MongoDB Umbrella (Gray)", "slogan": "Premium Umbrella", "description": "Our crook handle stick umbrella opens automatically with the push of a button. A traditional umbrella with classic appeal.", "stars": { "$numberInt": "0" }, "category": "Umbrellas", "img_url": "/img/products/umbrella.jpg", "price": { "$numberDouble": "21.0" } }, { "_id": { "$numberInt": "20" }, "title": "MongoDB University T-shirt", "slogan": "Show Your MDBU Alumni Status", "description": "Crafted from ultra-soft combed cotton, this essential t-shirt features sporty contrast tipping and MongoDB's signature leaf.", "stars": { "$numberInt": "0" }, "category": "Apparel", "img_url": "/img/products/univ-tshirt.jpg", "price": { "$numberDouble": "45.0" } }, { "_id": { "$numberInt": "21" }, "title": "USB Stick", "slogan": "5GB of space", "description": "MongoDB's Turbo USB 3.0 features lightning fast transfer speeds of up to 10X faster than standard MongoDB USB 2.0 drives. This ultra-fast USB allows for fast transfer of larger files such as movies and videos.", "stars": { "$numberInt": "0" }, "category": "Electronics", "img_url": "/img/products/leaf-usb.jpg", "price": { "$numberDouble": "40.0" } }, { "_id": { "$numberInt": "22" }, "title": "Water Bottle", "slogan": "Glass water bottle", "description": "High quality glass bottle provides a healthier way to drink. Silicone sleeve provides a good grip, a see-through window, and protects the glass vessel. Eliminates toxic leaching that plastic can cause. Innovative design holds 22-1/2 ounces. Dishwasher safe", "stars": { "$numberInt": "0" }, "category": "Kitchen", "img_url": "/img/products/water-bottle.jpg", "price": { "$numberDouble": "23.0" } }, { "_id": { "$numberInt": "17" }, "title": "MongoDB Umbrella (Brown)", "slogan": "Premium Umbrella", "description": "Our crook handle stick umbrella opens automatically with the push of a button. A traditional umbrella with classic appeal.", "stars": { "$numberInt": "0" }, "category": "Umbrellas", "img_url": "/img/products/umbrella-brown.jpg", "price": { "$numberDouble": "21.0" }, "reviews": [ { "name": "Donald Trump", "comment": "This is the best umbrella you will ever use.", "stars": { "$numberInt": "5" }, "date": { "$numberDouble": "1.456270097364E+12" } }, { "name": "Shannon", "comment": "Sturdy construction, but a little too big to fit in my bag for work.", "stars": { "$numberInt": "3" }, "date": { "$numberDouble": "1.456270240382E+12" } } ] }, { "_id": { "$numberInt": "19" }, "title": "MongoDB University Book", "slogan": "A concise summary of MongoDB commands", "description": "Keep the MongoDB commands you'll need at your fingertips with this concise book.", "stars": { "$numberInt": "0" }, "category": "Books", "img_url": "/img/products/univ-book.jpg", "price": { "$numberDouble": "4.0" } }, { "_id": { "$numberInt": "23" }, "title": "WiredTiger T-shirt", "slogan": "Unleash the tiger", "description": "Crafted from ultra-soft combed cotton, this essential t-shirt features sporty contrast tipping and MongoDB's signature leaf.", "stars": { "$numberInt": "0" }, "category": "Apparel", "img_url": "/img/products/wt-shirt.jpg", "price": { "$numberDouble": "22.0" } }, { "_id": { "$numberInt": "13" }, "title": "USB Stick (Green)", "slogan": "1GB of space", "description": "MongoDB's Turbo USB 3.0 features lightning fast transfer speeds of up to 10X faster than standard MongoDB USB 2.0 drives. This ultra-fast USB allows for fast transfer of larger files such as movies and videos.", "stars": { "$numberInt": "0" }, "category": "Electronics", "img_url": "/img/products/greenusb.jpg", "price": { "$numberDouble": "20.0" }, "reviews": [ { "name": "Ringo", "comment": "He's very green.", "stars": { "$numberInt": "4" }, "date": { "$numberDouble": "1.45580490225E+12" } } ] } ] \ No newline at end of file
0186d796d367bdde67782aa94571d99e5a452ea1
2023-05-25 15:13:08
Nayan
chore: Return snapshot date with application and details API (#23700)
false
Return snapshot date with application and details API (#23700)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationPagesDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationPagesDTO.java index 58cd5bd40baf..c8ce8b16bd53 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationPagesDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationPagesDTO.java @@ -16,4 +16,5 @@ public class ApplicationPagesDTO { List<PageNameIdDTO> pages; + String latestSnapshotTime; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageServiceImpl.java index 0ccafff60d8c..0a3a15d2b849 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageServiceImpl.java @@ -1,6 +1,7 @@ package com.appsmith.server.services; import com.appsmith.server.helpers.ResponseUtils; +import com.appsmith.server.repositories.ApplicationSnapshotRepository; import com.appsmith.server.repositories.NewPageRepository; import com.appsmith.server.services.ce.NewPageServiceCEImpl; import com.appsmith.server.solutions.ApplicationPermission; @@ -26,9 +27,10 @@ public NewPageServiceImpl(Scheduler scheduler, UserDataService userDataService, ResponseUtils responseUtils, ApplicationPermission applicationPermission, - PagePermission pagePermission) { + PagePermission pagePermission, + ApplicationSnapshotRepository applicationSnapshotRepository) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - applicationService, userDataService, responseUtils, applicationPermission, pagePermission); + applicationService, userDataService, responseUtils, applicationPermission, pagePermission, applicationSnapshotRepository); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java index 28c31bc3899b..3c5410ba2e94 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java @@ -6,6 +6,7 @@ import com.appsmith.server.domains.Application; import com.appsmith.server.domains.ApplicationMode; import com.appsmith.server.domains.ApplicationPage; +import com.appsmith.server.domains.ApplicationSnapshot; import com.appsmith.server.domains.Layout; import com.appsmith.server.domains.NewPage; import com.appsmith.server.dtos.ApplicationPagesDTO; @@ -15,6 +16,7 @@ import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.server.helpers.ResponseUtils; import com.appsmith.server.helpers.TextUtils; +import com.appsmith.server.repositories.ApplicationSnapshotRepository; import com.appsmith.server.repositories.NewPageRepository; import com.appsmith.server.services.AnalyticsService; import com.appsmith.server.services.ApplicationService; @@ -59,6 +61,8 @@ public class NewPageServiceCEImpl extends BaseService<NewPageRepository, NewPage private final ResponseUtils responseUtils; private final ApplicationPermission applicationPermission; private final PagePermission pagePermission; + private final ApplicationSnapshotRepository applicationSnapshotRepository; + @Autowired public NewPageServiceCEImpl(Scheduler scheduler, @@ -71,13 +75,15 @@ public NewPageServiceCEImpl(Scheduler scheduler, UserDataService userDataService, ResponseUtils responseUtils, ApplicationPermission applicationPermission, - PagePermission pagePermission) { + PagePermission pagePermission, + ApplicationSnapshotRepository applicationSnapshotRepository) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.applicationService = applicationService; this.userDataService = userDataService; this.responseUtils = responseUtils; this.applicationPermission = applicationPermission; this.pagePermission = pagePermission; + this.applicationSnapshotRepository = applicationSnapshotRepository; } @Override @@ -230,6 +236,9 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str permission = applicationPermission.getEditPermission(); } + Mono<ApplicationSnapshot> applicationSnapshotMono = applicationSnapshotRepository.findWithoutData(applicationId) + .defaultIfEmpty(new ApplicationSnapshot()); + Mono<Application> applicationMono = applicationService.findById(applicationId, permission) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) // Throw a 404 error if the application has never been published @@ -361,7 +370,7 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str return Mono.just(pageNameIdDTOList); }); - return Mono.zip(applicationMono, pagesListMono) + return Mono.zip(applicationMono, pagesListMono, applicationSnapshotMono) .map(tuple -> { log.debug("Populating applicationPagesDTO ..."); Application application = tuple.getT1(); @@ -373,6 +382,12 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str applicationPagesDTO.setWorkspaceId(application.getWorkspaceId()); applicationPagesDTO.setPages(nameIdDTOList); applicationPagesDTO.setApplication(application); + + // set the latest snapshot time if there is a snapshot for this application for edit mode + ApplicationSnapshot applicationSnapshot = tuple.getT3(); + if(!view && StringUtils.hasLength(applicationSnapshot.getId())) { + applicationPagesDTO.setLatestSnapshotTime(applicationSnapshot.getUpdatedTime()); + } return applicationPagesDTO; }); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java index e018fffc4741..9247a37ba2a3 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java @@ -5,11 +5,13 @@ import com.appsmith.server.domains.Application; import com.appsmith.server.domains.ApplicationMode; import com.appsmith.server.domains.ApplicationPage; +import com.appsmith.server.domains.ApplicationSnapshot; import com.appsmith.server.domains.PermissionGroup; import com.appsmith.server.domains.Workspace; import com.appsmith.server.dtos.ApplicationPagesDTO; import com.appsmith.server.dtos.PageDTO; import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.repositories.ApplicationSnapshotRepository; import com.appsmith.server.repositories.PermissionGroupRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -45,6 +47,9 @@ public class NewPageServiceTest { @Autowired ApplicationService applicationService; + @Autowired + ApplicationSnapshotRepository applicationSnapshotRepository; + @Test @WithUserDetails("api_user") public void testCreateDefault() { @@ -232,4 +237,29 @@ public void findApplicationPage_CheckPageIcon_IsValid() { .verifyComplete(); } + @Test + @WithUserDetails("api_user") + public void findApplicationPagesByApplicationIdViewMode_WhenSnapshotExists_SnapshotTimeReturned() { + String randomId = UUID.randomUUID().toString(); + Workspace workspace = new Workspace(); + workspace.setName("org_" + randomId); + Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService.create(workspace) + .flatMap(createdWorkspace -> { + Application application = new Application(); + application.setName("app_" + randomId); + return applicationPageService.createApplication(application, createdWorkspace.getId()); + }) + .flatMap(application -> { + ApplicationSnapshot snapshot = new ApplicationSnapshot(); + snapshot.setApplicationId(application.getId()); + snapshot.setChunkOrder(1); + return applicationSnapshotRepository.save(snapshot).thenReturn(application); + }) + .flatMap(application -> newPageService.findApplicationPagesByApplicationIdViewMode(application.getId(), false, false)); + + StepVerifier.create(applicationPagesDTOMono).assertNext(applicationPagesDTO -> { + assertThat(applicationPagesDTO.getLatestSnapshotTime()).isNotNull(); + }).verifyComplete(); + } + } \ No newline at end of file
a83bfc8acdeef56b7308d4c4f58cc83491ce9954
2022-12-15 15:34:21
Ankita Kinger
chore: Updating the version of the design system dependency (#18965)
false
Updating the version of the design system dependency (#18965)
chore
diff --git a/app/client/package.json b/app/client/package.json index 6f9dda1276d0..f62fda0c2334 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -46,7 +46,7 @@ "cypress-log-to-output": "^1.1.2", "dayjs": "^1.10.6", "deep-diff": "^1.0.2", - "design-system": "npm:@appsmithorg/[email protected]", + "design-system": "npm:@appsmithorg/[email protected]", "downloadjs": "^1.4.7", "draft-js": "^0.11.7", "exceljs-lightweight": "^1.14.0", diff --git a/app/client/yarn.lock b/app/client/yarn.lock index 782b130a5807..a2781a56a05e 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -6197,10 +6197,10 @@ depd@~1.1.2: version "1.1.2" resolved "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz" -"design-system@npm:@appsmithorg/[email protected]": - version "1.0.38" - resolved "https://registry.yarnpkg.com/@appsmithorg/design-system/-/design-system-1.0.38.tgz#e35de07566fcd3897122a81c9f8fb6278481db66" - integrity sha512-LWZB3hb+K4XXtmizyDRnnyzEdZrlnWtWiv8MLRjz8Aij7GAVn47SA51FtMJojyBWdU2f4uARWxrqkxa6RlXcXQ== +"design-system@npm:@appsmithorg/[email protected]": + version "1.0.39" + resolved "https://registry.yarnpkg.com/@appsmithorg/design-system/-/design-system-1.0.39.tgz#8f735ddca6768d647bb6187c8754e07b98a56f1b" + integrity sha512-ronzjAJyR1nc0Amya1jD1vsyrWKf+iSgOSg9mfRLfWBO52gn6fOStEAs9h+7FS8qvlXnww1MDGWfeK69pIXYRQ== dependencies: emoji-mart "3.0.1"
842e330db3c38e5723a6d4e152839bb26a7d6b3a
2022-04-02 21:03:14
Paul Li
feat: Internal property to detect changes in a form
false
Internal property to detect changes in a form
feat
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/RichTextEditor_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/RichTextEditor_spec.js index c43a0b0a1a99..dddcbb27b24a 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/RichTextEditor_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/RichTextEditor_spec.js @@ -136,13 +136,7 @@ describe("RichTextEditor Widget Functionality", function() { ); // Change defaultText cy.openPropertyPane("richtexteditorwidget"); - cy.updateCodeInput(".t--property-control-defaulttext", "a"); - cy.closePropertyPane(); - cy.wait("@updateLayout").should( - "have.nested.property", - "response.body.responseMeta.status", - 200, - ); + cy.testJsontext("defaulttext", "a"); // Check if isDirty has been changed into false cy.get(".t--widget-textwidget").should("contain", "false"); // Interact with UI @@ -151,13 +145,7 @@ describe("RichTextEditor Widget Functionality", function() { cy.get(".t--widget-textwidget").should("contain", "true"); // Change defaultText cy.openPropertyPane("richtexteditorwidget"); - cy.updateCodeInput(".t--property-control-defaulttext", "b"); - cy.closePropertyPane(); - cy.wait("@updateLayout").should( - "have.nested.property", - "response.body.responseMeta.status", - 200, - ); + cy.testJsontext("defaulttext", "b"); // Check if isDirty is reset to false cy.get(".t--widget-textwidget").should("contain", "false"); });
f0543928fa1b21dc886778e16f6dd53d4b9f0734
2023-04-28 17:18:29
Vemparala Surya Vamsi
feat: autocomplete feature for email and password (#22715)
false
autocomplete feature for email and password (#22715)
feat
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Input/Inputv2_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Input/Inputv2_spec.js index 2dd21eff65e6..e93d4fabe3ce 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Input/Inputv2_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Input/Inputv2_spec.js @@ -256,6 +256,8 @@ describe("Input widget V2 - ", () => { expected: "[email protected]:[email protected]:true", }, ].forEach(({ expected, input }) => enterAndTest(input, expected)); + + validateAutocompleteAttribute(); }); it("6. Validate DataType - EMAIL can be entered into Input widget", () => { @@ -325,6 +327,8 @@ describe("Input widget V2 - ", () => { expected: "[email protected]:[email protected]:true", }, ].forEach(({ expected, input }) => enterAndTest(input, expected)); + + validateAutocompleteAttribute(); }); it("7. Validating other properties - Input validity with #valid", () => { @@ -441,4 +445,40 @@ describe("Input widget V2 - ", () => { } cy.get(".t--widget-textwidget").should("contain", expected); } + + function validateAutocompleteAttribute() { + //validate autocomplete behaviour for email and password + + cy.openPropertyPane("textwidget"); + cy.openPropertyPane(widgetName); + //check if autofill toggle option is present and is checked by default + cy.get(".t--property-control-allowautofill input").should("be.checked"); + //check if autocomplete attribute is not present in the text widget when autofill is enabled + cy.get(widgetInput).should("not.have.attr", "autocomplete"); + + //toggle off autofill + cy.get(".t--property-control-allowautofill input").click({ force: true }); + cy.get(".t--property-control-allowautofill input").should("not.be.checked"); + + //autocomplete should now be present in the text widget + cy.get(widgetInput).should("have.attr", "autocomplete", "off"); + + //select a non email or password option + cy.selectDropdownValue(".t--property-control-datatype", "text"); + //autofill toggle should not be present as this restores autofill to be enabled + cy.get(".t--property-control-allowautofill input").should("not.exist"); + //autocomplete attribute should not be present in the text widget + cy.get(widgetInput).should("not.have.attr", "autocomplete"); + } + + function enterAndTest(text, expected) { + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + if (text) { + cy.get(`.t--widget-${widgetName} input`) + .click({ force: true }) + .type(text); + } + cy.get(".t--widget-textwidget").should("contain", expected); + } }); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/JSONForm/JSONForm_FieldProperties_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/JSONForm/JSONForm_FieldProperties_spec.js index a5db7575d131..8d3dd4c736b1 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/JSONForm/JSONForm_FieldProperties_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/JSONForm/JSONForm_FieldProperties_spec.js @@ -87,13 +87,14 @@ describe("Text Field Property Control", () => { cy.get(`${fieldPrefix}-name`).should("exist"); }); - it("8. disables field when disabled switched on", () => { + it("8. disables field when disabled switched on and when autofill is disabled we should see the autofill attribute in the input field", () => { cy.togglebar(`.t--property-control-disabled input`); cy.get(`${fieldPrefix}-name input`).each(($el) => { cy.wrap($el).should("have.attr", "disabled"); }); cy.togglebarDisable(`.t--property-control-disabled input`); + validateAutocompleteAttributeInJSONForm(); }); it("9. throws error when REGEX does not match the input value", () => { @@ -326,3 +327,31 @@ describe("Text Field Property Control", () => { cy.get(`${fieldPrefix}-radio`).should("exist"); }); }); + +function validateAutocompleteAttributeInJSONForm() { + //select password input fiel + cy.selectDropdownValue(commonlocators.jsonFormFieldType, "Password Input"); + + //check if autofill toggle option is present and is checked by default + cy.get(".t--property-control-allowautofill input").should("be.checked"); + //check if autocomplete attribute is not present in the text widget when autofill is enabled + cy.get(`${fieldPrefix}-name input`).should("not.have.attr", "autocomplete"); + + //toggle off autofill + cy.get(".t--property-control-allowautofill input").click({ force: true }); + cy.get(".t--property-control-allowautofill input").should("not.be.checked"); + + //autocomplete should now be present in the text widget + cy.get(`${fieldPrefix}-name input`).should( + "have.attr", + "autocomplete", + "off", + ); + + //select a non email or password option + cy.selectDropdownValue(commonlocators.jsonFormFieldType, /^Text Input/); + //autofill toggle should not be present as this restores autofill to be enabled + cy.get(".t--property-control-allowautofill input").should("not.exist"); + //autocomplete attribute should not be present in the text widget + cy.get(`${fieldPrefix}-name input`).should("not.have.attr", "autocomplete"); +} diff --git a/app/client/src/widgets/BaseInputWidget/component/index.tsx b/app/client/src/widgets/BaseInputWidget/component/index.tsx index e8a841fccff8..4efc93f596b1 100644 --- a/app/client/src/widgets/BaseInputWidget/component/index.tsx +++ b/app/client/src/widgets/BaseInputWidget/component/index.tsx @@ -583,6 +583,7 @@ class BaseInputComponent extends React.Component< this.textAreaInputComponent() ) : ( <InputGroup + autoComplete={this.props.autoComplete} autoFocus={this.props.autoFocus} className={this.props.isLoading ? "bp3-skeleton" : ""} disabled={this.props.disabled} @@ -757,6 +758,7 @@ export interface BaseInputComponentProps extends ComponentProps { compactMode: boolean; isInvalid: boolean; autoFocus?: boolean; + autoComplete?: string; iconName?: IconName; iconAlign?: Omit<Alignment, "center">; showError: boolean; diff --git a/app/client/src/widgets/BaseInputWidget/widget/index.tsx b/app/client/src/widgets/BaseInputWidget/widget/index.tsx index 4d409ea0dedf..2c9aaa8aacb6 100644 --- a/app/client/src/widgets/BaseInputWidget/widget/index.tsx +++ b/app/client/src/widgets/BaseInputWidget/widget/index.tsx @@ -10,6 +10,8 @@ import { isAutoLayout } from "utils/autoLayout/flexWidgetUtils"; import type { DerivedPropertiesMap } from "utils/WidgetFactory"; import type { WidgetProps, WidgetState } from "widgets/BaseWidget"; import BaseWidget from "widgets/BaseWidget"; +import type { InputWidgetProps } from "widgets/InputWidgetV2/widget"; +import { isInputTypeEmailOrPassword } from "widgets/InputWidgetV2/widget/Utilities"; import BaseInputComponent from "../component"; import { InputTypes } from "../constants"; import { checkInputTypeTextByProps } from "../utils"; @@ -241,6 +243,24 @@ class BaseInputWidget< isTriggerProperty: false, validation: { type: ValidationTypes.BOOLEAN }, }, + { + propertyName: "shouldAllowAutofill", + label: "Allow autofill", + helpText: "Allow users to autofill values from browser", + controlType: "SWITCH", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + hidden: (props: InputWidgetProps) => { + //should be shown for only inputWidgetV2 and for email or password input types + return !( + isInputTypeEmailOrPassword(props?.inputType) && + props.type === "INPUT_WIDGET_V2" + ); + }, + dependencies: ["inputType"], + }, { propertyName: "allowFormatting", label: "Enable Formatting", diff --git a/app/client/src/widgets/InputWidgetV2/component/index.tsx b/app/client/src/widgets/InputWidgetV2/component/index.tsx index f9f40a5e3049..6c50e5c61d6f 100644 --- a/app/client/src/widgets/InputWidgetV2/component/index.tsx +++ b/app/client/src/widgets/InputWidgetV2/component/index.tsx @@ -41,6 +41,7 @@ class InputComponent extends React.Component<InputComponentProps> { <BaseInputComponent accentColor={this.props.accentColor} allowNumericCharactersOnly={this.props.allowNumericCharactersOnly} + autoComplete={this.props.autoComplete} autoFocus={this.props.autoFocus} borderRadius={this.props.borderRadius} boxShadow={this.props.boxShadow} @@ -94,6 +95,7 @@ export interface InputComponentProps extends BaseInputComponentProps { borderRadius?: string; boxShadow?: string; accentColor?: string; + autoComplete?: string; } export default InputComponent; diff --git a/app/client/src/widgets/InputWidgetV2/widget/Utilities.ts b/app/client/src/widgets/InputWidgetV2/widget/Utilities.ts index b35021a9438f..73b52c15e553 100644 --- a/app/client/src/widgets/InputWidgetV2/widget/Utilities.ts +++ b/app/client/src/widgets/InputWidgetV2/widget/Utilities.ts @@ -28,3 +28,7 @@ export function getParsedText(value: string, inputType: InputTypes) { return text; } + +export function isInputTypeEmailOrPassword(inputType?: string) { + return inputType === InputTypes.EMAIL || inputType === InputTypes.PASSWORD; +} diff --git a/app/client/src/widgets/InputWidgetV2/widget/index.tsx b/app/client/src/widgets/InputWidgetV2/widget/index.tsx index c8b31f1f26d6..409fbecf3b58 100644 --- a/app/client/src/widgets/InputWidgetV2/widget/index.tsx +++ b/app/client/src/widgets/InputWidgetV2/widget/index.tsx @@ -26,7 +26,7 @@ import { InputTypes, NumberInputStepButtonPosition, } from "widgets/BaseInputWidget/constants"; -import { getParsedText } from "./Utilities"; +import { getParsedText, isInputTypeEmailOrPassword } from "./Utilities"; import type { Stylesheet } from "entities/AppTheming"; import { isAutoHeightEnabledForWidget, @@ -233,7 +233,7 @@ export function maxValueValidation(max: any, props: InputWidgetProps, _?: any) { function InputTypeUpdateHook( props: WidgetProps, propertyName: string, - propertyValue: unknown, + propertyValue: any, ) { const updates = [ { @@ -250,6 +250,12 @@ function InputTypeUpdateHook( }); } } + //if input type is email or password default the autofill state to be true + // the user needs to explicity set autofill to fault disable autofill + updates.push({ + propertyPath: "shouldAllowAutofill", + propertyValue: isInputTypeEmailOrPassword(propertyValue), + }); return updates; } @@ -672,10 +678,15 @@ class InputWidget extends BaseInputWidget<InputWidgetProps, WidgetState> { } else { conditionalProps.buttonPosition = NumberInputStepButtonPosition.NONE; } - + const autoFillProps = + !this.props.shouldAllowAutofill && + isInputTypeEmailOrPassword(this.props.inputType) + ? { autoComplete: "off" } + : {}; return ( <InputComponent accentColor={this.props.accentColor} + {...autoFillProps} // show label and Input side by side if true autoFocus={this.props.autoFocus} borderRadius={this.props.borderRadius} diff --git a/app/client/src/widgets/JSONFormWidget/constants.ts b/app/client/src/widgets/JSONFormWidget/constants.ts index 06f6f27e96e3..14abbab5e259 100644 --- a/app/client/src/widgets/JSONFormWidget/constants.ts +++ b/app/client/src/widgets/JSONFormWidget/constants.ts @@ -65,6 +65,7 @@ export type JSON = Obj | Obj[]; export type FieldComponentBaseProps = { defaultValue?: string | number; isDisabled: boolean; + shouldAllowAutofill?: boolean; isRequired?: boolean; isVisible: boolean; label: string; diff --git a/app/client/src/widgets/JSONFormWidget/fields/BaseInputField.tsx b/app/client/src/widgets/JSONFormWidget/fields/BaseInputField.tsx index 0e29253f6b03..eb14013bd0cd 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/BaseInputField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/BaseInputField.tsx @@ -349,9 +349,17 @@ function BaseInputField<TSchemaItem extends SchemaItem>({ }, [schemaItem, isDirty, isValueValid, inputText]); const fieldComponent = useMemo(() => { + const autoFillProps = + !schemaItem.shouldAllowAutofill && + [FieldType.EMAIL_INPUT, FieldType.PASSWORD_INPUT].includes( + schemaItem.fieldType, + ) + ? { autoComplete: "off" } + : {}; return ( <BaseInputComponent {...conditionalProps} + {...autoFillProps} accentColor={schemaItem.accentColor} borderRadius={schemaItem.borderRadius} boxShadow={schemaItem.boxShadow} diff --git a/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/helper.ts b/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/helper.ts index c75debfb3f4d..fabded8232a6 100644 --- a/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/helper.ts +++ b/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/helper.ts @@ -37,7 +37,17 @@ export const fieldTypeUpdateHook = ( widgetName, fieldThemeStylesheets: childStylesheet, }); - + const isInputOrEmailSelected = [ + FieldType.EMAIL_INPUT, + FieldType.PASSWORD_INPUT, + ].includes(fieldType); + + const schemaItemWithAutoFillState = isInputOrEmailSelected + ? { + ...newSchemaItem, + shouldAllowAutofill: true, + } + : newSchemaItem; /** * TODO(Ashit): Not suppose to update the whole schema but just * the path within the schema. This is just a hack to make sure @@ -45,7 +55,7 @@ export const fieldTypeUpdateHook = ( * the updateProperty function is fixed. */ const updatedSchema = { schema: klona(schema) }; - set(updatedSchema, schemaItemPath, newSchemaItem); + set(updatedSchema, schemaItemPath, schemaItemWithAutoFillState); return [{ propertyPath: "schema", propertyValue: updatedSchema.schema }]; }; diff --git a/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/common.ts b/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/common.ts index 788adb0bbcf9..6b2927e5a3cb 100644 --- a/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/common.ts +++ b/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/common.ts @@ -279,6 +279,24 @@ const COMMON_PROPERTIES = { dependencies: ["schema", "sourceData"], updateHook: updateChildrenDisabledStateHook, }, + { + propertyName: "shouldAllowAutofill", + label: "Allow autofill", + helpText: "Allow users to autofill values from browser", + controlType: "SWITCH", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + hidden: (...args: HiddenFnParams) => { + //should be shown for only inputWidgetV2 and for email or password input types + return getSchemaItem(...args).fieldTypeNotIncludes([ + FieldType.EMAIL_INPUT, + FieldType.PASSWORD_INPUT, + ]); + }, + dependencies: ["schema", "sourceData"], + }, ], events: [ {
7c7038c87a7df3f5afd03aeea6bb1b537e6f68a8
2024-04-05 11:10:30
Nidhi
ci: Removing ci-merge-check workflow as it is not required anymore (#32434)
false
Removing ci-merge-check workflow as it is not required anymore (#32434)
ci
diff --git a/.github/workflows/ci-merge-check.yml b/.github/workflows/ci-merge-check.yml deleted file mode 100644 index 8ba24d10ad63..000000000000 --- a/.github/workflows/ci-merge-check.yml +++ /dev/null @@ -1,112 +0,0 @@ -on: - #This workflow is only triggered by the ok to test command dispatch - repository_dispatch: - types: [ci-merge-check-command] - -jobs: - ci-merge-check: - runs-on: ubuntu-latest - steps: - # This step creates a comment on the PR with a link to this workflow run. - - name: Add a comment on the PR with link to workflow run - uses: peter-evans/create-or-update-comment@v3 - with: - issue-number: ${{ github.event.client_payload.pull_request.number }} - body: | - Merge check is running at: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}> - PR: ${{ github.event.client_payload.pull_request.number }} - - - name: Find the latest workflow run comment - uses: peter-evans/find-comment@v2 - id: find-comment - with: - issue-number: ${{ github.event.client_payload.pull_request.number }} - body-includes: "Appsmith External Integration Test Workflow" - comment-author: github-actions[bot] - direction: last - - - name: Get the workflow run_id - id: workflow - run: | - echo "run_id=$(echo '${{ steps.find-comment.outputs.comment-body }}' | grep -o 'runs/[0-9]\+' | cut -d/ -f2)" >> $GITHUB_OUTPUT - - - name: Get ci-test-result status from the run_id - id: ci_test_result_status - run: | - run_status=`curl -s -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" https://api.github.com/repos/${{github.repository}}/actions/runs/${{steps.workflow.outputs.run_id}}/jobs?per_page=100` - echo "ci_test_result=`echo $run_status | jq -r '[ .jobs[] | select (select(.name | contains("ci-test-result")) | .conclusion | contains("failure"))] | length'`" >> $GITHUB_OUTPUT - echo "ci_test_status=`echo $run_status | jq -r '[ .jobs[] | select (select(.name | contains("ci-test ")) | .conclusion | contains("failure"))] | length'`" >> $GITHUB_OUTPUT - echo "perf_test_status=`echo $run_status | jq -r '[ .jobs[] | select (select(.name | contains("perf-test")) | .conclusion | contains("failure"))] | length'`" >> $GITHUB_OUTPUT - - - name: get status-checks from pr - id: pr_status_check - run: | - status_link="https://api.github.com/repos/${{github.repository}}/statuses/${{github.event.client_payload.pull_request.head.sha}}" - echo "merge_freeze_status=`curl -s -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" $status_link | jq -r '[.[] | select( select( .context | contains("mergefreeze")) | .state | contains("success") | not)] | length'`" >> $GITHUB_OUTPUT - - - name: get status-checks from check suite - id: suite_status_check - run: | - check_runs_link="https://api.github.com/repos/${{github.repository}}/commits/${{github.event.client_payload.pull_request.head.sha}}/check-runs" - check_run_result=`curl -s -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" $check_runs_link` - echo "test_plan_approval_status=`echo $check_run_result | jq -r '[[.check_runs[]|select(.name | contains("Test Plan Approved"))][0] | select( .conclusion | contains("success") | not)] | length'`" >> $GITHUB_OUTPUT - echo "ci_test_available=`echo $check_run_result | jq -r '[.check_runs[] | select(.name | contains("ci-test-result"))] | length'`" >> $GITHUB_OUTPUT - - - name: get pr approval status - id: pr_approval_status - run: | - pr_reviews_link="https://api.github.com/repos/${{github.repository}}/pulls/${{github.event.client_payload.pull_request.number}}/reviews" - pr_reviews=`curl -s -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" $pr_reviews_link` - echo "approved_pr_reviews=`echo $pr_reviews | jq -r 'if length > 0 then [.[]|select(.state | contains ("APPROVED"))]|length else 0 end'`" >> $GITHUB_OUTPUT - - - name: Verify all the checks - id: verify_checks - run: | - if [ ${{ steps.ci_test_result_status.outputs.ci_test_result }} == 1 ]; then - if [ ${{ steps.ci_test_result_status.outputs.ci_test_status }} -gt 0 ]; then - echo "msg=Looks like there are some Cypress failures. Can't Merge." >> $GITHUB_OUTPUT - exit 1 - elif [ ${{ steps.ci_test_result_status.outputs.perf_test_status }} -gt 0 ]; then - echo "msg=Looks like Perf-Tests failed. Contact perf team to get their confirmation. Can't Merge." >> $GITHUB_OUTPUT - exit 1 - fi - elif [ ${{ steps.suite_status_check.outputs.ci_test_available }} == 0 ]; then - echo "msg=Looks like you forgot to run /ok-to-test on the latest commit. Can't Merge." >> $GITHUB_OUTPUT - exit 1 - elif [ ${{ steps.pr_status_check.outputs.merge_freeze_status }} != 0 ]; then - echo "msg=There's merge freeze. Can't Merge, please try after merge-freeze is lifted." >> $GITHUB_OUTPUT - exit 1 - elif [ ${{ steps.suite_status_check.outputs.test_plan_approval_status }} == 1 ]; then - echo "msg=Either get 'Test Plan Approved' or 'skip-testPlan' added and try again!" >> $GITHUB_OUTPUT - exit 1 - elif [ ${{ steps.pr_approval_status.outputs.approved_pr_reviews }} == 0 ]; then - echo "msg=Minimum 1 approval needed to merge this PR, please get it reviewed by your peer and try again!" >> $GITHUB_OUTPUT - exit 1 - elif [ ${{ steps.suite_status_check.outputs.test_plan_approval_status }} == 0 ]; then - echo "msg=Hurray!🎉 Proceeding to Merge!!!" >> $GITHUB_OUTPUT - exit 0 - else - echo "msg=Some checks have failed. Can't merge." >> $GITHUB_OUTPUT - exit 1 - fi - - - name: Add a comment on the PR after all checks - if: always() - uses: peter-evans/create-or-update-comment@v3 - with: - issue-number: ${{ github.event.client_payload.pull_request.number }} - body: | - ${{steps.verify_checks.outputs.msg}} - - - name: Auto merge if above checks are success and have 1 approval - if: success() - id: automerge - uses: juliangruber/merge-pull-request-action@v1 - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - number: ${{ github.event.client_payload.pull_request.number }} - method: merge - repo: ${{ github.repository }} - - - run: | - echo ${{ steps.automerge.outputs }} diff --git a/.github/workflows/ok-to-test.yml b/.github/workflows/ok-to-test.yml index 69dc60da61f8..f88c27467556 100644 --- a/.github/workflows/ok-to-test.yml +++ b/.github/workflows/ok-to-test.yml @@ -30,7 +30,6 @@ jobs: commands: | ok-to-test perf-test - ci-merge-check ci-test-limit ok-to-test-with-documentdb build-deploy-preview
dc8f8724bcc7ce8460d07566288006603c43f729
2023-05-03 09:56:52
rahulramesha
fix: Layout Conversion bugs for auto Layout (#22565)
false
Layout Conversion bugs for auto Layout (#22565)
fix
diff --git a/app/client/src/constants/WidgetConstants.tsx b/app/client/src/constants/WidgetConstants.tsx index a13ab33c937d..1203ae189ab5 100644 --- a/app/client/src/constants/WidgetConstants.tsx +++ b/app/client/src/constants/WidgetConstants.tsx @@ -217,4 +217,9 @@ export const WIDGET_PROPS_TO_SKIP_FROM_EVAL = { */ export const FLEXBOX_PADDING = 4; +/** + * max width of modal widget constant as a multiplier of Main canvasWidth + */ +export const MAX_MODAL_WIDTH_FROM_MAIN_WIDTH = 0.95; + export const FILE_SIZE_LIMIT_FOR_BLOBS = 5000 * 1024; // 5MB diff --git a/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useAutoToFixedLayoutFlow.ts b/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useAutoToFixedLayoutFlow.ts index 2a091c497263..3fe7434842b7 100644 --- a/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useAutoToFixedLayoutFlow.ts +++ b/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useAutoToFixedLayoutFlow.ts @@ -25,10 +25,11 @@ import { CONVERSION_STATES } from "reducers/uiReducers/layoutConversionReducer"; import { setLayoutConversionStateAction } from "actions/autoLayoutActions"; import { Colors } from "constants/Colors"; import { useSelector } from "react-redux"; -import { getReadableSnapShotDetails } from "selectors/autoLayoutSelectors"; +import { getSnapshotUpdatedTime } from "selectors/autoLayoutSelectors"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import { snapShotFlow } from "./useSnapShotForm"; import { commonConversionFlows } from "./CommonConversionFlows"; +import { getReadableSnapShotDetails } from "utils/autoLayout/AutoLayoutUtils"; //returns props for Auto to Fixed Layout conversion flows based on which the Conversion Form can be rendered export const useAutoToFixedLayoutFlow = ( @@ -43,7 +44,8 @@ export const useAutoToFixedLayoutFlow = ( icon: "desktop", }); - const readableSnapShotDetails = useSelector(getReadableSnapShotDetails); + const lastUpdatedTime = useSelector(getSnapshotUpdatedTime); + const readableSnapShotDetails = getReadableSnapShotDetails(lastUpdatedTime); return { [CONVERSION_STATES.START]: { diff --git a/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useSnapShotForm.ts b/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useSnapShotForm.ts index 2ea4523a3ecf..66ccc081ab03 100644 --- a/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useSnapShotForm.ts +++ b/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useSnapShotForm.ts @@ -16,13 +16,14 @@ import type { Dispatch } from "redux"; import { CONVERSION_STATES } from "reducers/uiReducers/layoutConversionReducer"; import { setLayoutConversionStateAction } from "actions/autoLayoutActions"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; -import type { ReadableSnapShotDetails } from "selectors/autoLayoutSelectors"; -import { getReadableSnapShotDetails } from "selectors/autoLayoutSelectors"; +import { getSnapshotUpdatedTime } from "selectors/autoLayoutSelectors"; import { Colors } from "constants/Colors"; import { commonConversionFlows } from "./CommonConversionFlows"; import { useDispatch, useSelector } from "react-redux"; import type { AppState } from "@appsmith/reducers"; import { Variant } from "design-system-old"; +import type { ReadableSnapShotDetails } from "utils/autoLayout/AutoLayoutUtils"; +import { getReadableSnapShotDetails } from "utils/autoLayout/AutoLayoutUtils"; //returns props for using snapshot flows based on which the Conversion Form can be rendered export const snapShotFlow = ( @@ -107,7 +108,9 @@ export const useSnapShotForm = (onCancel: () => void) => { const conversionState = useSelector( (state: AppState) => state.ui.layoutConversion.conversionState, ); - const readableSnapShotDetails = useSelector(getReadableSnapShotDetails); + const lastUpdatedTime = useSelector(getSnapshotUpdatedTime); + const readableSnapShotDetails = getReadableSnapShotDetails(lastUpdatedTime); + const dispatch = useDispatch(); const snapshotFlowStates = snapShotFlow( diff --git a/app/client/src/pages/Editor/WidgetsEditor/index.tsx b/app/client/src/pages/Editor/WidgetsEditor/index.tsx index 14aefdb82d53..10426e49a8aa 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/index.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/index.tsx @@ -43,7 +43,6 @@ import { } from "selectors/appSettingsPaneSelectors"; import { AppSettingsTabs } from "../AppSettingsPane/AppSettings"; import PropertyPaneContainer from "./PropertyPaneContainer"; -import { getReadableSnapShotDetails } from "selectors/autoLayoutSelectors"; import { BannerMessage, IconSize } from "design-system-old"; import { Colors } from "constants/Colors"; import { @@ -55,6 +54,8 @@ import SnapShotBannerCTA from "../CanvasLayoutConversion/SnapShotBannerCTA"; import { APP_MODE } from "entities/App"; import { getSelectedAppTheme } from "selectors/appThemingSelectors"; import { useIsMobileDevice } from "utils/hooks/useDeviceDetect"; +import { getSnapshotUpdatedTime } from "selectors/autoLayoutSelectors"; +import { getReadableSnapShotDetails } from "utils/autoLayout/AutoLayoutUtils"; function WidgetsEditor() { const { deselectAll, focusWidget } = useWidgetSelection(); @@ -66,7 +67,8 @@ function WidgetsEditor() { const guidedTourEnabled = useSelector(inGuidedTour); const isMultiPane = useSelector(isMultiPaneActive); const isPreviewMode = useSelector(previewModeSelector); - const readableSnapShotDetails = useSelector(getReadableSnapShotDetails); + const lastUpdatedTime = useSelector(getSnapshotUpdatedTime); + const readableSnapShotDetails = getReadableSnapShotDetails(lastUpdatedTime); const currentApplicationDetails = useSelector(getCurrentApplication); const isAppSidebarPinned = useSelector(getAppSidebarPinned); diff --git a/app/client/src/sagas/SnapshotSagas.ts b/app/client/src/sagas/SnapshotSagas.ts index cb59623b28eb..d37fbbacb8ab 100644 --- a/app/client/src/sagas/SnapshotSagas.ts +++ b/app/client/src/sagas/SnapshotSagas.ts @@ -4,7 +4,6 @@ import { } from "actions/autoLayoutActions"; import type { ApiResponse } from "api/ApiResponses"; import ApplicationApi from "@appsmith/api/ApplicationApi"; -import type { PageDefaultMeta } from "@appsmith/api/ApplicationApi"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import log from "loglevel"; import type { SnapShotDetails } from "reducers/uiReducers/layoutConversionReducer"; @@ -89,20 +88,6 @@ function* restoreApplicationFromSnapshotSaga() { getLogToSentryFromResponse(response), ); - // update the pages list temporarily with incomplete data. - if (response?.data?.pages) { - yield put({ - type: ReduxActionTypes.FETCH_PAGE_LIST_SUCCESS, - payload: { - pages: response.data.pages.map((page: PageDefaultMeta) => ({ - pageId: page.id, - isDefault: page.isDefault, - })), - applicationId, - }, - }); - } - //update layout positioning type from yield call( updateApplicationLayoutType, @@ -111,6 +96,14 @@ function* restoreApplicationFromSnapshotSaga() { : AppPositioningTypes.FIXED, ); + if (response?.data?.applicationDetail?.appPositioning?.type) { + //update layout positioning type from response + yield call( + updateApplicationLayoutType, + response.data.applicationDetail.appPositioning.type, + ); + } + if (isValidResponse) { //update conversion form state to success yield put( @@ -128,7 +121,7 @@ function* restoreApplicationFromSnapshotSaga() { } //Saga to delete application snapshot -function* deleteApplicationSnapshotSaga() { +export function* deleteApplicationSnapshotSaga() { let response: ApiResponse | undefined; try { const applicationId: string = yield select(getCurrentApplicationId); diff --git a/app/client/src/sagas/layoutConversionSagas.ts b/app/client/src/sagas/layoutConversionSagas.ts index f23edd51d898..21070f7a44ab 100644 --- a/app/client/src/sagas/layoutConversionSagas.ts +++ b/app/client/src/sagas/layoutConversionSagas.ts @@ -13,7 +13,10 @@ import { getPageWidgets } from "selectors/entitiesSelector"; import { convertNormalizedDSLToFixed } from "utils/DSLConversions/autoToFixedLayout"; import convertToAutoLayout from "utils/DSLConversions/fixedToAutoLayout"; import type { DSLWidget } from "widgets/constants"; -import { createSnapshotSaga } from "./SnapshotSagas"; +import { + createSnapshotSaga, + deleteApplicationSnapshotSaga, +} from "./SnapshotSagas"; import * as Sentry from "@sentry/react"; import log from "loglevel"; import { saveAllPagesSaga } from "./PageSagas"; @@ -26,6 +29,7 @@ import { updateApplicationLayoutType } from "./AutoLayoutUpdateSagas"; * @param action */ function* convertFromAutoToFixedSaga(action: ReduxAction<SupportedLayouts>) { + let snapshotSaveSuccess = false; try { const pageWidgetsList: PageWidgetsReduxState = yield select(getPageWidgets); @@ -33,6 +37,8 @@ function* convertFromAutoToFixedSaga(action: ReduxAction<SupportedLayouts>) { yield call(createSnapshotSaga); } + snapshotSaveSuccess = true; + //Set conversion form to indicated conversion loading state yield put( setLayoutConversionStateAction(CONVERSION_STATES.CONVERSION_SPINNER), @@ -73,6 +79,10 @@ function* convertFromAutoToFixedSaga(action: ReduxAction<SupportedLayouts>) { ); } catch (e) { log.error(e); + + if (snapshotSaveSuccess) { + yield call(deleteApplicationSnapshotSaga); + } //update conversion form state to error yield put( setLayoutConversionStateAction( @@ -88,6 +98,7 @@ function* convertFromAutoToFixedSaga(action: ReduxAction<SupportedLayouts>) { * @param action */ function* convertFromFixedToAutoSaga() { + let snapshotSaveSuccess = false; try { const pageWidgetsList: PageWidgetsReduxState = yield select(getPageWidgets); @@ -95,6 +106,8 @@ function* convertFromFixedToAutoSaga() { yield call(createSnapshotSaga); } + snapshotSaveSuccess = true; + yield put( setLayoutConversionStateAction(CONVERSION_STATES.CONVERSION_SPINNER), ); @@ -129,6 +142,9 @@ function* convertFromFixedToAutoSaga() { } catch (e) { log.error(e); //update conversion form state to error + if (snapshotSaveSuccess) { + yield call(deleteApplicationSnapshotSaga); + } yield put( setLayoutConversionStateAction( CONVERSION_STATES.COMPLETED_ERROR, diff --git a/app/client/src/selectors/autoLayoutSelectors.tsx b/app/client/src/selectors/autoLayoutSelectors.tsx index 9f30c4b08b9d..f197829c5e9a 100644 --- a/app/client/src/selectors/autoLayoutSelectors.tsx +++ b/app/client/src/selectors/autoLayoutSelectors.tsx @@ -1,9 +1,5 @@ import type { AppState } from "@appsmith/reducers"; import { FLEXBOX_PADDING, GridDefaults } from "constants/WidgetConstants"; -import dayjs from "dayjs"; -import duration from "dayjs/plugin/duration"; -import relativeTime from "dayjs/plugin/relativeTime"; -import advancedFormat from "dayjs/plugin/advancedFormat"; import { createSelector } from "reselect"; import { getWidgets } from "sagas/selectors"; import type { @@ -15,17 +11,6 @@ import type { import { getAlignmentColumnInfo } from "utils/autoLayout/AutoLayoutUtils"; import { getIsAutoLayoutMobileBreakPoint } from "./editorSelectors"; -//add formatting plugins -dayjs.extend(duration); -dayjs.extend(relativeTime); -dayjs.extend(advancedFormat); - -export type ReadableSnapShotDetails = { - timeSince: string; - timeTillExpiration: string; - readableDate: string; -}; - export const getIsCurrentlyConvertingLayout = (state: AppState) => state.ui.layoutConversion.isConverting; @@ -37,6 +22,9 @@ export const getFlexLayers = (parentId: string) => { }); }; +export const getSnapshotUpdatedTime = (state: AppState) => + state.ui.layoutConversion.snapshotDetails?.lastUpdatedTime; + export const getLayerIndex = (widgetId: string, parentId: string) => { return createSelector( getFlexLayers(parentId), @@ -102,39 +90,6 @@ export const getParentOffsetTop = (widgetId: string) => }, ); -export const getReadableSnapShotDetails = createSelector( - (state: AppState) => - state.ui.layoutConversion.snapshotDetails?.lastUpdatedTime, - ( - lastUpdatedDateString: string | undefined, - ): ReadableSnapShotDetails | undefined => { - if (!lastUpdatedDateString) return; - - const lastUpdatedDate = new Date(lastUpdatedDateString); - - if (Date.now() - lastUpdatedDate.getTime() <= 0) return; - - const millisecondsPerHour = 60 * 60 * 1000; - const ExpirationInMilliseconds = 5 * 24 * millisecondsPerHour; - const timePassedSince = Date.now() - lastUpdatedDate.getTime(); - - const timeSince: string = dayjs - .duration(timePassedSince, "milliseconds") - .humanize(); - const timeTillExpiration: string = dayjs - .duration(ExpirationInMilliseconds - timePassedSince, "milliseconds") - .humanize(); - - const readableDate = dayjs(lastUpdatedDate).format("Do MMMM, YYYY h:mm a"); - - return { - timeSince, - timeTillExpiration, - readableDate, - }; - }, -); - export const getAlignmentColumns = (widgetId: string, layerIndex: number) => createSelector( getWidgets, diff --git a/app/client/src/utils/DSLConversions/fixedToAutoLayout.ts b/app/client/src/utils/DSLConversions/fixedToAutoLayout.ts index 009578051df1..a5971e9514c7 100644 --- a/app/client/src/utils/DSLConversions/fixedToAutoLayout.ts +++ b/app/client/src/utils/DSLConversions/fixedToAutoLayout.ts @@ -13,6 +13,11 @@ import { Positioning, ResponsiveBehavior, } from "utils/autoLayout/constants"; +import type { DynamicPath } from "utils/DynamicBindingUtils"; +import { + isDynamicValue, + isPathDynamicTrigger, +} from "utils/DynamicBindingUtils"; import WidgetFactory from "utils/WidgetFactory"; import type { WidgetProps } from "widgets/BaseWidget"; import type { DSLWidget } from "widgets/constants"; @@ -163,10 +168,14 @@ export function fitChildWidgetsIntoLayers(widgets: DSLWidget[] | undefined): { //Add unhandled widgets to children for (const nonLayerWidget of nonLayerWidgets) { - const propUpdates = getPropertyUpdatesBasedOnConfig(nonLayerWidget); + const { propertyUpdates, removableDynamicBindingPathList } = + getPropertyUpdatesBasedOnConfig(nonLayerWidget); modifiedWidgets.push( unHandledWidgets.indexOf(nonLayerWidget.type) < 0 - ? { ...convertDSLtoAuto(nonLayerWidget), ...propUpdates } + ? verifyDynamicPathBindingList( + { ...convertDSLtoAuto(nonLayerWidget), ...propertyUpdates }, + removableDynamicBindingPathList, + ) : { ...nonLayerWidget, positioning: Positioning.Fixed }, ); @@ -220,18 +229,27 @@ function getNextLayer(currWidgets: DSLWidget[]): { ? convertDSLtoAuto(widget) : { ...widget, positioning: Positioning.Fixed }; - const propUpdates = getPropertyUpdatesBasedOnConfig(currWidget); + const { propertyUpdates, removableDynamicBindingPathList } = + getPropertyUpdatesBasedOnConfig(currWidget); //Get Alignment of the Widget alignment = alignmentMap[currWidget.widgetId] || FlexLayerAlignment.Start; const flexVerticalAlignment = getWidgetVerticalAlignment(currWidget); - modifiedWidgetsInLayer.push({ - ...currWidget, - ...propUpdates, - alignment, - flexVerticalAlignment, - }); + const modifiedCurrentWidget = + removeNullValuesFromObject<DSLWidget>(currWidget); + + modifiedWidgetsInLayer.push( + verifyDynamicPathBindingList( + { + ...modifiedCurrentWidget, + ...propertyUpdates, + alignment, + flexVerticalAlignment, + }, + removableDynamicBindingPathList, + ), + ); //If the widget type is not to be added in layer then add only to Children if (nonFlexLayerWidgets.indexOf(currWidget.type) < 0) { @@ -710,6 +728,7 @@ function getPropertyUpdatesBasedOnConfig(widget: DSLWidget) { const widgetConfig = WidgetFactory.widgetConfigMap.get(widget.type); let propertyUpdates: Partial<WidgetProps> = {}; + const removableDynamicBindingPathList: string[] = []; //get Responsive Behaviour propertyUpdates.responsiveBehavior = @@ -735,7 +754,14 @@ function getPropertyUpdatesBasedOnConfig(widget: DSLWidget) { propertyUpdates.minWidth = widgetConfig.minWidth; } - return propertyUpdates; + //Delete Dynamic values as they fail, while saving the application layout + for (const propertyPath in propertyUpdates) { + if (widget[propertyPath] && isDynamicValue(widget[propertyPath])) { + removableDynamicBindingPathList.push(propertyPath); + } + } + + return { propertyUpdates, removableDynamicBindingPathList }; } function handleSpecialCaseWidgets(dsl: DSLWidget): DSLWidget { @@ -758,3 +784,56 @@ function handleSpecialCaseWidgets(dsl: DSLWidget): DSLWidget { return dsl; } +/** + * Removes null values from object + * @param object + * @returns + */ +function removeNullValuesFromObject<T extends { [key: string]: any }>( + object: T, +): T { + const copiedObject: T = { ...object }; + + //remove null values and dynamic trigger paths which have "null" values + Object.keys(copiedObject).forEach( + (k) => + copiedObject[k] == null || + (isPathDynamicTrigger(copiedObject, k) && + copiedObject[k] === "null" && + delete copiedObject[k]), + ); + + return copiedObject; +} + +/** + * remove removableDynamicBindingPathList values from DynamicBindingPathList + * @param widget + * @param removableDynamicBindingPathList + * @returns + */ +function verifyDynamicPathBindingList( + widget: DSLWidget, + removableDynamicBindingPathList: string[], +) { + if (!removableDynamicBindingPathList || !widget.dynamicBindingPathList) + return widget; + + const dynamicBindingPathList: DynamicPath[] = []; + for (const dynamicBindingPath of widget.dynamicBindingPathList) { + //if the values are not dynamic, remove from the dynamic binding path list + if ( + !widget[dynamicBindingPath.key] || + !isDynamicValue(widget[dynamicBindingPath.key]) + ) { + continue; + } + + if (removableDynamicBindingPathList.indexOf(dynamicBindingPath.key) < 0) { + dynamicBindingPathList.push(dynamicBindingPath); + } + } + + widget.dynamicBindingPathList = dynamicBindingPathList; + return widget; +} diff --git a/app/client/src/utils/autoLayout/AutoLayoutUtils.ts b/app/client/src/utils/autoLayout/AutoLayoutUtils.ts index b4c040478c9e..3d454d9e2a76 100644 --- a/app/client/src/utils/autoLayout/AutoLayoutUtils.ts +++ b/app/client/src/utils/autoLayout/AutoLayoutUtils.ts @@ -10,6 +10,7 @@ import { MAIN_CONTAINER_WIDGET_ID, WIDGET_PADDING, DefaultDimensionMap, + MAX_MODAL_WIDTH_FROM_MAIN_WIDTH, AUTO_LAYOUT_CONTAINER_PADDING, } from "constants/WidgetConstants"; import type { @@ -22,6 +23,7 @@ import { FlexLayerAlignment, Positioning, ResponsiveBehavior, + SNAPSHOT_EXPIRY_IN_DAYS, } from "utils/autoLayout/constants"; import { updatePositionsOfParentAndSiblings, @@ -33,6 +35,13 @@ import { getWidgetWidth, } from "./flexWidgetUtils"; import type { DSLWidget } from "widgets/constants"; +import { getHumanizedTime, getReadableDateInFormat } from "utils/dayJsUtils"; + +export type ReadableSnapShotDetails = { + timeSince: string; + timeTillExpiration: string; + readableDate: string; +}; export function updateFlexLayersOnDelete( allWidgets: CanvasWidgetsReduxState, @@ -489,7 +498,10 @@ function getCanvasWidth( //modal will be the total width instead of the mainCanvasWidth if (widget.type === "MODAL_WIDGET") { - width = widget.width; + width = Math.min( + widget.width, + mainCanvasWidth * MAX_MODAL_WIDTH_FROM_MAIN_WIDTH, + ); } while (stack.length) { @@ -684,3 +696,39 @@ export function getAlignmentMarginInfo( return marginInfo[wrapInfo.map((x) => x.length).join("")](arr); } + +/** + * Gets readable values from the date String arguments + * @param dateString + * @returns + */ +export function getReadableSnapShotDetails( + dateString: string | undefined, +): ReadableSnapShotDetails | undefined { + if (!dateString) return; + + const lastUpdatedDate = new Date(dateString); + + if (Date.now() - lastUpdatedDate.getTime() <= 0) return; + + const millisecondsPerHour = 60 * 60 * 1000; + const ExpirationInMilliseconds = + SNAPSHOT_EXPIRY_IN_DAYS * 24 * millisecondsPerHour; + const timePassedSince = Date.now() - lastUpdatedDate.getTime(); + + const timeSince: string = getHumanizedTime(timePassedSince); + const timeTillExpiration: string = getHumanizedTime( + ExpirationInMilliseconds - timePassedSince, + ); + + const readableDate = getReadableDateInFormat( + lastUpdatedDate, + "Do MMMM, YYYY h:mm a", + ); + + return { + timeSince, + timeTillExpiration, + readableDate, + }; +} diff --git a/app/client/src/utils/autoLayout/constants.ts b/app/client/src/utils/autoLayout/constants.ts index 19b44411ed5c..3ba133d8f0e6 100644 --- a/app/client/src/utils/autoLayout/constants.ts +++ b/app/client/src/utils/autoLayout/constants.ts @@ -1,3 +1,5 @@ +export const SNAPSHOT_EXPIRY_IN_DAYS = 5; + export enum LayoutDirection { Horizontal = "Horizontal", Vertical = "Vertical", diff --git a/app/client/src/utils/dayJsUtils.ts b/app/client/src/utils/dayJsUtils.ts new file mode 100644 index 000000000000..2f963634dd7f --- /dev/null +++ b/app/client/src/utils/dayJsUtils.ts @@ -0,0 +1,32 @@ +import dayjs from "dayjs"; +import duration from "dayjs/plugin/duration"; +import relativeTime from "dayjs/plugin/relativeTime"; +import advancedFormat from "dayjs/plugin/advancedFormat"; + +//add formatting plugins +dayjs.extend(duration); +dayjs.extend(relativeTime); +dayjs.extend(advancedFormat); + +/** + * Gets humanized values of the time that has passed since like, + * a few seconds ago, an hour ago, 2 days ago etc + * @param timeInMilliseconds + * @returns humanized string + */ +export function getHumanizedTime(timeInMilliseconds: number): string { + return dayjs.duration(timeInMilliseconds, "milliseconds").humanize(); +} + +/** + * Gets readable date in the given format + * @param date + * @param formatString + * @returns readable date in format + */ +export function getReadableDateInFormat( + date: Date, + formatString: string, +): string { + return dayjs(date).format(formatString); +} diff --git a/app/client/src/widgets/ModalWidget/widget/index.tsx b/app/client/src/widgets/ModalWidget/widget/index.tsx index cd1b6ecd4966..9397c1ad0854 100644 --- a/app/client/src/widgets/ModalWidget/widget/index.tsx +++ b/app/client/src/widgets/ModalWidget/widget/index.tsx @@ -9,6 +9,7 @@ import type { UIElementSize } from "components/editorComponents/ResizableUtils"; import WidgetNameComponent from "components/editorComponents/WidgetNameComponent"; import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; import type { RenderMode } from "constants/WidgetConstants"; +import { MAX_MODAL_WIDTH_FROM_MAIN_WIDTH } from "constants/WidgetConstants"; import { WIDGET_PADDING } from "constants/WidgetConstants"; import { ValidationTypes } from "constants/WidgetValidation"; import type { Stylesheet } from "entities/AppTheming"; @@ -148,7 +149,7 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> { }; getMaxModalWidth() { - return this.props.mainCanvasWidth * 0.95; + return this.props.mainCanvasWidth * MAX_MODAL_WIDTH_FROM_MAIN_WIDTH; } getModalWidth(width: number) {
d4068a24af156e5b145bda3e37fed299a0a0be97
2022-10-31 09:48:03
dependabot[bot]
chore: bump jackson-databind from 2.12.6.1 to 2.13.4.1 in /app/server/appsmith-plugins/snowflakePlugin (#17695)
false
bump jackson-databind from 2.12.6.1 to 2.13.4.1 in /app/server/appsmith-plugins/snowflakePlugin (#17695)
chore
diff --git a/app/server/appsmith-plugins/snowflakePlugin/pom.xml b/app/server/appsmith-plugins/snowflakePlugin/pom.xml index 216fef29db1a..30dd5e34221c 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/pom.xml +++ b/app/server/appsmith-plugins/snowflakePlugin/pom.xml @@ -72,7 +72,7 @@ <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> - <version>2.12.6.1</version> + <version>2.13.4.1</version> <scope>provided</scope> </dependency>
01529c4db5e82c1891b5efb25bfdc7f4fcebcaa5
2024-05-30 13:51:39
Pawan Kumar
chore: Checkbox widget does not show an asterisk to indicate it's a required (#33814)
false
Checkbox widget does not show an asterisk to indicate it's a required (#33814)
chore
diff --git a/app/client/packages/design-system/widgets/src/components/Checkbox/chromatic/Checkbox.chromatic.stories.tsx b/app/client/packages/design-system/widgets/src/components/Checkbox/chromatic/Checkbox.chromatic.stories.tsx index f2a9def2a6fa..66f7a5357381 100644 --- a/app/client/packages/design-system/widgets/src/components/Checkbox/chromatic/Checkbox.chromatic.stories.tsx +++ b/app/client/packages/design-system/widgets/src/components/Checkbox/chromatic/Checkbox.chromatic.stories.tsx @@ -28,9 +28,12 @@ export const LightMode: Story = { </DataAttrWrapper> </> ))} - <Checkbox defaultSelected isReadOnly isRequired> + <Checkbox defaultSelected isReadOnly> Readonly </Checkbox> + <Checkbox defaultSelected isRequired> + Is Required + </Checkbox> </StoryGrid> ), }; diff --git a/app/client/packages/design-system/widgets/src/components/Checkbox/src/Checkbox.tsx b/app/client/packages/design-system/widgets/src/components/Checkbox/src/Checkbox.tsx index 0cd0ebb4a2fd..df5cea5d6783 100644 --- a/app/client/packages/design-system/widgets/src/components/Checkbox/src/Checkbox.tsx +++ b/app/client/packages/design-system/widgets/src/components/Checkbox/src/Checkbox.tsx @@ -25,7 +25,19 @@ const _Checkbox = (props: CheckboxProps, ref: HeadlessCheckboxRef) => { inlineLabelStyles["inline-label"], )} > - {Boolean(children) && <Text>{children}</Text>} + {Boolean(children) && ( + <> + <Text>{children}</Text> + {Boolean(props.isRequired) && ( + <Text + color="negative" + data-inline-label-necessity-indicator-icon="" + > + * + </Text> + )} + </> + )} </HeadlessCheckbox> ); }; diff --git a/app/client/packages/design-system/widgets/src/components/Checkbox/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/Checkbox/src/styles.module.css index 06da0adfa5f5..7cb25ebd8750 100644 --- a/app/client/packages/design-system/widgets/src/components/Checkbox/src/styles.module.css +++ b/app/client/packages/design-system/widgets/src/components/Checkbox/src/styles.module.css @@ -30,6 +30,11 @@ --checkbox-border-color: var(--color-bd-neutral-hover); } + & [data-inline-label-necessity-indicator-icon] { + color: var(--color-fg-negative); + margin-inline-start: var(--inner-spacing-1); + } + /** * ---------------------------------------------------------------------------- * LABEL POSITION @@ -86,10 +91,10 @@ } /** - * ---------------------------------------------------------------------------- - * ERROR ( INVALID ) - *----------------------------------------------------------------------------- - */ + * ---------------------------------------------------------------------------- + * ERROR ( INVALID ) + *----------------------------------------------------------------------------- + */ &[data-invalid] [data-icon] { --checkbox-border-color: var(--color-bd-negative); } diff --git a/app/client/packages/design-system/widgets/src/components/Checkbox/stories/Checkbox.stories.tsx b/app/client/packages/design-system/widgets/src/components/Checkbox/stories/Checkbox.stories.tsx index 576cbadf756e..18a8a856e1e4 100644 --- a/app/client/packages/design-system/widgets/src/components/Checkbox/stories/Checkbox.stories.tsx +++ b/app/client/packages/design-system/widgets/src/components/Checkbox/stories/Checkbox.stories.tsx @@ -64,3 +64,11 @@ export const CustomIcon: Story = { </Flex> ), }; + +export const IsRequired: Story = { + render: () => ( + <Flex direction="column" gap="1rem" wrap="wrap"> + <Checkbox isRequired>Required</Checkbox> + </Flex> + ), +}; diff --git a/app/client/packages/design-system/widgets/src/styles/src/field.module.css b/app/client/packages/design-system/widgets/src/styles/src/field.module.css index d1cbd6944a8b..59cca9f6205a 100644 --- a/app/client/packages/design-system/widgets/src/styles/src/field.module.css +++ b/app/client/packages/design-system/widgets/src/styles/src/field.module.css @@ -41,7 +41,7 @@ */ & [data-field-necessity-indicator-icon] { color: var(--color-fg-negative); - margin-left: var(--inner-spacing-1); + margin-inline-start: var(--inner-spacing-1); } /**
f2709d6de7b8dcb9ea3dc99b0aa781788d139c9b
2022-12-16 12:06:55
Dhruvik Neharia
fix: Button Group Menu Item Label Misaligned (#18951)
false
Button Group Menu Item Label Misaligned (#18951)
fix
diff --git a/app/client/src/widgets/ButtonGroupWidget/component/index.tsx b/app/client/src/widgets/ButtonGroupWidget/component/index.tsx index 654764d2a138..c8f4957316d7 100644 --- a/app/client/src/widgets/ButtonGroupWidget/component/index.tsx +++ b/app/client/src/widgets/ButtonGroupWidget/component/index.tsx @@ -347,25 +347,22 @@ function PopoverContent(props: PopoverContentProps) { onClick, textColor, } = menuItem; - if (iconAlign === Alignment.RIGHT) { - return ( - <BaseMenuItem - backgroundColor={backgroundColor} - disabled={isDisabled} - key={id} - labelElement={<Icon color={iconColor} icon={iconName} />} - onClick={() => onItemClicked(onClick, buttonId)} - text={label} - textColor={textColor} - /> - ); - } + return ( <BaseMenuItem backgroundColor={backgroundColor} disabled={isDisabled} - icon={<Icon color={iconColor} icon={iconName} />} + icon={ + iconAlign !== Alignment.RIGHT && iconName ? ( + <Icon color={iconColor} icon={iconName} /> + ) : null + } key={id} + labelElement={ + iconAlign === Alignment.RIGHT && iconName ? ( + <Icon color={iconColor} icon={iconName} /> + ) : null + } onClick={() => onItemClicked(onClick, buttonId)} text={label} textColor={textColor}
95e6b4fb9814af549a929e90d0ae43a077aa7de4
2022-06-01 00:13:32
Bhavin K
fix: switch group added check for inline width (#14190)
false
switch group added check for inline width (#14190)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js new file mode 100644 index 000000000000..dd58a820b59b --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js @@ -0,0 +1,47 @@ +describe("Visual regression tests", () => { + // for any changes in UI, update the screenshot in snapshot folder, to do so: + // 1. Delete the required screenshot which you want to update + // 2. Run test in headless mode with any browser (to maintain same resolution in CI) + // 3. New screenshot will be generated in the snapshot folder + + it("Verify SwitchGroup inline enable/disbale", () => { + cy.dragAndDropToCanvas("switchgroupwidget", { x: 300, y: 300 }); + cy.wait(1000); + + //Verify default check + cy.get(".t--property-control-inline input").should("be.checked"); + // taking screenshot of switch container + cy.get("[data-testid=switchgroup-container]").matchImageSnapshot( + "inlineEnabled", + ); + + //Unchecking & verify snap + cy.get(".t--property-control-inline input") + .uncheck({ force: true }) + .wait(200) + .should("not.be.checked"); + cy.get("[data-testid=switchgroup-container]").matchImageSnapshot( + "inlineDisabled", + ); + + //Checking again & verify snap + cy.get(".t--property-control-inline input") + .check({ force: true }) + .wait(200) + .should("be.checked"); + + cy.get("[data-testid=switchgroup-container]").matchImageSnapshot( + "inlineEnabled", + ); + + //Unchecking again & verify snap + cy.get(".t--property-control-inline input") + .uncheck({ force: true }) + .wait(200) + .should("not.be.checked"); + // taking screenshot of app home page in edit mode + cy.get("[data-testid=switchgroup-container]").matchImageSnapshot( + "inlineDisabled", + ); + }); +}); diff --git a/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js/inlineDisabled.snap.png b/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js/inlineDisabled.snap.png new file mode 100644 index 000000000000..0e852dbeb17d Binary files /dev/null and b/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js/inlineDisabled.snap.png differ diff --git a/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js/inlineEnabled.snap.png b/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js/inlineEnabled.snap.png new file mode 100644 index 000000000000..b53ee1e0bbc5 Binary files /dev/null and b/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/LayoutValidation/WidgetsLayout_spec.js/inlineEnabled.snap.png differ diff --git a/app/client/src/widgets/SwitchWidget/component/index.tsx b/app/client/src/widgets/SwitchWidget/component/index.tsx index a00d8de3e186..dd8f15b56091 100644 --- a/app/client/src/widgets/SwitchWidget/component/index.tsx +++ b/app/client/src/widgets/SwitchWidget/component/index.tsx @@ -55,6 +55,7 @@ const SwitchLabel = styled.div<{ export const StyledSwitch = styled(Switch)<{ accentColor: string; + inline?: boolean; }>` &.${Classes.CONTROL} { margin: 0; @@ -68,7 +69,7 @@ export const StyledSwitch = styled(Switch)<{ } &.${Classes.SWITCH} { - width: 100%; + ${({ inline }) => (!!inline ? "" : "width: 100%;")} & input:not(:disabled):active:checked ~ .${Classes.CONTROL_INDICATOR} { background: ${({ accentColor }) => `${accentColor}`} !important; }
2a9eb75f5173d514789b6b94b3c8586e8bf7f74d
2023-05-12 12:54:11
Ivan Akulov
fix: ensure the code doesn’t crash in the worker environment (#23238)
false
ensure the code doesn’t crash in the worker environment (#23238)
fix
diff --git a/app/client/src/ce/configs/index.ts b/app/client/src/ce/configs/index.ts index 4cbf1c29a69f..cf78f5ed2757 100644 --- a/app/client/src/ce/configs/index.ts +++ b/app/client/src/ce/configs/index.ts @@ -2,7 +2,6 @@ import type { AppsmithUIConfigs } from "./types"; import { Integrations } from "@sentry/tracing"; import * as Sentry from "@sentry/react"; import { createBrowserHistory } from "history"; -const history = createBrowserHistory(); export interface INJECTED_CONFIGS { sentry: { @@ -136,62 +135,64 @@ const getConfig = (fromENV: string, fromWindow = "") => { // TODO(Abhinav): See if this is called so many times, that we may need some form of memoization. export const getAppsmithConfigs = (): AppsmithUIConfigs => { - const { APPSMITH_FEATURE_CONFIGS } = window; + const APPSMITH_FEATURE_CONFIGS = + // This code might be called both from the main thread and a web worker + typeof window === "undefined" ? undefined : window.APPSMITH_FEATURE_CONFIGS; const ENV_CONFIG = getConfigsFromEnvVars(); // const sentry = getConfig(ENV_CONFIG.sentry, APPSMITH_FEATURE_CONFIGS.sentry); const sentryDSN = getConfig( ENV_CONFIG.sentry.dsn, - APPSMITH_FEATURE_CONFIGS.sentry.dsn, + APPSMITH_FEATURE_CONFIGS?.sentry.dsn, ); const sentryRelease = getConfig( ENV_CONFIG.sentry.release, - APPSMITH_FEATURE_CONFIGS.sentry.release, + APPSMITH_FEATURE_CONFIGS?.sentry.release, ); const sentryENV = getConfig( ENV_CONFIG.sentry.environment, - APPSMITH_FEATURE_CONFIGS.sentry.environment, + APPSMITH_FEATURE_CONFIGS?.sentry.environment, ); const segment = getConfig( ENV_CONFIG.segment.apiKey, - APPSMITH_FEATURE_CONFIGS.segment.apiKey, + APPSMITH_FEATURE_CONFIGS?.segment.apiKey, ); const fusioncharts = getConfig( ENV_CONFIG.fusioncharts.licenseKey, - APPSMITH_FEATURE_CONFIGS.fusioncharts.licenseKey, + APPSMITH_FEATURE_CONFIGS?.fusioncharts.licenseKey, ); const googleRecaptchaSiteKey = getConfig( ENV_CONFIG.googleRecaptchaSiteKey, - APPSMITH_FEATURE_CONFIGS.googleRecaptchaSiteKey, + APPSMITH_FEATURE_CONFIGS?.googleRecaptchaSiteKey, ); // As the following shows, the config variables can be set using a combination // of env variables and injected configs const smartLook = getConfig( ENV_CONFIG.smartLook.id, - APPSMITH_FEATURE_CONFIGS.smartLook.id, + APPSMITH_FEATURE_CONFIGS?.smartLook.id, ); const algoliaAPIID = getConfig( ENV_CONFIG.algolia.apiId, - APPSMITH_FEATURE_CONFIGS.algolia.apiId, + APPSMITH_FEATURE_CONFIGS?.algolia.apiId, ); const algoliaAPIKey = getConfig( ENV_CONFIG.algolia.apiKey, - APPSMITH_FEATURE_CONFIGS.algolia.apiKey, + APPSMITH_FEATURE_CONFIGS?.algolia.apiKey, ); const algoliaIndex = getConfig( ENV_CONFIG.algolia.indexName, - APPSMITH_FEATURE_CONFIGS.algolia.indexName, + APPSMITH_FEATURE_CONFIGS?.algolia.indexName, ); const algoliaSnippetIndex = getConfig( ENV_CONFIG.algolia.indexName, - APPSMITH_FEATURE_CONFIGS.algolia.snippetIndex, + APPSMITH_FEATURE_CONFIGS?.algolia.snippetIndex, ); const segmentCEKey = getConfig( ENV_CONFIG.segment.ceKey, - APPSMITH_FEATURE_CONFIGS.segment.ceKey, + APPSMITH_FEATURE_CONFIGS?.segment.ceKey, ); // We enable segment tracking if either the Cloud API key is set or the self-hosted CE key is set @@ -205,11 +206,16 @@ export const getAppsmithConfigs = (): AppsmithUIConfigs => { environment: sentryENV.value, normalizeDepth: 3, integrations: [ - new Integrations.BrowserTracing({ - // Can also use reactRouterV4Instrumentation - routingInstrumentation: Sentry.reactRouterV5Instrumentation(history), - }), - ], + typeof window === "undefined" + ? // The Browser Tracing instrumentation isn’t working (and is unnecessary) in the worker environment + undefined + : new Integrations.BrowserTracing({ + // Can also use reactRouterV4Instrumentation + routingInstrumentation: Sentry.reactRouterV5Instrumentation( + createBrowserHistory(), + ), + }), + ].filter((i) => i !== undefined), tracesSampleRate: 0.1, }, smartLook: { @@ -237,33 +243,53 @@ export const getAppsmithConfigs = (): AppsmithUIConfigs => { apiKey: googleRecaptchaSiteKey.value, }, enableRapidAPI: - ENV_CONFIG.enableRapidAPI || APPSMITH_FEATURE_CONFIGS.enableRapidAPI, + ENV_CONFIG.enableRapidAPI || + APPSMITH_FEATURE_CONFIGS?.enableRapidAPI || + false, disableLoginForm: - ENV_CONFIG.disableLoginForm || APPSMITH_FEATURE_CONFIGS.disableLoginForm, + ENV_CONFIG.disableLoginForm || + APPSMITH_FEATURE_CONFIGS?.disableLoginForm || + false, disableSignup: - ENV_CONFIG.disableSignup || APPSMITH_FEATURE_CONFIGS.disableSignup, + ENV_CONFIG.disableSignup || + APPSMITH_FEATURE_CONFIGS?.disableSignup || + false, enableMixpanel: - ENV_CONFIG.enableMixpanel || APPSMITH_FEATURE_CONFIGS.enableMixpanel, + ENV_CONFIG.enableMixpanel || + APPSMITH_FEATURE_CONFIGS?.enableMixpanel || + false, cloudHosting: - ENV_CONFIG.cloudHosting || APPSMITH_FEATURE_CONFIGS.cloudHosting, - logLevel: ENV_CONFIG.logLevel || APPSMITH_FEATURE_CONFIGS.logLevel, - enableTNCPP: ENV_CONFIG.enableTNCPP || APPSMITH_FEATURE_CONFIGS.enableTNCPP, - appVersion: ENV_CONFIG.appVersion || APPSMITH_FEATURE_CONFIGS.appVersion, + ENV_CONFIG.cloudHosting || + APPSMITH_FEATURE_CONFIGS?.cloudHosting || + false, + logLevel: + ENV_CONFIG.logLevel || APPSMITH_FEATURE_CONFIGS?.logLevel || false, + enableTNCPP: + ENV_CONFIG.enableTNCPP || APPSMITH_FEATURE_CONFIGS?.enableTNCPP || false, + appVersion: + ENV_CONFIG.appVersion || APPSMITH_FEATURE_CONFIGS?.appVersion || false, intercomAppID: - ENV_CONFIG.intercomAppID || APPSMITH_FEATURE_CONFIGS.intercomAppID, - mailEnabled: ENV_CONFIG.mailEnabled || APPSMITH_FEATURE_CONFIGS.mailEnabled, + ENV_CONFIG.intercomAppID || APPSMITH_FEATURE_CONFIGS?.intercomAppID || "", + mailEnabled: + ENV_CONFIG.mailEnabled || APPSMITH_FEATURE_CONFIGS?.mailEnabled || false, cloudServicesBaseUrl: ENV_CONFIG.cloudServicesBaseUrl || - APPSMITH_FEATURE_CONFIGS.cloudServicesBaseUrl, + APPSMITH_FEATURE_CONFIGS?.cloudServicesBaseUrl || + "", appsmithSupportEmail: ENV_CONFIG.supportEmail, hideWatermark: - ENV_CONFIG.hideWatermark || APPSMITH_FEATURE_CONFIGS.hideWatermark, + ENV_CONFIG.hideWatermark || + APPSMITH_FEATURE_CONFIGS?.hideWatermark || + false, disableIframeWidgetSandbox: ENV_CONFIG.disableIframeWidgetSandbox || - APPSMITH_FEATURE_CONFIGS.disableIframeWidgetSandbox, - pricingUrl: ENV_CONFIG.pricingUrl || APPSMITH_FEATURE_CONFIGS.pricingUrl, + APPSMITH_FEATURE_CONFIGS?.disableIframeWidgetSandbox || + false, + pricingUrl: + ENV_CONFIG.pricingUrl || APPSMITH_FEATURE_CONFIGS?.pricingUrl || "", customerPortalUrl: ENV_CONFIG.customerPortalUrl || - APPSMITH_FEATURE_CONFIGS.customerPortalUrl, + APPSMITH_FEATURE_CONFIGS?.customerPortalUrl || + "", }; };
1ba5c70a7fccbc311a38fdd9baf23899b2cc4d7e
2023-05-03 12:13:27
sneha122
fix: firefox file picker not showing up issue fixed (#22778)
false
firefox file picker not showing up issue fixed (#22778)
fix
diff --git a/app/client/src/constants/Datasource.ts b/app/client/src/constants/Datasource.ts index 58ba0a860f23..4967da521cce 100644 --- a/app/client/src/constants/Datasource.ts +++ b/app/client/src/constants/Datasource.ts @@ -2,3 +2,4 @@ export const TEMP_DATASOURCE_ID = "temp-id-0"; export const DATASOURCE_NAME_DEFAULT_PREFIX = "Untitled Datasource "; export const GOOGLE_SHEET_SPECIFIC_SHEETS_SCOPE = "https://www.googleapis.com/auth/drive.file"; +export const GOOGLE_SHEET_FILE_PICKER_OVERLAY_CLASS = "overlay"; diff --git a/app/client/src/pages/Editor/SaaSEditor/GoogleSheetFilePicker.tsx b/app/client/src/pages/Editor/SaaSEditor/GoogleSheetFilePicker.tsx index 4cfb9c2708fb..e3194c961064 100644 --- a/app/client/src/pages/Editor/SaaSEditor/GoogleSheetFilePicker.tsx +++ b/app/client/src/pages/Editor/SaaSEditor/GoogleSheetFilePicker.tsx @@ -3,6 +3,7 @@ import React, { useState, useEffect } from "react"; import { FilePickerActionStatus } from "entities/Datasource"; import { useDispatch } from "react-redux"; import { filePickerCallbackAction } from "actions/datasourceActions"; +import { GOOGLE_SHEET_FILE_PICKER_OVERLAY_CLASS } from "constants/Datasource"; interface Props { datasourceId: string; @@ -80,6 +81,17 @@ function GoogleSheetFilePicker({ } }, [gsheetToken, scriptLoadedFlag, pickerInitiated, gsheetProjectID]); + // This is added in useEffect instead of file picker callback, + // because in case when browser has blocked third party cookies + // The file picker needs to be displayed with allow cookies option + // hence as soon as file picker is visible we should remove the overlay + // Ref: https://github.com/appsmithorg/appsmith/issues/22753 + useEffect(() => { + if (!!pickerVisible) { + removeClassFromDocumentBody(GOOGLE_SHEET_FILE_PICKER_OVERLAY_CLASS); + } + }, [pickerVisible]); + // This triggers google's picker object from google apis script to create file picker and display it // It takes google sheet token and project id as inputs const createPicker = async (accessToken: string, projectID: string) => { @@ -98,12 +110,7 @@ function GoogleSheetFilePicker({ }; const pickerCallback = async (data: any) => { - if (data.action === FilePickerActionStatus.LOADED) { - // Remove document body overlay as soon as file picker is loaded - // As we are adding overlay for file picker background div - const className = "overlay"; - removeClassFromDocumentBody(className); - } else if ( + if ( data.action === FilePickerActionStatus.CANCEL || data.action === FilePickerActionStatus.PICKED ) { diff --git a/app/client/src/sagas/DatasourcesSagas.ts b/app/client/src/sagas/DatasourcesSagas.ts index 99a4e177a5b5..8664347ebc08 100644 --- a/app/client/src/sagas/DatasourcesSagas.ts +++ b/app/client/src/sagas/DatasourcesSagas.ts @@ -120,6 +120,7 @@ import { } from "RouteBuilder"; import { DATASOURCE_NAME_DEFAULT_PREFIX, + GOOGLE_SHEET_FILE_PICKER_OVERLAY_CLASS, TEMP_DATASOURCE_ID, } from "constants/Datasource"; import { getUntitledDatasourceSequence } from "utils/DatasourceSagaUtils"; @@ -1425,7 +1426,6 @@ function* loadFilePickerSaga() { // This adds overlay on document body // This is done for google sheets file picker, as file picker needs to be shown on blank page // when overlay needs to be shown, we get showPicker search param in redirect url - const className = "overlay"; const appsmithToken = localStorage.getItem(APPSMITH_TOKEN_STORAGE_KEY); const search = new URLSearchParams(window.location.search); const isShowFilePicker = search.get(SHOW_FILE_PICKER_KEY); @@ -1438,7 +1438,7 @@ function* loadFilePickerSaga() { !!appsmithToken && !!gapiScriptLoaded ) { - addClassToDocumentBody(className); + addClassToDocumentBody(GOOGLE_SHEET_FILE_PICKER_OVERLAY_CLASS); } }
d70d6a7426509cd96f06b1ea109f40c5e1d35484
2022-12-22 23:10:56
Ankita Kinger
fix: Updating error message and placeholders for cloud instance (#19113)
false
Updating error message and placeholders for cloud instance (#19113)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts index 138342b75430..5867dc4d844f 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts @@ -14,6 +14,8 @@ describe("Create new workspace and invite user & validate all roles", () => { //localStorage.setItem("WorkspaceName", workspaceId); homePage.CreateNewWorkspace(workspaceId); homePage.CheckWorkspaceShareUsersCount(workspaceId, 1); + homePage.InviteUserToWorkspaceErrorMessage(workspaceId, "abcdef"); + cy.visit("/applications"); homePage.InviteUserToWorkspace( workspaceId, Cypress.env("TESTUSERNAME1"), diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/UpdateWorkspaceTests_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/UpdateWorkspaceTests_spec.js index 77896907f48d..ec859428b956 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/UpdateWorkspaceTests_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/UpdateWorkspaceTests_spec.js @@ -26,7 +26,7 @@ describe("Update Workspace", function() { cy.wait(2000); cy.get(homePage.workspaceHeaderName).should( "have.text", - `Members in ${workspaceId}`, + `${workspaceId}`, ); }); cy.NavigateToHome(); diff --git a/app/client/cypress/support/Pages/HomePage.ts b/app/client/cypress/support/Pages/HomePage.ts index ff9029cfa0f1..9561c16881a1 100644 --- a/app/client/cypress/support/Pages/HomePage.ts +++ b/app/client/cypress/support/Pages/HomePage.ts @@ -25,7 +25,9 @@ export class HomePage { workspaceName + ") button:contains('Share')"; private _email = - "//input[@type='text' and contains(@class,'bp3-input-ghost')]"; + Cypress.env("Edition") === 0 + ? "//input[@type='email' and contains(@class,'bp3-input-ghost')]" + : "//input[@type='text' and contains(@class,'bp3-input-ghost')]"; _visibleTextSpan = (spanText: string) => "//span[text()='" + spanText + "']"; private _userRole = (role: string) => "//div[contains(@class, 'label-container')]//span[1][text()='" + @@ -152,6 +154,26 @@ export class HomePage { cy.contains(successMessage); } + public InviteUserToWorkspaceErrorMessage( + workspaceName: string, + text: string, + ) { + const errorMessage = + Cypress.env("Edition") === 0 + ? "Invalid email address(es) found" + : "Invalid email address(es) or group(s) found"; + this.StubPostHeaderReq(); + this.agHelper.AssertElementVisible(this._workspaceList(workspaceName)); + this.agHelper.GetNClick(this._shareWorkspace(workspaceName), 0, true); + cy.xpath(this._email) + .click({ force: true }) + .type(text); + this.agHelper.ClickButton("Invite"); + cy.contains(text, { matchCase: false }); + cy.contains(errorMessage, { matchCase: false }); + cy.get(".bp3-dialog-close-button").click({ force: true }); + } + public StubPostHeaderReq() { cy.intercept("POST", "/api/v1/users/invite", (req) => { req.headers["origin"] = "Cypress"; diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 2da745937380..0bf36950d715 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -132,7 +132,7 @@ export const PAGE_NOT_FOUND_ERROR = () => export const INVALID_URL_ERROR = () => `Invalid URL`; export const INVITE_USERS_VALIDATION_EMAIL_LIST = () => - `Invalid Email address(es) found`; + `Invalid email address(es) found`; export const INVITE_USERS_VALIDATION_ROLE_EMPTY = () => `Please select a role`; export const INVITE_USERS_EMAIL_LIST_PLACEHOLDER = () => diff --git a/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx b/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx index d8aa3e52a99f..5d1c68f64bf7 100644 --- a/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx +++ b/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx @@ -429,18 +429,8 @@ function WorkspaceInviteUsersForm(props: any) { ); }; - const errorHandler = (error: string, values: string[]) => { - if (values && values.length > 0) { - let error = ""; - values.forEach((user: any) => { - if (!isEmail(user)) { - error = createMessage(INVITE_USERS_VALIDATION_EMAIL_LIST); - } - }); - setEmailError(error); - } else { - props.customError?.(""); - } + const errorHandler = (error: string) => { + setEmailError(error); }; return ( @@ -480,15 +470,13 @@ function WorkspaceInviteUsersForm(props: any) { <div className="wrapper"> <TagListField autofocus - customError={(err: string, values?: string[]) => - errorHandler(err, values || []) - } + customError={(err: string) => errorHandler(err)} data-cy="t--invite-email-input" intent="success" label="Emails" name="users" - placeholder={placeholder || "Enter email address"} - type="text" + placeholder={placeholder || "Enter email address(es)"} + type="email" /> <SelectField allowDeselection={isMultiSelectDropdown} diff --git a/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx b/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx index 915c369942ee..e5a596f643fa 100644 --- a/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx +++ b/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx @@ -20,7 +20,6 @@ const ListItem = styled.div<{ disabled?: boolean }>` img { width: 24pxx; height: 22.5px; - margin-right: ${(props) => props.theme.spaces[3]}px; } `; diff --git a/app/client/src/pages/workspace/SettingsPageHeader.tsx b/app/client/src/pages/workspace/SettingsPageHeader.tsx index cce099ca6436..15e46dd3513a 100644 --- a/app/client/src/pages/workspace/SettingsPageHeader.tsx +++ b/app/client/src/pages/workspace/SettingsPageHeader.tsx @@ -29,6 +29,7 @@ type PageHeaderProps = { pageMenuItems: MenuItemProps[]; title?: string; showMoreOptions?: boolean; + showSearchNButton?: boolean; }; const Container = styled.div<{ isMobile?: boolean }>` @@ -79,6 +80,7 @@ export function SettingsPageHeader(props: PageHeaderProps) { pageMenuItems, searchPlaceholder, showMoreOptions, + showSearchNButton = true, title, } = props; @@ -114,7 +116,7 @@ export function SettingsPageHeader(props: PageHeaderProps) { </HeaderWrapper> <Container isMobile={isMobile}> <SearchWrapper> - {onSearch && ( + {onSearch && showSearchNButton && ( <StyledSearchInput className="search-input" data-testid={"t--search-input"} @@ -127,7 +129,7 @@ export function SettingsPageHeader(props: PageHeaderProps) { </SearchWrapper> {/* <VerticalDelimeter /> */} <ActionsWrapper> - {buttonText && ( + {buttonText && showSearchNButton && ( <StyledButton data-testid={"t--page-header-input"} height="36" diff --git a/app/client/src/pages/workspace/__tests__/settings.test.tsx b/app/client/src/pages/workspace/__tests__/settings.test.tsx index 4d5a1721eb7e..90070d9b86e1 100644 --- a/app/client/src/pages/workspace/__tests__/settings.test.tsx +++ b/app/client/src/pages/workspace/__tests__/settings.test.tsx @@ -182,18 +182,11 @@ describe("<Settings />", () => { renderComponent(); const title = screen.getAllByTestId("t--page-title"); expect(title).toHaveLength(1); - expect(title[0].textContent).toBe(`Members in ${mockWorkspaceData.name}`); + expect(title[0].textContent).toBe(`${mockWorkspaceData.name}`); }); it("displays tabs", () => { renderComponent(); const tabList = screen.getAllByRole("tab"); expect(tabList).toHaveLength(2); }); - it("should search and filter users and usergroups", async () => { - renderComponent(); - const searchInput = screen.getAllByTestId("t--search-input"); - expect(searchInput).toHaveLength(1); - await userEvent.type(searchInput[0], "k"); - expect(searchInput[0]).toHaveValue("k"); - }); }); diff --git a/app/client/src/pages/workspace/settings.tsx b/app/client/src/pages/workspace/settings.tsx index 7e94de024794..c834ae644fb0 100644 --- a/app/client/src/pages/workspace/settings.tsx +++ b/app/client/src/pages/workspace/settings.tsx @@ -106,7 +106,7 @@ export default function Settings() { useEffect(() => { if (currentWorkspace) { - setPageTitle(`Members in ${currentWorkspace?.name}`); + setPageTitle(`${currentWorkspace?.name}`); } }, [currentWorkspace]); @@ -194,6 +194,7 @@ export default function Settings() { pageMenuItems={pageMenuItems} searchPlaceholder="Search" showMoreOptions={false} + showSearchNButton={isMembersPage} title={pageTitle} /> </StyledStickyHeader>
e1bc86b9e9921d663f9b7a868609817cc264aa1b
2022-03-10 14:57:27
f0c1s
fix: remove text area from commit message box (#11342)
false
remove text area from commit message box (#11342)
fix
diff --git a/app/client/src/components/ads/TextInput.tsx b/app/client/src/components/ads/TextInput.tsx index 4758f25e6d48..2aa05b0df512 100644 --- a/app/client/src/components/ads/TextInput.tsx +++ b/app/client/src/components/ads/TextInput.tsx @@ -75,6 +75,7 @@ export type TextInputProps = CommonComponentProps & { $padding?: string; useTextArea?: boolean; isCopy?: boolean; + style?: any; }; type boxReturnType = { @@ -125,7 +126,6 @@ const InputLoader = styled.div<{ : "100%"}; height: ${(props) => props.$height || "36px"}; - border-radius: 0; `; const StyledInput = styled((props) => { @@ -217,7 +217,7 @@ const InputWrapper = styled.div<{ }>` position: relative; display: flex; - align-items: center; + align-items: center; width: ${(props) => props.fill ? "100%" : props.width ? props.width : "260px"}; height: ${(props) => props.height || "36px"}; @@ -241,7 +241,7 @@ const InputWrapper = styled.div<{ .${Classes.TEXT} { color: ${(props) => props.theme.colors.danger.main}; } - ​ .helper { + .helper { .${Classes.TEXT} { color: ${(props) => props.theme.colors.textInput.helper}; } diff --git a/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx b/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx index a35584917cb1..e541d4686924 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx @@ -73,6 +73,7 @@ const SectionTitle = styled.div` ${(props) => getTypographyByKey(props, "p1")}; color: ${Colors.CHARCOAL}; display: inline-flex; + & .branch { color: ${Colors.CRUSTA}; width: 240px; @@ -84,9 +85,11 @@ const SectionTitle = styled.div` const Container = styled.div` width: 100%; + && ${LabelContainer} span { color: ${Colors.CHARCOAL}; } + .bp3-popover-target { width: fit-content; } @@ -220,6 +223,7 @@ function Deploy() { onChange={setCommitMessage} placeholder={"Your commit message here"} ref={commitInputRef} + style={{ resize: "none" }} trimValue={false} useTextArea value={commitMessageDisplay}
345372d49f590299fe3f703d93cb5da3b6f8c3a6
2024-07-18 12:59:50
NandanAnantharamu
test: increased timeout for Sidebar (#35013)
false
increased timeout for Sidebar (#35013)
test
diff --git a/app/client/cypress/support/Pages/IDE/Sidebar.ts b/app/client/cypress/support/Pages/IDE/Sidebar.ts index 58dc4c370b91..00a75a1c7ca6 100644 --- a/app/client/cypress/support/Pages/IDE/Sidebar.ts +++ b/app/client/cypress/support/Pages/IDE/Sidebar.ts @@ -22,7 +22,7 @@ export class Sidebar { ); } - assertVisible(timeout: number = 4000) { + assertVisible(timeout: number = 10000) { cy.get(this.locators.sidebar, { timeout }).should("be.visible"); } }
7615cd0a3f2604531a6bb6e24d3268afd5f7e9c1
2024-11-28 06:58:36
Shrikant Sharat Kandula
chore: Fix start-https when backend isn't set
false
Fix start-https when backend isn't set
chore
diff --git a/app/client/start-https.sh b/app/client/start-https.sh index 82762756db48..50633878cdb5 100755 --- a/app/client/start-https.sh +++ b/app/client/start-https.sh @@ -86,7 +86,7 @@ if [[ ${backend-} == release ]]; then backend=https://release.app.appsmith.com fi -if [[ $backend == https://release.app.appsmith.com ]]; then +if [[ ${backend-} == https://release.app.appsmith.com ]]; then # If running client against release, we get the release's version and set it up, so we don't see version mismatches. APPSMITH_VERSION_ID="$( curl -sS "$backend/info" | grep -Eo '"version": ".+?"' | cut -d\" -f4
110b985f12f8a07eee5dd47c45eccf7abb4ac136
2023-11-17 18:18:34
Abhijeet
chore: Add `LaunchDarkly` configs in CI run to mock feature flags (#28761)
false
Add `LaunchDarkly` configs in CI run to mock feature flags (#28761)
chore
diff --git a/.github/workflows/ci-test-custom-script.yml b/.github/workflows/ci-test-custom-script.yml index 3c2f74149d7f..c009d7bb1df0 100644 --- a/.github/workflows/ci-test-custom-script.yml +++ b/.github/workflows/ci-test-custom-script.yml @@ -186,6 +186,8 @@ jobs: - name: Run Appsmith & TED docker image if: steps.run_result.outputs.run_result != 'success' + env: + LAUNCHDARKLY_BUSINESS_FLAGS_SERVER_KEY: ${{ secrets.LAUNCHDARKLY_BUSINESS_FLAGS_SERVER_KEY }} working-directory: "." run: | sudo /etc/init.d/ssh stop ; @@ -223,6 +225,7 @@ jobs: -e FLAGSMITH_URL=http://host.docker.internal:5001/flagsmith \ -e FLAGSMITH_SERVER_KEY=dummykey \ -e FLAGSMITH_SERVER_KEY_BUSINESS_FEATURES=dummykeybusinessfeatures \ + -e LAUNCHDARKLY_BUSINESS_FLAGS_SERVER_KEY=$LAUNCHDARKLY_BUSINESS_FLAGS_SERVER_KEY \ appsmith/cloud-services:release cd cicontainerlocal docker run -d --name appsmith -p 80:80 -p 9001:9001 \
99b03f2fa00daea98f163ba89e4fe9e0680ef212
2023-03-22 11:40:27
subratadeypappu
fix: Don't disclose sensitive info in case of DuplicateKeyException (#21568) (#21596)
false
Don't disclose sensitive info in case of DuplicateKeyException (#21568) (#21596)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java index 5b3760533f9d..4530dad46481 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java @@ -69,7 +69,7 @@ public enum AppsmithError { JSON_PROCESSING_ERROR(400, AppsmithErrorCode.JSON_PROCESSING_ERROR.getCode(), "Json processing error with error {0}", AppsmithErrorAction.LOG_EXTERNALLY, "Json processing error", ErrorType.INTERNAL_ERROR, null), INVALID_CREDENTIALS(200, AppsmithErrorCode.INVALID_CREDENTIALS.getCode(), "Invalid credentials provided. Did you input the credentials correctly?", AppsmithErrorAction.DEFAULT, "Invalid credentials", ErrorType.AUTHENTICATION_ERROR, null), UNAUTHORIZED_ACCESS(403, AppsmithErrorCode.UNAUTHORIZED_ACCESS.getCode(), "Unauthorized access", AppsmithErrorAction.DEFAULT, "Unauthorized access", ErrorType.AUTHENTICATION_ERROR, null), - DUPLICATE_KEY(409, AppsmithErrorCode.DUPLICATE_KEY.getCode(), "Unexpected state: Duplicate key error. Message: {0}. Please reach out to Appsmith customer support to report this", + DUPLICATE_KEY(409, AppsmithErrorCode.DUPLICATE_KEY.getCode(), "Duplicate key error: An object with the name {0} already exists. Please use a different name or reach out to Appsmith customer support to resolve this.", AppsmithErrorAction.DEFAULT, "Duplicate key", ErrorType.BAD_REQUEST, null), USER_ALREADY_EXISTS_SIGNUP(409, AppsmithErrorCode.USER_ALREADY_EXISTS_SIGNUP.getCode(), "There is already an account registered with this email {0}. Please sign in instead.", AppsmithErrorAction.DEFAULT, "Account already exists with this email", ErrorType.BAD_REQUEST, null), diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java index eb2e202db189..0ff965261c28 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java @@ -5,6 +5,7 @@ import com.appsmith.external.exceptions.ErrorDTO; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.server.dtos.ResponseDTO; +import com.appsmith.server.exceptions.util.DuplicateKeyExceptionUtils; import com.appsmith.server.helpers.RedisUtils; import io.micrometer.core.instrument.util.StringUtils; import com.appsmith.server.filters.MDCFilter; @@ -116,8 +117,9 @@ public Mono<ResponseDTO<ErrorDTO>> catchDuplicateKeyException(org.springframewor doLog(e); String urlPath = exchange.getRequest().getPath().toString(); + String conflictingObjectName = DuplicateKeyExceptionUtils.extractConflictingObjectName(e.getCause().getMessage()); ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), appsmithError.getErrorType(), - appsmithError.getMessage(e.getCause().getMessage()), appsmithError.getTitle())); + appsmithError.getMessage(conflictingObjectName), appsmithError.getTitle())); return getResponseDTOMono(urlPath, response); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/DuplicateKeyExceptionUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/DuplicateKeyExceptionUtils.java new file mode 100644 index 000000000000..b4516c3b58e9 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/DuplicateKeyExceptionUtils.java @@ -0,0 +1,25 @@ +package com.appsmith.server.exceptions.util; + +import lombok.extern.slf4j.Slf4j; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Slf4j +public class DuplicateKeyExceptionUtils { + private final static Pattern pattern = Pattern.compile("dup key: \\{ .*:(.*)}'"); + + public static String extractConflictingObjectName(String duplicateKeyErrorMessage) { + Matcher matcher = pattern.matcher(duplicateKeyErrorMessage); + if (matcher.find()) { + return matcher.group(1).trim(); + } + log.warn("DuplicateKeyException regex needs attention. It's unable to extract object name from the error message. Possible reason: the underlying library may have changed the format of the error message."); + /* + [Fallback strategy] + AppsmithError.DUPLICATE_KEY has a placeholder where it expects the name of the object that conflicts with the existing names. + In case the execution reaches here we don't want to render `null` rather the string returned as below will yet make the message look good. + */ + return "that you provided"; + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java index 5769872adf59..d4047fa9513d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java @@ -194,7 +194,7 @@ public Mono<UpdateResult> addPageToApplication(Application application, PageDTO } }); } else { - return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY, "Page already exists with id " + page.getId())); + return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY, page.getId())); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCEImpl.java index 0d2ee1ad58d6..a63cfd5b1fe3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCEImpl.java @@ -26,6 +26,7 @@ import com.appsmith.server.dtos.GitDeployKeyDTO; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.exceptions.util.DuplicateKeyExceptionUtils; import com.appsmith.server.helpers.GitDeployKeyGenerator; import com.appsmith.server.helpers.PolicyUtils; import com.appsmith.server.helpers.ResponseUtils; @@ -263,7 +264,7 @@ public Mono<Application> update(String id, Application application) { new AppsmithException(AppsmithError.DUPLICATE_KEY_USER_ERROR, FieldName.APPLICATION, FieldName.NAME) ); } - return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY, error.getCause().getMessage())); + return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY, DuplicateKeyExceptionUtils.extractConflictingObjectName(((DuplicateKeyException) error).getCause().getMessage()))); } return Mono.error(error); }) diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/AppsmithErrorTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/AppsmithErrorTest.java index a743c94abaaa..e5bfde46360b 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/AppsmithErrorTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/AppsmithErrorTest.java @@ -1,14 +1,34 @@ package com.appsmith.server.helpers; import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.exceptions.util.DuplicateKeyExceptionUtils; import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; import java.util.Arrays; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class AppsmithErrorTest { @Test public void verifyUniquenessOfAppsmithErrorCode() { assert (Arrays.stream(AppsmithError.values()).map(AppsmithError::getAppErrorCode).distinct().count() == AppsmithError.values().length); + } + + @Test + public void verifyDuplicateKeyExceptionDoesnotDiscloseSensitiveInformation() { + //Context: https://github.com/appsmithorg/appsmith/issues/21568 + final DuplicateKeyException exception = assertThrows( + DuplicateKeyException.class, + () -> generateDuplicateKeyException()); + + AppsmithError appsmithError = AppsmithError.DUPLICATE_KEY; + assertEquals(appsmithError.getMessage("\\\"MyJSObject\\\""), appsmithError.getMessage(DuplicateKeyExceptionUtils.extractConflictingObjectName(exception.getMessage()))); + } + private void generateDuplicateKeyException() { + String originalErrorMessage = "Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: appsmith.actionCollection index: unpublishedCollection.name_1 dup key: { unpublishedCollection.name: \\\"MyJSObject\\\" }', details={}}."; + throw new DuplicateKeyException(originalErrorMessage); } }
e37f7419b9f19c2310f7ff96578327a3d5289c18
2022-12-07 15:58:29
Favour Ohanekwu
fix: Aggregate calls to add and remove Appsmith errors (#18285)
false
Aggregate calls to add and remove Appsmith errors (#18285)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Button/ButtonLintErrorValidation_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Button/ButtonLintErrorValidation_spec.js index c96a1a01cbfb..efd12627be6c 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Button/ButtonLintErrorValidation_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Button/ButtonLintErrorValidation_spec.js @@ -52,12 +52,6 @@ describe("Linting warning validation with button widget", function() { .should("be.visible") .click({ force: true }); - cy.get(commonlocators.debugErrorMsg) - .eq(0) - .contains("ReferenceError: Nodata is not defined"); - - cy.get(commonlocators.debugErrorMsg) - .eq(2) - .contains("ReferenceError: lintError is not defined"); + cy.get(commonlocators.debugErrorMsg).should("have.length", 3); }); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/ListWidgetLintErrorValidation.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/ListWidgetLintErrorValidation.js index 2a10590cf0d0..ae54d4bb027c 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/ListWidgetLintErrorValidation.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/ListWidgetLintErrorValidation.js @@ -52,12 +52,6 @@ describe("Linting warning validation with list widget", function() { .should("be.visible") .click({ force: true }); - cy.get(commonlocators.debugErrorMsg) - .eq(0) - .contains("ReferenceError: ERROR is not defined"); - - cy.get(commonlocators.debugErrorMsg) - .eq(1) - .contains("SyntaxError: Unexpected identifier"); + cy.get(commonlocators.debugErrorMsg).should("have.length", 6); }); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Text/TextWidget_LintErrorValidation_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Text/TextWidget_LintErrorValidation_spec.js index be7604831551..a3287e60deef 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Text/TextWidget_LintErrorValidation_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Text/TextWidget_LintErrorValidation_spec.js @@ -53,12 +53,6 @@ describe("Linting warning validation with text widget", function() { .should("be.visible") .click({ force: true }); - cy.get(commonlocators.debugErrorMsg) - .eq(0) - .contains("ReferenceError: error is not defined"); - - cy.get(commonlocators.debugErrorMsg) - .eq(1) - .contains("ReferenceError: lintErrror is not defined"); + cy.get(commonlocators.debugErrorMsg).should("have.length", 3); }); }); diff --git a/app/client/src/actions/debuggerActions.ts b/app/client/src/actions/debuggerActions.ts index 4c634a2996fb..8a0402790337 100644 --- a/app/client/src/actions/debuggerActions.ts +++ b/app/client/src/actions/debuggerActions.ts @@ -15,7 +15,7 @@ export interface LogDebuggerErrorAnalyticsPayload { analytics?: Log["analytics"]; } -export const debuggerLogInit = (payload: Log) => ({ +export const debuggerLogInit = (payload: Log[]) => ({ type: ReduxActionTypes.DEBUGGER_LOG_INIT, payload, }); @@ -35,30 +35,26 @@ export const showDebugger = (payload?: boolean) => ({ }); // Add an error -export const addErrorLogInit = (payload: Log) => ({ +export const addErrorLogInit = (payload: Log[]) => ({ type: ReduxActionTypes.DEBUGGER_ADD_ERROR_LOG_INIT, payload, }); -export const addErrorLog = (payload: Log) => ({ - type: ReduxActionTypes.DEBUGGER_ADD_ERROR_LOG, +export const addErrorLogs = (payload: Log[]) => ({ + type: ReduxActionTypes.DEBUGGER_ADD_ERROR_LOGS, payload, }); -export const deleteErrorLogInit = ( - id: string, - analytics?: Log["analytics"], +export const deleteErrorLogsInit = ( + payload: { id: string; analytics?: Log["analytics"] }[], ) => ({ type: ReduxActionTypes.DEBUGGER_DELETE_ERROR_LOG_INIT, - payload: { - id, - analytics, - }, + payload, }); -export const deleteErrorLog = (id: string) => ({ +export const deleteErrorLog = (ids: string[]) => ({ type: ReduxActionTypes.DEBUGGER_DELETE_ERROR_LOG, - payload: id, + payload: ids, }); // Only used for analytics diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index a434eeeddc9f..33bfad601aeb 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -160,7 +160,7 @@ export const ReduxActionTypes = { DEBUGGER_LOG: "DEBUGGER_LOG", DEBUGGER_LOG_INIT: "DEBUGGER_LOG_INIT", DEBUGGER_ERROR_ANALYTICS: "DEBUGGER_ERROR_ANALYTICS", - DEBUGGER_ADD_ERROR_LOG: "DEBUGGER_ADD_ERROR_LOG", + DEBUGGER_ADD_ERROR_LOGS: "DEBUGGER_ADD_ERROR_LOGS", DEBUGGER_DELETE_ERROR_LOG: "DEBUGGER_DELETE_ERROR_LOG", DEBUGGER_ADD_ERROR_LOG_INIT: "DEBUGGER_ADD_ERROR_LOG_INIT", DEBUGGER_DELETE_ERROR_LOG_INIT: "DEBUGGER_DELETE_ERROR_LOG_INIT", diff --git a/app/client/src/reducers/uiReducers/debuggerReducer.ts b/app/client/src/reducers/uiReducers/debuggerReducer.ts index ef8a2e7ce201..62835d9717ad 100644 --- a/app/client/src/reducers/uiReducers/debuggerReducer.ts +++ b/app/client/src/reducers/uiReducers/debuggerReducer.ts @@ -4,7 +4,7 @@ import { ReduxAction, ReduxActionTypes, } from "@appsmith/constants/ReduxActionConstants"; -import { omit, isUndefined } from "lodash"; +import { omit, isUndefined, isEmpty } from "lodash"; import equal from "fast-deep-equal"; const initialState: DebuggerReduxState = { @@ -61,23 +61,33 @@ const debuggerReducer = createImmerReducer(initialState, { ) => { state.isOpen = isUndefined(action.payload) ? !state.isOpen : action.payload; }, - [ReduxActionTypes.DEBUGGER_ADD_ERROR_LOG]: ( + [ReduxActionTypes.DEBUGGER_ADD_ERROR_LOGS]: ( state: DebuggerReduxState, - action: ReduxAction<Log>, + action: ReduxAction<Log[]>, ) => { - if (!action.payload.id) return state; + const { payload } = action; + // Remove Logs without IDs + const validDebuggerErrors = payload.reduce((validLogs, currentLog) => { + if (!currentLog.id) return validLogs; + return { + ...validLogs, + [currentLog.id]: currentLog, + }; + }, {}); + + if (isEmpty(validDebuggerErrors)) return state; // Moving recent update to the top of the error list - const errors = omit(state.errors, action.payload.id); + const errors = omit(state.errors, Object.keys(validDebuggerErrors)); state.errors = { - [action.payload.id]: action.payload, + ...validDebuggerErrors, ...errors, }; }, [ReduxActionTypes.DEBUGGER_DELETE_ERROR_LOG]: ( state: DebuggerReduxState, - action: ReduxAction<string>, + action: ReduxAction<string[]>, ) => { state.errors = omit(state.errors, action.payload); }, diff --git a/app/client/src/sagas/ActionExecution/ActionExecutionSagas.ts b/app/client/src/sagas/ActionExecution/ActionExecutionSagas.ts index b519a6592a90..ebff28437ffe 100644 --- a/app/client/src/sagas/ActionExecution/ActionExecutionSagas.ts +++ b/app/client/src/sagas/ActionExecution/ActionExecutionSagas.ts @@ -193,7 +193,9 @@ function* initiateActionTriggerExecution( const { event, source, triggerPropertyName } = action.payload; // Clear all error for this action trigger. In case the error still exists, // it will be created again while execution - AppsmithConsole.deleteError(`${source?.id}-${triggerPropertyName}`); + AppsmithConsole.deleteErrors([ + { id: `${source?.id}-${triggerPropertyName}` }, + ]); try { yield call(executeAppAction, action.payload); if (event.callback) { diff --git a/app/client/src/sagas/ActionExecution/PluginActionSaga.ts b/app/client/src/sagas/ActionExecution/PluginActionSaga.ts index bf688a96a81b..f6eb50ae7a5f 100644 --- a/app/client/src/sagas/ActionExecution/PluginActionSaga.ts +++ b/app/client/src/sagas/ActionExecution/PluginActionSaga.ts @@ -384,28 +384,32 @@ export default function* executePluginActionTriggerSaga( const { isError, payload } = executePluginActionResponse; if (isError) { - AppsmithConsole.addError({ - id: actionId, - logType: LOG_TYPE.ACTION_EXECUTION_ERROR, - text: `Execution failed with status ${payload.statusCode}`, - source: { - type: ENTITY_TYPE.ACTION, - name: action.name, - id: actionId, - }, - state: payload.request, - messages: [ - { - // Need to stringify cause this gets rendered directly - // and rendering objects can crash the app - message: !isString(payload.body) - ? JSON.stringify(payload.body) - : payload.body, - type: PLATFORM_ERROR.PLUGIN_EXECUTION, - subType: payload.errorType, + AppsmithConsole.addErrors([ + { + payload: { + id: actionId, + logType: LOG_TYPE.ACTION_EXECUTION_ERROR, + text: `Execution failed with status ${payload.statusCode}`, + source: { + type: ENTITY_TYPE.ACTION, + name: action.name, + id: actionId, + }, + state: payload.request, + messages: [ + { + // Need to stringify cause this gets rendered directly + // and rendering objects can crash the app + message: !isString(payload.body) + ? JSON.stringify(payload.body) + : payload.body, + type: PLATFORM_ERROR.PLUGIN_EXECUTION, + subType: payload.errorType, + }, + ], }, - ], - }); + }, + ]); if (onError) { yield call(executeAppAction, { event: { type: eventType }, @@ -627,20 +631,24 @@ function* runActionSaga( }); } - AppsmithConsole.addError({ - id: actionId, - logType: LOG_TYPE.ACTION_EXECUTION_ERROR, - text: `Execution failed${ - payload.statusCode ? ` with status ${payload.statusCode}` : "" - }`, - source: { - type: ENTITY_TYPE.ACTION, - name: actionObject.name, - id: actionId, + AppsmithConsole.addErrors([ + { + payload: { + id: actionId, + logType: LOG_TYPE.ACTION_EXECUTION_ERROR, + text: `Execution failed${ + payload.statusCode ? ` with status ${payload.statusCode}` : "" + }`, + source: { + type: ENTITY_TYPE.ACTION, + name: actionObject.name, + id: actionId, + }, + messages: appsmithConsoleErrorMessageList, + state: payload.request, + }, }, - messages: appsmithConsoleErrorMessageList, - state: payload.request, - }); + ]); Toaster.show({ text: createMessage(ERROR_ACTION_EXECUTE_FAIL, actionObject.name), @@ -782,24 +790,28 @@ function* executePageLoadAction(pageAction: PageAction) { } if (isError) { - AppsmithConsole.addError({ - id: pageAction.id, - logType: LOG_TYPE.ACTION_EXECUTION_ERROR, - text: `Execution failed with status ${payload.statusCode}`, - source: { - type: ENTITY_TYPE.ACTION, - name: pageAction.name, - id: pageAction.id, - }, - state: payload.request, - messages: [ - { - message: error, - type: PLATFORM_ERROR.PLUGIN_EXECUTION, - subType: payload.errorType, + AppsmithConsole.addErrors([ + { + payload: { + id: pageAction.id, + logType: LOG_TYPE.ACTION_EXECUTION_ERROR, + text: `Execution failed with status ${payload.statusCode}`, + source: { + type: ENTITY_TYPE.ACTION, + name: pageAction.name, + id: pageAction.id, + }, + state: payload.request, + messages: [ + { + message: error, + type: PLATFORM_ERROR.PLUGIN_EXECUTION, + subType: payload.errorType, + }, + ], }, - ], - }); + }, + ]); yield put( executePluginActionError({ diff --git a/app/client/src/sagas/ActionExecution/errorUtils.ts b/app/client/src/sagas/ActionExecution/errorUtils.ts index 484825582f12..c6c4127ccd1d 100644 --- a/app/client/src/sagas/ActionExecution/errorUtils.ts +++ b/app/client/src/sagas/ActionExecution/errorUtils.ts @@ -65,23 +65,27 @@ export const logActionExecutionError = ( errorType?: PropertyEvaluationErrorType, ) => { if (triggerPropertyName) { - AppsmithConsole.addError({ - id: `${source?.id}-${triggerPropertyName}`, - logType: LOG_TYPE.TRIGGER_EVAL_ERROR, - text: createMessage(DEBUGGER_TRIGGER_ERROR, triggerPropertyName), - source: { - type: ENTITY_TYPE.WIDGET, - id: source?.id ?? "", - name: source?.name ?? "", - propertyPath: triggerPropertyName, - }, - messages: [ - { - type: errorType, - message: errorMessage, + AppsmithConsole.addErrors([ + { + payload: { + id: `${source?.id}-${triggerPropertyName}`, + logType: LOG_TYPE.TRIGGER_EVAL_ERROR, + text: createMessage(DEBUGGER_TRIGGER_ERROR, triggerPropertyName), + source: { + type: ENTITY_TYPE.WIDGET, + id: source?.id ?? "", + name: source?.name ?? "", + propertyPath: triggerPropertyName, + }, + messages: [ + { + type: errorType, + message: errorMessage, + }, + ], }, - ], - }); + }, + ]); } Toaster.show({ diff --git a/app/client/src/sagas/DebuggerSagas.ts b/app/client/src/sagas/DebuggerSagas.ts index 4bf7781fb819..996150267cb3 100644 --- a/app/client/src/sagas/DebuggerSagas.ts +++ b/app/client/src/sagas/DebuggerSagas.ts @@ -1,5 +1,5 @@ import { - addErrorLog, + addErrorLogs, debuggerLog, debuggerLogInit, deleteErrorLog, @@ -25,7 +25,7 @@ import { take, takeEvery, } from "redux-saga/effects"; -import { findIndex, get, isMatch, set } from "lodash"; +import { findIndex, flatten, get, isEmpty, isMatch, set } from "lodash"; import { getDebuggerErrors } from "selectors/debuggerSelectors"; import { getAction, @@ -116,160 +116,260 @@ function* formatActionRequestSaga( } } -function* onEntityDeleteSaga(payload: Log) { - const source = payload.source; - - if (!source) { - yield put(debuggerLog([payload])); - return; +function* onEntityDeleteSaga(payload: Log[]) { + const sortedLogs = payload.reduce( + ( + sortedLogs: { + withSource: Log[]; + withoutSource: Log[]; + }, + log, + ) => { + return log.source + ? { ...sortedLogs, withSource: [...sortedLogs.withSource, log] } + : { ...sortedLogs, withSource: [...sortedLogs.withoutSource, log] }; + }, + { + withSource: [], + withoutSource: [], + }, + ); + if (!isEmpty(sortedLogs.withoutSource)) { + yield put(debuggerLog(sortedLogs.withoutSource)); } + if (isEmpty(sortedLogs.withSource)) return; const errors: Record<string, Log> = yield select(getDebuggerErrors); const errorIds = Object.keys(errors); + const logSourceIds = sortedLogs.withSource.map((log) => log.source?.id); + + const errorsToDelete = errorIds.reduce((errorList: Log[], currentId) => { + const isPresent = logSourceIds.some((id) => id && currentId.includes(id)); + return isPresent ? [...errorList, errors[currentId]] : errorList; + }, []); - errorIds.map((e) => { - const includes = e.includes(source.id); + sortedLogs.withSource.filter( + (log) => log.source && errorIds.includes(log.source.id), + ); + + if (!isEmpty(errorsToDelete)) { + const errorPayload = errorsToDelete.map((log) => ({ + id: log.id as string, + analytics: log.analytics, + })); + AppsmithConsole.deleteErrors(errorPayload); + } + yield put(debuggerLog(sortedLogs.withSource)); +} + +function getLogsFromDependencyChain( + dependencyChain: string[], + payload: Log, + dataTree: DataTree, +) { + return dependencyChain.map((path) => { + const entityInfo = getEntityNameAndPropertyPath(path); + const entity = dataTree[entityInfo.entityName]; + let log = { + ...payload, + state: { + [entityInfo.propertyPath]: get(dataTree, path), + }, + }; - if (includes) { - AppsmithConsole.deleteError(e, payload.analytics); + if (isAction(entity)) { + log = { + ...log, + text: createMessage(ACTION_CONFIGURATION_UPDATED), + source: { + type: ENTITY_TYPE.ACTION, + name: entityInfo.entityName, + id: entity.actionId, + }, + }; + } else if (isWidget(entity)) { + log = { + ...log, + text: createMessage(WIDGET_PROPERTIES_UPDATED), + source: { + type: ENTITY_TYPE.WIDGET, + name: entityInfo.entityName, + id: entity.widgetId, + }, + }; } - }); - yield put(debuggerLog([payload])); + return log; + }); } -function* logDependentEntityProperties(payload: Log) { - const { source, state } = payload; - if (!state || !source) return; +function* logDependentEntityProperties(payload: Log[]) { + const validLogs = payload.filter((log) => log.state && log.source); + if (isEmpty(validLogs)) return; yield take(ReduxActionTypes.SET_EVALUATED_TREE); const dataTree: DataTree = yield select(getDataTree); - - const propertyPath = `${source.name}.` + payload.source?.propertyPath; const inverseDependencyMap: DependencyMap = yield select( getEvaluationInverseDependencyMap, ); - const finalValue = getDependencyChain(propertyPath, inverseDependencyMap); - //logging them all at once rather than updating them individually - yield put( - debuggerLog( - finalValue.map((path) => { - const entityInfo = getEntityNameAndPropertyPath(path); - const entity = dataTree[entityInfo.entityName]; - let log = { - ...payload, - state: { - [entityInfo.propertyPath]: get(dataTree, path), - }, - }; + const finalPayload: Log[][] = []; - if (isAction(entity)) { - log = { - ...log, - text: createMessage(ACTION_CONFIGURATION_UPDATED), - source: { - type: ENTITY_TYPE.ACTION, - name: entityInfo.entityName, - id: entity.actionId, - }, - }; - } else if (isWidget(entity)) { - log = { - ...log, - text: createMessage(WIDGET_PROPERTIES_UPDATED), - source: { - type: ENTITY_TYPE.WIDGET, - name: entityInfo.entityName, - id: entity.widgetId, - }, - }; - } + for (const log of validLogs) { + const propertyPath = `${log.source?.name}.` + log.source?.propertyPath; + const dependencyChain = getDependencyChain( + propertyPath, + inverseDependencyMap, + ); + const payloadValue = getLogsFromDependencyChain( + dependencyChain, + log, + dataTree, + ); + finalPayload.push(payloadValue); + } - return log; - }), - ), - ); + //logging them all at once rather than updating them individually + yield put(debuggerLog(flatten(finalPayload))); } -function* onTriggerPropertyUpdates(payload: Log) { +function* onTriggerPropertyUpdates(payload: Log[]) { const dataTree: DataTree = yield select(getDataTree); - const source = payload.source; - - if (!source || !source.propertyPath) return; - const widget = dataTree[source.name]; - // If property is not a trigger property we ignore - if (!isWidget(widget) || !(source.propertyPath in widget.triggerPaths)) - return; - // If the value of the property is empty(or set to 'No Action') - if (widget[source.propertyPath] === "") { - AppsmithConsole.deleteError(`${source.id}-${source.propertyPath}`); + const validLogs = payload.filter( + (log) => log.source && log.source.propertyPath, + ); + if (isEmpty(validLogs)) return; + + const errorsPathsToDeleteFromConsole = new Set<string>(); + + for (const log of validLogs) { + const { source } = log; + if (!source || !source.propertyPath) continue; + const widget = dataTree[source.name]; + // If property is not a trigger property we ignore + if (!isWidget(widget) || !(source.propertyPath in widget.triggerPaths)) + return false; + // If the value of the property is empty(or set to 'No Action') + if (widget[source.propertyPath] === "") { + errorsPathsToDeleteFromConsole.add(`${source.id}-${source.propertyPath}`); + } } + const errorIdsToDelete = Array.from( + errorsPathsToDeleteFromConsole, + ).map((path) => ({ id: path })); + AppsmithConsole.deleteErrors(errorIdsToDelete); } -function* debuggerLogSaga(action: ReduxAction<Log>) { - const { payload } = action; - - switch (payload.logType) { - case LOG_TYPE.WIDGET_UPDATE: - yield put(debuggerLog([payload])); - yield call(logDependentEntityProperties, payload); - yield call(onTriggerPropertyUpdates, payload); - return; - case LOG_TYPE.ACTION_UPDATE: - yield put(debuggerLog([payload])); - yield call(logDependentEntityProperties, payload); - return; - case LOG_TYPE.JS_ACTION_UPDATE: - yield put(debuggerLog([payload])); - return; - case LOG_TYPE.JS_PARSE_ERROR: - yield put(addErrorLog(payload)); - break; - case LOG_TYPE.JS_PARSE_SUCCESS: - AppsmithConsole.deleteError(payload.source?.id ?? ""); - break; - // @ts-expect-error: Types are not available - case LOG_TYPE.TRIGGER_EVAL_ERROR: - yield put(debuggerLog([payload])); - case LOG_TYPE.EVAL_ERROR: - case LOG_TYPE.LINT_ERROR: - case LOG_TYPE.EVAL_WARNING: - case LOG_TYPE.WIDGET_PROPERTY_VALIDATION_ERROR: - if (payload.source && payload.source.propertyPath) { - if (payload.text) { - yield put(addErrorLog(payload)); - } +function* debuggerLogSaga(action: ReduxAction<Log[]>) { + const { payload: logs } = action; + // array of logs without LOG_TYPE and logs which are not handled in switch statement below. + let otherLogs: Log[] = []; + + // Group logs by LOG_TYPE + const sortedLogs = logs.reduce( + (sortedLogs: Record<string, Log[]>, currentLog: Log) => { + if (currentLog.logType) { + return sortedLogs.hasOwnProperty(currentLog.logType) + ? { + ...sortedLogs, + [currentLog.logType]: [ + ...sortedLogs[currentLog.logType], + currentLog, + ], + } + : { + ...sortedLogs, + [currentLog.logType]: [currentLog], + }; + } else { + otherLogs.push(currentLog); + return sortedLogs; } - break; - case LOG_TYPE.ACTION_EXECUTION_ERROR: - { - const formattedLog: Log = yield call( - formatActionRequestSaga, - payload, - "state", - ); - yield put(addErrorLog(formattedLog)); - yield put(debuggerLog([formattedLog])); + }, + {}, + ); + for (const item in sortedLogs) { + const logType = Number(item); + const payload = sortedLogs[item]; + switch (logType) { + case LOG_TYPE.WIDGET_UPDATE: + yield put(debuggerLog(payload)); + yield call(logDependentEntityProperties, payload); + yield call(onTriggerPropertyUpdates, payload); + return; + case LOG_TYPE.ACTION_UPDATE: + yield put(debuggerLog(payload)); + yield call(logDependentEntityProperties, payload); + return; + case LOG_TYPE.JS_ACTION_UPDATE: + yield put(debuggerLog(payload)); + return; + case LOG_TYPE.JS_PARSE_ERROR: + yield put(addErrorLogs(payload)); + break; + case LOG_TYPE.JS_PARSE_SUCCESS: { + const errorIds = payload.map((log) => ({ id: log.source?.id ?? "" })); + AppsmithConsole.deleteErrors(errorIds); + break; } - break; - case LOG_TYPE.ACTION_EXECUTION_SUCCESS: - { - const formattedLog: Log = yield call( - formatActionRequestSaga, - payload, - "state.request", + // @ts-expect-error: Types are not available + case LOG_TYPE.TRIGGER_EVAL_ERROR: + yield put(debuggerLog(payload)); + case LOG_TYPE.EVAL_ERROR: + case LOG_TYPE.LINT_ERROR: + case LOG_TYPE.EVAL_WARNING: + case LOG_TYPE.WIDGET_PROPERTY_VALIDATION_ERROR: { + const filteredLogs = payload.filter( + (log) => log.source && log.source.propertyPath && log.text, ); - - AppsmithConsole.deleteError(payload.source?.id ?? ""); - - yield put(debuggerLog([formattedLog])); + yield put(addErrorLogs(filteredLogs)); + break; } - break; - case LOG_TYPE.ENTITY_DELETED: - yield fork(onEntityDeleteSaga, payload); - break; - default: - yield put(debuggerLog([payload])); + + case LOG_TYPE.ACTION_EXECUTION_ERROR: + { + const allFormatedLogs: Log[] = []; + + for (const log of payload) { + const formattedLog: Log = yield call( + formatActionRequestSaga, + log, + "state", + ); + allFormatedLogs.push(formattedLog); + } + yield put(addErrorLogs(allFormatedLogs)); + yield put(debuggerLog(allFormatedLogs)); + } + break; + case LOG_TYPE.ACTION_EXECUTION_SUCCESS: + { + const allFormatedLogs: Log[] = []; + + for (const log of payload) { + const formattedLog: Log = yield call( + formatActionRequestSaga, + log, + "state.request", + ); + allFormatedLogs.push(formattedLog); + } + const payloadIds = payload.map((log) => ({ + id: log.source?.id ?? "", + })); + AppsmithConsole.deleteErrors(payloadIds); + + yield put(debuggerLog(allFormatedLogs)); + } + break; + case LOG_TYPE.ENTITY_DELETED: + yield fork(onEntityDeleteSaga, payload); + break; + default: + otherLogs = otherLogs.concat(payload); + } + } + if (!isEmpty(otherLogs)) { + yield put(debuggerLog(otherLogs)); } } @@ -344,152 +444,169 @@ function* logDebuggerErrorAnalyticsSaga( } } -function* addDebuggerErrorLogSaga(action: ReduxAction<Log>) { - const payload = action.payload; - const errors: Record<string, Log> = yield select(getDebuggerErrors); +function* addDebuggerErrorLogsSaga(action: ReduxAction<Log[]>) { + const errorLogs = action.payload; + const currentDebuggerErrors: Record<string, Log> = yield select( + getDebuggerErrors, + ); + yield put(debuggerLogInit(errorLogs)); + const validErrorLogs = errorLogs.filter((log) => log.source && log.id); + if (isEmpty(validErrorLogs)) return; + + for (const errorLog of validErrorLogs) { + const { id, messages, source } = errorLog; + if (!source || !id) continue; + const analyticsPayload = { + entityName: source.name, + entityType: source.type, + entityId: source.id, + propertyPath: source.propertyPath ?? "", + }; + + // If this is a new error + if (!currentDebuggerErrors.hasOwnProperty(id)) { + const errorMessages = errorLog.messages ?? []; + + yield put({ + type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, + payload: { + ...analyticsPayload, + eventName: "DEBUGGER_NEW_ERROR", + errorMessages, + }, + }); - if (!payload.source || !payload.id) return; + // Log analytics for new error messages + if (errorMessages.length && errorLog) { + yield all( + errorMessages.map((errorMessage) => + put({ + type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, + payload: { + ...analyticsPayload, + eventName: "DEBUGGER_NEW_ERROR_MESSAGE", + errorMessage: errorMessage.message, + errorType: errorMessage.type, + errorSubType: errorMessage.subType, + }, + }), + ), + ); + } + } else { + const updatedErrorMessages = messages ?? []; + const existingErrorMessages = currentDebuggerErrors[id].messages ?? []; + // Log new error messages + yield all( + updatedErrorMessages.map((updatedErrorMessage) => { + const exists = findIndex( + existingErrorMessages, + (existingErrorMessage) => { + return isMatch(existingErrorMessage, updatedErrorMessage); + }, + ); + + if (exists < 0) { + return put({ + type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, + payload: { + ...analyticsPayload, + eventName: "DEBUGGER_NEW_ERROR_MESSAGE", + errorMessage: updatedErrorMessage.message, + errorType: updatedErrorMessage.type, + errorSubType: updatedErrorMessage.subType, + }, + }); + } + }), + ); + // Log resolved error messages + yield all( + existingErrorMessages.map((existingErrorMessage) => { + const exists = findIndex( + updatedErrorMessages, + (updatedErrorMessage) => { + return isMatch(updatedErrorMessage, existingErrorMessage); + }, + ); + + if (exists < 0) { + return put({ + type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, + payload: { + ...analyticsPayload, + eventName: "DEBUGGER_RESOLVED_ERROR_MESSAGE", + errorMessage: existingErrorMessage.message, + errorType: existingErrorMessage.type, + errorSubType: existingErrorMessage.subType, + }, + }); + } + }), + ); + } + } +} + +function* deleteDebuggerErrorLogsSaga( + action: ReduxAction<{ id: string; analytics: Log["analytics"] }[]>, +) { + const { payload } = action; + const currentDebuggerErrors: Record<string, Log> = yield select( + getDebuggerErrors, + ); + const existingErrorPayloads = payload.filter((item) => + currentDebuggerErrors.hasOwnProperty(item.id), + ); + if (isEmpty(existingErrorPayloads)) return; - yield put(debuggerLogInit(payload)); + const validErrorPayloadsToDelete = existingErrorPayloads.filter((payload) => { + const existingError = currentDebuggerErrors[payload.id]; + return existingError && existingError.source; + }); - const analyticsPayload = { - entityName: payload.source.name, - entityType: payload.source.type, - entityId: payload.source.id, - propertyPath: payload.source.propertyPath ?? "", - }; + if (isEmpty(validErrorPayloadsToDelete)) return; - // If this is a new error - if (!(payload.id in errors)) { - const errorMessages = payload.messages ?? []; + for (const validErrorPayload of validErrorPayloadsToDelete) { + const error = currentDebuggerErrors[validErrorPayload.id]; + if (!error || !error.source) continue; + const analyticsPayload = { + entityName: error.source.name, + entityType: error.source.type, + entityId: error.source.id, + propertyPath: error.source.propertyPath ?? "", + analytics: validErrorPayload.analytics, + }; + const errorMessages = error.messages; yield put({ type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, payload: { ...analyticsPayload, - eventName: "DEBUGGER_NEW_ERROR", - errorMessages: payload.messages, + eventName: "DEBUGGER_RESOLVED_ERROR", + errorMessages, }, }); - // Log analytics for new error messages - if (errorMessages.length && payload) { + if (errorMessages) { yield all( - errorMessages.map((errorMessage) => - put({ + errorMessages.map((errorMessage) => { + return put({ type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, payload: { ...analyticsPayload, - eventName: "DEBUGGER_NEW_ERROR_MESSAGE", + eventName: "DEBUGGER_RESOLVED_ERROR_MESSAGE", errorMessage: errorMessage.message, errorType: errorMessage.type, errorSubType: errorMessage.subType, }, - }), - ), + }); + }), ); } - } else { - const updatedErrorMessages = payload.messages ?? []; - const existingErrorMessages = errors[payload.id].messages ?? []; - // Log new error messages - yield all( - updatedErrorMessages.map((updatedErrorMessage) => { - const exists = findIndex( - existingErrorMessages, - (existingErrorMessage) => { - return isMatch(existingErrorMessage, updatedErrorMessage); - }, - ); - - if (exists < 0) { - return put({ - type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, - payload: { - ...analyticsPayload, - eventName: "DEBUGGER_NEW_ERROR_MESSAGE", - errorMessage: updatedErrorMessage.message, - errorType: updatedErrorMessage.type, - errorSubType: updatedErrorMessage.subType, - }, - }); - } - }), - ); - // Log resolved error messages - yield all( - existingErrorMessages.map((existingErrorMessage) => { - const exists = findIndex( - updatedErrorMessages, - (updatedErrorMessage) => { - return isMatch(updatedErrorMessage, existingErrorMessage); - }, - ); - - if (exists < 0) { - return put({ - type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, - payload: { - ...analyticsPayload, - eventName: "DEBUGGER_RESOLVED_ERROR_MESSAGE", - errorMessage: existingErrorMessage.message, - errorType: existingErrorMessage.type, - errorSubType: existingErrorMessage.subType, - }, - }); - } - }), - ); } -} - -function* deleteDebuggerErrorLogSaga( - action: ReduxAction<{ id: string; analytics: Log["analytics"] }>, -) { - const errors: Record<string, Log> = yield select(getDebuggerErrors); - // If no error exists with this id - if (!(action.payload.id in errors)) return; - - const error = errors[action.payload.id]; - - if (!error || !error.source) return; - - const analyticsPayload = { - entityName: error.source.name, - entityType: error.source.type, - entityId: error.source.id, - propertyPath: error.source.propertyPath ?? "", - analytics: action.payload.analytics, - }; - const errorMessages = error.messages; - - yield put({ - type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, - payload: { - ...analyticsPayload, - eventName: "DEBUGGER_RESOLVED_ERROR", - errorMessages, - }, - }); - - if (errorMessages) { - yield all( - errorMessages.map((errorMessage) => { - return put({ - type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, - payload: { - ...analyticsPayload, - eventName: "DEBUGGER_RESOLVED_ERROR_MESSAGE", - errorMessage: errorMessage.message, - errorType: errorMessage.type, - errorSubType: errorMessage.subType, - }, - }); - }), - ); - } - - yield put(deleteErrorLog(action.payload.id)); + const validErrorIds = validErrorPayloadsToDelete.map((payload) => payload.id); + yield put(deleteErrorLog(validErrorIds)); } // takes a log object array and stores it in the redux store @@ -551,11 +668,11 @@ export default function* debuggerSagasListeners() { ), takeEvery( ReduxActionTypes.DEBUGGER_ADD_ERROR_LOG_INIT, - addDebuggerErrorLogSaga, + addDebuggerErrorLogsSaga, ), takeEvery( ReduxActionTypes.DEBUGGER_DELETE_ERROR_LOG_INIT, - deleteDebuggerErrorLogSaga, + deleteDebuggerErrorLogsSaga, ), ]); } diff --git a/app/client/src/sagas/JSPaneSagas.ts b/app/client/src/sagas/JSPaneSagas.ts index deafc5f3f42c..e5d3e63422a3 100644 --- a/app/client/src/sagas/JSPaneSagas.ts +++ b/app/client/src/sagas/JSPaneSagas.ts @@ -286,7 +286,9 @@ function* updateJSCollection(data: { ); // delete all execution error logs for deletedActions if present deletedActions.forEach((action) => - AppsmithConsole.deleteError(`${jsCollection.id}-${action.id}`), + AppsmithConsole.deleteErrors([ + { id: `${jsCollection.id}-${action.id}` }, + ]), ); } @@ -399,22 +401,26 @@ export function* handleExecuteJSFunctionSaga(data: { variant: Variant.success, }); } catch (error) { - AppsmithConsole.addError({ - id: actionId, - logType: LOG_TYPE.ACTION_EXECUTION_ERROR, - text: createMessage(JS_EXECUTION_FAILURE), - source: { - type: ENTITY_TYPE.JSACTION, - name: collectionName + "." + action.name, - id: collectionId, - }, - messages: [ - { - message: (error as Error).message, - type: PLATFORM_ERROR.PLUGIN_EXECUTION, + AppsmithConsole.addErrors([ + { + payload: { + id: actionId, + logType: LOG_TYPE.ACTION_EXECUTION_ERROR, + text: createMessage(JS_EXECUTION_FAILURE), + source: { + type: ENTITY_TYPE.JSACTION, + name: collectionName + "." + action.name, + id: collectionId, + }, + messages: [ + { + message: (error as Error).message, + type: PLATFORM_ERROR.PLUGIN_EXECUTION, + }, + ], }, - ], - }); + }, + ]); Toaster.show({ text: (error as Error).message || createMessage(JS_EXECUTION_FAILURE_TOASTER), diff --git a/app/client/src/sagas/PostEvaluationSagas.ts b/app/client/src/sagas/PostEvaluationSagas.ts index ad8fdf8c3965..c404237ba6ef 100644 --- a/app/client/src/sagas/PostEvaluationSagas.ts +++ b/app/client/src/sagas/PostEvaluationSagas.ts @@ -54,6 +54,8 @@ function logLatestEvalPropertyErrors( dataTree: DataTree, evaluationOrder: Array<string>, ) { + const errorsToAdd = []; + const errorsToDelete = []; const updatedDebuggerErrors: Record<string, Log> = { ...currentDebuggerErrors, }; @@ -119,7 +121,6 @@ function logLatestEvalPropertyErrors( // if debugger has error and data tree has error -> update error // if debugger has error but data tree does not -> remove // if debugger or data tree does not have an error -> no change - if (errors.length) { // TODO Rank and set the most critical error // const error = evalErrors[0]; @@ -145,8 +146,8 @@ function logLatestEvalPropertyErrors( !isJSAction(entity) || (isJSAction(entity) && propertyPath === "body") ) { - AppsmithConsole.addError( - { + errorsToAdd.push({ + payload: { id: debuggerKey, logType: isWarning ? LOG_TYPE.EVAL_WARNING @@ -168,15 +169,18 @@ function logLatestEvalPropertyErrors( }, analytics: analyticsData, }, - isWarning ? Severity.WARNING : Severity.ERROR, - ); + severity: isWarning ? Severity.WARNING : Severity.ERROR, + }); } } else if (debuggerKey in updatedDebuggerErrors) { - AppsmithConsole.deleteError(debuggerKey); + errorsToDelete.push({ id: debuggerKey }); } } } } + // Add and delete errors from debugger + AppsmithConsole.addErrors(errorsToAdd); + AppsmithConsole.deleteErrors(errorsToDelete); } export function* evalErrorHandler( @@ -376,23 +380,27 @@ export function* handleJSFunctionExecutionErrorLog( errors: any[], ) { errors.length - ? AppsmithConsole.addError({ - id: `${collectionId}-${action.id}`, - logType: LOG_TYPE.EVAL_ERROR, - text: `${createMessage(JS_EXECUTION_FAILURE)}: ${collectionName}.${ - action.name - }`, - messages: errors.map((error) => ({ - message: error.errorMessage || error.message, - type: PLATFORM_ERROR.JS_FUNCTION_EXECUTION, - subType: error.errorType, - })), - source: { - id: action.id, - name: `${collectionName}.${action.name}`, - type: ENTITY_TYPE.JSACTION, - propertyPath: `${collectionName}.${action.name}`, + ? AppsmithConsole.addErrors([ + { + payload: { + id: `${collectionId}-${action.id}`, + logType: LOG_TYPE.EVAL_ERROR, + text: `${createMessage(JS_EXECUTION_FAILURE)}: ${collectionName}.${ + action.name + }`, + messages: errors.map((error) => ({ + message: error.errorMessage || error.message, + type: PLATFORM_ERROR.JS_FUNCTION_EXECUTION, + subType: error.errorType, + })), + source: { + id: action.id, + name: `${collectionName}.${action.name}`, + type: ENTITY_TYPE.JSACTION, + propertyPath: `${collectionName}.${action.name}`, + }, + }, }, - }) - : AppsmithConsole.deleteError(`${collectionId}-${action.id}`); + ]) + : AppsmithConsole.deleteErrors([{ id: `${collectionId}-${action.id}` }]); } diff --git a/app/client/src/sagas/PostLintingSagas.ts b/app/client/src/sagas/PostLintingSagas.ts index 6e833cd4454d..716dd91515bf 100644 --- a/app/client/src/sagas/PostLintingSagas.ts +++ b/app/client/src/sagas/PostLintingSagas.ts @@ -21,6 +21,9 @@ export function* logLatestLintPropertyErrors({ errors: LintErrors; dataTree: DataTree; }) { + const errorsToAdd = []; + const errorsToRemove = []; + for (const path of Object.keys(errors)) { const { entityName, propertyPath } = getEntityNameAndPropertyPath(path); const entity = dataTree[entityName]; @@ -37,20 +40,24 @@ export function* logLatestLintPropertyErrors({ const debuggerKey = entity.actionId + propertyPath + "-lint"; if (isEmpty(lintErrorsInPath)) { - AppsmithConsole.deleteError(debuggerKey); + errorsToRemove.push({ id: debuggerKey }); continue; } - AppsmithConsole.addError({ - id: debuggerKey, - logType: LOG_TYPE.LINT_ERROR, - text: createMessage(JS_OBJECT_BODY_INVALID), - messages: lintErrorMessagesInPath, - source: { - id: path, - name: entityName, - type: ENTITY_TYPE.JSACTION, - propertyPath, + errorsToAdd.push({ + payload: { + id: debuggerKey, + logType: LOG_TYPE.LINT_ERROR, + text: createMessage(JS_OBJECT_BODY_INVALID), + messages: lintErrorMessagesInPath, + source: { + id: path, + name: entityName, + type: ENTITY_TYPE.JSACTION, + propertyPath, + }, }, }); } + AppsmithConsole.addErrors(errorsToAdd); + AppsmithConsole.deleteErrors(errorsToRemove); } diff --git a/app/client/src/utils/AppsmithConsole.ts b/app/client/src/utils/AppsmithConsole.ts index eebb19e6128b..46b50995a854 100644 --- a/app/client/src/utils/AppsmithConsole.ts +++ b/app/client/src/utils/AppsmithConsole.ts @@ -2,7 +2,7 @@ import { addErrorLogInit, debuggerLog, debuggerLogInit, - deleteErrorLogInit, + deleteErrorLogsInit, } from "actions/debuggerActions"; import { ReduxAction } from "@appsmith/constants/ReduxActionConstants"; import { @@ -14,6 +14,7 @@ import { import moment from "moment"; import store from "store"; import AnalyticsUtil from "./AnalyticsUtil"; +import { isEmpty } from "lodash"; function dispatchAction(action: ReduxAction<unknown>) { store.dispatch(action); @@ -26,7 +27,7 @@ function log(ev: Log) { entityType: ev.source?.type, }); } - dispatchAction(debuggerLogInit(ev)); + dispatchAction(debuggerLogInit([ev])); } function getTimeStamp() { @@ -82,26 +83,30 @@ function error( }); } -// This is used to add an error to the errors tab -function addError( - payload: LogActionPayload, - severity = Severity.ERROR, - category = LOG_CATEGORY.PLATFORM_GENERATED, +// Function used to add errors to the error tab of the debugger +function addErrors( + errors: { + payload: LogActionPayload; + severity?: Severity; + category?: LOG_CATEGORY; + }[], ) { - dispatchAction( - addErrorLogInit({ - ...payload, - severity: severity, - timestamp: getTimeStamp(), - category, - occurrenceCount: 1, - }), - ); + if (isEmpty(errors)) return; + const refinedErrors = errors.map((error) => ({ + ...error.payload, + severity: error.severity ?? Severity.ERROR, + timestamp: getTimeStamp(), + occurrenceCount: 1, + category: error.category ?? LOG_CATEGORY.PLATFORM_GENERATED, + })); + + dispatchAction(addErrorLogInit(refinedErrors)); } -// This is used to remove an error from the errors tab -function deleteError(id: string, analytics?: Log["analytics"]) { - dispatchAction(deleteErrorLogInit(id, analytics)); +// This is used to remove errors from the error tab of the debugger +function deleteErrors(errors: { id: string; analytics?: Log["analytics"] }[]) { + if (isEmpty(errors)) return; + dispatchAction(deleteErrorLogsInit(errors)); } export default { @@ -109,6 +114,6 @@ export default { info, warning, error, - addError, - deleteError, + addErrors, + deleteErrors, };
5aa93926ef3e024b0e2274829bdc0088b79dbe8a
2024-09-05 10:41:26
Ankita Kinger
feat: Action redesign: Updating the config for SMTP plugin to use sections and zones format (#36091)
false
Action redesign: Updating the config for SMTP plugin to use sections and zones format (#36091)
feat
diff --git a/app/client/src/components/formControls/DynamicInputTextControl.tsx b/app/client/src/components/formControls/DynamicInputTextControl.tsx index 874a8c9e9e32..752dbede4233 100644 --- a/app/client/src/components/formControls/DynamicInputTextControl.tsx +++ b/app/client/src/components/formControls/DynamicInputTextControl.tsx @@ -84,7 +84,10 @@ export function InputText(props: { } } return ( - <div className={`t--${props?.name}`} style={customStyle}> + <div + className={`t--${props?.name} uqi-dynamic-input-text`} + style={customStyle} + > {/* <div style={customStyle}> */} <StyledDynamicTextField dataTreePath={dataTreePath} diff --git a/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css b/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css index 93953ba2b370..721ced408468 100644 --- a/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css +++ b/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css @@ -47,6 +47,11 @@ } } } + /* DynamicInputTextControl min height and width removed */ + & :global(.uqi-dynamic-input-text) { + width: unset !important; + min-height: unset !important; + } /* Remove when code editor min width is resolved in DynamicTextFeildControl */ & :global(.dynamic-text-field-control) { diff --git a/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/body.json b/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/body.json new file mode 100644 index 000000000000..90620553a1bf --- /dev/null +++ b/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/body.json @@ -0,0 +1,108 @@ +{ + "controlType": "SECTION_V2", + "identifier": "BODY", + "conditionals": { + "show": "{{actionConfiguration.formData.command === 'SEND'}}" + }, + "children": [ + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "BODY-Z1", + "children": [ + { + "label": "Recepients", + "subtitle": "Separate with comma", + "configProperty": "actionConfiguration.formData.send.to", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "[email protected], [email protected]", + "isRequired": true + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "BODY-Z2", + "children": [ + { + "label": "CC", + "subtitle": "Separate with comma", + "configProperty": "actionConfiguration.formData.send.cc", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "[email protected], [email protected]" + }, + { + "label": "BCC", + "subtitle": "Separate with comma", + "configProperty": "actionConfiguration.formData.send.bcc", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "[email protected], [email protected]" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "BODY-Z3", + "children": [ + { + "label": "Subject", + "configProperty": "actionConfiguration.formData.send.subject", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "Awesome email subject" + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "BODY-Z4", + "children": [ + { + "label": "Body type", + "configProperty": "actionConfiguration.formData.send.bodyType", + "controlType": "DROP_DOWN", + "initialValue": "text/plain", + "options": [ + { + "label": "Plain text", + "value": "text/plain" + }, + { + "label": "HTML", + "value": "text/html" + } + ], + "evaluationSubstitutionType": "TEMPLATE" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "BODY-Z5", + "children": [ + { + "label": "Body", + "configProperty": "actionConfiguration.body", + "controlType": "QUERY_DYNAMIC_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "Incredible body text" + } + ] + }, + { + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "BODY-Z6", + "children": [ + { + "label": "Attachment(s)", + "configProperty": "actionConfiguration.formData.send.attachments", + "controlType": "QUERY_DYNAMIC_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "placeholderText": "{{Filepicker.files}}" + } + ] + } + ] +} diff --git a/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/root.json b/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/root.json index 191cbf2a73bf..8a59a0c4c875 100644 --- a/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/root.json +++ b/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/root.json @@ -1,24 +1,30 @@ { "editor": [ { - "controlType": "SECTION", + "controlType": "SECTION_V2", "identifier": "SELECTOR", "children": [ { - "label": "Command", - "description": "Choose method you would like to use to send an email", - "configProperty": "actionConfiguration.formData.command", - "controlType": "DROP_DOWN", - "initialValue": "SEND", - "options": [ + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SELECTOR-Z1", + "children": [ { - "label": "Send email", - "value": "SEND" + "label": "Command", + "description": "Choose method you would like to use to send an email", + "configProperty": "actionConfiguration.formData.command", + "controlType": "DROP_DOWN", + "initialValue": "SEND", + "options": [ + { + "label": "Send email", + "value": "SEND" + } + ] } ] } ] } ], - "files": ["send.json"] + "files": ["send.json", "body.json"] } diff --git a/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/send.json b/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/send.json index babfc19e1dfd..68d6e80193ae 100644 --- a/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/send.json +++ b/app/server/appsmith-plugins/smtpPlugin/src/main/resources/editor/send.json @@ -1,96 +1,49 @@ { + "controlType": "SECTION_V2", "identifier": "SEND", - "controlType": "SECTION", "conditionals": { "show": "{{actionConfiguration.formData.command === 'SEND'}}" }, "children": [ { - "controlType": "SECTION", - "label": "Email Configuration", - "description": "Optional", + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SEND-Z1", "children": [ { - "label": "From email *", + "label": "From email", "configProperty": "actionConfiguration.formData.send.from", "controlType": "QUERY_DYNAMIC_INPUT_TEXT", "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "[email protected]" - }, + "placeholderText": "[email protected]", + "isRequired": true + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SEND-Z2", + "children": [ { - "label": "Set Reply To Email", + "label": "Set reply to email", "configProperty": "actionConfiguration.formData.send.isReplyTo", "controlType": "SWITCH", "evaluationSubstitutionType": "TEMPLATE" - }, + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SEND-Z3", + "children": [ { "label": "Reply to email", "configProperty": "actionConfiguration.formData.send.replyTo", "controlType": "QUERY_DYNAMIC_INPUT_TEXT", "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "[email protected]", + "placeholderText": "[email protected]", "conditionals": { "show": "{{actionConfiguration.formData.send.isReplyTo === true}}" } - }, - { - "label": "To email(s) *", - "configProperty": "actionConfiguration.formData.send.to", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "[email protected],[email protected]" - }, - { - "label": "CC email(s)", - "configProperty": "actionConfiguration.formData.send.cc", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "[email protected],[email protected]" - }, - { - "label": "BCC email(s)", - "configProperty": "actionConfiguration.formData.send.bcc", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "[email protected],[email protected]" - }, - { - "label": "Subject", - "configProperty": "actionConfiguration.formData.send.subject", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "Awesome email subject" - }, - { - "label": "Body type", - "configProperty": "actionConfiguration.formData.send.bodyType", - "controlType": "DROP_DOWN", - "initialValue": "text/plain", - "options": [ - { - "label": "Plain text", - "value": "text/plain" - }, - { - "label": "HTML", - "value": "text/html" - } - ], - "evaluationSubstitutionType": "TEMPLATE" - }, - { - "label": "Body", - "configProperty": "actionConfiguration.body", - "controlType": "QUERY_DYNAMIC_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "Incredible body text" - }, - { - "label": "Attachment(s)", - "configProperty": "actionConfiguration.formData.send.attachments", - "controlType": "QUERY_DYNAMIC_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "placeholderText": "{{Filepicker.files}}" } ] }
bdb9fe8d54ce96d65e84a53cf1ac1448fcbf5d0f
2023-04-10 11:12:55
Ankita Kinger
fix: Adding dependencies in RTS (#22192)
false
Adding dependencies in RTS (#22192)
fix
diff --git a/app/rts/package.json b/app/rts/package.json index 8b16ea186f27..4b90405f01ba 100644 --- a/app/rts/package.json +++ b/app/rts/package.json @@ -30,10 +30,13 @@ "start": "./start-server.sh" }, "dependencies": { + "@babel/runtime": "^7.21.0", + "astravel": "^0.6.1", "escodegen": "^2.0.0", "express": "^4.18.2", "express-validator": "^6.14.2", "http-status-codes": "^2.2.0", + "klona": "^2.0.5", "loglevel": "^1.8.1", "socket.io": "^4.5.4", "socket.io-adapter": "^2.4.0" diff --git a/app/rts/yarn.lock b/app/rts/yarn.lock index 3e28abfa2df6..59419e42af55 100644 --- a/app/rts/yarn.lock +++ b/app/rts/yarn.lock @@ -258,6 +258,13 @@ dependencies: "@babel/helper-plugin-utils" "^7.18.6" +"@babel/runtime@^7.21.0": + version "7.21.0" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.21.0.tgz#5b55c9d394e5fcf304909a8b00c07dc217b56673" + integrity sha512-xwII0//EObnq89Ji5AKYQaRYiW/nZ3llSv29d49IuxPhKbtJoLP+9QUUZ4nVragQVtaVGeZrpB+ZtG/Pdy/POw== + dependencies: + regenerator-runtime "^0.13.11" + "@babel/template@^7.18.10", "@babel/template@^7.3.3": version "7.18.10" resolved "https://registry.npmjs.org/@babel/template/-/template-7.18.10.tgz" @@ -854,6 +861,11 @@ asap@^2.0.0: resolved "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz" integrity sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA== +astravel@^0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/astravel/-/astravel-0.6.1.tgz#be4073b060ff8fc0d2f80953389d5429675f609a" + integrity sha512-ZIkgWFIV0Yo423Vqalz7VcF+BAiISvSgplnkV2abPGACPFKofsWTcvr9SFyYM/t/vMZWqmdP/Eze6ATX7r84Dg== + asynckit@^0.4.0: version "0.4.0" resolved "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz" @@ -2304,6 +2316,11 @@ kleur@^3.0.3: resolved "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz" integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w== +klona@^2.0.5: + version "2.0.6" + resolved "https://registry.yarnpkg.com/klona/-/klona-2.0.6.tgz#85bffbf819c03b2f53270412420a4555ef882e22" + integrity sha512-dhG34DXATL5hSxJbIexCft8FChFXtmskoZYnoPWjXQuebWYCNkVeV3KkGegCK9CP1oswI/vQibS2GY7Em/sJJA== + leven@^3.1.0: version "3.1.0" resolved "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz" @@ -2720,6 +2737,11 @@ readdirp@~3.6.0: dependencies: picomatch "^2.2.1" +regenerator-runtime@^0.13.11: + version "0.13.11" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz#f6dca3e7ceec20590d07ada785636a90cdca17f9" + integrity sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg== + require-directory@^2.1.1: version "2.1.1" resolved "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz" diff --git a/app/shared/ast/package.json b/app/shared/ast/package.json index 25a7c1ab19b2..f1c789a89050 100644 --- a/app/shared/ast/package.json +++ b/app/shared/ast/package.json @@ -20,7 +20,6 @@ "link-package": "yarn install && rollup -c && cd build && cp -R ../node_modules ./node_modules && yarn link" }, "dependencies": { - "@babel/runtime": "^7.20.7", "@babel/runtime": "^7.21.0", "acorn": "^8.8.0", "acorn-walk": "^8.2.0",
d71253ee9413cacd8c33e401ed66d4a705c7be06
2021-09-02 17:43:01
Paul Li
fix: Iframe onUrlChanged Prevented from being triggered on initial mount (#6961)
false
Iframe onUrlChanged Prevented from being triggered on initial mount (#6961)
fix
diff --git a/app/client/src/components/designSystems/blueprint/IframeComponent.tsx b/app/client/src/components/designSystems/blueprint/IframeComponent.tsx index 3d161cf6ab8b..b67e20530ce9 100644 --- a/app/client/src/components/designSystems/blueprint/IframeComponent.tsx +++ b/app/client/src/components/designSystems/blueprint/IframeComponent.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from "react"; +import React, { useEffect, useRef, useState } from "react"; import styled from "styled-components"; import { ComponentProps } from "components/designSystems/appsmith/BaseComponent"; @@ -70,6 +70,8 @@ function IframeComponent(props: IframeComponentProps) { widgetId, } = props; + const isFirstRender = useRef(true); + const [message, setMessage] = useState(""); useEffect(() => { @@ -81,6 +83,10 @@ function IframeComponent(props: IframeComponentProps) { }, []); useEffect(() => { + if (isFirstRender.current) { + isFirstRender.current = false; + return; + } onURLChanged(source); if (!source) { setMessage("Valid source url is required");
9a80b6d8569a55d8949a2f6baa9cd61ed0dadcc9
2023-02-14 17:05:59
Saroj
test: Fix to run Upgrade cypress test only in CE (#20472)
false
Fix to run Upgrade cypress test only in CE (#20472)
test
diff --git a/app/client/cypress/integration/Regression_TestSuite/UpgradeAppsmith/UpgradeAppsimth_spec.js b/app/client/cypress/integration/Regression_TestSuite/UpgradeAppsmith/UpgradeAppsimth_spec.js index e7d46e7fd5f3..7a9053b27c1d 100644 --- a/app/client/cypress/integration/Regression_TestSuite/UpgradeAppsmith/UpgradeAppsimth_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/UpgradeAppsmith/UpgradeAppsimth_spec.js @@ -18,8 +18,8 @@ describe("Upgrade appsmith version", () => { localStorage.setItem("ContainerName", `appsmith-${name}`); - //Start CE Container with old stack - cy.StartCEContainer( + //Start a new Container with old stack + cy.StartNewContainer( tedUrl, path + "/oldstack/tempStacks/oldstacks", "cicontainer", @@ -32,63 +32,63 @@ describe("Upgrade appsmith version", () => { cy.GetAndVerifyLogs(tedUrl, `appsmith-${name}`); }); - //verify the Applications after upgrade - cy.forceVisit(testdata.APPURL); - //Commenting this to fix the test - // agHelper.GetNClick(".t--widget-iconbuttonwidget button", 0, true); - // agHelper.Sleep(1000); - // agHelper.GetNAssertElementText( - // ".tbody>div", - // "1Developmentexpertise", - // "have.text", - // 1, - // ); - - // agHelper.GetNClick(".tbody>div", 1, true, 1000); - // agHelper.GetNAssertElementText( - // ".t--jsonformfield-label input", - // "Development", - // "have.value", - // ); - // agHelper.GetNAssertElementText( - // ".t--jsonformfield-type input", - // "expertise", - // "have.value", - // ); - // agHelper.GetNAssertElementText( - // ".t--jsonformfield-rowIndex input", - // "1", - // "have.value", - // ); + //verify the Applications after upgrade only on CE and skip for BE + if (Cypress.env("Edition") !== 0) { + cy.forceVisit(testdata.APPURL); + agHelper.GetNClick(".t--widget-iconbuttonwidget button", 0, true); + agHelper.Sleep(1000); + agHelper.GetNAssertElementText( + ".tbody>div", + "1Developmentexpertise", + "have.text", + 1, + ); - // cy.get(".t--jsonformfield-label input") - // .clear() - // .type("DevelopmentUpdate"); - // agHelper.GetNClick(".t--jsonform-footer button", 1, true); - // agHelper.Sleep(2000); - // agHelper.GetNClick(".t--widget-iconbuttonwidget button", 0, true, 1000); - // agHelper.GetNAssertElementText( - // ".tbody>div", - // "1DevelopmentUpdateexpertise", - // "have.text", - // 1, - // ); + agHelper.GetNClick(".tbody>div", 1, true, 1000); + agHelper.GetNAssertElementText( + ".t--jsonformfield-label input", + "Development", + "have.value", + ); + agHelper.GetNAssertElementText( + ".t--jsonformfield-type input", + "expertise", + "have.value", + ); + agHelper.GetNAssertElementText( + ".t--jsonformfield-rowIndex input", + "1", + "have.value", + ); - // //Resetting the data - // agHelper.GetNClick(".tbody>div", 1, true, 1000); - // cy.get(".t--jsonformfield-label input") - // .clear() - // .type("Development"); - // agHelper.GetNClick(".t--jsonform-footer button", 1, true); - // agHelper.Sleep(2000); - // agHelper.GetNClick(".t--widget-iconbuttonwidget button", 0, true, 1000); - // agHelper.GetNAssertElementText( - // ".tbody>div", - // "1Developmentexpertise", - // "have.text", - // 1, - // ); + cy.get(".t--jsonformfield-label input") + .clear() + .type("DevelopmentUpdate"); + agHelper.GetNClick(".t--jsonform-footer button", 1, true); + agHelper.Sleep(2000); + agHelper.GetNClick(".t--widget-iconbuttonwidget button", 0, true, 1000); + agHelper.GetNAssertElementText( + ".tbody>div", + "1DevelopmentUpdateexpertise", + "have.text", + 1, + ); + //Resetting the data + agHelper.GetNClick(".tbody>div", 1, true, 1000); + cy.get(".t--jsonformfield-label input") + .clear() + .type("Development"); + agHelper.GetNClick(".t--jsonform-footer button", 1, true); + agHelper.Sleep(2000); + agHelper.GetNClick(".t--widget-iconbuttonwidget button", 0, true, 1000); + agHelper.GetNAssertElementText( + ".tbody>div", + "1Developmentexpertise", + "have.text", + 1, + ); + } // stop the container cy.StopContainer(tedUrl, localStorage.getItem("ContainerName")); agHelper.Sleep(2000); diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js index 17eab346c29a..30657fab6fcb 100644 --- a/app/client/cypress/support/commands.js +++ b/app/client/cypress/support/commands.js @@ -1884,14 +1884,14 @@ Cypress.Commands.add("StartContainer", (path, containerName) => { }); Cypress.Commands.add( - "StartCEContainer", + "StartNewContainer", (url, path, version, containerName) => { let comm = "docker run -d --name " + containerName + ' -p 8081:80 -p 9002:9002 -v "' + path + - '/stacks:/appsmith-stacks" -e APPSMITH_CLOUD_SERVICES_BASE_URL=http://host.docker.internal:5001 ' + + '/stacks:/appsmith-stacks" ' + version; cy.log(comm); @@ -1909,31 +1909,6 @@ Cypress.Commands.add( }, ); -Cypress.Commands.add( - "StartEEContainer", - (url, path, version, containerName) => { - let comm = - "docker run -d --name " + - containerName + - ' -p 8081:80 -p 9002:9002 -v "' + - path + - '/stacks:/appsmith-stacks" ' + - version; - - cy.log(comm); - cy.request({ - method: "GET", - url: url, - qs: { - cmd: comm, - }, - }).then((res) => { - cy.log(res.body.stdout, res.body.stderr); - expect(res.status).equal(200); - }); - }, -); - Cypress.Commands.add("GetPath", (path, containerName) => { cy.request({ method: "GET",
41e44eed306b874920807b16564189774abf046d
2021-04-08 09:49:05
Sumit Kumar
feature: add title to action execution errors to improve user experience (#3872)
false
add title to action execution errors to improve user experience (#3872)
feature
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/BaseException.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/BaseException.java new file mode 100644 index 000000000000..d48807ca1e54 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/BaseException.java @@ -0,0 +1,21 @@ +package com.appsmith.external.exceptions; + +public abstract class BaseException extends Exception { + + public BaseException(String message) { + super(message); + } + + public abstract Integer getHttpStatus(); + + public abstract Integer getAppErrorCode(); + + public abstract AppsmithErrorAction getErrorAction(); + + public abstract String getTitle(); + + public String getMessage() { + return super.getMessage(); + } + +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java index 9e6b5ae991d8..15fddf3ccac1 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java @@ -8,34 +8,39 @@ @Getter public enum AppsmithPluginError { - PLUGIN_ERROR(500, 5000, "{0}", AppsmithErrorAction.LOG_EXTERNALLY), + PLUGIN_ERROR(500, 5000, "{0}", AppsmithErrorAction.LOG_EXTERNALLY, "Query execution error"), PLUGIN_GET_STRUCTURE_ERROR(500, 5001, "Failed to get database structure with error: {0}", - AppsmithErrorAction.LOG_EXTERNALLY), + AppsmithErrorAction.LOG_EXTERNALLY, "Failed to get datasource structure"), PLUGIN_QUERY_TIMEOUT_ERROR(504, 5002, "{0} timed out in {1} milliseconds. " + - "Please increase timeout. This can be found in Settings tab of {0}.", AppsmithErrorAction.DEFAULT), + "Please increase timeout. This can be found in Settings tab of {0}.", AppsmithErrorAction.DEFAULT, "Timed" + + " out on query execution"), PLUGIN_GET_STRUCTURE_TIMEOUT_ERROR(504, 5003, "Plugin timed out when fetching structure.", - AppsmithErrorAction.DEFAULT), - PLUGIN_DATASOURCE_ARGUMENT_ERROR(500, 5004, "{0}", AppsmithErrorAction.DEFAULT), - PLUGIN_EXECUTE_ARGUMENT_ERROR(500, 5005, "{0}", AppsmithErrorAction.DEFAULT), + AppsmithErrorAction.DEFAULT, "Timed out when fetching datasource structure"), + PLUGIN_DATASOURCE_ARGUMENT_ERROR(500, 5004, "{0}", AppsmithErrorAction.DEFAULT, "Datasource configuration is " + + "invalid"), + PLUGIN_EXECUTE_ARGUMENT_ERROR(500, 5005, "{0}", AppsmithErrorAction.DEFAULT, "Query configuration is invalid"), PLUGIN_JSON_PARSE_ERROR(500, 5006, "Plugin failed to parse JSON \"{0}\" with error: {1}", - AppsmithErrorAction.DEFAULT), + AppsmithErrorAction.DEFAULT, "Invalid JSON found"), PLUGIN_DATASOURCE_TEST_GENERIC_ERROR(500, 5007, "Plugin failed to test with the given configuration. Please reach out to Appsmith customer support to report this", - AppsmithErrorAction.LOG_EXTERNALLY), - PLUGIN_DATASOURCE_TIMEOUT_ERROR(504, 5008, "{0}", AppsmithErrorAction.DEFAULT), + AppsmithErrorAction.LOG_EXTERNALLY, "Datasource configuration is invalid"), + PLUGIN_DATASOURCE_TIMEOUT_ERROR(504, 5008, "{0}", AppsmithErrorAction.DEFAULT, "Timed out when connecting to " + + "datasource"), ; private final Integer httpErrorCode; private final Integer appErrorCode; private final String message; + private final String title; private final AppsmithErrorAction errorAction; AppsmithPluginError(Integer httpErrorCode, Integer appErrorCode, String message, AppsmithErrorAction errorAction, - Object... args) { + String title, Object... args) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; MessageFormat fmt = new MessageFormat(message); - this.message = fmt.format(args); this.errorAction = errorAction; + this.message = fmt.format(args); + this.title = title; } public String getMessage(Object... args) { diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginException.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginException.java index 7fd396ad7e12..7767ff2d6c8f 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginException.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginException.java @@ -1,12 +1,13 @@ package com.appsmith.external.exceptions.pluginExceptions; import com.appsmith.external.exceptions.AppsmithErrorAction; +import com.appsmith.external.exceptions.BaseException; import lombok.Getter; import lombok.Setter; @Getter @Setter -public class AppsmithPluginException extends Exception { +public class AppsmithPluginException extends BaseException { private final AppsmithPluginError error; private final Object[] args; @@ -33,4 +34,5 @@ public AppsmithErrorAction getErrorAction() { return this.error.getErrorAction(); } + public String getTitle() { return this.error.getTitle(); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionResult.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionResult.java index 743b766f7c29..0191e6b53e4b 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionResult.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionResult.java @@ -1,5 +1,7 @@ package com.appsmith.external.models; +import com.appsmith.external.exceptions.BaseException; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.fasterxml.jackson.databind.JsonNode; import lombok.Getter; import lombok.NoArgsConstructor; @@ -15,6 +17,7 @@ public class ActionExecutionResult { String statusCode; + String title; JsonNode headers; Object body; Boolean isExecutionSuccess = false; @@ -27,4 +30,13 @@ public class ActionExecutionResult { ActionExecutionRequest request; + public void setErrorInfo(Throwable error) { + this.body = error.getMessage(); + + if (error instanceof BaseException) { + this.statusCode = ((BaseException) error).getAppErrorCode().toString(); + this.title = ((BaseException) error).getTitle(); + } + } + } diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java index 13327a5220b7..cfe2641971d6 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java @@ -203,7 +203,7 @@ String uploadFileFromBody(AmazonS3 connection, payload = Base64.getDecoder().decode(encodedPayload); } catch (IllegalArgumentException e) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_ERROR, + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "File content is not base64 encoded. File content needs to be base64 encoded when the " + "'File Data Type: Base64/Text' field is selected 'Yes'." ); @@ -540,10 +540,7 @@ public Mono<ActionExecutionResult> execute(AmazonS3 connection, } ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - result.setBody(e.getMessage()); - if (e instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) e).getAppErrorCode().toString()); - } + result.setErrorInfo(e); return Mono.just(result); }) diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/plugins/AmazonS3PluginTest.java b/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/plugins/AmazonS3PluginTest.java index 23b3ff9ad20a..69b6ac697d20 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/plugins/AmazonS3PluginTest.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/plugins/AmazonS3PluginTest.java @@ -6,6 +6,7 @@ import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.util.Base64; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionResult; @@ -319,6 +320,7 @@ public void testCreateFileFromBodyWithFalseCredentialsAndNonNullDuration() { String message = (String) result.getBody(); assertTrue(message.contains("The AWS Access Key Id you provided does not exist in " + "our records")); + assertEquals(AppsmithPluginError.PLUGIN_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); } @@ -365,6 +367,7 @@ public void testFileUploadFromBodyWithMissingDuration() { String message = (String) result.getBody(); assertTrue(message.contains("The AWS Access Key Id you provided does not exist in " + "our records")); + assertEquals(AppsmithPluginError.PLUGIN_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); } @@ -405,6 +408,7 @@ public void testFileUploadFromBodyWithFilepickerAndNonBase64() { assertFalse(result.getIsExecutionSuccess()); String message = (String) result.getBody(); assertTrue(message.contains("File content is not base64 encoded")); + assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); } diff --git a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java index f484018d294e..803bb288477e 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java +++ b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java @@ -340,10 +340,7 @@ public Mono<ActionExecutionResult> execute(DynamoDbClient ddb, .onErrorResume(error -> { ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - result.setBody(error.getMessage()); + result.setErrorInfo(error); return Mono.just(result); }) // Now set the request in the result to be returned back to the server diff --git a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java index f2b05179f2a4..fe37bf526f5f 100644 --- a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java +++ b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java @@ -123,10 +123,7 @@ public Mono<ActionExecutionResult> execute(RestClient client, .onErrorResume(error -> { ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - result.setBody(error.getMessage()); + result.setErrorInfo(error); return Mono.just(result); }) // Now set the request in the result to be returned back to the server diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java index 9aa5dbd46d2a..a585bdfc9fef 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java @@ -223,10 +223,7 @@ public Mono<ActionExecutionResult> executeParameterized( .onErrorResume(error -> { ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - result.setBody(error.getMessage()); + result.setErrorInfo(error); return Mono.just(result); }) // Now set the request in the result to be returned back to the server diff --git a/app/server/appsmith-plugins/firestorePlugin/src/test/java/com/external/plugins/FirestorePluginTest.java b/app/server/appsmith-plugins/firestorePlugin/src/test/java/com/external/plugins/FirestorePluginTest.java index a57622e5cfba..f8698f9ce256 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/test/java/com/external/plugins/FirestorePluginTest.java +++ b/app/server/appsmith-plugins/firestorePlugin/src/test/java/com/external/plugins/FirestorePluginTest.java @@ -2,6 +2,7 @@ import com.appsmith.external.dtos.ExecuteActionDTO; import com.appsmith.external.exceptions.AppsmithErrorAction; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionResult; @@ -739,6 +740,7 @@ public void testFieldValueDeleteWithUnsupportedAction() { String expectedErrorMessage = "Appsmith has found an unexpected query form property - 'Delete Key " + "Value Pair Path'. Please reach out to Appsmith customer support to resolve this."; assertTrue(expectedErrorMessage.equals(result.getBody())); + assertEquals(AppsmithPluginError.PLUGIN_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); @@ -773,6 +775,7 @@ public void testFieldValueTimestampWithUnsupportedAction() { String expectedErrorMessage = "Appsmith has found an unexpected query form property - 'Timestamp " + "Value Path'. Please reach out to Appsmith customer support to resolve this."; assertTrue(expectedErrorMessage.equals(result.getBody())); + assertEquals(AppsmithPluginError.PLUGIN_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); } @@ -807,9 +810,9 @@ public void testFieldValueDeleteWithBadArgument() { String expectedErrorMessage = "Appsmith failed to parse the query editor form field 'Delete Key " + "Value Pair Path'. Please check out Appsmith's documentation to find the correct syntax."; assertTrue(expectedErrorMessage.equals(result.getBody())); + assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); - } @Test @@ -842,6 +845,7 @@ public void testFieldValueTimestampWithBadArgument() { String expectedErrorMessage = "Appsmith failed to parse the query editor form field 'Timestamp " + "Value Path'. Please check out Appsmith's documentation to find the correct syntax."; assertTrue(expectedErrorMessage.equals(result.getBody())); + assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java index e59084526689..9314b3141bb4 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java @@ -21,6 +21,7 @@ import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.external.plugins.SmartSubstitutionInterface; import com.mongodb.MongoCommandException; +import com.mongodb.MongoTimeoutException; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoDatabase; @@ -192,10 +193,17 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, ActionExecutionResult result = new ActionExecutionResult(); return mongoOutputMono + .onErrorMap( + MongoTimeoutException.class, + error -> new AppsmithPluginException( + AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR, + error.getMessage() + ) + ) .onErrorMap( MongoCommandException.class, error -> new AppsmithPluginException( - AppsmithPluginError.PLUGIN_ERROR, + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, error.getErrorMessage() ) ) @@ -273,10 +281,7 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, } ActionExecutionResult actionExecutionResult = new ActionExecutionResult(); actionExecutionResult.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - actionExecutionResult.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - actionExecutionResult.setBody(error.getMessage()); + actionExecutionResult.setErrorInfo(error); return Mono.just(actionExecutionResult); }) // Now set the request in the result to be returned back to the server diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginTest.java index 39a8d60ecc55..f25bc3f25b4a 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginTest.java @@ -1,5 +1,6 @@ package com.external.plugins; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.dtos.ExecuteActionDTO; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionRequest; @@ -229,6 +230,7 @@ public void testExecuteInvalidReadQuery() { assertFalse(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); assertEquals("unknown top level operator: $is", result.getBody()); + assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); } @@ -559,7 +561,10 @@ public void testSslEnabled() { * - Expect error here because testcontainer does not support SSL connection. */ StepVerifier.create(executeMono) - .assertNext(result -> assertFalse(result.getIsExecutionSuccess())) + .assertNext(result -> { + assertFalse(result.getIsExecutionSuccess()); + assertEquals(AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR.getTitle(), result.getTitle()); + }) .verifyComplete(); } diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java index 524956fc5f01..5c2d9fa0ba72 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java @@ -300,10 +300,7 @@ public Mono<ActionExecutionResult> executeCommon(Connection connection, } ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - result.setBody(error.getMessage()); + result.setErrorInfo(error); return Mono.just(result); }) // Now set the request in the result to be returned back to the server diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java index 616adf895ec7..784b243f0038 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java @@ -181,6 +181,7 @@ public Mono<ActionExecutionResult> executeParameterized(Connection connection, errorResult.setIsExecutionSuccess(false); errorResult.setBody(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getMessage("Missing required " + "parameter: Query.")); + errorResult.setTitle(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle()); ActionExecutionRequest actionExecutionRequest = new ActionExecutionRequest(); actionExecutionRequest.setProperties(requestData); errorResult.setRequest(actionExecutionRequest); @@ -282,10 +283,7 @@ public Mono<ActionExecutionResult> executeCommon(Connection connection, } ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - result.setBody(error.getMessage()); + result.setErrorInfo(error); return Mono.just(result); }) // Now set the request in the result to be returned back to the server diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlPluginTest.java b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlPluginTest.java index d2c2e582d6cc..77ba126fb895 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlPluginTest.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlPluginTest.java @@ -692,7 +692,6 @@ public void testSslRequired() { assertTrue(result.getIsExecutionSuccess()); Object body = result.getBody(); assertNotNull(body); - System.out.println("devtest: body: " + result.getBody()); assertEquals("[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"ECDHE-RSA-AES128-SHA\"}]", body.toString()); }) @@ -717,7 +716,6 @@ public void testSslPreferred() { assertTrue(result.getIsExecutionSuccess()); Object body = result.getBody(); assertNotNull(body); - System.out.println("devtest: body: " + result.getBody()); assertEquals("[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"ECDHE-RSA-AES128-SHA\"}]", body.toString()); }) @@ -742,7 +740,6 @@ public void testSslDefault() { assertTrue(result.getIsExecutionSuccess()); Object body = result.getBody(); assertNotNull(body); - System.out.println("devtest: body: " + result.getBody()); assertEquals("[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"ECDHE-RSA-AES128-SHA\"}]", body.toString()); }) diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java index 57ac179a6219..40deb74009c0 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java @@ -24,6 +24,7 @@ import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariPoolMXBean; import com.zaxxer.hikari.pool.HikariProxyConnection; +import com.zaxxer.hikari.pool.HikariPool.PoolInitializationException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ObjectUtils; import org.pf4j.Extension; @@ -386,10 +387,7 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, } ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - result.setBody(error.getMessage()); + result.setErrorInfo(error); return Mono.just(result); }) // Now set the request in the result to be returned back to the server @@ -925,7 +923,15 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat config.setLeakDetectionThreshold(LEAK_DETECTION_TIME_MS); // Now create the connection pool from the configuration - HikariDataSource datasource = new HikariDataSource(config); + HikariDataSource datasource = null; + try { + datasource = new HikariDataSource(config); + } catch (PoolInitializationException e) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + e.getMessage() + ); + } return datasource; } @@ -937,7 +943,8 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat * @param connectionPool * @return SQL Connection */ - private static Connection getConnectionFromConnectionPool(HikariDataSource connectionPool, DatasourceConfiguration datasourceConfiguration) throws SQLException { + private static Connection getConnectionFromConnectionPool(HikariDataSource connectionPool, + DatasourceConfiguration datasourceConfiguration) throws SQLException { if (connectionPool == null || connectionPool.isClosed() || !connectionPool.isRunning()) { System.out.println(Thread.currentThread().getName() + diff --git a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java index 3245f55b5134..720608f80ff7 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java +++ b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java @@ -89,10 +89,7 @@ public Mono<ActionExecutionResult> execute(Jedis jedis, .onErrorResume(error -> { ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - result.setBody(error.getMessage()); + result.setErrorInfo(error); return Mono.just(result); }) // Now set the request in the result to be returned back to the server diff --git a/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java b/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java index a35843689d9a..48b1e689b77e 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java +++ b/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java @@ -1,5 +1,6 @@ package com.external.plugins; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionResult; import com.appsmith.external.models.DBAuth; @@ -155,6 +156,7 @@ public void itShouldThrowErrorIfEmptyBody() { .assertNext(result -> { Assert.assertNotNull(result); Assert.assertFalse(result.getIsExecutionSuccess()); + Assert.assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); } @@ -174,6 +176,7 @@ public void itShouldThrowErrorIfInvalidRedisCommand() { .assertNext(result -> { Assert.assertNotNull(result); Assert.assertFalse(result.getIsExecutionSuccess()); + Assert.assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); } diff --git a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java index 2eeb0e12c7fd..78d9b3e4d9ac 100644 --- a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java +++ b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java @@ -309,10 +309,7 @@ public Mono<ActionExecutionResult> execute(Connection connection, } ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - result.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - result.setBody(error.getMessage()); + result.setErrorInfo(error); return Mono.just(result); }) // Now set the request in the result to be returned back to the server diff --git a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java index 7c1302ddb6ed..24b56d33365c 100644 --- a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java +++ b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java @@ -157,9 +157,9 @@ public Mono<ActionExecutionResult> executeParameterized(APIConnection connection parameters); } catch (AppsmithPluginException e) { ActionExecutionResult errorResult = new ActionExecutionResult(); - errorResult.setStatusCode(AppsmithPluginError.PLUGIN_ERROR.getAppErrorCode().toString()); errorResult.setIsExecutionSuccess(false); - errorResult.setBody(e.getMessage()); + errorResult.setErrorInfo(e); + errorResult.setStatusCode(AppsmithPluginError.PLUGIN_ERROR.getAppErrorCode().toString()); return Mono.just(errorResult); } @@ -197,6 +197,7 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, ActionExecutionResult errorResult = new ActionExecutionResult(); errorResult.setStatusCode(AppsmithPluginError.PLUGIN_ERROR.getAppErrorCode().toString()); errorResult.setIsExecutionSuccess(false); + errorResult.setTitle(AppsmithPluginError.PLUGIN_ERROR.getTitle()); // Initializing request URL String path = (actionConfiguration.getPath() == null) ? "" : actionConfiguration.getPath(); @@ -377,10 +378,7 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, }) .onErrorResume(error -> { errorResult.setIsExecutionSuccess(false); - if (error instanceof AppsmithPluginException) { - errorResult.setStatusCode(((AppsmithPluginException) error).getAppErrorCode().toString()); - } - errorResult.setBody(error.getMessage()); + errorResult.setErrorInfo(error); return Mono.just(errorResult); }); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java index f382d260ac91..d925de015a3f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java @@ -7,29 +7,31 @@ @Getter public enum AppsmithError { - INVALID_PARAMETER(400, 4000, "Please enter a valid parameter {0}.", AppsmithErrorAction.DEFAULT), - PLUGIN_NOT_INSTALLED(400, 4001, "Plugin {0} not installed", AppsmithErrorAction.DEFAULT), - PLUGIN_ID_NOT_GIVEN(400, 4002, "Missing plugin id. Please enter one.", AppsmithErrorAction.DEFAULT), - DATASOURCE_NOT_GIVEN(400, 4003, "Missing datasource. Add/enter/connect a datasource to create a valid action.", AppsmithErrorAction.DEFAULT), - PAGE_ID_NOT_GIVEN(400, 4004, "Missing page id. Please enter one.", AppsmithErrorAction.DEFAULT), + INVALID_PARAMETER(400, 4000, "Please enter a valid parameter {0}.", AppsmithErrorAction.DEFAULT, null), + PLUGIN_NOT_INSTALLED(400, 4001, "Plugin {0} not installed", AppsmithErrorAction.DEFAULT, null), + PLUGIN_ID_NOT_GIVEN(400, 4002, "Missing plugin id. Please enter one.", AppsmithErrorAction.DEFAULT, null), + DATASOURCE_NOT_GIVEN(400, 4003, "Missing datasource. Add/enter/connect a datasource to create a valid action.", AppsmithErrorAction.DEFAULT, null), + PAGE_ID_NOT_GIVEN(400, 4004, "Missing page id. Please enter one.", AppsmithErrorAction.DEFAULT, null), PAGE_DOESNT_BELONG_TO_USER_ORGANIZATION(400, 4006, "Page {0} does not belong to the current user {1} " + - "organization", AppsmithErrorAction.LOG_EXTERNALLY), - UNSUPPORTED_OPERATION(400, 4007, "Unsupported operation", AppsmithErrorAction.DEFAULT), + "organization", AppsmithErrorAction.LOG_EXTERNALLY, null), + UNSUPPORTED_OPERATION(400, 4007, "Unsupported operation", AppsmithErrorAction.DEFAULT, null), USER_DOESNT_BELONG_ANY_ORGANIZATION(400, 4009, "User {0} does not belong to any organization", - AppsmithErrorAction.LOG_EXTERNALLY), + AppsmithErrorAction.LOG_EXTERNALLY, null), USER_DOESNT_BELONG_TO_ORGANIZATION(400, 4010, "User {0} does not belong to an organization with id {1}", - AppsmithErrorAction.LOG_EXTERNALLY), - NO_CONFIGURATION_FOUND_IN_DATASOURCE(400, 4011, "No datasource configuration found. Please configure it and try again.", AppsmithErrorAction.DEFAULT), - INVALID_ACTION(400, 4012, "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", AppsmithErrorAction.DEFAULT), - INVALID_DATASOURCE(400, 4013, "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", AppsmithErrorAction.DEFAULT), - INVALID_DATASOURCE_CONFIGURATION(400, 4015, "Datasource configuration is invalid", AppsmithErrorAction.DEFAULT), + AppsmithErrorAction.LOG_EXTERNALLY, null), + NO_CONFIGURATION_FOUND_IN_DATASOURCE(400, 4011, "No datasource configuration found. Please configure it and try again.", AppsmithErrorAction.DEFAULT, "Datasource configuration is invalid"), + INVALID_ACTION(400, 4012, "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", + AppsmithErrorAction.DEFAULT, "Action configuration is invalid"), + INVALID_DATASOURCE(400, 4013, "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", + AppsmithErrorAction.DEFAULT, "Datasource configuration is invalid"), + INVALID_DATASOURCE_CONFIGURATION(400, 4015, "Datasource configuration is invalid", AppsmithErrorAction.DEFAULT, "Datasource configuration is invalid"), INVALID_ACTION_NAME(400, 4014, "Appsmith expects the action naming to follow variable naming conventions. " + "It must be a single word contain any alphabets, numbers, or \"_\". Hyphen (\"-\") symbol is not allowed. " - + "Please change the name.", AppsmithErrorAction.DEFAULT), - NO_CONFIGURATION_FOUND_IN_ACTION(400, 4016, "No configurations found in this action", AppsmithErrorAction.DEFAULT), - NAME_CLASH_NOT_ALLOWED_IN_REFACTOR(400, 4017, "The new name {1} already exists in the current page. Choose another name.", AppsmithErrorAction.DEFAULT), + + "Please change the name.", AppsmithErrorAction.DEFAULT, null), + NO_CONFIGURATION_FOUND_IN_ACTION(400, 4016, "No configurations found in this action", AppsmithErrorAction.DEFAULT, null), + NAME_CLASH_NOT_ALLOWED_IN_REFACTOR(400, 4017, "The new name {1} already exists in the current page. Choose another name.", AppsmithErrorAction.DEFAULT, null), PAGE_DOESNT_BELONG_TO_APPLICATION(400, 4018, "Unexpected state. Page {0} does not seem belong to the application {1}. Please reach out to Appsmith customer support to resolve this.", - AppsmithErrorAction.LOG_EXTERNALLY), + AppsmithErrorAction.LOG_EXTERNALLY, null), INVALID_DYNAMIC_BINDING_REFERENCE(400, 4022, " \"widgetType\" : \"{0}\"," + " \"bindingPath\" : \"{3}\"," + @@ -39,61 +41,64 @@ public enum AppsmithError { " \"pageId\" : \"{4}\"," + " \"layoutId\" : \"{5}\"," + " \"dynamicBinding\" : {6}", - AppsmithErrorAction.LOG_EXTERNALLY), - USER_ALREADY_EXISTS_IN_ORGANIZATION(400, 4021, "The user {0} has already been added to the organization with role {1}. To change the role, please navigate to `Manage Users` page.", AppsmithErrorAction.DEFAULT), - UNAUTHORIZED_DOMAIN(401, 4019, "Invalid email domain {0} used for sign in/sign up. Please contact the administrator to configure this domain if this is unexpected.", AppsmithErrorAction.DEFAULT), + AppsmithErrorAction.LOG_EXTERNALLY, null), + USER_ALREADY_EXISTS_IN_ORGANIZATION(400, 4021, "The user {0} has already been added to the organization with role {1}. To change the role, please navigate to `Manage Users` page.", AppsmithErrorAction.DEFAULT, null), + UNAUTHORIZED_DOMAIN(401, 4019, "Invalid email domain {0} used for sign in/sign up. Please contact the administrator to configure this domain if this is unexpected.", AppsmithErrorAction.DEFAULT, null), USER_NOT_SIGNED_IN(401, 4020, "You are not logged in. Please sign in with the registered email ID or sign up", - AppsmithErrorAction.DEFAULT), + AppsmithErrorAction.DEFAULT, null), INVALID_PASSWORD_RESET(400, 4020, "Cannot find an outstanding reset password request for this email. Please initiate a request via 'forgot password' " + - "button to reset your password", AppsmithErrorAction.DEFAULT), - JSON_PROCESSING_ERROR(400, 4022, "Json processing error with error {0}", AppsmithErrorAction.LOG_EXTERNALLY), - INVALID_CREDENTIALS(200, 4023, "Invalid credentials provided. Did you input the credentials correctly?", AppsmithErrorAction.DEFAULT), - UNAUTHORIZED_ACCESS(403, 4025, "Unauthorized access", AppsmithErrorAction.DEFAULT), - DUPLICATE_KEY(409, 4024, "Unexpected state : Duplicate key error. Please reach out to Appsmith customer support to report this", AppsmithErrorAction.DEFAULT), - USER_ALREADY_EXISTS_SIGNUP(409, 4025, "There is already an account registered with this email {0}. Please sign in instead.", AppsmithErrorAction.DEFAULT), - ACTION_IS_NOT_AUTHORIZED(403, 4026, "Uh oh! You do not have permissions to do : {0}", AppsmithErrorAction.DEFAULT), - NO_RESOURCE_FOUND(404, 4027, "Unable to find {0} {1}", AppsmithErrorAction.DEFAULT), - USER_NOT_FOUND(404, 4027, "Unable to find user with email {0}", AppsmithErrorAction.DEFAULT), - ACL_NO_RESOURCE_FOUND(404, 4028, "Unable to find {0} {1}. Either the asset doesn't exist or you don't have required permissions", AppsmithErrorAction.DEFAULT), - GENERIC_BAD_REQUEST(400, 4028, "Bad Request: {0}", AppsmithErrorAction.DEFAULT), - VALIDATION_FAILURE(400, 4028, "Validation Failure(s): {0}", AppsmithErrorAction.DEFAULT), - INVALID_CURL_COMMAND(400, 4029, "Invalid cURL command, couldn't import.", AppsmithErrorAction.DEFAULT), - INTERNAL_SERVER_ERROR(500, 5000, "Internal server error while processing request", AppsmithErrorAction.LOG_EXTERNALLY), - REPOSITORY_SAVE_FAILED(500, 5001, "Failed to save the repository. Try again.", AppsmithErrorAction.DEFAULT), + "button to reset your password", AppsmithErrorAction.DEFAULT, null), + JSON_PROCESSING_ERROR(400, 4022, "Json processing error with error {0}", AppsmithErrorAction.LOG_EXTERNALLY, null), + INVALID_CREDENTIALS(200, 4023, "Invalid credentials provided. Did you input the credentials correctly?", AppsmithErrorAction.DEFAULT, null), + UNAUTHORIZED_ACCESS(403, 4025, "Unauthorized access", AppsmithErrorAction.DEFAULT, null), + DUPLICATE_KEY(409, 4024, "Unexpected state : Duplicate key error. Please reach out to Appsmith customer support to report this", AppsmithErrorAction.DEFAULT, null), + USER_ALREADY_EXISTS_SIGNUP(409, 4025, "There is already an account registered with this email {0}. Please sign in instead.", AppsmithErrorAction.DEFAULT, null), + ACTION_IS_NOT_AUTHORIZED(403, 4026, "Uh oh! You do not have permissions to do : {0}", AppsmithErrorAction.DEFAULT, null), + NO_RESOURCE_FOUND(404, 4027, "Unable to find {0} {1}", AppsmithErrorAction.DEFAULT, null), + USER_NOT_FOUND(404, 4027, "Unable to find user with email {0}", AppsmithErrorAction.DEFAULT, null), + ACL_NO_RESOURCE_FOUND(404, 4028, "Unable to find {0} {1}. Either the asset doesn't exist or you don't have required permissions", AppsmithErrorAction.DEFAULT, null), + GENERIC_BAD_REQUEST(400, 4028, "Bad Request: {0}", AppsmithErrorAction.DEFAULT, null), + VALIDATION_FAILURE(400, 4028, "Validation Failure(s): {0}", AppsmithErrorAction.DEFAULT, null), + INVALID_CURL_COMMAND(400, 4029, "Invalid cURL command, couldn't import.", AppsmithErrorAction.DEFAULT, null), + INTERNAL_SERVER_ERROR(500, 5000, "Internal server error while processing request", AppsmithErrorAction.LOG_EXTERNALLY, null), + REPOSITORY_SAVE_FAILED(500, 5001, "Failed to save the repository. Try again.", AppsmithErrorAction.DEFAULT, null), PLUGIN_INSTALLATION_FAILED_DOWNLOAD_ERROR(500, 5002, "Plugin installation failed due to an error while " + - "downloading it. Check the jar location & try again.", AppsmithErrorAction.LOG_EXTERNALLY), - PLUGIN_RUN_FAILED(500, 5003, "Plugin execution failed with error {0}", AppsmithErrorAction.DEFAULT), - PLUGIN_EXECUTION_TIMEOUT(504, 5040, "Plugin Execution exceeded the maximum allowed time. Please increase the timeout in your action settings or check your backend action endpoint", AppsmithErrorAction.DEFAULT), + "downloading it. Check the jar location & try again.", AppsmithErrorAction.LOG_EXTERNALLY, null), + PLUGIN_RUN_FAILED(500, 5003, "Plugin execution failed with error {0}", AppsmithErrorAction.DEFAULT, null), + PLUGIN_EXECUTION_TIMEOUT(504, 5040, "Plugin Execution exceeded the maximum allowed time. Please increase the timeout in your action settings or check your backend action endpoint", AppsmithErrorAction.DEFAULT, null), PLUGIN_LOAD_FORM_JSON_FAIL(500, 5004, "Unable to load datasource form configuration. Details: {0}.", - AppsmithErrorAction.LOG_EXTERNALLY), + AppsmithErrorAction.LOG_EXTERNALLY, null), PLUGIN_LOAD_TEMPLATES_FAIL(500, 5005, "Unable to load datasource templates. Details: {0}.", - AppsmithErrorAction.LOG_EXTERNALLY), - MARKETPLACE_TIMEOUT(504, 5041, "Marketplace is responding too slowly. Please try again later", AppsmithErrorAction.DEFAULT), - DATASOURCE_HAS_ACTIONS(409, 4030, "Cannot delete datasource since it has {0} action(s) using it.", AppsmithErrorAction.DEFAULT), - ORGANIZATION_ID_NOT_GIVEN(400, 4031, "Missing organization id. Please enter one.", AppsmithErrorAction.DEFAULT), - INVALID_CURL_METHOD(400, 4032, "Invalid method in cURL command: {0}.", AppsmithErrorAction.DEFAULT), - OAUTH_NOT_AVAILABLE(500, 5006, "Login with {0} is not supported.", AppsmithErrorAction.LOG_EXTERNALLY), - MARKETPLACE_NOT_CONFIGURED(500, 5007, "Marketplace is not configured.", AppsmithErrorAction.DEFAULT), - PAYLOAD_TOO_LARGE(413, 4028, "The request payload is too large. Max allowed size for request payload is {0} KB", AppsmithErrorAction.DEFAULT), - SIGNUP_DISABLED(403, 4033, "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite.", AppsmithErrorAction.DEFAULT), - FAIL_UPDATE_USER_IN_SESSION(500, 5008, "Unable to update user in session.", AppsmithErrorAction.LOG_EXTERNALLY), - APPLICATION_FORKING_NOT_ALLOWED(403, 4034, "Forking this application is not permitted at this time.", AppsmithErrorAction.DEFAULT), - GOOGLE_RECAPTCHA_TIMEOUT(504, 5042, "Google recaptcha verification timeout. Please try again.", AppsmithErrorAction.DEFAULT), - GOOGLE_RECAPTCHA_FAILED(401, 4034, "Google recaptcha verification failed. Please try again.", AppsmithErrorAction.DEFAULT), + AppsmithErrorAction.LOG_EXTERNALLY, null), + MARKETPLACE_TIMEOUT(504, 5041, "Marketplace is responding too slowly. Please try again later", AppsmithErrorAction.DEFAULT, null), + DATASOURCE_HAS_ACTIONS(409, 4030, "Cannot delete datasource since it has {0} action(s) using it.", AppsmithErrorAction.DEFAULT, null), + ORGANIZATION_ID_NOT_GIVEN(400, 4031, "Missing organization id. Please enter one.", AppsmithErrorAction.DEFAULT, null), + INVALID_CURL_METHOD(400, 4032, "Invalid method in cURL command: {0}.", AppsmithErrorAction.DEFAULT, null), + OAUTH_NOT_AVAILABLE(500, 5006, "Login with {0} is not supported.", AppsmithErrorAction.LOG_EXTERNALLY, null), + MARKETPLACE_NOT_CONFIGURED(500, 5007, "Marketplace is not configured.", AppsmithErrorAction.DEFAULT, null), + PAYLOAD_TOO_LARGE(413, 4028, "The request payload is too large. Max allowed size for request payload is {0} KB", AppsmithErrorAction.DEFAULT, null), + SIGNUP_DISABLED(403, 4033, "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite.", AppsmithErrorAction.DEFAULT, null), + FAIL_UPDATE_USER_IN_SESSION(500, 5008, "Unable to update user in session.", AppsmithErrorAction.LOG_EXTERNALLY, null), + APPLICATION_FORKING_NOT_ALLOWED(403, 4034, "Forking this application is not permitted at this time.", AppsmithErrorAction.DEFAULT, null), + GOOGLE_RECAPTCHA_TIMEOUT(504, 5042, "Google recaptcha verification timeout. Please try again.", AppsmithErrorAction.DEFAULT, null), + GOOGLE_RECAPTCHA_FAILED(401, 4034, "Google recaptcha verification failed. Please try again.", AppsmithErrorAction.DEFAULT, null), ; private final Integer httpErrorCode; private final Integer appErrorCode; private final String message; + private final String title; private final AppsmithErrorAction errorAction; - AppsmithError(Integer httpErrorCode, Integer appErrorCode, String message, AppsmithErrorAction errorAction, Object... args) { + AppsmithError(Integer httpErrorCode, Integer appErrorCode, String message, AppsmithErrorAction errorAction, + String title, Object... args) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; MessageFormat fmt = new MessageFormat(message); this.message = fmt.format(args); this.errorAction = errorAction; + this.title = title; } public String getMessage(Object... args) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithException.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithException.java index b9f49ee5f1d6..164e53efe044 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithException.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithException.java @@ -1,12 +1,13 @@ package com.appsmith.server.exceptions; import com.appsmith.external.exceptions.AppsmithErrorAction; +import com.appsmith.external.exceptions.BaseException; import lombok.Getter; import lombok.Setter; @Getter @Setter -public class AppsmithException extends Exception { +public class AppsmithException extends BaseException { private final AppsmithError error; private final transient Object[] args; @@ -34,4 +35,6 @@ public AppsmithErrorAction getErrorAction() { return this.error.getErrorAction(); } + public String getTitle() { return this.error.getTitle(); } + } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java index 3c0e5a02b3c9..392c54dcc0aa 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java @@ -1,6 +1,7 @@ package com.appsmith.server.exceptions; import com.appsmith.external.exceptions.AppsmithErrorAction; +import com.appsmith.external.exceptions.BaseException; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.server.dtos.ResponseDTO; import io.sentry.Sentry; @@ -53,14 +54,8 @@ private void doLog(Throwable error) { } ); - if (error instanceof AppsmithException || error instanceof AppsmithPluginException) { - if (error instanceof AppsmithException - && ((AppsmithException)error).getErrorAction() == AppsmithErrorAction.LOG_EXTERNALLY) { - Sentry.captureException(error); - } - - if (error instanceof AppsmithPluginException - && ((AppsmithPluginException)error).getErrorAction() == AppsmithErrorAction.LOG_EXTERNALLY) { + if (error instanceof BaseException) { + if (((BaseException)error).getErrorAction() == AppsmithErrorAction.LOG_EXTERNALLY) { Sentry.captureException(error); } } else { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionServiceImpl.java index 9a665ee69c2b..e751ae8c31bf 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionServiceImpl.java @@ -480,7 +480,6 @@ public Mono<ActionDTO> updateUnpublishedAction(String id, ActionDTO action) { @Override public Mono<ActionExecutionResult> executeAction(ExecuteActionDTO executeActionDTO) { - // 1. Validate input parameters which are required for mustache replacements List<Param> params = executeActionDTO.getParams(); if (!CollectionUtils.isEmpty(params)) { @@ -545,6 +544,7 @@ public Mono<ActionExecutionResult> executeAction(ExecuteActionDTO executeActionD FieldName.DATASOURCE, action.getDatasource().getId()))); } + // This is a nested datasource. Return as is. return Mono.just(action.getDatasource()); }) @@ -641,8 +641,13 @@ public Mono<ActionExecutionResult> executeAction(ExecuteActionDTO executeActionD // Set the status code for Appsmith plugin errors if (e instanceof AppsmithPluginException) { result.setStatusCode(((AppsmithPluginException) e).getAppErrorCode().toString()); + result.setTitle(((AppsmithPluginException) e).getTitle()); } else { result.setStatusCode(AppsmithPluginError.PLUGIN_ERROR.getAppErrorCode().toString()); + + if (e instanceof AppsmithException) { + result.setTitle(((AppsmithException) e).getTitle()); + } } return Mono.just(result); }) @@ -679,6 +684,7 @@ public Mono<ActionExecutionResult> executeAction(ExecuteActionDTO executeActionD result.setIsExecutionSuccess(false); result.setStatusCode(error.getAppErrorCode().toString()); result.setBody(error.getMessage()); + result.setTitle(error.getTitle()); return Mono.just(result); }) .map(result -> { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionServiceTest.java index ff81c7eaf43a..d224d388aafe 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionServiceTest.java @@ -525,6 +525,7 @@ public void testActionExecuteErrorResponse() { .assertNext(result -> { assertThat(result.getIsExecutionSuccess()).isFalse(); assertThat(result.getStatusCode()).isEqualTo(pluginException.getAppErrorCode().toString()); + assertThat(result.getTitle()).isEqualTo(pluginException.getTitle()); }) .verifyComplete(); } @@ -570,6 +571,7 @@ public void testActionExecuteNullPaginationParameters() { .assertNext(result -> { assertThat(result.getIsExecutionSuccess()).isFalse(); assertThat(result.getStatusCode()).isEqualTo(pluginException.getAppErrorCode().toString()); + assertThat(result.getTitle()).isEqualTo(pluginException.getTitle()); }) .verifyComplete(); } @@ -611,6 +613,7 @@ public void testActionExecuteSecondaryStaleConnection() { .assertNext(result -> { assertThat(result.getIsExecutionSuccess()).isFalse(); assertThat(result.getStatusCode()).isEqualTo(AppsmithPluginError.PLUGIN_ERROR.getAppErrorCode().toString()); + assertThat(result.getTitle()).isEqualTo(AppsmithPluginError.PLUGIN_ERROR.getTitle()); }) .verifyComplete(); } @@ -652,6 +655,7 @@ public void testActionExecuteTimeout() { .assertNext(result -> { assertThat(result.getIsExecutionSuccess()).isFalse(); assertThat(result.getStatusCode()).isEqualTo(AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR.getAppErrorCode().toString()); + assertThat(result.getTitle()).isEqualTo(AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR.getTitle()); }) .verifyComplete(); }
7d9b58c471db3132072d1fd9d7fec14296f13d44
2023-08-04 15:26:05
Dancia
fix: Added utm codes to readme links (#26033)
false
Added utm codes to readme links (#26033)
fix
diff --git a/README.md b/README.md index 48bee638a6c3..f0cc18f323b6 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ --- -Organizations build internal applications such as dashboards, database GUIs, admin panels, approval apps, customer support dashboards, and more to help their teams perform day-to-day operations. Appsmith is an open-source tool that enables the rapid development of these internal apps. Read more on our [website](https://appsmith.com?utm_source=github&utm_medium=organic&utm_campaign=readme). +Organizations build internal applications such as dashboards, database GUIs, admin panels, approval apps, customer support dashboards, and more to help their teams perform day-to-day operations. Appsmith is an open-source tool that enables the rapid development of these internal apps. Read more on our [website](https://www.appsmith.com?utm_source=github&utm_medium=organic&utm_campaign=readme). [![Appsmith in 100 secs](/static/images/appsmith-in-100-seconds.png)](https://www.youtube.com/watch?v=Dxe_NzdGzL4&utm_source=github&utm_medium=organic&utm_campaign=readme/?target=_blank) @@ -27,7 +27,7 @@ Organizations build internal applications such as dashboards, database GUIs, adm ## Installation There are two ways to start using Appsmith: -- Signup on [Appsmith Cloud](https://app.appsmith.com/). +- Signup on [Appsmith Cloud](https://app.appsmith.com/?utm_source=github&utm_medium=organic&utm_campaign=readme). - Install Appsmith on your machine. See the installation guides below. | Installation Methods | Documentation | @@ -44,13 +44,13 @@ To build and run Appsmith in your local dev environment, see [Setup for local de ## Learning Resources - [Documentation](https://docs.appsmith.com?utm_source=github&utm_medium=organic&utm_campaign=readme) -- [Tutorials](https://docs.appsmith.com/getting-started/tutorials) +- [Tutorials](https://docs.appsmith.com/getting-started/tutorials?utm_source=github&utm_medium=organic&utm_campaign=readme) - [Videos](https://www.youtube.com/appsmith?utm_source=github&utm_medium=organic&utm_campaign=readme) - [Templates](https://www.appsmith.com/templates?utm_source=github&utm_medium=organic&utm_campaign=readme&utm_content=support) ## Need Help? -- [Discord](https://discord.gg/rBTTVJp) -- [Community Portal](https://community.appsmith.com/) +- [Discord](https://discord.gg/rBTTVJp?utm_source=github&utm_medium=organic&utm_campaign=readme) +- [Community Portal](https://community.appsmith.com/?utm_source=github&utm_medium=organic&utm_campaign=readme) - [[email protected]](mailto:[email protected])
b4e9f648c31760e02421f326fa4d881b787e4672
2022-08-09 22:40:10
rahulramesha
fix: Multiple scrolls in view mode (#15679)
false
Multiple scrolls in view mode (#15679)
fix
diff --git a/app/client/src/pages/AppViewer/AppViewerPageContainer.tsx b/app/client/src/pages/AppViewer/AppViewerPageContainer.tsx index 3d80df63edb8..8c7618e0ca15 100644 --- a/app/client/src/pages/AppViewer/AppViewerPageContainer.tsx +++ b/app/client/src/pages/AppViewer/AppViewerPageContainer.tsx @@ -20,11 +20,9 @@ import { } from "../Applications/permissionHelpers"; import { builderURL } from "RouteBuilder"; -const Section = styled.section<{ - height: number; -}>` +const Section = styled.section` height: 100%; - min-height: ${({ height }) => height}px; + width: 100%; margin: 0 auto; position: relative; overflow-x: auto; @@ -91,7 +89,7 @@ function AppViewerPageContainer(props: AppViewerPageContainerProps) { if (!(widgets.children && widgets.children.length > 0)) return pageNotFound; return ( - <Section height={widgets.bottomRow}> + <Section> <AppPage appName={currentApplication?.name} dsl={widgets}
2ca5993b18b2f288c1082bb8c54574b7c21a2e66
2025-01-20 23:23:26
albinAppsmith
fix: Stopped calling usage pulse in air-gapped instance (#38749)
false
Stopped calling usage pulse in air-gapped instance (#38749)
fix
diff --git a/app/client/src/usagePulse/index.ts b/app/client/src/usagePulse/index.ts index 0587889db13f..53edcb3b04ec 100644 --- a/app/client/src/usagePulse/index.ts +++ b/app/client/src/usagePulse/index.ts @@ -18,6 +18,7 @@ import { PULSE_INTERVAL as PULSE_INTERVAL_CE } from "ce/constants/UsagePulse"; import { PULSE_INTERVAL as PULSE_INTERVAL_EE } from "ee/constants/UsagePulse"; import store from "store"; import type { PageListReduxState } from "reducers/entityReducers/pageListReducer"; +import { isAirgapped } from "ee/utils/airgapHelpers"; class UsagePulse { static userAnonymousId: string | undefined; @@ -26,6 +27,7 @@ class UsagePulse { static isTelemetryEnabled: boolean; static isAnonymousUser: boolean; static isFreePlan: boolean; + static isAirgapped = isAirgapped(); /* * Function to check if the given URL is trakable or not. @@ -143,6 +145,10 @@ class UsagePulse { * registers listeners to wait for the user to go to a trackable url */ static async sendPulseAndScheduleNext() { + if (UsagePulse.isAirgapped) { + return; + } + UsagePulse.sendPulse(); UsagePulse.scheduleNextActivityListeners(); } diff --git a/app/client/src/usagePulse/usagePulse.test.ts b/app/client/src/usagePulse/usagePulse.test.ts index 9929128ea5df..2fa3c4507647 100644 --- a/app/client/src/usagePulse/usagePulse.test.ts +++ b/app/client/src/usagePulse/usagePulse.test.ts @@ -29,4 +29,34 @@ describe("Usage pulse", () => { }); }); }); + + describe("sendPulseAndScheduleNext", () => { + let sendPulseSpy: jest.SpyInstance; + let scheduleNextActivityListenersSpy: jest.SpyInstance; + + beforeEach(() => { + sendPulseSpy = jest + .spyOn(UsagePulse, "sendPulse") + .mockImplementation(() => {}); + scheduleNextActivityListenersSpy = jest + .spyOn(UsagePulse, "scheduleNextActivityListeners") + .mockImplementation(() => {}); + UsagePulse.isAirgapped = false; + }); + + it("should not send pulse or schedule next when airgapped", () => { + UsagePulse.isAirgapped = true; + UsagePulse.sendPulseAndScheduleNext(); + + expect(sendPulseSpy).not.toHaveBeenCalled(); + expect(scheduleNextActivityListenersSpy).not.toHaveBeenCalled(); + }); + + it("should send pulse and schedule next activity listeners when not airgapped", () => { + UsagePulse.sendPulseAndScheduleNext(); + + expect(sendPulseSpy).toHaveBeenCalledTimes(1); + expect(scheduleNextActivityListenersSpy).toHaveBeenCalledTimes(1); + }); + }); });
7b9ed8021ee6d7a7efbef3995a6ac8b17669beee
2023-08-30 18:21:48
Saroj
ci: Fix non-duplicate specs rerun (#26796)
false
Fix non-duplicate specs rerun (#26796)
ci
diff --git a/.github/workflows/ci-test-custom-script.yml b/.github/workflows/ci-test-custom-script.yml index 4bc883b0ae7c..17f6ad77f289 100644 --- a/.github/workflows/ci-test-custom-script.yml +++ b/.github/workflows/ci-test-custom-script.yml @@ -114,12 +114,16 @@ jobs: file_path=$(echo "$line" | awk -F'/' '{print $(NF-1)"/"$NF}') spec_name=$(echo "$file_path" | awk -F'/' '{print $NF}') failed_spec=$(find . -name "$spec_name" | sed 's|./||') - for file in $failed_spec; do - new_file_path=$(echo "$file" | awk -F'/' '{print $(NF-1)"/"$NF}') - if [ "$new_file_path" == "$file_path" ]; then - failed_spec_env="$failed_spec_env,$file" - fi - done + if [ "$(echo "$failed_spec" | wc -l)" -eq 1 ]; then + failed_spec_env="$failed_spec_env,$failed_spec" + else + for file in $failed_spec; do + new_file_path=$(echo "$file" | awk -F'/' '{print $(NF-1)"/"$NF}') + if [ "$new_file_path" == "$file_path" ]; then + failed_spec_env="$failed_spec_env,$file" + fi + done + fi done < ~/failed_spec_ci/failed_spec_ci-${{ matrix.job }} failed_spec_env=${failed_spec_env#,} echo "failed_spec_env=$failed_spec_env" >> $GITHUB_ENV
34b7a841b71ef425753857cd84060e344868122b
2022-12-23 17:05:27
Abhinav Jha
fix: Enable auto height by default for JSONForm widget (#18932)
false
Enable auto height by default for JSONForm widget (#18932)
fix
diff --git a/app/client/src/utils/WidgetFeatures.ts b/app/client/src/utils/WidgetFeatures.ts index 4296ef6bcf12..1c0f555cda74 100644 --- a/app/client/src/utils/WidgetFeatures.ts +++ b/app/client/src/utils/WidgetFeatures.ts @@ -64,7 +64,17 @@ export const WidgetFeaturePropertyEnhancements: Record< newProperties.minDynamicHeight = config.defaults.minDynamicHeight || WidgetHeightLimits.MIN_CANVAS_HEIGHT_IN_ROWS; + newProperties.maxDynamicHeight = + config.defaults.maxDynamicHeight || + WidgetHeightLimits.MAX_HEIGHT_IN_ROWS; newProperties.shouldScrollContents = true; + } else { + newProperties.minDynamicHeight = + config.defaults.minDynamicHeight || + WidgetHeightLimits.MIN_HEIGHT_IN_ROWS; + newProperties.maxDynamicHeight = + config.defaults.maxDynamicHeight || + WidgetHeightLimits.MAX_HEIGHT_IN_ROWS; } if (config.defaults.overflow) newProperties.overflow = "NONE"; return newProperties; diff --git a/app/client/src/widgets/JSONFormWidget/component/index.tsx b/app/client/src/widgets/JSONFormWidget/component/index.tsx index 43336eb437ce..17fc1b0fb505 100644 --- a/app/client/src/widgets/JSONFormWidget/component/index.tsx +++ b/app/client/src/widgets/JSONFormWidget/component/index.tsx @@ -35,6 +35,7 @@ export type JSONFormComponentProps<TValues = any> = { fieldLimitExceeded: boolean; fixedFooter: boolean; getFormData: () => TValues; + fixMessageHeight: boolean; isWidgetMounting: boolean; isSubmitting: boolean; onFormValidityUpdate: (isValid: boolean) => void; @@ -64,27 +65,37 @@ const StyledContainer = styled(WidgetStyleContainer)<StyledContainerProps>` overflow-y: auto; `; -const MessageStateWrapper = styled.div` +const MessageStateWrapper = styled.div<{ $fixHeight: boolean }>` align-items: center; display: flex; - height: 100%; + ${(props) => (props.$fixHeight ? "height: 303px" : "height: 100%")}; justify-content: center; `; -const Message = styled(Text)` +const Message = styled(Text)<{ $fixHeight: boolean }>` font-size: ${TEXT_SIZES.HEADING3}; - left: 50%; - position: absolute; text-align: center; + width: 100%; + left: 50%; + ${(props) => + !props.$fixHeight + ? `position: absolute; top: 50%; transform: translate(-50%, -50%); - width: 100%; + ` + : ""} `; -function InfoMessage({ children }: { children: React.ReactNode }) { +function InfoMessage({ + children, + fixHeight, +}: { + children: React.ReactNode; + fixHeight: boolean; +}) { return ( - <MessageStateWrapper> - <Message>{children}</Message> + <MessageStateWrapper $fixHeight={fixHeight}> + <Message $fixHeight={fixHeight}>{children}</Message> </MessageStateWrapper> ); } @@ -94,6 +105,7 @@ function JSONFormComponent<TValues>( backgroundColor, executeAction, fieldLimitExceeded, + fixMessageHeight, getFormData, isSubmitting, isWidgetMounting, @@ -144,7 +156,7 @@ function JSONFormComponent<TValues>( const renderComponent = (() => { if (fieldLimitExceeded) { return ( - <InfoMessage> + <InfoMessage fixHeight={fixMessageHeight}> Source data exceeds {MAX_ALLOWED_FIELDS} fields.&nbsp; {renderMode === RenderModes.PAGE ? "Please contact your developer for more information" @@ -154,7 +166,7 @@ function JSONFormComponent<TValues>( } if (isSchemaEmpty) { return ( - <InfoMessage> + <InfoMessage fixHeight={fixMessageHeight}> Connect data or paste JSON to add items to this form. </InfoMessage> ); diff --git a/app/client/src/widgets/JSONFormWidget/index.ts b/app/client/src/widgets/JSONFormWidget/index.ts index a9caf80d3cc7..a6de1bb771be 100644 --- a/app/client/src/widgets/JSONFormWidget/index.ts +++ b/app/client/src/widgets/JSONFormWidget/index.ts @@ -17,7 +17,7 @@ export const CONFIG = { features: { dynamicHeight: { sectionIndex: 1, - defaultValue: DynamicHeight.FIXED, + defaultValue: DynamicHeight.AUTO_HEIGHT, active: true, }, }, @@ -31,7 +31,7 @@ export const CONFIG = { columns: 25, disabledWhenInvalid: true, fixedFooter: true, - rows: 50, + rows: 41, schema: {}, scrollContents: true, showReset: true, diff --git a/app/client/src/widgets/JSONFormWidget/widget/index.tsx b/app/client/src/widgets/JSONFormWidget/widget/index.tsx index e8356f8e5a5b..f7611005feec 100644 --- a/app/client/src/widgets/JSONFormWidget/widget/index.tsx +++ b/app/client/src/widgets/JSONFormWidget/widget/index.tsx @@ -29,6 +29,7 @@ import { BoxShadow } from "components/designSystems/appsmith/WidgetStyleContaine import { convertSchemaItemToFormData } from "../helper"; import { ButtonStyles, ChildStylesheet, Stylesheet } from "entities/AppTheming"; import { BatchPropertyUpdatePayload } from "actions/controlActions"; +import { isAutoHeightEnabledForWidget } from "widgets/WidgetUtils"; export interface JSONFormWidgetProps extends WidgetProps { autoGenerateForm?: boolean; @@ -493,6 +494,7 @@ class JSONFormWidget extends BaseWidget< }; getPageView() { + const isAutoHeightEnabled = isAutoHeightEnabledForWidget(this.props); return ( // Warning!!! Do not ever introduce formData as a prop directly, // it would lead to severe performance degradation due to frequent @@ -507,6 +509,7 @@ class JSONFormWidget extends BaseWidget< disabledWhenInvalid={this.props.disabledWhenInvalid} executeAction={this.onExecuteAction} fieldLimitExceeded={this.props.fieldLimitExceeded} + fixMessageHeight={isAutoHeightEnabled} fixedFooter={this.props.fixedFooter} getFormData={this.getFormData} isSubmitting={this.state.isSubmitting}
6b278ae7eee4b3a39c73424f4dd7106b048157c7
2024-05-15 15:34:36
vadim
fix: WDS, increase perceived darkness of modal overlay (#33476)
false
WDS, increase perceived darkness of modal overlay (#33476)
fix
diff --git a/app/client/packages/design-system/theming/src/color/src/DarkModeTheme.ts b/app/client/packages/design-system/theming/src/color/src/DarkModeTheme.ts index 92cdcf8fcda0..8346c8a6ad70 100644 --- a/app/client/packages/design-system/theming/src/color/src/DarkModeTheme.ts +++ b/app/client/packages/design-system/theming/src/color/src/DarkModeTheme.ts @@ -330,10 +330,10 @@ export class DarkModeTheme implements ColorModeTheme { // Overlay behind modal dialogue const color = this.bgNeutral.clone(); - color.alpha = 0.5; + color.alpha = 0.7; - if (color.oklch.l > 0.15) { - color.oklch.l = 0.15; + if (color.oklch.l > 0.12) { + color.oklch.l = 0.12; } return color; diff --git a/app/client/packages/design-system/theming/src/color/src/LightModeTheme.ts b/app/client/packages/design-system/theming/src/color/src/LightModeTheme.ts index 0d2f336b6c09..a1bceb246005 100644 --- a/app/client/packages/design-system/theming/src/color/src/LightModeTheme.ts +++ b/app/client/packages/design-system/theming/src/color/src/LightModeTheme.ts @@ -330,7 +330,7 @@ export class LightModeTheme implements ColorModeTheme { // Overlay behind modal dialogue const color = this.bgNeutral.clone(); - color.alpha = 0.5; + color.alpha = 0.6; if (color.oklch.l > 0.15) { color.oklch.l = 0.15; diff --git a/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts b/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts index 9b3c1b49dfd3..fc8ad80917f8 100644 --- a/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts +++ b/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts @@ -214,7 +214,7 @@ describe("bgNeutralOpacity color", () => { const { bgNeutralOpacity } = new DarkModeTheme( "oklch(0.51 0.24 279)", ).getColors(); - expect(bgNeutralOpacity).toEqual("rgb(3.6355% 4.017% 7.6512% / 0.5)"); + expect(bgNeutralOpacity).toEqual("rgb(1.7871% 1.9891% 5.049% / 0.7)"); }); }); diff --git a/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts b/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts index 1d8c702cabcd..c7be28ccda65 100644 --- a/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts +++ b/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts @@ -231,7 +231,7 @@ describe("bgNeutralOpacity color", () => { const { bgNeutralOpacity } = new LightModeTheme( "oklch(0.51 0.24 279)", ).getColors(); - expect(bgNeutralOpacity).toEqual("rgb(4.2704% 4.3279% 4.6942% / 0.5)"); + expect(bgNeutralOpacity).toEqual("rgb(4.2704% 4.3279% 4.6942% / 0.6)"); }); });
b458bd09b2928623112ee505cddcc2cd3dbc3621
2024-02-12 10:53:48
Rudraprasad Das
fix: autocommit ui issues (#30887)
false
autocommit ui issues (#30887)
fix
diff --git a/app/client/src/actions/gitSyncActions.ts b/app/client/src/actions/gitSyncActions.ts index 6092825e9b76..6ad11513f20b 100644 --- a/app/client/src/actions/gitSyncActions.ts +++ b/app/client/src/actions/gitSyncActions.ts @@ -483,7 +483,7 @@ export const setIsAutocommitModalOpen = (isAutocommitModalOpen: boolean) => ({ }); export const startAutocommitProgressPolling = () => ({ - type: ReduxActionTypes.GIT_AUTOCOMMIT_START_PROGRESS_POLLING, + type: ReduxActionTypes.GIT_AUTOCOMMIT_INITIATE_PROGRESS_POLLING, }); export const stopAutocommitProgressPolling = () => ({ diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index c11975349f12..9cb429c4d771 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -130,6 +130,8 @@ const ActionTypes = { GIT_TOGGLE_AUTOCOMMIT_ENABLED_INIT: "GIT_TOGGLE_AUTOCOMMIT_ENABLED_INIT", GIT_TOGGLE_AUTOCOMMIT_ENABLED_SUCCESS: "GIT_TOGGLE_AUTOCOMMIT_ENABLED_SUCCESS", + GIT_AUTOCOMMIT_INITIATE_PROGRESS_POLLING: + "GIT_AUTOCOMMIT_INITIATE_PROGRESS_POLLING", GIT_AUTOCOMMIT_START_PROGRESS_POLLING: "GIT_AUTOCOMMIT_START_PROGRESS_POLLING", GIT_AUTOCOMMIT_STOP_PROGRESS_POLLING: "GIT_AUTOCOMMIT_STOP_PROGRESS_POLLING", diff --git a/app/client/src/pages/Editor/gitSync/GitSettingsModal/index.test.tsx b/app/client/src/pages/Editor/gitSync/GitSettingsModal/index.test.tsx new file mode 100644 index 000000000000..12ac0e96c643 --- /dev/null +++ b/app/client/src/pages/Editor/gitSync/GitSettingsModal/index.test.tsx @@ -0,0 +1,107 @@ +import React from "react"; +import { render } from "@testing-library/react"; + +import type { MockStoreEnhanced } from "redux-mock-store"; +import configureStore from "redux-mock-store"; +import { Provider } from "react-redux"; +import { GitSettingsTab } from "reducers/uiReducers/gitSyncReducer"; +import GitSettingsModal from "."; + +const createInitialState = (overrideFn = (o: any) => o) => { + const initialState = { + ui: { + gitSync: { + isGitSettingsModalOpen: true, + activeGitSettingsModalTab: "GENERAL", + }, + applications: { + currentApplication: { + userPermissions: [ + "manageAutoCommit:applications", + "manageProtectedBranches:applications", + "manageDefaultBranches:applications", + "connectToGit:applications", + ], + gitApplicationMetadata: { + defaultBranchName: "master", + }, + }, + }, + users: { + featureFlag: { + data: { + license_git_continuous_delivery_enabled: true, + release_git_continuous_delivery_enabled: true, + }, + }, + }, + }, + }; + return overrideFn(initialState); +}; +const mockStore = configureStore(); + +jest.mock("./TabGeneral", () => { + return () => null; +}); + +jest.mock("./TabBranch", () => { + return () => null; +}); + +jest.mock("@appsmith/components/gitComponents/GitSettingsCDTab", () => { + return () => null; +}); + +const renderComponent = (store: MockStoreEnhanced<unknown, any>) => { + return render( + <Provider store={store}> + <GitSettingsModal /> + </Provider>, + ); +}; + +describe("Git Settings Modal", () => { + it("is rendered properly", () => { + const store = mockStore(createInitialState()); + const { queryByTestId } = renderComponent(store); + expect(queryByTestId("t--git-settings-modal")).toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.GENERAL}`)).toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.BRANCH}`)).toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.CD}`)).toBeTruthy(); + }); + + it("is not rendering branch tab when neither of the features are enabled", () => { + const initialState = createInitialState((initialState) => { + const newState = { ...initialState }; + newState.ui.applications.currentApplication.userPermissions = [ + "manageAutoCommit:applications", + "connectToGit:applications", + ]; + return newState; + }); + const store = mockStore(initialState); + const { queryByTestId } = renderComponent(store); + expect(queryByTestId("t--git-settings-modal")).toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.GENERAL}`)).toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.BRANCH}`)).not.toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.CD}`)).toBeTruthy(); + }); + + it("is not rendering CD when feature flag is not enabled", () => { + const initialState = createInitialState((initialState) => { + const newState = { ...initialState }; + newState.ui.users.featureFlag.data = { + license_git_continuous_delivery_enabled: false, + release_git_continuous_delivery_enabled: false, + }; + return newState; + }); + const store = mockStore(initialState); + const { queryByTestId } = renderComponent(store); + expect(queryByTestId("t--git-settings-modal")).toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.GENERAL}`)).toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.BRANCH}`)).toBeTruthy(); + expect(queryByTestId(`t--tab-${GitSettingsTab.CD}`)).not.toBeTruthy(); + }); +}); diff --git a/app/client/src/pages/Editor/gitSync/GitSettingsModal/index.tsx b/app/client/src/pages/Editor/gitSync/GitSettingsModal/index.tsx index fd452379cfaa..657be5f34e6e 100644 --- a/app/client/src/pages/Editor/gitSync/GitSettingsModal/index.tsx +++ b/app/client/src/pages/Editor/gitSync/GitSettingsModal/index.tsx @@ -6,8 +6,6 @@ import { import { useDispatch, useSelector } from "react-redux"; import { setGitSettingsModalOpenAction } from "actions/gitSyncActions"; -import GitErrorPopup from "../components/GitErrorPopup"; - import { Modal, ModalBody, ModalContent, ModalHeader } from "design-system"; import styled from "styled-components"; import Menu from "../Menu"; @@ -24,6 +22,10 @@ import TabBranch from "./TabBranch"; import GitSettingsCDTab from "@appsmith/components/gitComponents/GitSettingsCDTab"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; +import { + useHasManageDefaultBranchPermission, + useHasManageProtectedBranchesPermission, +} from "../hooks/gitPermissionHooks"; const StyledModalContent = styled(ModalContent)` &&& { @@ -36,6 +38,13 @@ const StyledModalContent = styled(ModalContent)` `; function GitSettingsModal() { + const isManageProtectedBranchesPermitted = + useHasManageProtectedBranchesPermission(); + const isManageDefaultBranchPermitted = useHasManageDefaultBranchPermission(); + + const showBranchTab = + isManageDefaultBranchPermitted || isManageProtectedBranchesPermitted; + const isModalOpen = useSelector(isGitSettingsModalOpenSelector); const activeTabKey = useSelector(activeGitSettingsModalTabSelector); @@ -49,11 +58,14 @@ function GitSettingsModal() { key: GitSettingsTab.GENERAL, title: createMessage(GENERAL), }, - { + ]; + + if (showBranchTab) { + menuOptions.push({ key: GitSettingsTab.BRANCH, title: createMessage(BRANCH), - }, - ]; + }); + } if (isGitCDEnabled) { menuOptions.push({ @@ -81,35 +93,32 @@ function GitSettingsModal() { }; return ( - <> - <Modal - onOpenChange={(open) => { - if (!open) { - handleClose(); + <Modal + onOpenChange={(open) => { + if (!open) { + handleClose(); + } + }} + open={isModalOpen} + > + <StyledModalContent data-testid="t--git-settings-modal"> + <ModalHeader>{createMessage(SETTINGS_GIT)}</ModalHeader> + <Menu + activeTabKey={activeTabKey} + onSelect={(tabKey: string) => + setActiveTabKey(tabKey as GitSettingsTab) } - }} - open={isModalOpen} - > - <StyledModalContent data-testid="t--git-settings-modal"> - <ModalHeader>{createMessage(SETTINGS_GIT)}</ModalHeader> - <Menu - activeTabKey={activeTabKey} - onSelect={(tabKey: string) => - setActiveTabKey(tabKey as GitSettingsTab) - } - options={menuOptions} - /> - <ModalBody> - {activeTabKey === GitSettingsTab.GENERAL && <TabGeneral />} - {activeTabKey === GitSettingsTab.BRANCH && <TabBranch />} - {isGitCDEnabled && activeTabKey === GitSettingsTab.CD && ( - <GitSettingsCDTab /> - )} - </ModalBody> - </StyledModalContent> - </Modal> - <GitErrorPopup /> - </> + options={menuOptions} + /> + <ModalBody> + {activeTabKey === GitSettingsTab.GENERAL && <TabGeneral />} + {activeTabKey === GitSettingsTab.BRANCH && <TabBranch />} + {isGitCDEnabled && activeTabKey === GitSettingsTab.CD && ( + <GitSettingsCDTab /> + )} + </ModalBody> + </StyledModalContent> + </Modal> ); } diff --git a/app/client/src/pages/Editor/gitSync/QuickGitActions/index.tsx b/app/client/src/pages/Editor/gitSync/QuickGitActions/index.tsx index 59e402463e8e..f16f434e5324 100644 --- a/app/client/src/pages/Editor/gitSync/QuickGitActions/index.tsx +++ b/app/client/src/pages/Editor/gitSync/QuickGitActions/index.tsx @@ -30,6 +30,7 @@ import { import { GitSyncModalTab } from "entities/GitSync"; import { getCountOfChangesToCommit, + getGitMetadataSelector, getGitStatus, getIsDiscardInProgress, getIsFetchingGitStatus, @@ -306,7 +307,9 @@ export default function QuickGitActions() { const isAutocommitFeatureEnabled = useFeatureFlag( FEATURE_FLAG.release_git_autocommit_feature_enabled, ); + const gitMetadata = useSelector(getGitMetadataSelector); const isPollingAutocommit = useSelector(getIsPollingAutocommit); + const isAutocommitEnabled = gitMetadata?.autoCommitConfig?.enabled; const quickActionButtons = getQuickActionButtons({ commit: () => { @@ -368,7 +371,9 @@ export default function QuickGitActions() { return isGitConnected ? ( <Container> <BranchButton /> - {isAutocommitFeatureEnabled && isPollingAutocommit ? ( + {isAutocommitFeatureEnabled && + isAutocommitEnabled && + isPollingAutocommit ? ( <AutocommitStatusbar completed={!isPollingAutocommit} /> ) : ( quickActionButtons.map((button) => ( diff --git a/app/client/src/sagas/GitSyncSagas.ts b/app/client/src/sagas/GitSyncSagas.ts index 4698bf170b15..8cba8d67a7f2 100644 --- a/app/client/src/sagas/GitSyncSagas.ts +++ b/app/client/src/sagas/GitSyncSagas.ts @@ -1159,39 +1159,62 @@ function* getGitMetadataSaga() { function* pollAutocommitProgressSaga(): any { const applicationId: string = yield select(getCurrentApplicationId); try { - while (true) { - const response: ApiResponse<any> = yield call( - GitSyncAPI.getAutocommitProgress, - applicationId, - ); - const isValidResponse: boolean = yield validateResponse( - response, - false, - getLogToSentryFromResponse(response), - ); - if (isValidResponse) { - yield put({ - type: ReduxActionTypes.GIT_SET_AUTOCOMMIT_PROGRESS, - payload: response.data, - }); - if (!response?.data?.isRunning) { + const response: ApiResponse<any> = yield call( + GitSyncAPI.getAutocommitProgress, + applicationId, + ); + const isValidResponse: boolean = yield validateResponse( + response, + false, + getLogToSentryFromResponse(response), + ); + if (isValidResponse && response?.data?.isRunning) { + yield put({ + type: ReduxActionTypes.GIT_AUTOCOMMIT_START_PROGRESS_POLLING, + }); + while (true) { + const response: ApiResponse<any> = yield call( + GitSyncAPI.getAutocommitProgress, + applicationId, + ); + const isValidResponse: boolean = yield validateResponse( + response, + false, + getLogToSentryFromResponse(response), + ); + if (isValidResponse) { yield put({ - type: ReduxActionTypes.GIT_AUTOCOMMIT_STOP_PROGRESS_POLLING, + type: ReduxActionTypes.GIT_SET_AUTOCOMMIT_PROGRESS, payload: response.data, }); + if (!response?.data?.isRunning) { + yield put({ + type: ReduxActionTypes.GIT_AUTOCOMMIT_STOP_PROGRESS_POLLING, + }); + } + } else { + yield put({ + type: ReduxActionTypes.GIT_AUTOCOMMIT_STOP_PROGRESS_POLLING, + }); + yield put({ + type: ReduxActionErrorTypes.GIT_AUTOCOMMIT_PROGRESS_POLLING_ERROR, + payload: { + error: response?.responseMeta?.error?.message, + show: true, + }, + }); } - } else { - yield put({ - type: ReduxActionErrorTypes.GIT_AUTOCOMMIT_PROGRESS_POLLING_ERROR, - payload: { - error: response?.responseMeta?.error?.message, - show: true, - }, - }); + yield delay(1000); } - yield delay(1000); + } else { + yield put({ + type: ReduxActionTypes.GIT_AUTOCOMMIT_STOP_PROGRESS_POLLING, + }); } } catch (error) { + yield put({ + type: ReduxActionTypes.GIT_AUTOCOMMIT_STOP_PROGRESS_POLLING, + }); yield put({ type: ReduxActionErrorTypes.GIT_AUTOCOMMIT_PROGRESS_POLLING_ERROR, payload: { error }, @@ -1274,7 +1297,7 @@ function* watchGitNonBlockingRequests() { function* watchGitAutocommitPolling() { while (true) { - yield take(ReduxActionTypes.GIT_AUTOCOMMIT_START_PROGRESS_POLLING); + yield take(ReduxActionTypes.GIT_AUTOCOMMIT_INITIATE_PROGRESS_POLLING); /* @ts-expect-error: not sure how to do typings of this */ const pollTask = yield fork(pollAutocommitProgressSaga); yield take(ReduxActionTypes.GIT_AUTOCOMMIT_STOP_PROGRESS_POLLING);
5eba842e8b49ba79ffadd62f93efbee4a8714dc2
2023-06-08 18:33:34
Vemparala Surya Vamsi
chore: [One-click binding] design and QA callouts one click binding (#23997)
false
[One-click binding] design and QA callouts one click binding (#23997)
chore
diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts index 0c7c5fe3ae8c..4bb4e1ef2056 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts @@ -1,20 +1,31 @@ import * as _ from "../../../../support/Objects/ObjectsCore"; -import { ChooseAndAssertForm } from "./spec_utility"; -import locator from "../../../../locators/OneClickBindingLocator"; import CommonLocators from "../../../../locators/commonlocators.json"; import DatasourceEditor from "../../../../locators/DatasourcesEditor.json"; +import { OneClickBinding } from "./spec_utility"; +import oneClickBindingLocator from "../../../../locators/OneClickBindingLocator"; +import onboardingLocator from "../../../../locators/FirstTimeUserOnboarding.json"; -describe.skip("One click binding control", () => { +const oneClickBinding = new OneClickBinding(); + +describe("One click binding control", () => { before(() => { - _.entityExplorer.DragDropWidgetNVerify("tablewidgetv2"); + _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE); }); it("1.should check the datasource selector and the form", () => { - _.agHelper.AssertElementExist(locator.datasourceDropdownSelector); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); - _.agHelper.AssertElementAbsence(locator.datasourceQueryBindHeaderSelector); - _.agHelper.AssertElementExist(locator.datasourceGenerateAQuerySelector); - _.agHelper.AssertElementExist(locator.datasourceOtherActionsSelector); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceDropdownSelector, + ); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); + _.agHelper.AssertElementAbsence( + oneClickBindingLocator.datasourceQueryBindHeaderSelector, + ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceGenerateAQuerySelector, + ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceOtherActionsSelector, + ); _.entityExplorer.NavigateToSwitcher("Explorer"); cy.wait(500); @@ -29,49 +40,64 @@ describe.skip("One click binding control", () => { _.entityExplorer.NavigateToSwitcher("Explorer"); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); - _.agHelper.AssertElementExist(locator.datasourceQueryBindHeaderSelector); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceQueryBindHeaderSelector, + ); - _.agHelper.AssertElementLength(locator.datasourceQuerySelector, 1); + _.agHelper.AssertElementLength( + oneClickBindingLocator.datasourceQuerySelector, + 1, + ); - _.agHelper.AssertElementExist(locator.datasourceGenerateAQuerySelector); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceGenerateAQuerySelector, + ); - _.agHelper.AssertElementExist(locator.datasourceSelector()); + _.agHelper.AssertElementExist(oneClickBindingLocator.datasourceSelector()); - _.agHelper.AssertElementExist(locator.datasourceOtherActionsSelector); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceOtherActionsSelector, + ); - _.agHelper.AssertElementExist(locator.otherActionSelector()); + _.agHelper.AssertElementExist(oneClickBindingLocator.otherActionSelector()); _.agHelper.AssertElementExist( - locator.otherActionSelector("Connect new datasource"), + oneClickBindingLocator.otherActionSelector("Connect new datasource"), ); - _.agHelper.GetNClick(locator.otherActionSelector("Connect new datasource")); + _.agHelper.GetNClick( + oneClickBindingLocator.otherActionSelector("Connect new datasource"), + ); - _.agHelper.AssertElementExist(locator.datasourcePage); + _.agHelper.AssertElementExist(onboardingLocator.datasourcePage); - _.agHelper.GetNClick(locator.backButton); + _.agHelper.GetNClick(onboardingLocator.datasourceBackBtn); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); _.agHelper.AssertElementExist( - locator.otherActionSelector("Insert snippet"), + oneClickBindingLocator.otherActionSelector("Insert snippet"), ); - _.agHelper.GetNClick(locator.otherActionSelector("Insert snippet")); + _.agHelper.GetNClick( + oneClickBindingLocator.otherActionSelector("Insert snippet"), + ); _.agHelper.AssertElementExist(CommonLocators.globalSearchModal); _.agHelper.TypeText(CommonLocators.globalSearchInput, "{esc}", 0, true); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); _.agHelper.AssertElementExist( - locator.otherActionSelector("Insert binding"), + oneClickBindingLocator.otherActionSelector("Insert binding"), ); - _.agHelper.GetNClick(locator.otherActionSelector("Insert binding")); + _.agHelper.GetNClick( + oneClickBindingLocator.otherActionSelector("Insert binding"), + ); _.propPane.ValidatePropertyFieldValue("Table data", "{{}}"); @@ -79,15 +105,17 @@ describe.skip("One click binding control", () => { _.propPane.ToggleJsMode("Table data"); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); _.agHelper.AssertElementAbsence( - locator.datasourceDropdownOptionSelector("Query1"), + oneClickBindingLocator.datasourceDropdownOptionSelector("Query1"), ); - _.agHelper.GetNClick(locator.datasourceQuerySelector, 0); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceQuerySelector, 0); - _.agHelper.AssertElementExist(locator.dropdownOptionSelector("Query1")); + _.agHelper.AssertElementExist( + oneClickBindingLocator.dropdownOptionSelector("Query1"), + ); _.propPane.ToggleJsMode("Table data"); @@ -97,13 +125,23 @@ describe.skip("One click binding control", () => { _.propPane.ToggleJsMode("Table data"); - ChooseAndAssertForm("New from Users", "Users", "public.users", "gender"); + oneClickBinding.ChooseAndAssertForm( + "New from Users", + "Users", + "public.users", + "gender", + ); _.propPane.MoveToTab("Style"); _.propPane.MoveToTab("Content"); - ChooseAndAssertForm("New from sample Movies", "movies", "movies", "status"); + oneClickBinding.ChooseAndAssertForm( + "New from sample Movies", + "movies", + "movies", + "status", + ); _.entityExplorer.NavigateToSwitcher("Explorer"); @@ -130,14 +168,16 @@ describe.skip("One click binding control", () => { _.entityExplorer.NavigateToSwitcher("Widgets"); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); - _.agHelper.GetNClick(locator.datasourceSelector("myinvalidds")); + _.agHelper.GetNClick( + oneClickBindingLocator.datasourceSelector("myinvalidds"), + ); cy.wait("@getDatasourceStructure", { timeout: 20000 }); _.agHelper.AssertElementExist( - locator.tableError( + oneClickBindingLocator.tableError( "Appsmith server timed out when fetching structure. Please reach out to appsmith customer support to resolve this.", ), ); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts index 6a935b49b669..8b2f6ae3c144 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts @@ -1,13 +1,16 @@ +import oneClickBindingLocator from "../../../../../locators/OneClickBindingLocator"; import * as _ from "../../../../../support/Objects/ObjectsCore"; -import locators from "../../../../../locators/OneClickBindingLocator"; describe("Table widget one click binding feature", () => { it("1.should check that connect data overlay is shown on the table", () => { - _.entityExplorer.DragDropWidgetNVerify("tablewidgetv2"); + _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE); _.agHelper.AssertElementExist(_.table._connectDataHeader); _.agHelper.AssertElementExist(_.table._connectDataButton); // should check that tableData one click property control" - _.propPane.openWidgetPropertyPane(_.draggableWidgets.TABLE); - _.agHelper.AssertElementExist(locators.datasourceDropdownSelector); + _.entityExplorer.SelectEntityByName("Table1", "Widgets"); + + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceDropdownSelector, + ); }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts index 9224c11eaf63..7e05ddd4e9fe 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts @@ -1,9 +1,10 @@ -import { WIDGET } from "../../../../../locators/WidgetLocators"; +import oneClickBindingLocator from "../../../../../locators/OneClickBindingLocator"; import * as _ from "../../../../../support/Objects/ObjectsCore"; -import { ChooseAndAssertForm } from "../spec_utility"; -import locators from "../../../../../locators/OneClickBindingLocator"; +import { OneClickBinding } from "../spec_utility"; -describe.skip("one click binding mongodb datasource", function () { +const oneClickBinding = new OneClickBinding(); + +describe("one click binding mongodb datasource", function () { before(() => { _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE, 400); }); @@ -15,16 +16,19 @@ describe.skip("one click binding mongodb datasource", function () { _.dataSources.CreateDataSource("Mongo"); cy.get("@dsName").then((dsName) => { - _.entityExplorer.NavigateToSwitcher("Widgets"); - - (cy as any).openPropertyPane(WIDGET.TABLE); - - ChooseAndAssertForm(`New from ${dsName}`, dsName, "netflix", "creator"); + _.entityExplorer.SelectEntityByName("Table1", "Widgets"); + + oneClickBinding.ChooseAndAssertForm( + `New from ${dsName}`, + dsName, + "netflix", + "creator", + ); }); - _.agHelper.GetNClick(locators.connectData); + _.agHelper.GetNClick(oneClickBindingLocator.connectData); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); _.agHelper.Sleep(2000); //#endregion @@ -36,7 +40,7 @@ describe.skip("one click binding mongodb datasource", function () { _.agHelper.Sleep(); // check if the table rows are present for the given search entry _.agHelper.GetNAssertContains( - '.t--widget-tablewidgetv2 [role="rowgroup"] [role="button"]', + oneClickBindingLocator.validTableRowData, rowWithAValidText, ); //#endregion @@ -89,7 +93,7 @@ describe.skip("one click binding mongodb datasource", function () { //check if that row is present _.agHelper.GetNAssertContains( - '.t--widget-tablewidgetv2 [role="rowgroup"] [role="button"]', + oneClickBindingLocator.validTableRowData, someText, ); //#endregion diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts index 2975ee474c82..e6a84e1ff024 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts @@ -1,9 +1,10 @@ -import { WIDGET } from "../../../../../locators/WidgetLocators"; +import oneClickBindingLocator from "../../../../../locators/OneClickBindingLocator"; import * as _ from "../../../../../support/Objects/ObjectsCore"; -import { ChooseAndAssertForm } from "../spec_utility"; -import locators from "../../../../../locators/OneClickBindingLocator"; +import { OneClickBinding } from "../spec_utility"; -describe.skip("Table widget one click binding feature", () => { +const oneClickBinding = new OneClickBinding(); + +describe("Table widget one click binding feature", () => { it("should check that queries are created and bound to table widget properly", () => { _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE, 400); @@ -14,14 +15,19 @@ describe.skip("Table widget one click binding feature", () => { cy.get("@dsName").then((dsName) => { _.entityExplorer.NavigateToSwitcher("Widgets"); - (cy as any).openPropertyPane(WIDGET.TABLE); + _.entityExplorer.SelectEntityByName("Table1", "Widgets"); - ChooseAndAssertForm(`New from ${dsName}`, dsName, "public.users", "name"); + oneClickBinding.ChooseAndAssertForm( + `New from ${dsName}`, + dsName, + "public.users", + "name", + ); }); - _.agHelper.GetNClick(locators.connectData); + _.agHelper.GetNClick(oneClickBindingLocator.connectData); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); cy.wait(2000); @@ -43,19 +49,19 @@ describe.skip("Table widget one click binding feature", () => { (cy as any).enterTableCellValue(3, 0, " 2016-06-22 19:10:25-07"); - _.agHelper.GetNClick(`[data-testid="datepicker-container"] input`, 0, true); + _.agHelper.GetNClick(oneClickBindingLocator.dateInput, 0, true); - _.agHelper.GetNClick(".DayPicker-Day", 0, true); + _.agHelper.GetNClick(oneClickBindingLocator.dayViewFromDate, 0, true); (cy as any).wait(2000); _.agHelper.GetNClick(_.table._saveNewRow, 0, true); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); _.agHelper.TypeText(_.table._searchInput, "cypress@appsmith"); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); _.agHelper.AssertElementExist(_.table._bodyCell("cypress@appsmith")); @@ -73,9 +79,9 @@ describe.skip("Table widget one click binding feature", () => { (cy as any).saveTableRow(12, 0); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); (cy as any).wait(500); @@ -83,7 +89,7 @@ describe.skip("Table widget one click binding feature", () => { _.agHelper.TypeText(_.table._searchInput, "automation@appsmith"); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); (cy as any).wait(2000); @@ -93,7 +99,7 @@ describe.skip("Table widget one click binding feature", () => { _.agHelper.TypeText(_.table._searchInput, "cypress@appsmith"); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); (cy as any).wait(2000); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/spec_utility.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/spec_utility.ts index 42aadf2ec8ca..84c797571f61 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/spec_utility.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/spec_utility.ts @@ -1,68 +1,62 @@ import * as _ from "../../../../support/Objects/ObjectsCore"; +import oneClickBindingLocator from "../../../../locators/OneClickBindingLocator"; -export function ChooseAndAssertForm(source, selectedSource, table, column) { - _.agHelper.GetNClick(".t--one-click-binding-datasource-selector"); +export class OneClickBinding { + public ChooseAndAssertForm( + source?: string, + selectedSource?: any, + table?: string, + column?: string, + ) { + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); - _.agHelper.AssertElementAbsence( - '[data-testId="t--one-click-binding-connect-data"]', - ); + _.agHelper.AssertElementAbsence(oneClickBindingLocator.connectData); - _.agHelper.GetNClick( - `[data-testid="t--one-click-binding-datasource-selector--datasource"]:contains(${source})`, - ); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceSelector(source)); - cy.wait("@getDatasourceStructure").should( - "have.nested.property", - "response.body.responseMeta.status", - 200, - ); + cy.wait("@getDatasourceStructure").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); - _.agHelper.Sleep(500); - _.agHelper.AssertElementExist( - '[data-testId="t--one-click-binding-connect-data"]', - ); + _.agHelper.Sleep(500); + _.agHelper.AssertElementExist(oneClickBindingLocator.connectData); - _.agHelper.AssertElementEnabledDisabled( - '[data-testId="t--one-click-binding-connect-data"]', - ); + _.agHelper.AssertElementEnabledDisabled(oneClickBindingLocator.connectData); - _.agHelper.AssertElementExist( - '[data-testid="t--one-click-binding-table-selector"]', - ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.tableOrSpreadsheetDropdown, + ); - _.agHelper.GetNClick('[data-testid="t--one-click-binding-table-selector"]'); + _.agHelper.GetNClick(oneClickBindingLocator.tableOrSpreadsheetDropdown); - _.agHelper.GetNClick( - `.t--one-click-binding-table-selector--table:contains(${table})`, - ); + _.agHelper.GetNClick( + oneClickBindingLocator.tableOrSpreadsheetDropdownOption(table), + ); - _.agHelper.AssertElementExist( - `[data-testid="t--one-click-binding-table-selector"] .rc-select-selection-item:contains(${table})`, - ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.tableOrSpreadsheetSelectedOption(table), + ); - _.agHelper.AssertElementExist( - '[data-testid="t--one-click-binding-column-searchableColumn"]', - ); + _.agHelper.AssertElementExist(oneClickBindingLocator.searchableColumn); - _.agHelper.GetNClick( - '[data-testid="t--one-click-binding-column-searchableColumn"]', - ); + _.agHelper.GetNClick(oneClickBindingLocator.searchableColumn); - _.agHelper.GetNClick( - `.t--one-click-binding-column-searchableColumn--column:contains(${column})`, - ); + _.agHelper.GetNClick( + oneClickBindingLocator.searchableColumnDropdownOption(column), + ); - _.agHelper.AssertElementExist( - `[data-testid="t--one-click-binding-column-searchableColumn"] .rc-select-selection-item:contains(${column})`, - ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.searchableColumnSelectedOption(column), + ); - _.agHelper.AssertElementExist( - '[data-testId="t--one-click-binding-connect-data"]', - ); + _.agHelper.AssertElementExist(oneClickBindingLocator.connectData); - _.agHelper.AssertElementEnabledDisabled( - '[data-testId="t--one-click-binding-connect-data"]', - 0, - false, - ); + _.agHelper.AssertElementEnabledDisabled( + oneClickBindingLocator.connectData, + 0, + false, + ); + } } diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/Add_new_row_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/Add_new_row_spec.js index 4fb41d8f2161..6c603de34a37 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/Add_new_row_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/Add_new_row_spec.js @@ -207,10 +207,8 @@ describe("Table widget Add new row feature's", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); propPane.UpdatePropertyFieldValue("Valid", ""); @@ -218,22 +216,17 @@ describe("Table widget Add new row feature's", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); propPane.UpdatePropertyFieldValue("Regex", ""); propPane.ToggleOnOrOff("Required", "On"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, ""); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.get(commonlocators.changeColType).last().click(); @@ -242,37 +235,27 @@ describe("Table widget Add new row feature's", () => { propPane.UpdatePropertyFieldValue("Min", "5"); cy.enterTableCellValue(0, 0, "6"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "7"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "4"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "8"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); propPane.UpdatePropertyFieldValue("Min", ""); propPane.UpdatePropertyFieldValue("Max", "5"); cy.enterTableCellValue(0, 0, "6"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "7"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "4"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "8"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); propPane.UpdatePropertyFieldValue("Max", ""); @@ -287,23 +270,18 @@ describe("Table widget Add new row feature's", () => { cy.editTableCell(0, 0); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "2"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.discardTableCellValue(0, 0); cy.wait(500); cy.get(".t--add-new-row").click(); cy.wait(1000); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "2"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.get(".t--discard-new-row").click({ force: true }); }); @@ -338,10 +316,8 @@ describe("Table widget Add new row feature's", () => { cy.get(".t--save-new-row").should("be.disabled"); cy.get(`.t--inlined-cell-editor-has-error`).should("have.length", 2); cy.enterTableCellValue(0, 0, "1"); - cy.wait(1000); cy.get(`.t--inlined-cell-editor-has-error`).should("have.length", 1); cy.enterTableCellValue(1, 0, "invalid"); - cy.wait(1000); cy.get(`.t--inlined-cell-editor-has-error`).should("have.length", 0); cy.get(".t--save-new-row").should("not.be.disabled"); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/freeze_column_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/freeze_column_spec.js index 786a4e4e131f..2d970994cf96 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/freeze_column_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/freeze_column_spec.js @@ -400,8 +400,7 @@ describe("2. Check column freeze and unfreeze mechanism in page mode", () => { }); after(() => { - cy.openPropertyPane(WIDGET.TABLE); - _.propPane.DeleteWidget(); + _.propPane.DeleteWidgetFromPropertyPane("Table1"); }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/inline_editing_validations_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/inline_editing_validations_spec.js index 8f1afcfeb4d2..c2b2e507cc79 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/inline_editing_validations_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/inline_editing_validations_spec.js @@ -84,10 +84,8 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); }); @@ -100,10 +98,8 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); }); @@ -116,13 +112,10 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, ""); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); }); }); @@ -143,19 +136,14 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "6"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "7"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "4"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "8"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); }); @@ -174,19 +162,14 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "6"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "7"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "4"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "8"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); }); }); @@ -200,7 +183,6 @@ describe("Table widget inline editing validation functionality", () => { cy.editTableCell(0, 0); cy.wait(1000); cy.enterTableCellValue(0, 0, "123"); - cy.wait(500); cy.get(".bp3-overlay.error-tooltip .bp3-popover-content").should( "contain", "You got error mate!!", @@ -224,7 +206,6 @@ describe("Table widget inline editing validation functionality", () => { cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.get(widgetsPage.toastAction).should("not.exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.saveTableCellValue(0, 0); cy.get(`.t--inlined-cell-editor`).should("not.exist"); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); diff --git a/app/client/cypress/locators/OneClickBindingLocator.ts b/app/client/cypress/locators/OneClickBindingLocator.ts index be9620b866c9..e22126789ced 100644 --- a/app/client/cypress/locators/OneClickBindingLocator.ts +++ b/app/client/cypress/locators/OneClickBindingLocator.ts @@ -20,8 +20,30 @@ export default { `.t--one-click-binding-datasource-selector--other-action${ action ? `:contains(${action})` : "" }`, - datasourcePage: ".t--integrationsHomePage", - backButton: ".t--back-button", + tableOrSpreadsheetDropdown: + '[data-testid="t--one-click-binding-table-selector"]', + tableOrSpreadsheetDropdownOption: (table?: string) => + `.t--one-click-binding-table-selector--table${ + table ? `:contains(${table})` : "" + }`, + tableOrSpreadsheetSelectedOption: (table?: string) => + `[data-testid="t--one-click-binding-table-selector"] .rc-select-selection-item${ + table ? `:contains(${table})` : "" + }`, + searchableColumn: + '[data-testid="t--one-click-binding-column-searchableColumn"]', + searchableColumnDropdownOption: (column?: string) => + `.t--one-click-binding-column-searchableColumn--column${ + column ? `:contains(${column})` : "" + }`, + searchableColumnSelectedOption: (column?: string) => + `[data-testid="t--one-click-binding-column-searchableColumn"] .rc-select-selection-item${ + column ? `:contains(${column})` : "" + }`, + validTableRowData: + '.t--widget-tablewidgetv2 [role="rowgroup"] [role="button"]', tableError: (error: string) => `[data-testId="t--one-click-binding-table-selector--error"]:contains(${error})`, + dateInput: `[data-testid="datepicker-container"] input`, + dayViewFromDate: ".DayPicker-Day", }; diff --git a/app/client/cypress/support/Pages/PropertyPane.ts b/app/client/cypress/support/Pages/PropertyPane.ts index 3982fa06f0bf..86f2a5b89d1c 100644 --- a/app/client/cypress/support/Pages/PropertyPane.ts +++ b/app/client/cypress/support/Pages/PropertyPane.ts @@ -101,13 +101,6 @@ export class PropertyPane { this.isMac ? "{cmd}{a}" : "{ctrl}{a}" }`; - private getWidgetSelector = (widgetType: string) => - `div.t--widget-${widgetType}`; - - public openWidgetPropertyPane(widgetType: string) { - this.agHelper.GetNClick(this.getWidgetSelector(widgetType)); - } - public OpenJsonFormFieldSettings(fieldName: string) { this.agHelper.GetNClick(this._fieldConfig(fieldName)); } @@ -462,10 +455,4 @@ export class PropertyPane { this.agHelper.GetNClick(this._pageName(pageName)); this.agHelper.AssertAutoSave(); } - - public DeleteWidget() { - ObjectsRegistry.AggregateHelper.GetNClick( - `[data-testid="t--delete-widget"]`, - ); - } } diff --git a/app/client/cypress/support/widgetCommands.js b/app/client/cypress/support/widgetCommands.js index c9a6ec85ef20..15a52a9d2df0 100644 --- a/app/client/cypress/support/widgetCommands.js +++ b/app/client/cypress/support/widgetCommands.js @@ -1478,7 +1478,8 @@ Cypress.Commands.add("enterTableCellValue", (x, y, text) => { `[data-colindex="${x}"][data-rowindex="${y}"] .t--inlined-cell-editor input.bp3-input`, ) .focus() - .type(text); + .type(text) + .wait(500); } }); diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/DropdownOption.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/DropdownOption.tsx index 1f7aa689b754..37c353ca5a27 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/DropdownOption.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/DropdownOption.tsx @@ -4,6 +4,7 @@ import styled from "styled-components"; const Container = styled.div` display: flex; width: calc(100% - 10px); + height: 100%; `; const LeftSection = styled.div` @@ -12,14 +13,9 @@ const LeftSection = styled.div` align-items: center; `; -const RightSection = styled.div` - width: 16px; -`; - const IconContainer = styled.div` width: 24px; display: flex; - margin-top: 3px; `; const Label = styled.div` @@ -43,11 +39,7 @@ export function DropdownOption(props: Props) { {leftIcon && <IconContainer>{leftIcon}</IconContainer>} <Label>{label}</Label> </LeftSection> - {rightIcon && ( - <RightSection> - <IconContainer>{rightIcon}</IconContainer> - </RightSection> - )} + {rightIcon && <IconContainer>{rightIcon}</IconContainer>} </Container> ); } diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/index.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/index.tsx index 9beda7e315c5..accbbad0399b 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/index.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/index.tsx @@ -4,7 +4,6 @@ import { useDatasource } from "./useDatasource"; import { Select, Option, Icon } from "design-system"; import { DropdownOption } from "./DropdownOption"; import styled from "styled-components"; -import { Colors } from "constants/Colors"; import type { DropdownOptionType } from "../../types"; import type { DefaultOptionType } from "rc-select/lib/Select"; import { DATASOURCE_DROPDOWN_SECTIONS } from "../../constants"; @@ -13,7 +12,7 @@ const SectionHeader = styled.div` cursor: default; font-weight: 500; line-height: 19px; - color: ${Colors.GREY_900}; + color: var(--ads-v2-color-gray-600); `; function DatasourceDropdown() { @@ -128,10 +127,10 @@ function DatasourceDropdown() { > <DropdownOption label={ - <> + <span> New from {option.data.isSample ? "sample " : ""} <Bold>{option.label?.replace("sample ", "")}</Bold> - </> + </span> } leftIcon={option.icon} rightIcon={<Icon name="add-box-line" size="md" />} diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/ConnectData/index.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/ConnectData/index.tsx index 6b021e53a1ad..2b4c9e5a45b9 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/ConnectData/index.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/ConnectData/index.tsx @@ -13,6 +13,7 @@ export function ConnectData() { isDisabled={disabled} isLoading={isLoading} onClick={onClick} + size="md" > Connect data </StyledButton> diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/styles.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/styles.tsx index eda5d757f87a..b62d33ccda8b 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/styles.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/styles.tsx @@ -18,7 +18,7 @@ export const Label = styled.p` `; export const Bold = styled.span` - font-weight: 700; + font-weight: 500; `; export const Section = styled.div``; @@ -40,13 +40,6 @@ export const RowHeading = styled.p` export const StyledButton = styled(Button)` &&& { width: 100%; - height: 50px !important; - border-radius: 1px !important; - - & > div { - padding: 10px 0px; - height: 36px; - } } `; diff --git a/app/client/src/widgets/TableWidgetV2/component/ConnectDataOverlay.tsx b/app/client/src/widgets/TableWidgetV2/component/ConnectDataOverlay.tsx index 5003f1379df6..5daaaa2295ee 100644 --- a/app/client/src/widgets/TableWidgetV2/component/ConnectDataOverlay.tsx +++ b/app/client/src/widgets/TableWidgetV2/component/ConnectDataOverlay.tsx @@ -1,4 +1,5 @@ import { Colors } from "constants/Colors"; +import { Button } from "design-system"; import React from "react"; import styled from "styled-components"; @@ -30,17 +31,11 @@ const Header = styled.div` font-size: 16px; line-height: 24px; color: ${Colors.GREY_900}; - margin-bottom: 15px; + margin-bottom: 12px; `; -const ConnecData = styled.button` - padding: 6px 15px; - max-width: 250px; - margin-bottom: 15px; - width: 100%; - background: #f86a2b; - color: #fff; - font-size: 12px; +const ConnecData = styled(Button)` + margin-bottom: 16px; `; const Footer = styled.div` @@ -59,6 +54,7 @@ export function ConnectDataOverlay(props: { onConnectData: () => void }) { <ConnecData className="t--cypress-table-overlay-connectdata" onClick={props.onConnectData} + size="md" > Connect data </ConnecData>
d6e74bf0122b0e5a91e175c3d2a70fef9fd68bb1
2023-07-07 00:43:11
Nidhi
chore: Applied Spotless formatter (#25173)
false
Applied Spotless formatter (#25173)
chore
diff --git a/app/server/appsmith-git/pom.xml b/app/server/appsmith-git/pom.xml index 31a4b9de3cf9..c99fbc40d582 100644 --- a/app/server/appsmith-git/pom.xml +++ b/app/server/appsmith-git/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> - <artifactId>integrated</artifactId> <groupId>com.appsmith</groupId> + <artifactId>integrated</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.appsmith</groupId> <artifactId>appsmith-git</artifactId> <version>1.0-SNAPSHOT</version> @@ -17,13 +16,6 @@ <name>appsmith-git</name> <description>This is the git server to handle all the git operations</description> - <repositories> - <repository> - <id>jgit-repository</id> - <url>https://repo.eclipse.org/content/groups/releases/</url> - </repository> - </repositories> - <dependencies> <dependency> @@ -53,8 +45,6 @@ <scope>test</scope> </dependency> - - <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> @@ -94,6 +84,13 @@ </dependency> </dependencies> + <repositories> + <repository> + <id>jgit-repository</id> + <url>https://repo.eclipse.org/content/groups/releases/</url> + </repository> + </repositories> + <build> <plugins> <plugin> @@ -101,10 +98,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> @@ -115,4 +112,4 @@ </plugins> </build> -</project> \ No newline at end of file +</project> diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/configurations/GitServiceConfig.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/configurations/GitServiceConfig.java index 7e252a9868e8..35fc7ffe2403 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/configurations/GitServiceConfig.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/configurations/GitServiceConfig.java @@ -13,5 +13,4 @@ public class GitServiceConfig { @Value("gitInitializeRepo/GitConnect-Initialize-Repo-Template") private String readmeTemplatePath; - } diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/constants/AppsmithBotAsset.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/constants/AppsmithBotAsset.java index be8fcedc74f2..146c24316e1b 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/constants/AppsmithBotAsset.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/constants/AppsmithBotAsset.java @@ -1,6 +1,6 @@ package com.appsmith.git.constants; public class AppsmithBotAsset { - public final static String APPSMITH_BOT_USERNAME = "Appsmith_Bot"; - public final static String APPSMITH_BOT_EMAIL = "[email protected]"; + public static final String APPSMITH_BOT_USERNAME = "Appsmith_Bot"; + public static final String APPSMITH_BOT_EMAIL = "[email protected]"; } diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/constants/CommonConstants.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/constants/CommonConstants.java index cf32e6253e09..74d7704fa73b 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/constants/CommonConstants.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/constants/CommonConstants.java @@ -1,7 +1,8 @@ package com.appsmith.git.constants; public class CommonConstants { - // This field will be useful when we migrate fields within JSON files (currently this will be useful for Git feature) + // This field will be useful when we migrate fields within JSON files (currently this will be useful for Git + // feature) public static Integer fileFormatVersion = 5; public static String FILE_FORMAT_VERSION = "fileFormatVersion"; @@ -23,5 +24,6 @@ public class CommonConstants { public static final String DELIMITER_POINT = "."; public static final String DELIMITER_PATH = "/"; public static final String EMPTY_STRING = ""; - public static final String FILE_MIGRATION_MESSAGE = "Some of the changes above are due to an improved file structure designed to reduce merge conflicts. You can safely commit them to your repository."; + public static final String FILE_MIGRATION_MESSAGE = + "Some of the changes above are due to an improved file structure designed to reduce merge conflicts. You can safely commit them to your repository."; } diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonDoubleToLongConverter.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonDoubleToLongConverter.java index ce7dfdcfb507..c4cecf9e7923 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonDoubleToLongConverter.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonDoubleToLongConverter.java @@ -8,11 +8,11 @@ import java.lang.reflect.Type; public class GsonDoubleToLongConverter implements JsonSerializer<Double> { - @Override - public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { - if(src == src.longValue()) { - return new JsonPrimitive(src.longValue()); - } - return new JsonPrimitive(src); + @Override + public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { + if (src == src.longValue()) { + return new JsonPrimitive(src.longValue()); } + return new JsonPrimitive(src); + } } diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonUnorderedToOrderedConverter.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonUnorderedToOrderedConverter.java index 506682a9aeed..604a488cf90e 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonUnorderedToOrderedConverter.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonUnorderedToOrderedConverter.java @@ -21,8 +21,7 @@ public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext con Gson gson = new Gson(); if (src instanceof Set) { return gson.toJsonTree(getOrderedResource((Set<?>) src)); - } - else if (src instanceof Map) { + } else if (src instanceof Map) { return gson.toJsonTree(new TreeMap<>((Map<?, ?>) src)); } return (JsonElement) src; diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/DSLTransformerHelper.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/DSLTransformerHelper.java index 09c159bc5160..32dcd8cbaccf 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/DSLTransformerHelper.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/DSLTransformerHelper.java @@ -14,7 +14,6 @@ import java.util.TreeMap; import java.util.stream.Collectors; - @Component @RequiredArgsConstructor @Slf4j @@ -83,7 +82,9 @@ public static boolean isCanvasWidget(JSONObject jsonObject) { public static Map<String, List<String>> calculateParentDirectories(List<String> paths) { Map<String, List<String>> parentDirectories = new HashMap<>(); - paths = paths.stream().map(currentPath -> currentPath.replace(CommonConstants.JSON_EXTENSION, CommonConstants.EMPTY_STRING)).collect(Collectors.toList()); + paths = paths.stream() + .map(currentPath -> currentPath.replace(CommonConstants.JSON_EXTENSION, CommonConstants.EMPTY_STRING)) + .collect(Collectors.toList()); for (String path : paths) { String[] directories = path.split(CommonConstants.DELIMITER_PATH); int lastDirectoryIndex = directories.length - 1; @@ -118,7 +119,8 @@ public static Map<String, List<String>> calculateParentDirectories(List<String> * /List1/Container1/Container1.json, * /MainContainer.json */ - public static JSONObject getNestedDSL(Map<String, JSONObject> jsonMap, Map<String, List<String>> pathMapping, JSONObject mainContainer) { + public static JSONObject getNestedDSL( + Map<String, JSONObject> jsonMap, Map<String, List<String>> pathMapping, JSONObject mainContainer) { // start from the root // Empty page with no widgets if (!pathMapping.containsKey(CommonConstants.MAIN_CONTAINER)) { @@ -138,9 +140,10 @@ public static JSONObject getNestedDSL(Map<String, JSONObject> jsonMap, Map<Strin return mainContainer; } - public static JSONObject getChildren(String pathToWidget, Map<String, JSONObject> jsonMap, Map<String, List<String>> pathMapping) { + public static JSONObject getChildren( + String pathToWidget, Map<String, JSONObject> jsonMap, Map<String, List<String>> pathMapping) { // Recursively get the children - List<String> children = pathMapping.get(getWidgetName(pathToWidget)); + List<String> children = pathMapping.get(getWidgetName(pathToWidget)); JSONObject parentObject = jsonMap.get(pathToWidget + CommonConstants.JSON_EXTENSION); if (children != null) { JSONArray childArray = new JSONArray(); @@ -177,4 +180,4 @@ public static JSONObject appendChildren(JSONObject parent, JSONArray childWidget } return parent; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java index 156db0ce663b..18946517388a 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java @@ -12,17 +12,13 @@ import com.appsmith.git.constants.CommonConstants; import com.appsmith.git.converters.GsonDoubleToLongConverter; import com.appsmith.git.converters.GsonUnorderedToOrderedConverter; -import com.appsmith.util.WebClientUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; -import lombok.AllArgsConstructor; import lombok.Getter; -import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; -import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -30,16 +26,12 @@ import org.json.JSONArray; import org.json.JSONObject; import org.springframework.context.annotation.Import; -import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.util.FileSystemUtils; import org.springframework.util.StringUtils; -import org.springframework.web.reactive.function.BodyInserters; -import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; -import reactor.netty.resources.ConnectionProvider; import java.io.BufferedWriter; import java.io.File; @@ -52,10 +44,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.time.Duration; import java.time.Instant; import java.util.Arrays; -import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -65,18 +55,17 @@ import java.util.regex.Pattern; import java.util.stream.Stream; +import static com.appsmith.external.constants.GitConstants.ACTION_COLLECTION_LIST; +import static com.appsmith.external.constants.GitConstants.ACTION_LIST; import static com.appsmith.external.constants.GitConstants.CUSTOM_JS_LIB_LIST; import static com.appsmith.external.constants.GitConstants.NAME_SEPARATOR; import static com.appsmith.external.constants.GitConstants.PAGE_LIST; -import static com.appsmith.external.constants.GitConstants.ACTION_LIST; -import static com.appsmith.external.constants.GitConstants.ACTION_COLLECTION_LIST; import static com.appsmith.git.constants.GitDirectories.ACTION_COLLECTION_DIRECTORY; import static com.appsmith.git.constants.GitDirectories.ACTION_DIRECTORY; import static com.appsmith.git.constants.GitDirectories.DATASOURCE_DIRECTORY; import static com.appsmith.git.constants.GitDirectories.JS_LIB_DIRECTORY; import static com.appsmith.git.constants.GitDirectories.PAGE_DIRECTORY; - @Slf4j @Getter @RequiredArgsConstructor @@ -92,99 +81,99 @@ public class FileUtilsImpl implements FileInterface { private static final String VIEW_MODE_URL_TEMPLATE = "{{viewModeUrl}}"; - private static final Pattern ALLOWED_FILE_EXTENSION_PATTERN = Pattern.compile("(.*?)\\.(md|git|gitignore|yml|yaml)$"); + private static final Pattern ALLOWED_FILE_EXTENSION_PATTERN = + Pattern.compile("(.*?)\\.(md|git|gitignore|yml|yaml)$"); private final Scheduler scheduler = Schedulers.boundedElastic(); private static final String CANVAS_WIDGET = "(Canvas)[0-9]*."; /** - Application will be stored in the following structure: - - For v1: - repo_name - application.json - metadata.json - datasource - datasource1Name.json - datasource2Name.json - queries (Only requirement here is the filename should be unique) - action1_page1 - action2_page2 - jsobjects (Only requirement here is the filename should be unique) - jsobject1_page1 - jsobject2_page2 - pages - page1 - page2 - - For v2: - repo_name - application.json - metadata.json - theme - publishedTheme.json - editModeTheme.json - pages - page1 - canvas.json - queries - Query1.json - Query2.json - jsobjects - JSObject1.json - page2 - page3 - datasources - datasource1.json - datasource2.json - - For v3: - repo_name - application.json - metadata.json - theme - publishedTheme.json - editModeTheme.json - pages - page1 - canvas.json - queries - Query1.json - jsobjects - JSObject1 - JSObject1.js - Metadata.json - page2 - page3 - datasources - datasource1.json - datasource2.json - - For v4: - repo_name - application.json - metadata.json - theme - publishedTheme.json - editModeTheme.json - pages - page1 - canvas.json - queries - Query1.json - jsobjects - JSObject1 - JSObject1.js - Metadata.json - page2 - page3 - datasources - datasource1.json - datasource2.json + * Application will be stored in the following structure: + * + * For v1: + * repo_name + * application.json + * metadata.json + * datasource + * datasource1Name.json + * datasource2Name.json + * queries (Only requirement here is the filename should be unique) + * action1_page1 + * action2_page2 + * jsobjects (Only requirement here is the filename should be unique) + * jsobject1_page1 + * jsobject2_page2 + * pages + * page1 + * page2 + * + * For v2: + * repo_name + * application.json + * metadata.json + * theme + * publishedTheme.json + * editModeTheme.json + * pages + * page1 + * canvas.json + * queries + * Query1.json + * Query2.json + * jsobjects + * JSObject1.json + * page2 + * page3 + * datasources + * datasource1.json + * datasource2.json + * + * For v3: + * repo_name + * application.json + * metadata.json + * theme + * publishedTheme.json + * editModeTheme.json + * pages + * page1 + * canvas.json + * queries + * Query1.json + * jsobjects + * JSObject1 + * JSObject1.js + * Metadata.json + * page2 + * page3 + * datasources + * datasource1.json + * datasource2.json + * + * For v4: + * repo_name + * application.json + * metadata.json + * theme + * publishedTheme.json + * editModeTheme.json + * pages + * page1 + * canvas.json + * queries + * Query1.json + * jsobjects + * JSObject1 + * JSObject1.js + * Metadata.json + * page2 + * page3 + * datasources + * datasource1.json + * datasource2.json */ - /** * This method will save the complete application in the local repo directory. * Path to repo will be : ./container-volumes/git-repo/workspaceId/defaultApplicationId/repoName/{application_data} @@ -193,24 +182,24 @@ public class FileUtilsImpl implements FileInterface { * @param branchName name of the branch for the current application * @return repo path where the application is stored */ - public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, - ApplicationGitReference applicationGitReference, - String branchName) throws GitAPIException, IOException { + public Mono<Path> saveApplicationToGitRepo( + Path baseRepoSuffix, ApplicationGitReference applicationGitReference, String branchName) + throws GitAPIException, IOException { // Repo path will be: // baseRepo : root/orgId/defaultAppId/repoName/{applicationData} // Checkout to mentioned branch if not already checked-out Stopwatch processStopwatch = new Stopwatch("FS application save"); - return gitExecutor.resetToLastCommit(baseRepoSuffix, branchName) + return gitExecutor + .resetToLastCommit(baseRepoSuffix, branchName) .flatMap(isSwitched -> { - Path baseRepo = Paths.get(gitServiceConfig.getGitRootPath()).resolve(baseRepoSuffix); // Gson to pretty format JSON file // Keep Long type as is by default GSON have behavior to convert to Double // Convert unordered set to ordered one Gson gson = new GsonBuilder() - .registerTypeAdapter(Double.class, new GsonDoubleToLongConverter()) + .registerTypeAdapter(Double.class, new GsonDoubleToLongConverter()) .registerTypeAdapter(Set.class, new GsonUnorderedToOrderedConverter()) .registerTypeAdapter(Map.class, new GsonUnorderedToOrderedConverter()) .registerTypeAdapter(Instant.class, new ISOStringToInstantConverter()) @@ -226,34 +215,51 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, deleteDirectory(baseRepo.resolve(ACTION_COLLECTION_DIRECTORY)); // Save application - saveResource(applicationGitReference.getApplication(), baseRepo.resolve(CommonConstants.APPLICATION + CommonConstants.JSON_EXTENSION), gson); + saveResource( + applicationGitReference.getApplication(), + baseRepo.resolve(CommonConstants.APPLICATION + CommonConstants.JSON_EXTENSION), + gson); // Save application metadata - JsonObject metadata = gson.fromJson(gson.toJson(applicationGitReference.getMetadata()), JsonObject.class); + JsonObject metadata = + gson.fromJson(gson.toJson(applicationGitReference.getMetadata()), JsonObject.class); metadata.addProperty(CommonConstants.FILE_FORMAT_VERSION, CommonConstants.fileFormatVersion); - saveResource(metadata, baseRepo.resolve(CommonConstants.METADATA + CommonConstants.JSON_EXTENSION), gson); + saveResource( + metadata, + baseRepo.resolve(CommonConstants.METADATA + CommonConstants.JSON_EXTENSION), + gson); // Save application theme - saveResource(applicationGitReference.getTheme(), baseRepo.resolve(CommonConstants.THEME + CommonConstants.JSON_EXTENSION), gson); + saveResource( + applicationGitReference.getTheme(), + baseRepo.resolve(CommonConstants.THEME + CommonConstants.JSON_EXTENSION), + gson); // Save pages Path pageDirectory = baseRepo.resolve(PAGE_DIRECTORY); - Set<Map.Entry<String, Object>> pageEntries = applicationGitReference.getPages().entrySet(); + Set<Map.Entry<String, Object>> pageEntries = + applicationGitReference.getPages().entrySet(); Set<String> validPages = new HashSet<>(); for (Map.Entry<String, Object> pageResource : pageEntries) { Map<String, String> validWidgetToParentMap = new HashMap<>(); final String pageName = pageResource.getKey(); Path pageSpecificDirectory = pageDirectory.resolve(pageName); - Boolean isResourceUpdated = updatedResources.get(PAGE_LIST).contains(pageName); - if(Boolean.TRUE.equals(isResourceUpdated)) { + Boolean isResourceUpdated = + updatedResources.get(PAGE_LIST).contains(pageName); + if (Boolean.TRUE.equals(isResourceUpdated)) { // Save page metadata - saveResource(pageResource.getValue(), pageSpecificDirectory.resolve(pageName + CommonConstants.JSON_EXTENSION), gson); - Map<String, JSONObject> result = DSLTransformerHelper.flatten(new JSONObject(applicationGitReference.getPageDsl().get(pageName))); + saveResource( + pageResource.getValue(), + pageSpecificDirectory.resolve(pageName + CommonConstants.JSON_EXTENSION), + gson); + Map<String, JSONObject> result = DSLTransformerHelper.flatten(new JSONObject( + applicationGitReference.getPageDsl().get(pageName))); result.forEach((key, jsonObject) -> { // get path with splitting the name via key - String widgetName = key.substring(key.lastIndexOf(CommonConstants.DELIMITER_POINT ) + 1 ); - String childPath = key.replace(CommonConstants.MAIN_CONTAINER, CommonConstants.EMPTY_STRING) + String widgetName = key.substring(key.lastIndexOf(CommonConstants.DELIMITER_POINT) + 1); + String childPath = key.replace( + CommonConstants.MAIN_CONTAINER, CommonConstants.EMPTY_STRING) .replace(CommonConstants.DELIMITER_POINT, CommonConstants.DELIMITER_PATH); // Replace the canvas Widget as a child and add it to the same level as parent childPath = childPath.replaceAll(CANVAS_WIDGET, CommonConstants.EMPTY_STRING); @@ -261,19 +267,23 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, // Save the widget as a directory or Save the widget as a file childPath = childPath.replace(widgetName, CommonConstants.EMPTY_STRING); } - Path path = Paths.get(String.valueOf(pageSpecificDirectory.resolve(CommonConstants.WIDGETS)), childPath); - validWidgetToParentMap.put(widgetName, path.toFile().toString()); - saveWidgets( - jsonObject, - widgetName, - path - ); + Path path = Paths.get( + String.valueOf(pageSpecificDirectory.resolve(CommonConstants.WIDGETS)), + childPath); + validWidgetToParentMap.put( + widgetName, path.toFile().toString()); + saveWidgets(jsonObject, widgetName, path); }); // Remove deleted widgets from the file system - deleteWidgets(pageSpecificDirectory.resolve(CommonConstants.WIDGETS).toFile(), validWidgetToParentMap); + deleteWidgets( + pageSpecificDirectory + .resolve(CommonConstants.WIDGETS) + .toFile(), + validWidgetToParentMap); // Remove the canvas.json from the file system since the value is stored in the page.json - deleteFile(pageSpecificDirectory.resolve(CommonConstants.CANVAS + CommonConstants.JSON_EXTENSION)); + deleteFile(pageSpecificDirectory.resolve( + CommonConstants.CANVAS + CommonConstants.JSON_EXTENSION)); } validPages.add(pageName); } @@ -281,21 +291,20 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, // Save JS Libs Path jsLibDirectory = baseRepo.resolve(JS_LIB_DIRECTORY); - Set<Map.Entry<String, Object>> jsLibEntries = applicationGitReference.getJsLibraries().entrySet(); + Set<Map.Entry<String, Object>> jsLibEntries = + applicationGitReference.getJsLibraries().entrySet(); Set<String> validJsLibs = new HashSet<>(); - jsLibEntries - .forEach(jsLibEntry -> { - String uidString = jsLibEntry.getKey(); - Boolean isResourceUpdated = updatedResources.get(CUSTOM_JS_LIB_LIST).contains(uidString); - String fileNameWithExtension = - uidString.replaceAll("/", "_") + CommonConstants.JSON_EXTENSION; - Path jsLibSpecificFile = - jsLibDirectory.resolve(fileNameWithExtension); - if (isResourceUpdated) { - saveResource(jsLibEntry.getValue(), jsLibSpecificFile, gson); - } - validJsLibs.add(fileNameWithExtension); - }); + jsLibEntries.forEach(jsLibEntry -> { + String uidString = jsLibEntry.getKey(); + Boolean isResourceUpdated = + updatedResources.get(CUSTOM_JS_LIB_LIST).contains(uidString); + String fileNameWithExtension = uidString.replaceAll("/", "_") + CommonConstants.JSON_EXTENSION; + Path jsLibSpecificFile = jsLibDirectory.resolve(fileNameWithExtension); + if (isResourceUpdated) { + saveResource(jsLibEntry.getValue(), jsLibSpecificFile, gson); + } + validJsLibs.add(fileNameWithExtension); + }); scanAndDeleteFileForDeletedResources(validJsLibs, jsLibDirectory); // Create HashMap for valid actions and actionCollections @@ -307,7 +316,8 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, }); // Save actions - for (Map.Entry<String, Object> resource : applicationGitReference.getActions().entrySet()) { + for (Map.Entry<String, Object> resource : + applicationGitReference.getActions().entrySet()) { // queryName_pageName => nomenclature for the keys // TODO // queryName => for app level queries, this is not implemented yet @@ -315,38 +325,45 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, if (names.length > 1 && StringUtils.hasLength(names[1])) { // For actions, we are referring to validNames to maintain unique file names as just name // field don't guarantee unique constraint for actions within JSObject - Boolean isResourceUpdated = updatedResources.get(ACTION_LIST).contains(resource.getKey()); + Boolean isResourceUpdated = + updatedResources.get(ACTION_LIST).contains(resource.getKey()); final String queryName = names[0].replace(".", "-"); final String pageName = names[1]; Path pageSpecificDirectory = pageDirectory.resolve(pageName); Path actionSpecificDirectory = pageSpecificDirectory.resolve(ACTION_DIRECTORY); - if(!validActionsMap.containsKey(pageName)) { + if (!validActionsMap.containsKey(pageName)) { validActionsMap.put(pageName, new HashSet<>()); } validActionsMap.get(pageName).add(queryName); - if(Boolean.TRUE.equals(isResourceUpdated)) { + if (Boolean.TRUE.equals(isResourceUpdated)) { saveActions( resource.getValue(), - applicationGitReference.getActionBody().containsKey(resource.getKey()) ? applicationGitReference.getActionBody().get(resource.getKey()) : null, + applicationGitReference.getActionBody().containsKey(resource.getKey()) + ? applicationGitReference + .getActionBody() + .get(resource.getKey()) + : null, queryName, actionSpecificDirectory.resolve(queryName), - gson - ); + gson); // Delete the resource from the old file structure v2 - deleteFile(pageSpecificDirectory.resolve(ACTION_DIRECTORY).resolve(queryName + CommonConstants.JSON_EXTENSION)); + deleteFile(pageSpecificDirectory + .resolve(ACTION_DIRECTORY) + .resolve(queryName + CommonConstants.JSON_EXTENSION)); } - } } validActionsMap.forEach((pageName, validActionNames) -> { Path pageSpecificDirectory = pageDirectory.resolve(pageName); - scanAndDeleteDirectoryForDeletedResources(validActionNames, pageSpecificDirectory.resolve(ACTION_DIRECTORY)); + scanAndDeleteDirectoryForDeletedResources( + validActionNames, pageSpecificDirectory.resolve(ACTION_DIRECTORY)); }); // Save JSObjects - for (Map.Entry<String, Object> resource : applicationGitReference.getActionCollections().entrySet()) { + for (Map.Entry<String, Object> resource : + applicationGitReference.getActionCollections().entrySet()) { // JSObjectName_pageName => nomenclature for the keys // TODO JSObjectName => for app level JSObjects, this is not implemented yet String[] names = resource.getKey().split(NAME_SEPARATOR); @@ -354,23 +371,27 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, final String actionCollectionName = names[0]; final String pageName = names[1]; Path pageSpecificDirectory = pageDirectory.resolve(pageName); - Path actionCollectionSpecificDirectory = pageSpecificDirectory.resolve(ACTION_COLLECTION_DIRECTORY); + Path actionCollectionSpecificDirectory = + pageSpecificDirectory.resolve(ACTION_COLLECTION_DIRECTORY); - if(!validActionCollectionsMap.containsKey(pageName)) { + if (!validActionCollectionsMap.containsKey(pageName)) { validActionCollectionsMap.put(pageName, new HashSet<>()); } validActionCollectionsMap.get(pageName).add(actionCollectionName); - Boolean isResourceUpdated = updatedResources.get(ACTION_COLLECTION_LIST).contains(resource.getKey()); - if(Boolean.TRUE.equals(isResourceUpdated)) { + Boolean isResourceUpdated = + updatedResources.get(ACTION_COLLECTION_LIST).contains(resource.getKey()); + if (Boolean.TRUE.equals(isResourceUpdated)) { saveActionCollection( resource.getValue(), - applicationGitReference.getActionCollectionBody().get(resource.getKey()), + applicationGitReference + .getActionCollectionBody() + .get(resource.getKey()), actionCollectionName, actionCollectionSpecificDirectory.resolve(actionCollectionName), - gson - ); + gson); // Delete the resource from the old file structure v2 - deleteFile(actionCollectionSpecificDirectory.resolve(actionCollectionName + CommonConstants.JSON_EXTENSION)); + deleteFile(actionCollectionSpecificDirectory.resolve( + actionCollectionName + CommonConstants.JSON_EXTENSION)); } } } @@ -378,12 +399,18 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, // Verify if the old files are deleted validActionCollectionsMap.forEach((pageName, validActionCollectionNames) -> { Path pageSpecificDirectory = pageDirectory.resolve(pageName); - scanAndDeleteDirectoryForDeletedResources(validActionCollectionNames, pageSpecificDirectory.resolve(ACTION_COLLECTION_DIRECTORY)); + scanAndDeleteDirectoryForDeletedResources( + validActionCollectionNames, pageSpecificDirectory.resolve(ACTION_COLLECTION_DIRECTORY)); }); // Save datasources ref - for (Map.Entry<String, Object> resource : applicationGitReference.getDatasources().entrySet()) { - saveResource(resource.getValue(), baseRepo.resolve(DATASOURCE_DIRECTORY).resolve(resource.getKey() + CommonConstants.JSON_EXTENSION), gson); + for (Map.Entry<String, Object> resource : + applicationGitReference.getDatasources().entrySet()) { + saveResource( + resource.getValue(), + baseRepo.resolve(DATASOURCE_DIRECTORY) + .resolve(resource.getKey() + CommonConstants.JSON_EXTENSION), + gson); validFileNames.add(resource.getKey() + CommonConstants.JSON_EXTENSION); } // Scan datasource directory and delete any unwanted files if present @@ -502,12 +529,11 @@ private boolean writeToFile(Object sourceEntity, Path path, Gson gson) throws IO public void scanAndDeleteFileForDeletedResources(Set<String> validResources, Path resourceDirectory) { // Scan resource directory and delete any unwanted file if present // unwanted file : corresponding resource from DB has been deleted - if(resourceDirectory.toFile().exists()) { + if (resourceDirectory.toFile().exists()) { try (Stream<Path> paths = Files.walk(resourceDirectory)) { - paths.filter(pathLocal -> - Files.isRegularFile(pathLocal) && - !validResources.contains(pathLocal.getFileName().toString()) - ) + paths.filter(pathLocal -> Files.isRegularFile(pathLocal) + && !validResources.contains( + pathLocal.getFileName().toString())) .forEach(this::deleteFile); } catch (IOException e) { log.debug("Error while scanning directory: {}, with error {}", resourceDirectory, e); @@ -524,10 +550,11 @@ public void scanAndDeleteFileForDeletedResources(Set<String> validResources, Pat public void scanAndDeleteDirectoryForDeletedResources(Set<String> validResources, Path resourceDirectory) { // Scan resource directory and delete any unwanted directory if present // unwanted directory : corresponding resource from DB has been deleted - if(resourceDirectory.toFile().exists()) { + if (resourceDirectory.toFile().exists()) { try (Stream<Path> paths = Files.walk(resourceDirectory, 1)) { - paths - .filter(path -> Files.isDirectory(path) && !path.equals(resourceDirectory) && !validResources.contains(path.getFileName().toString())) + paths.filter(path -> Files.isDirectory(path) + && !path.equals(resourceDirectory) + && !validResources.contains(path.getFileName().toString())) .forEach(this::deleteDirectory); } catch (IOException e) { log.debug("Error while scanning directory: {}, with error {}", resourceDirectory, e); @@ -539,11 +566,11 @@ public void scanAndDeleteDirectoryForDeletedResources(Set<String> validResources * This method will delete the directory and all its contents * @param directory */ - private void deleteDirectory(Path directory){ - if(directory.toFile().exists()) { + private void deleteDirectory(Path directory) { + if (directory.toFile().exists()) { try { FileUtils.deleteDirectory(directory.toFile()); - } catch (IOException e){ + } catch (IOException e) { log.error("Unable to delete directory for path {} with message {}", directory, e.getMessage()); } } @@ -554,16 +581,11 @@ private void deleteDirectory(Path directory){ * @param filePath file that needs to be deleted */ private void deleteFile(Path filePath) { - try - { + try { Files.deleteIfExists(filePath); - } - catch(DirectoryNotEmptyException e) - { + } catch (DirectoryNotEmptyException e) { log.error("Unable to delete non-empty directory at {}", filePath); - } - catch(IOException e) - { + } catch (IOException e) { log.error("Unable to delete file, {}", e.getMessage()); } } @@ -575,24 +597,25 @@ private void deleteFile(Path filePath) { * @param branchName for which the application needs to be rehydrate * @return application reference from which entire application can be rehydrated */ - public Mono<ApplicationGitReference> reconstructApplicationReferenceFromGitRepo(String organisationId, - String defaultApplicationId, - String repoName, - String branchName) { + public Mono<ApplicationGitReference> reconstructApplicationReferenceFromGitRepo( + String organisationId, String defaultApplicationId, String repoName, String branchName) { Stopwatch processStopwatch = new Stopwatch("FS reconstruct application"); Path baseRepoSuffix = Paths.get(organisationId, defaultApplicationId, repoName); // Checkout to mentioned branch if not already checked-out - return gitExecutor.checkoutToBranch(baseRepoSuffix, branchName) + return gitExecutor + .checkoutToBranch(baseRepoSuffix, branchName) .map(isSwitched -> { + Path baseRepoPath = + Paths.get(gitServiceConfig.getGitRootPath()).resolve(baseRepoSuffix); - Path baseRepoPath = Paths.get(gitServiceConfig.getGitRootPath()).resolve(baseRepoSuffix); - - // Instance creator is required while de-serialising using Gson as key instance can't be invoked with + // Instance creator is required while de-serialising using Gson as key instance can't be invoked + // with // no-args constructor Gson gson = new GsonBuilder() - .registerTypeAdapter(DatasourceStructure.Key.class, new DatasourceStructure.KeyInstanceCreator()) + .registerTypeAdapter( + DatasourceStructure.Key.class, new DatasourceStructure.KeyInstanceCreator()) .create(); ApplicationGitReference applicationGitReference = fetchApplicationReference(baseRepoPath, gson); @@ -612,29 +635,37 @@ public Mono<ApplicationGitReference> reconstructApplicationReferenceFromGitRepo( * @throws IOException */ @Override - public Mono<Path> initializeReadme(Path baseRepoSuffix, - String viewModeUrl, - String editModeUrl) throws IOException { + public Mono<Path> initializeReadme(Path baseRepoSuffix, String viewModeUrl, String editModeUrl) throws IOException { return Mono.fromCallable(() -> { - ClassLoader classLoader = getClass().getClassLoader(); - InputStream inputStream = classLoader.getResourceAsStream(gitServiceConfig.getReadmeTemplatePath()); - - StringWriter stringWriter = new StringWriter(); - IOUtils.copy(inputStream, stringWriter, "UTF-8"); - String data = stringWriter.toString().replace(EDIT_MODE_URL_TEMPLATE, editModeUrl).replace(VIEW_MODE_URL_TEMPLATE, viewModeUrl); - - File file = new File(Paths.get(gitServiceConfig.getGitRootPath()).resolve(baseRepoSuffix).toFile().toString()); - FileUtils.writeStringToFile(file, data, "UTF-8", true); - - // Remove readme.md from the path - return file.toPath().getParent(); - }).subscribeOn(scheduler); + ClassLoader classLoader = getClass().getClassLoader(); + InputStream inputStream = classLoader.getResourceAsStream(gitServiceConfig.getReadmeTemplatePath()); + + StringWriter stringWriter = new StringWriter(); + IOUtils.copy(inputStream, stringWriter, "UTF-8"); + String data = stringWriter + .toString() + .replace(EDIT_MODE_URL_TEMPLATE, editModeUrl) + .replace(VIEW_MODE_URL_TEMPLATE, viewModeUrl); + + File file = new File(Paths.get(gitServiceConfig.getGitRootPath()) + .resolve(baseRepoSuffix) + .toFile() + .toString()); + FileUtils.writeStringToFile(file, data, "UTF-8", true); + + // Remove readme.md from the path + return file.toPath().getParent(); + }) + .subscribeOn(scheduler); } @Override public Mono<Boolean> deleteLocalRepo(Path baseRepoSuffix) { // Remove the complete directory from path: baseRepo/workspaceId/defaultApplicationId - File file = Paths.get(gitServiceConfig.getGitRootPath()).resolve(baseRepoSuffix).getParent().toFile(); + File file = Paths.get(gitServiceConfig.getGitRootPath()) + .resolve(baseRepoSuffix) + .getParent() + .toFile(); while (file.exists()) { FileSystemUtils.deleteRecursively(file); } @@ -644,10 +675,14 @@ public Mono<Boolean> deleteLocalRepo(Path baseRepoSuffix) { @Override public Mono<Boolean> checkIfDirectoryIsEmpty(Path baseRepoSuffix) { return Mono.fromCallable(() -> { - File[] files = Paths.get(gitServiceConfig.getGitRootPath()).resolve(baseRepoSuffix).toFile().listFiles(); - for(File file : files) { - if(!ALLOWED_FILE_EXTENSION_PATTERN.matcher(file.getName()).matches() && !file.getName().equals("LICENSE")) { - //Remove the cloned repo from the file system since the repo doesnt satisfy the criteria + File[] files = Paths.get(gitServiceConfig.getGitRootPath()) + .resolve(baseRepoSuffix) + .toFile() + .listFiles(); + for (File file : files) { + if (!ALLOWED_FILE_EXTENSION_PATTERN.matcher(file.getName()).matches() + && !file.getName().equals("LICENSE")) { + // Remove the cloned repo from the file system since the repo doesnt satisfy the criteria while (file.exists()) { FileSystemUtils.deleteRecursively(file); } @@ -718,18 +753,24 @@ private String readFileAsString(Path filePath) { * @param directoryPath file path for files on which read operation will be performed * @return resources stored in the directory */ - private Map<String, Object> readActionCollection(Path directoryPath, Gson gson, String keySuffix, Map<String, String> actionCollectionBodyMap) { + private Map<String, Object> readActionCollection( + Path directoryPath, Gson gson, String keySuffix, Map<String, String> actionCollectionBodyMap) { Map<String, Object> resource = new HashMap<>(); File directory = directoryPath.toFile(); if (directory.isDirectory()) { for (File dirFile : Objects.requireNonNull(directory.listFiles())) { String resourceName = dirFile.getName(); - Path resourcePath = directoryPath.resolve(resourceName).resolve( resourceName + CommonConstants.JS_EXTENSION); + Path resourcePath = + directoryPath.resolve(resourceName).resolve(resourceName + CommonConstants.JS_EXTENSION); String body = CommonConstants.EMPTY_STRING; if (resourcePath.toFile().exists()) { body = readFileAsString(resourcePath); } - Object file = readFile(directoryPath.resolve(resourceName).resolve( CommonConstants.METADATA + CommonConstants.JSON_EXTENSION), gson); + Object file = readFile( + directoryPath + .resolve(resourceName) + .resolve(CommonConstants.METADATA + CommonConstants.JSON_EXTENSION), + gson); actionCollectionBodyMap.put(resourceName + keySuffix, body); resource.put(resourceName + keySuffix, file); } @@ -744,18 +785,24 @@ private Map<String, Object> readActionCollection(Path directoryPath, Gson gson, * @param gson * @return resources stored in the directory */ - private Map<String, Object> readAction(Path directoryPath, Gson gson, String keySuffix, Map<String, String> actionCollectionBodyMap) { + private Map<String, Object> readAction( + Path directoryPath, Gson gson, String keySuffix, Map<String, String> actionCollectionBodyMap) { Map<String, Object> resource = new HashMap<>(); File directory = directoryPath.toFile(); if (directory.isDirectory()) { for (File dirFile : Objects.requireNonNull(directory.listFiles())) { String resourceName = dirFile.getName(); String body = CommonConstants.EMPTY_STRING; - Path queryPath = directoryPath.resolve(resourceName).resolve( resourceName + CommonConstants.TEXT_FILE_EXTENSION); + Path queryPath = + directoryPath.resolve(resourceName).resolve(resourceName + CommonConstants.TEXT_FILE_EXTENSION); if (queryPath.toFile().exists()) { body = readFileAsString(queryPath); } - Object file = readFile(directoryPath.resolve(resourceName).resolve( CommonConstants.METADATA + CommonConstants.JSON_EXTENSION), gson); + Object file = readFile( + directoryPath + .resolve(resourceName) + .resolve(CommonConstants.METADATA + CommonConstants.JSON_EXTENSION), + gson); actionCollectionBodyMap.put(resourceName + keySuffix, body); resource.put(resourceName + keySuffix, file); } @@ -770,37 +817,45 @@ private Object readPageMetadata(Path directoryPath, Gson gson) { private ApplicationGitReference fetchApplicationReference(Path baseRepoPath, Gson gson) { ApplicationGitReference applicationGitReference = new ApplicationGitReference(); // Extract application metadata from the json - Object metadata = readFile(baseRepoPath.resolve(CommonConstants.METADATA + CommonConstants.JSON_EXTENSION), gson); + Object metadata = + readFile(baseRepoPath.resolve(CommonConstants.METADATA + CommonConstants.JSON_EXTENSION), gson); Integer fileFormatVersion = getFileFormatVersion(metadata); // Check if fileFormat of the saved files in repo is compatible - if(!isFileFormatCompatible(fileFormatVersion)) { + if (!isFileFormatCompatible(fileFormatVersion)) { throw new AppsmithPluginException(AppsmithPluginError.INCOMPATIBLE_FILE_FORMAT); } // Extract application data from the json - applicationGitReference.setApplication(readFile(baseRepoPath.resolve(CommonConstants.APPLICATION + CommonConstants.JSON_EXTENSION), gson)); - applicationGitReference.setTheme(readFile(baseRepoPath.resolve(CommonConstants.THEME + CommonConstants.JSON_EXTENSION), gson)); + applicationGitReference.setApplication( + readFile(baseRepoPath.resolve(CommonConstants.APPLICATION + CommonConstants.JSON_EXTENSION), gson)); + applicationGitReference.setTheme( + readFile(baseRepoPath.resolve(CommonConstants.THEME + CommonConstants.JSON_EXTENSION), gson)); Path pageDirectory = baseRepoPath.resolve(PAGE_DIRECTORY); // Reconstruct application from given file format switch (fileFormatVersion) { - case 1 : + case 1: // Extract actions - applicationGitReference.setActions(readFiles(baseRepoPath.resolve(ACTION_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); + applicationGitReference.setActions( + readFiles(baseRepoPath.resolve(ACTION_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); // Extract actionCollections - applicationGitReference.setActionCollections(readFiles(baseRepoPath.resolve(ACTION_COLLECTION_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); + applicationGitReference.setActionCollections(readFiles( + baseRepoPath.resolve(ACTION_COLLECTION_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); // Extract pages applicationGitReference.setPages(readFiles(pageDirectory, gson, CommonConstants.EMPTY_STRING)); // Extract datasources - applicationGitReference.setDatasources(readFiles(baseRepoPath.resolve(DATASOURCE_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); + applicationGitReference.setDatasources( + readFiles(baseRepoPath.resolve(DATASOURCE_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); break; case 2: case 3: case 4: - updateGitApplicationReference(baseRepoPath, gson, applicationGitReference, pageDirectory, fileFormatVersion); + updateGitApplicationReference( + baseRepoPath, gson, applicationGitReference, pageDirectory, fileFormatVersion); break; case 5: - updateGitApplicationReferenceV2(baseRepoPath, gson, applicationGitReference, pageDirectory, fileFormatVersion); + updateGitApplicationReferenceV2( + baseRepoPath, gson, applicationGitReference, pageDirectory, fileFormatVersion); break; default: @@ -815,7 +870,12 @@ private ApplicationGitReference fetchApplicationReference(Path baseRepoPath, Gso } @Deprecated - private void updateGitApplicationReference(Path baseRepoPath, Gson gson, ApplicationGitReference applicationGitReference, Path pageDirectory, int fileFormatVersion) { + private void updateGitApplicationReference( + Path baseRepoPath, + Gson gson, + ApplicationGitReference applicationGitReference, + Path pageDirectory, + int fileFormatVersion) { // Extract pages and nested actions and actionCollections File directory = pageDirectory.toFile(); Map<String, Object> pageMap = new HashMap<>(); @@ -827,18 +887,26 @@ private void updateGitApplicationReference(Path baseRepoPath, Gson gson, Appli // Loop through all the directories and nested directories inside the pages directory to extract // pages, actions and actionCollections from the JSON files for (File page : Objects.requireNonNull(directory.listFiles())) { - pageMap.put(page.getName(), readFile(page.toPath().resolve(CommonConstants.CANVAS + CommonConstants.JSON_EXTENSION), gson)); + pageMap.put( + page.getName(), + readFile(page.toPath().resolve(CommonConstants.CANVAS + CommonConstants.JSON_EXTENSION), gson)); if (fileFormatVersion >= 4) { - actionMap.putAll(readAction(page.toPath().resolve(ACTION_DIRECTORY), gson, page.getName(), actionBodyMap)); + actionMap.putAll( + readAction(page.toPath().resolve(ACTION_DIRECTORY), gson, page.getName(), actionBodyMap)); } else { actionMap.putAll(readFiles(page.toPath().resolve(ACTION_DIRECTORY), gson, page.getName())); } if (fileFormatVersion >= 3) { - actionCollectionMap.putAll(readActionCollection(page.toPath().resolve(ACTION_COLLECTION_DIRECTORY), gson, page.getName(), actionCollectionBodyMap)); + actionCollectionMap.putAll(readActionCollection( + page.toPath().resolve(ACTION_COLLECTION_DIRECTORY), + gson, + page.getName(), + actionCollectionBodyMap)); } else { - actionCollectionMap.putAll(readFiles(page.toPath().resolve(ACTION_COLLECTION_DIRECTORY), gson, page.getName())); + actionCollectionMap.putAll( + readFiles(page.toPath().resolve(ACTION_COLLECTION_DIRECTORY), gson, page.getName())); } } } @@ -848,7 +916,8 @@ private void updateGitApplicationReference(Path baseRepoPath, Gson gson, Appli applicationGitReference.setActionCollectionBody(actionCollectionBodyMap); applicationGitReference.setPages(pageMap); // Extract datasources - applicationGitReference.setDatasources(readFiles(baseRepoPath.resolve(DATASOURCE_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); + applicationGitReference.setDatasources( + readFiles(baseRepoPath.resolve(DATASOURCE_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); } private Integer getFileFormatVersion(Object metadata) { @@ -865,7 +934,12 @@ private boolean isFileFormatCompatible(int savedFileFormat) { return savedFileFormat <= CommonConstants.fileFormatVersion; } - private void updateGitApplicationReferenceV2(Path baseRepoPath, Gson gson, ApplicationGitReference applicationGitReference, Path pageDirectory, int fileFormatVersion) { + private void updateGitApplicationReferenceV2( + Path baseRepoPath, + Gson gson, + ApplicationGitReference applicationGitReference, + Path pageDirectory, + int fileFormatVersion) { // Extract pages and nested actions and actionCollections File directory = pageDirectory.toFile(); Map<String, Object> pageMap = new HashMap<>(); @@ -883,13 +957,20 @@ private void updateGitApplicationReferenceV2(Path baseRepoPath, Gson gson, Appli JSONObject mainContainer = getMainContainer(pageMap.get(page.getName()), gson); // Read widgets data recursively from the widgets directory - Map<String, JSONObject> widgetsData = readWidgetsData(page.toPath().resolve(CommonConstants.WIDGETS).toString()); + Map<String, JSONObject> widgetsData = readWidgetsData( + page.toPath().resolve(CommonConstants.WIDGETS).toString()); // Construct the nested DSL from the widgets data - Map<String, List<String>> parentDirectories = DSLTransformerHelper.calculateParentDirectories(widgetsData.keySet().stream().toList()); + Map<String, List<String>> parentDirectories = DSLTransformerHelper.calculateParentDirectories( + widgetsData.keySet().stream().toList()); JSONObject nestedDSL = DSLTransformerHelper.getNestedDSL(widgetsData, parentDirectories, mainContainer); pageDsl.put(page.getName(), nestedDSL.toString()); - actionMap.putAll(readAction(page.toPath().resolve(ACTION_DIRECTORY), gson, page.getName(), actionBodyMap)); - actionCollectionMap.putAll(readActionCollection(page.toPath().resolve(ACTION_COLLECTION_DIRECTORY), gson, page.getName(), actionCollectionBodyMap)); + actionMap.putAll( + readAction(page.toPath().resolve(ACTION_DIRECTORY), gson, page.getName(), actionBodyMap)); + actionCollectionMap.putAll(readActionCollection( + page.toPath().resolve(ACTION_COLLECTION_DIRECTORY), + gson, + page.getName(), + actionCollectionBodyMap)); } } applicationGitReference.setActions(actionMap); @@ -899,7 +980,8 @@ private void updateGitApplicationReferenceV2(Path baseRepoPath, Gson gson, Appli applicationGitReference.setPages(pageMap); applicationGitReference.setPageDsl(pageDsl); // Extract datasources - applicationGitReference.setDatasources(readFiles(baseRepoPath.resolve(DATASOURCE_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); + applicationGitReference.setDatasources( + readFiles(baseRepoPath.resolve(DATASOURCE_DIRECTORY), gson, CommonConstants.EMPTY_STRING)); } private Map<String, JSONObject> readWidgetsData(String directoryPath) { @@ -920,7 +1002,8 @@ private Map<String, JSONObject> readWidgetsData(String directoryPath) { return jsonMap; } - private void readFilesRecursively(File directory, Map<String, JSONObject> jsonMap, String rootPath) throws IOException { + private void readFilesRecursively(File directory, Map<String, JSONObject> jsonMap, String rootPath) + throws IOException { File[] files = directory.listFiles(); if (files == null) { return; @@ -930,7 +1013,9 @@ private void readFilesRecursively(File directory, Map<String, JSONObject> jsonMa if (file.isFile()) { String filePath = file.getAbsolutePath(); String relativePath = filePath.replace(rootPath, CommonConstants.EMPTY_STRING); - relativePath = CommonConstants.DELIMITER_PATH + CommonConstants.MAIN_CONTAINER + relativePath.substring(relativePath.indexOf("//") + 1); + relativePath = CommonConstants.DELIMITER_PATH + + CommonConstants.MAIN_CONTAINER + + relativePath.substring(relativePath.indexOf("//") + 1); try { String fileContent = new String(Files.readAllBytes(file.toPath())); JSONObject jsonObject = new JSONObject(fileContent); @@ -959,14 +1044,14 @@ private void deleteWidgets(File directory, Map<String, String> validWidgetToPare // If input widget was inside a container before, but the user moved it out of the container // then we need to delete the widget from the container directory // The check here is to validate if the parent is correct or not - if ( !validWidgetToParentMap.containsKey(name)) { + if (!validWidgetToParentMap.containsKey(name)) { if (file.isDirectory()) { deleteDirectory(file.toPath()); } else { deleteFile(file.toPath()); } - } else if(!file.getParentFile().getPath().toString().equals(validWidgetToParentMap.get(name)) - && !file.getPath().toString().equals(validWidgetToParentMap.get(name))) { + } else if (!file.getParentFile().getPath().equals(validWidgetToParentMap.get(name)) + && !file.getPath().equals(validWidgetToParentMap.get(name))) { if (file.isDirectory()) { deleteDirectory(file.toPath()); } else { @@ -978,7 +1063,7 @@ private void deleteWidgets(File directory, Map<String, String> validWidgetToPare private JSONObject getMainContainer(Object pageJson, Gson gson) { JSONObject pageJSON = new JSONObject(gson.toJson(pageJson)); - JSONArray layouts = pageJSON.getJSONObject("unpublishedPage").getJSONArray("layouts"); + JSONArray layouts = pageJSON.getJSONObject("unpublishedPage").getJSONArray("layouts"); return layouts.getJSONObject(0).getJSONObject("dsl"); } } diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/StopwatchHelpers.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/StopwatchHelpers.java index 233e3a3c7038..640144204223 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/StopwatchHelpers.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/StopwatchHelpers.java @@ -7,7 +7,8 @@ public class StopwatchHelpers { public static Stopwatch startStopwatch(Path path, String flowName) { // path => ..../{orgId}/{appId}/{repoName} - String modifiedFlowName = String.format("JGIT %s, appId %s", flowName, path.getParent().getFileName().toString()); + String modifiedFlowName = String.format( + "JGIT %s, appId %s", flowName, path.getParent().getFileName().toString()); return new Stopwatch(modifiedFlowName); } } diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/StringOutputStream.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/StringOutputStream.java index 156e1e6a20ae..75cebbbf72c4 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/StringOutputStream.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/StringOutputStream.java @@ -8,7 +8,7 @@ public class StringOutputStream extends OutputStream { @Override public void write(int b) throws IOException { - this.string.append((char) b ); + this.string.append((char) b); } public String toString() { diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java index 1db371d58a00..ac1c46b307d5 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java @@ -2,7 +2,6 @@ import com.appsmith.external.constants.AnalyticsEvents; import com.appsmith.external.constants.ErrorReferenceDocUrl; -import com.appsmith.external.constants.GitConstants; import com.appsmith.external.dtos.GitBranchDTO; import com.appsmith.external.dtos.GitLogDTO; import com.appsmith.external.dtos.GitStatusDTO; @@ -30,11 +29,7 @@ import org.eclipse.jgit.api.Status; import org.eclipse.jgit.api.TransportConfigCallback; import org.eclipse.jgit.api.errors.CheckoutConflictException; -import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException; import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.api.errors.NoMessageException; -import org.eclipse.jgit.api.errors.UnmergedPathsException; -import org.eclipse.jgit.api.errors.WrongRepositoryStateException; import org.eclipse.jgit.lib.BranchTrackingStatus; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; @@ -61,7 +56,6 @@ import java.util.Arrays; import java.util.Date; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; @@ -75,7 +69,8 @@ public class GitExecutorImpl implements GitExecutor { private final GitServiceConfig gitServiceConfig; - public static final DateTimeFormatter ISO_FORMATTER = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.from(ZoneOffset.UTC)); + public static final DateTimeFormatter ISO_FORMATTER = + DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.from(ZoneOffset.UTC)); private final Scheduler scheduler = Schedulers.boundedElastic(); @@ -92,45 +87,48 @@ public class GitExecutorImpl implements GitExecutor { * @return if the commit was successful */ @Override - public Mono<String> commitApplication(Path path, - String commitMessage, - String authorName, - String authorEmail, - boolean isSuffixedPath, - boolean doAmend) { - - final String finalAuthorName = StringUtils.isEmptyOrNull(authorName) ? AppsmithBotAsset.APPSMITH_BOT_USERNAME : authorName; - final String finalAuthorEmail = StringUtils.isEmptyOrNull(authorEmail) ? AppsmithBotAsset.APPSMITH_BOT_EMAIL : authorEmail; + public Mono<String> commitApplication( + Path path, + String commitMessage, + String authorName, + String authorEmail, + boolean isSuffixedPath, + boolean doAmend) { + + final String finalAuthorName = + StringUtils.isEmptyOrNull(authorName) ? AppsmithBotAsset.APPSMITH_BOT_USERNAME : authorName; + final String finalAuthorEmail = + StringUtils.isEmptyOrNull(authorEmail) ? AppsmithBotAsset.APPSMITH_BOT_EMAIL : authorEmail; return Mono.fromCallable(() -> { - log.debug("Trying to commit to local repo path, {}", path); - Path repoPath = path; - if (Boolean.TRUE.equals(isSuffixedPath)) { - repoPath = createRepoPath(repoPath); - } - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoPath, AnalyticsEvents.GIT_COMMIT.getEventName()); - // Just need to open a repository here and make a commit - try (Git git = Git.open(repoPath.toFile())) { - // Stage all the files added and modified - git.add().addFilepattern(".").call(); - // Stage modified and deleted files - git.add().setUpdate(true).addFilepattern(".").call(); - - // Commit the changes - git.commit() - .setMessage(commitMessage) - // Only make a commit if there are any updates - .setAllowEmpty(false) - .setAuthor(finalAuthorName, finalAuthorEmail) - .setCommitter(finalAuthorName, finalAuthorEmail) - .setAmend(doAmend) - .call(); - processStopwatch.stopAndLogTimeInMillis(); - return "Committed successfully!"; - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); - + log.debug("Trying to commit to local repo path, {}", path); + Path repoPath = path; + if (Boolean.TRUE.equals(isSuffixedPath)) { + repoPath = createRepoPath(repoPath); + } + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoPath, AnalyticsEvents.GIT_COMMIT.getEventName()); + // Just need to open a repository here and make a commit + try (Git git = Git.open(repoPath.toFile())) { + // Stage all the files added and modified + git.add().addFilepattern(".").call(); + // Stage modified and deleted files + git.add().setUpdate(true).addFilepattern(".").call(); + + // Commit the changes + git.commit() + .setMessage(commitMessage) + // Only make a commit if there are any updates + .setAllowEmpty(false) + .setAuthor(finalAuthorName, finalAuthorEmail) + .setCommitter(finalAuthorName, finalAuthorEmail) + .setAmend(doAmend) + .call(); + processStopwatch.stopAndLogTimeInMillis(); + return "Committed successfully!"; + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } /** @@ -154,29 +152,31 @@ public boolean createNewRepository(Path repoPath) throws GitAPIException { @Override public Mono<List<GitLogDTO>> getCommitHistory(Path repoSuffix) { return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": get commit history for " + repoSuffix); - List<GitLogDTO> commitLogs = new ArrayList<>(); - Path repoPath = createRepoPath(repoSuffix); - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoPath, AnalyticsEvents.GIT_COMMIT_HISTORY.getEventName()); - try (Git git = Git.open(repoPath.toFile())) { - Iterable<RevCommit> gitLogs = git.log().setMaxCount(Constraint.MAX_COMMIT_LOGS).call(); - gitLogs.forEach(revCommit -> { - PersonIdent author = revCommit.getAuthorIdent(); - GitLogDTO gitLog = new GitLogDTO( - revCommit.getName(), - author.getName(), - author.getEmailAddress(), - revCommit.getFullMessage(), - ISO_FORMATTER.format(new Date(revCommit.getCommitTime() * 1000L).toInstant()) - ); - processStopwatch.stopAndLogTimeInMillis(); - commitLogs.add(gitLog); - }); - return commitLogs; - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + log.debug(Thread.currentThread().getName() + ": get commit history for " + repoSuffix); + List<GitLogDTO> commitLogs = new ArrayList<>(); + Path repoPath = createRepoPath(repoSuffix); + Stopwatch processStopwatch = StopwatchHelpers.startStopwatch( + repoPath, AnalyticsEvents.GIT_COMMIT_HISTORY.getEventName()); + try (Git git = Git.open(repoPath.toFile())) { + Iterable<RevCommit> gitLogs = git.log() + .setMaxCount(Constraint.MAX_COMMIT_LOGS) + .call(); + gitLogs.forEach(revCommit -> { + PersonIdent author = revCommit.getAuthorIdent(); + GitLogDTO gitLog = new GitLogDTO( + revCommit.getName(), + author.getName(), + author.getEmailAddress(), + revCommit.getFullMessage(), + ISO_FORMATTER.format(new Date(revCommit.getCommitTime() * 1000L).toInstant())); + processStopwatch.stopAndLogTimeInMillis(); + commitLogs.add(gitLog); + }); + return commitLogs; + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } private Path createRepoPath(Path suffix) { @@ -192,43 +192,44 @@ private Path createRepoPath(Path suffix) { * @return Success message */ @Override - public Mono<String> pushApplication(Path repoSuffix, - String remoteUrl, - String publicKey, - String privateKey, - String branchName) { + public Mono<String> pushApplication( + Path repoSuffix, String remoteUrl, String publicKey, String privateKey, String branchName) { // We can safely assume that repo has been already initialised either in commit or clone flow and can directly // open the repo return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": pushing changes to remote " + remoteUrl); - // open the repo - Path baseRepoPath = createRepoPath(repoSuffix); - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(baseRepoPath, AnalyticsEvents.GIT_PUSH.getEventName()); - try (Git git = Git.open(baseRepoPath.toFile())) { - TransportConfigCallback transportConfigCallback = new SshTransportConfigCallback(privateKey, publicKey); - - StringBuilder result = new StringBuilder("Pushed successfully with status : "); - git.push() - .setTransportConfigCallback(transportConfigCallback) - .setRemote(remoteUrl) - .call() - .forEach(pushResult -> - pushResult.getRemoteUpdates() + log.debug(Thread.currentThread().getName() + ": pushing changes to remote " + remoteUrl); + // open the repo + Path baseRepoPath = createRepoPath(repoSuffix); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(baseRepoPath, AnalyticsEvents.GIT_PUSH.getEventName()); + try (Git git = Git.open(baseRepoPath.toFile())) { + TransportConfigCallback transportConfigCallback = + new SshTransportConfigCallback(privateKey, publicKey); + + StringBuilder result = new StringBuilder("Pushed successfully with status : "); + git.push() + .setTransportConfigCallback(transportConfigCallback) + .setRemote(remoteUrl) + .call() + .forEach(pushResult -> pushResult + .getRemoteUpdates() .forEach(remoteRefUpdate -> { - result.append(remoteRefUpdate.getStatus()).append(","); + result.append(remoteRefUpdate.getStatus()) + .append(","); if (!StringUtils.isEmptyOrNull(remoteRefUpdate.getMessage())) { - result.append(remoteRefUpdate.getMessage()).append(","); + result.append(remoteRefUpdate.getMessage()) + .append(","); } - }) - ); - // We can support username and password in future if needed - // pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", "password")); - processStopwatch.stopAndLogTimeInMillis(); - return result.substring(0, result.length() - 1); - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + })); + // We can support username and password in future if needed + // pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", + // "password")); + processStopwatch.stopAndLogTimeInMillis(); + return result.substring(0, result.length() - 1); + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } /** Clone the repo to the file path : container-volume/orgId/defaultAppId/repo/applicationData @@ -240,227 +241,249 @@ public Mono<String> pushApplication(Path repoSuffix, * @return defaultBranchName of the repo * */ @Override - public Mono<String> cloneApplication(Path repoSuffix, - String remoteUrl, - String privateKey, - String publicKey) { + public Mono<String> cloneApplication(Path repoSuffix, String remoteUrl, String privateKey, String publicKey) { - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_CLONE.getEventName()); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_CLONE.getEventName()); return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": Cloning the repo from the remote " + remoteUrl); - final TransportConfigCallback transportConfigCallback = new SshTransportConfigCallback(privateKey, publicKey); - File file = Paths.get(gitServiceConfig.getGitRootPath()).resolve(repoSuffix).toFile(); - while (file.exists()) { - FileSystemUtils.deleteRecursively(file); - } - - Git git = Git.cloneRepository() - .setURI(remoteUrl) - .setTransportConfigCallback(transportConfigCallback) - .setDirectory(file) - .call(); - String branchName = git.getRepository().getBranch(); - - repositoryHelper.updateRemoteBranchTrackingConfig(branchName, git); - git.close(); - processStopwatch.stopAndLogTimeInMillis(); - return branchName; - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + log.debug(Thread.currentThread().getName() + ": Cloning the repo from the remote " + remoteUrl); + final TransportConfigCallback transportConfigCallback = + new SshTransportConfigCallback(privateKey, publicKey); + File file = Paths.get(gitServiceConfig.getGitRootPath()) + .resolve(repoSuffix) + .toFile(); + while (file.exists()) { + FileSystemUtils.deleteRecursively(file); + } + + Git git = Git.cloneRepository() + .setURI(remoteUrl) + .setTransportConfigCallback(transportConfigCallback) + .setDirectory(file) + .call(); + String branchName = git.getRepository().getBranch(); + + repositoryHelper.updateRemoteBranchTrackingConfig(branchName, git); + git.close(); + processStopwatch.stopAndLogTimeInMillis(); + return branchName; + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } @Override public Mono<String> createAndCheckoutToBranch(Path repoSuffix, String branchName) { // We can safely assume that repo has been already initialised either in commit or clone flow and can directly // open the repo - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_CREATE_BRANCH.getEventName()); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_CREATE_BRANCH.getEventName()); return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": Creating branch " + branchName + "for the repo " + repoSuffix); - // open the repo - Path baseRepoPath = createRepoPath(repoSuffix); - try (Git git = Git.open(baseRepoPath.toFile())) { - // Create and checkout to new branch - git.checkout() - .setCreateBranch(Boolean.TRUE) - .setName(branchName) - .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) - .call(); - - repositoryHelper.updateRemoteBranchTrackingConfig(branchName, git); - processStopwatch.stopAndLogTimeInMillis(); - return git.getRepository().getBranch(); - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + log.debug(Thread.currentThread().getName() + ": Creating branch " + branchName + "for the repo " + + repoSuffix); + // open the repo + Path baseRepoPath = createRepoPath(repoSuffix); + try (Git git = Git.open(baseRepoPath.toFile())) { + // Create and checkout to new branch + git.checkout() + .setCreateBranch(Boolean.TRUE) + .setName(branchName) + .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) + .call(); + + repositoryHelper.updateRemoteBranchTrackingConfig(branchName, git); + processStopwatch.stopAndLogTimeInMillis(); + return git.getRepository().getBranch(); + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } @Override public Mono<Boolean> deleteBranch(Path repoSuffix, String branchName) { // We can safely assume that repo has been already initialised either in commit or clone flow and can directly // open the repo - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_DELETE_BRANCH.getEventName()); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_DELETE_BRANCH.getEventName()); return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": Deleting branch " + branchName + "for the repo " + repoSuffix); - // open the repo - Path baseRepoPath = createRepoPath(repoSuffix); - try (Git git = Git.open(baseRepoPath.toFile())) { - // Create and checkout to new branch - List<String> deleteBranchList =git.branchDelete() - .setBranchNames(branchName) - .setForce(Boolean.TRUE) - .call(); - processStopwatch.stopAndLogTimeInMillis(); - if(deleteBranchList.isEmpty()) { - return Boolean.FALSE; - } - return Boolean.TRUE; - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + log.debug(Thread.currentThread().getName() + ": Deleting branch " + branchName + "for the repo " + + repoSuffix); + // open the repo + Path baseRepoPath = createRepoPath(repoSuffix); + try (Git git = Git.open(baseRepoPath.toFile())) { + // Create and checkout to new branch + List<String> deleteBranchList = git.branchDelete() + .setBranchNames(branchName) + .setForce(Boolean.TRUE) + .call(); + processStopwatch.stopAndLogTimeInMillis(); + if (deleteBranchList.isEmpty()) { + return Boolean.FALSE; + } + return Boolean.TRUE; + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } @Override public Mono<Boolean> checkoutToBranch(Path repoSuffix, String branchName) { - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_CHECKOUT.getEventName()); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_CHECKOUT.getEventName()); return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": Switching to the branch " + branchName); - // We can safely assume that repo has been already initialised either in commit or clone flow and can directly - // open the repo - Path baseRepoPath = createRepoPath(repoSuffix); - try (Git git = Git.open(baseRepoPath.toFile())) { - if (StringUtils.equalsIgnoreCase(branchName, git.getRepository().getBranch())) { - return Boolean.TRUE; - } - // Create and checkout to new branch - String checkedOutBranch = git.checkout() - .setCreateBranch(Boolean.FALSE) - .setName(branchName) - .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM) - .call() - .getName(); - processStopwatch.stopAndLogTimeInMillis(); - return StringUtils.equalsIgnoreCase(checkedOutBranch, "refs/heads/"+branchName); - } catch (Exception e) { - throw new Exception(e); - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + log.debug(Thread.currentThread().getName() + ": Switching to the branch " + branchName); + // We can safely assume that repo has been already initialised either in commit or clone flow and + // can directly + // open the repo + Path baseRepoPath = createRepoPath(repoSuffix); + try (Git git = Git.open(baseRepoPath.toFile())) { + if (StringUtils.equalsIgnoreCase( + branchName, git.getRepository().getBranch())) { + return Boolean.TRUE; + } + // Create and checkout to new branch + String checkedOutBranch = git.checkout() + .setCreateBranch(Boolean.FALSE) + .setName(branchName) + .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM) + .call() + .getName(); + processStopwatch.stopAndLogTimeInMillis(); + return StringUtils.equalsIgnoreCase(checkedOutBranch, "refs/heads/" + branchName); + } catch (Exception e) { + throw new Exception(e); + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } @Override - public Mono<MergeStatusDTO> pullApplication(Path repoSuffix, - String remoteUrl, - String branchName, - String privateKey, - String publicKey) throws IOException { + public Mono<MergeStatusDTO> pullApplication( + Path repoSuffix, String remoteUrl, String branchName, String privateKey, String publicKey) + throws IOException { - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_PULL.getEventName()); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_PULL.getEventName()); TransportConfigCallback transportConfigCallback = new SshTransportConfigCallback(privateKey, publicKey); try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": Pull changes from remote " + remoteUrl + " for the branch "+ branchName); - //checkout the branch on which the merge command is run - git.checkout().setName(branchName).setCreateBranch(false).call(); - MergeResult mergeResult = git - .pull() - .setRemoteBranchName(branchName) - .setTransportConfigCallback(transportConfigCallback) - .setFastForward(MergeCommand.FastForwardMode.FF) - .call() - .getMergeResult(); - MergeStatusDTO mergeStatus = new MergeStatusDTO(); - Long count = Arrays.stream(mergeResult.getMergedCommits()).count(); - if (mergeResult.getMergeStatus().isSuccessful()) { - mergeStatus.setMergeAble(true); - mergeStatus.setStatus(count + " commits merged from origin/" + branchName); - } else { - //If there are conflicts add the conflicting file names to the response structure - mergeStatus.setMergeAble(false); - List<String> mergeConflictFiles = new ArrayList<>(); - if(!Optional.ofNullable(mergeResult.getConflicts()).isEmpty()) { - mergeConflictFiles.addAll(mergeResult.getConflicts().keySet()); + log.debug(Thread.currentThread().getName() + ": Pull changes from remote " + remoteUrl + + " for the branch " + branchName); + // checkout the branch on which the merge command is run + git.checkout() + .setName(branchName) + .setCreateBranch(false) + .call(); + MergeResult mergeResult = git.pull() + .setRemoteBranchName(branchName) + .setTransportConfigCallback(transportConfigCallback) + .setFastForward(MergeCommand.FastForwardMode.FF) + .call() + .getMergeResult(); + MergeStatusDTO mergeStatus = new MergeStatusDTO(); + Long count = + Arrays.stream(mergeResult.getMergedCommits()).count(); + if (mergeResult.getMergeStatus().isSuccessful()) { + mergeStatus.setMergeAble(true); + mergeStatus.setStatus(count + " commits merged from origin/" + branchName); + } else { + // If there are conflicts add the conflicting file names to the response structure + mergeStatus.setMergeAble(false); + List<String> mergeConflictFiles = new ArrayList<>(); + if (!Optional.ofNullable(mergeResult.getConflicts()).isEmpty()) { + mergeConflictFiles.addAll( + mergeResult.getConflicts().keySet()); + } + mergeStatus.setConflictingFiles(mergeConflictFiles); + // On merge conflicts abort the merge => git merge --abort + git.getRepository().writeMergeCommitMsg(null); + git.getRepository().writeMergeHeads(null); + processStopwatch.stopAndLogTimeInMillis(); + throw new org.eclipse.jgit.errors.CheckoutConflictException(mergeConflictFiles.toString()); } - mergeStatus.setConflictingFiles(mergeConflictFiles); - //On merge conflicts abort the merge => git merge --abort - git.getRepository().writeMergeCommitMsg(null); - git.getRepository().writeMergeHeads(null); processStopwatch.stopAndLogTimeInMillis(); - throw new org.eclipse.jgit.errors.CheckoutConflictException(mergeConflictFiles.toString()); - } - processStopwatch.stopAndLogTimeInMillis(); - return mergeStatus; - }) - .onErrorResume(error -> { - try { - return resetToLastCommit(git) - .flatMap(ignore -> Mono.error(error)); - } catch (GitAPIException e) { - log.error("Error for hard resetting to latest commit {0}", e); - return Mono.error(e); - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + return mergeStatus; + }) + .onErrorResume(error -> { + try { + return resetToLastCommit(git).flatMap(ignore -> Mono.error(error)); + } catch (GitAPIException e) { + log.error("Error for hard resetting to latest commit {0}", e); + return Mono.error(e); + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } } @Override - public Mono<List<GitBranchDTO>> listBranches(Path repoSuffix, - String remoteUrl, - String privateKey, - String publicKey, - Boolean refreshBranches) { - - String gitAction = Boolean.TRUE.equals(refreshBranches) ? AnalyticsEvents.GIT_SYNC_BRANCH.getEventName() : AnalyticsEvents.GIT_LIST_LOCAL_BRANCH.getEventName(); - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, gitAction);; + public Mono<List<GitBranchDTO>> listBranches( + Path repoSuffix, String remoteUrl, String privateKey, String publicKey, Boolean refreshBranches) { + + String gitAction = Boolean.TRUE.equals(refreshBranches) + ? AnalyticsEvents.GIT_SYNC_BRANCH.getEventName() + : AnalyticsEvents.GIT_LIST_LOCAL_BRANCH.getEventName(); + Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, gitAction); + ; Path baseRepoPath = createRepoPath(repoSuffix); return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": Get branches for the application " + repoSuffix); - TransportConfigCallback transportConfigCallback = new SshTransportConfigCallback(privateKey, publicKey); - Git git = Git.open(baseRepoPath.toFile()); - List<Ref> refList = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call(); - String defaultBranch = null; - - if (Boolean.TRUE.equals(refreshBranches)) { - // Get default branch name from the remote - defaultBranch = git.lsRemote().setRemote(remoteUrl).setTransportConfigCallback(transportConfigCallback).callAsMap().get("HEAD").getTarget().getName(); - } - - List<GitBranchDTO> branchList = new ArrayList<>(); - GitBranchDTO gitBranchDTO = new GitBranchDTO(); - if(refList.isEmpty()) { - gitBranchDTO.setBranchName(git.getRepository().getBranch()); - gitBranchDTO.setDefault(true); - branchList.add(gitBranchDTO); - } else { - if (Boolean.TRUE.equals(refreshBranches)) { - gitBranchDTO.setBranchName(defaultBranch.replace("refs/heads/","")); - gitBranchDTO.setDefault(true); - branchList.add(gitBranchDTO); - } - - for(Ref ref : refList) { - if(!ref.getName().equals(defaultBranch)) { - gitBranchDTO = new GitBranchDTO(); - gitBranchDTO.setBranchName(ref.getName() - .replace("refs/","").replace("heads/", "").replace("remotes/", "")); - gitBranchDTO.setDefault(false); + log.debug(Thread.currentThread().getName() + ": Get branches for the application " + repoSuffix); + TransportConfigCallback transportConfigCallback = + new SshTransportConfigCallback(privateKey, publicKey); + Git git = Git.open(baseRepoPath.toFile()); + List<Ref> refList = git.branchList() + .setListMode(ListBranchCommand.ListMode.ALL) + .call(); + String defaultBranch = null; + + if (Boolean.TRUE.equals(refreshBranches)) { + // Get default branch name from the remote + defaultBranch = git.lsRemote() + .setRemote(remoteUrl) + .setTransportConfigCallback(transportConfigCallback) + .callAsMap() + .get("HEAD") + .getTarget() + .getName(); + } + + List<GitBranchDTO> branchList = new ArrayList<>(); + GitBranchDTO gitBranchDTO = new GitBranchDTO(); + if (refList.isEmpty()) { + gitBranchDTO.setBranchName(git.getRepository().getBranch()); + gitBranchDTO.setDefault(true); branchList.add(gitBranchDTO); + } else { + if (Boolean.TRUE.equals(refreshBranches)) { + gitBranchDTO.setBranchName(defaultBranch.replace("refs/heads/", "")); + gitBranchDTO.setDefault(true); + branchList.add(gitBranchDTO); + } + + for (Ref ref : refList) { + if (!ref.getName().equals(defaultBranch)) { + gitBranchDTO = new GitBranchDTO(); + gitBranchDTO.setBranchName(ref.getName() + .replace("refs/", "") + .replace("heads/", "") + .replace("remotes/", "")); + gitBranchDTO.setDefault(false); + branchList.add(gitBranchDTO); + } + } } - } - } - git.close(); - processStopwatch.stopAndLogTimeInMillis(); - return branchList; - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + git.close(); + processStopwatch.stopAndLogTimeInMillis(); + return branchList; + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } /** @@ -472,106 +495,115 @@ public Mono<List<GitBranchDTO>> listBranches(Path repoSuffix, */ @Override public Mono<GitStatusDTO> getStatus(Path repoPath, String branchName) { - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoPath, AnalyticsEvents.GIT_STATUS.getEventName()); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoPath, AnalyticsEvents.GIT_STATUS.getEventName()); return Mono.fromCallable(() -> { - try (Git git = Git.open(repoPath.toFile())) { - log.debug(Thread.currentThread().getName() + ": Get status for repo " + repoPath + ", branch " + branchName); - Status status = git.status().call(); - GitStatusDTO response = new GitStatusDTO(); - Set<String> modifiedAssets = new HashSet<>(); - modifiedAssets.addAll(status.getModified()); - modifiedAssets.addAll(status.getAdded()); - modifiedAssets.addAll(status.getRemoved()); - modifiedAssets.addAll(status.getUncommittedChanges()); - modifiedAssets.addAll(status.getUntracked()); - response.setAdded(status.getAdded()); - response.setRemoved(status.getRemoved()); - - Set<String> queriesModified = new HashSet<>(); - Set<String> jsObjectsModified = new HashSet<>(); - Set<String> pagesModified = new HashSet<>(); - int modifiedPages = 0; - int modifiedQueries = 0; - int modifiedJSObjects = 0; - int modifiedDatasources = 0; - int modifiedJSLibs = 0; - for (String x : modifiedAssets) { - // begins with pages and filename and parent name should be same or contains widgets - if (x.contains(CommonConstants.WIDGETS)) { - if (!pagesModified.contains(getPageName(x))) { - pagesModified.add(getPageName(x)); - modifiedPages++; - } - } else if (!x.contains(CommonConstants.WIDGETS) - && x.startsWith(GitDirectories.PAGE_DIRECTORY) - && !x.contains(GitDirectories.ACTION_DIRECTORY) - && !x.contains(GitDirectories.ACTION_COLLECTION_DIRECTORY)) { - if (!pagesModified.contains(getPageName(x))) { - pagesModified.add(getPageName(x)); - modifiedPages++; - } - } else if (x.contains(GitDirectories.ACTION_DIRECTORY + CommonConstants.DELIMITER_PATH)) { - String queryName = x.split(GitDirectories.ACTION_DIRECTORY + CommonConstants.DELIMITER_PATH)[1]; - int position = queryName.indexOf(CommonConstants.DELIMITER_PATH); - if(position != -1) { - queryName = queryName.substring(0, position); - String pageName = x.split(CommonConstants.DELIMITER_PATH)[1]; - if (!queriesModified.contains(pageName + queryName)) { - queriesModified.add(pageName + queryName); - modifiedQueries++; + try (Git git = Git.open(repoPath.toFile())) { + log.debug(Thread.currentThread().getName() + ": Get status for repo " + repoPath + ", branch " + + branchName); + Status status = git.status().call(); + GitStatusDTO response = new GitStatusDTO(); + Set<String> modifiedAssets = new HashSet<>(); + modifiedAssets.addAll(status.getModified()); + modifiedAssets.addAll(status.getAdded()); + modifiedAssets.addAll(status.getRemoved()); + modifiedAssets.addAll(status.getUncommittedChanges()); + modifiedAssets.addAll(status.getUntracked()); + response.setAdded(status.getAdded()); + response.setRemoved(status.getRemoved()); + + Set<String> queriesModified = new HashSet<>(); + Set<String> jsObjectsModified = new HashSet<>(); + Set<String> pagesModified = new HashSet<>(); + int modifiedPages = 0; + int modifiedQueries = 0; + int modifiedJSObjects = 0; + int modifiedDatasources = 0; + int modifiedJSLibs = 0; + for (String x : modifiedAssets) { + // begins with pages and filename and parent name should be same or contains widgets + if (x.contains(CommonConstants.WIDGETS)) { + if (!pagesModified.contains(getPageName(x))) { + pagesModified.add(getPageName(x)); + modifiedPages++; + } + } else if (!x.contains(CommonConstants.WIDGETS) + && x.startsWith(GitDirectories.PAGE_DIRECTORY) + && !x.contains(GitDirectories.ACTION_DIRECTORY) + && !x.contains(GitDirectories.ACTION_COLLECTION_DIRECTORY)) { + if (!pagesModified.contains(getPageName(x))) { + pagesModified.add(getPageName(x)); + modifiedPages++; + } + } else if (x.contains(GitDirectories.ACTION_DIRECTORY + CommonConstants.DELIMITER_PATH)) { + String queryName = + x.split(GitDirectories.ACTION_DIRECTORY + CommonConstants.DELIMITER_PATH)[1]; + int position = queryName.indexOf(CommonConstants.DELIMITER_PATH); + if (position != -1) { + queryName = queryName.substring(0, position); + String pageName = x.split(CommonConstants.DELIMITER_PATH)[1]; + if (!queriesModified.contains(pageName + queryName)) { + queriesModified.add(pageName + queryName); + modifiedQueries++; + } + } + } else if (x.contains( + GitDirectories.ACTION_COLLECTION_DIRECTORY + CommonConstants.DELIMITER_PATH) + && !x.endsWith(CommonConstants.JSON_EXTENSION)) { + String queryName = x.substring(x.lastIndexOf(CommonConstants.DELIMITER_PATH) + 1); + String pageName = x.split(CommonConstants.DELIMITER_PATH)[1]; + if (!jsObjectsModified.contains(pageName + queryName)) { + jsObjectsModified.add(pageName + queryName); + modifiedJSObjects++; + } + } else if (x.contains( + GitDirectories.DATASOURCE_DIRECTORY + CommonConstants.DELIMITER_PATH)) { + modifiedDatasources++; + } else if (x.contains(GitDirectories.JS_LIB_DIRECTORY + CommonConstants.DELIMITER_PATH)) { + modifiedJSLibs++; + } else if (x.equals(CommonConstants.METADATA + CommonConstants.JSON_EXTENSION)) { + response.setMigrationMessage(CommonConstants.FILE_MIGRATION_MESSAGE); } } - } else if (x.contains(GitDirectories.ACTION_COLLECTION_DIRECTORY + CommonConstants.DELIMITER_PATH) && !x.endsWith(CommonConstants.JSON_EXTENSION)) { - String queryName = x.substring(x.lastIndexOf(CommonConstants.DELIMITER_PATH) + 1); - String pageName = x.split(CommonConstants.DELIMITER_PATH)[1]; - if (!jsObjectsModified.contains(pageName + queryName)) { - jsObjectsModified.add(pageName + queryName); - modifiedJSObjects++; + response.setModified(modifiedAssets); + response.setConflicting(status.getConflicting()); + response.setIsClean(status.isClean()); + response.setModifiedPages(modifiedPages); + response.setModifiedQueries(modifiedQueries); + response.setModifiedJSObjects(modifiedJSObjects); + response.setModifiedDatasources(modifiedDatasources); + response.setModifiedJSLibs(modifiedJSLibs); + + BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(git.getRepository(), branchName); + if (trackingStatus != null) { + response.setAheadCount(trackingStatus.getAheadCount()); + response.setBehindCount(trackingStatus.getBehindCount()); + response.setRemoteBranch(trackingStatus.getRemoteTrackingBranch()); + } else { + log.debug( + "Remote tracking details not present for branch: {}, repo: {}", + branchName, + repoPath); + response.setAheadCount(0); + response.setBehindCount(0); + response.setRemoteBranch("untracked"); } - } else if (x.contains(GitDirectories.DATASOURCE_DIRECTORY + CommonConstants.DELIMITER_PATH)) { - modifiedDatasources++; - } else if (x.contains(GitDirectories.JS_LIB_DIRECTORY + CommonConstants.DELIMITER_PATH)) { - modifiedJSLibs++; - } else if (x.equals(CommonConstants.METADATA + CommonConstants.JSON_EXTENSION)) { - response.setMigrationMessage(CommonConstants.FILE_MIGRATION_MESSAGE); - } - } - response.setModified(modifiedAssets); - response.setConflicting(status.getConflicting()); - response.setIsClean(status.isClean()); - response.setModifiedPages(modifiedPages); - response.setModifiedQueries(modifiedQueries); - response.setModifiedJSObjects(modifiedJSObjects); - response.setModifiedDatasources(modifiedDatasources); - response.setModifiedJSLibs(modifiedJSLibs); - - BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(git.getRepository(), branchName); - if (trackingStatus != null) { - response.setAheadCount(trackingStatus.getAheadCount()); - response.setBehindCount(trackingStatus.getBehindCount()); - response.setRemoteBranch(trackingStatus.getRemoteTrackingBranch()); - } else { - log.debug("Remote tracking details not present for branch: {}, repo: {}", branchName, repoPath); - response.setAheadCount(0); - response.setBehindCount(0); - response.setRemoteBranch("untracked"); - } - - // Remove modified changes from current branch so that checkout to other branches will be possible - if (!status.isClean()) { - return resetToLastCommit(git) - .map(ref -> { + + // Remove modified changes from current branch so that checkout to other branches will be + // possible + if (!status.isClean()) { + return resetToLastCommit(git).map(ref -> { processStopwatch.stopAndLogTimeInMillis(); return response; }); - } - processStopwatch.stopAndLogTimeInMillis(); - return Mono.just(response); - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .flatMap(response -> response) - .subscribeOn(scheduler); + } + processStopwatch.stopAndLogTimeInMillis(); + return Mono.just(response); + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .flatMap(response -> response) + .subscribeOn(scheduler); } private String getPageName(String path) { @@ -582,206 +614,235 @@ private String getPageName(String path) { @Override public Mono<String> mergeBranch(Path repoSuffix, String sourceBranch, String destinationBranch) { return Mono.fromCallable(() -> { - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_MERGE.getEventName()); - log.debug(Thread.currentThread().getName() + ": Merge branch " + sourceBranch + " on " + destinationBranch); - try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { - try { - //checkout the branch on which the merge command is run - git.checkout().setName(destinationBranch).setCreateBranch(false).call(); - - MergeResult mergeResult = git.merge().include(git.getRepository().findRef(sourceBranch)).setStrategy(MergeStrategy.RECURSIVE).call(); - processStopwatch.stopAndLogTimeInMillis(); - return mergeResult.getMergeStatus().name(); - } catch (GitAPIException e) { - //On merge conflicts abort the merge => git merge --abort - git.getRepository().writeMergeCommitMsg(null); - git.getRepository().writeMergeHeads(null); - processStopwatch.stopAndLogTimeInMillis(); - throw new Exception(e); - } - } - }) - .onErrorResume(error -> { - try { - return resetToLastCommit(repoSuffix, destinationBranch) - .thenReturn(error.getMessage()); - } catch (GitAPIException | IOException e) { - log.error("Error while hard resetting to latest commit {0}", e); - return Mono.error(e); - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_MERGE.getEventName()); + log.debug(Thread.currentThread().getName() + ": Merge branch " + sourceBranch + " on " + + destinationBranch); + try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { + try { + // checkout the branch on which the merge command is run + git.checkout() + .setName(destinationBranch) + .setCreateBranch(false) + .call(); + + MergeResult mergeResult = git.merge() + .include(git.getRepository().findRef(sourceBranch)) + .setStrategy(MergeStrategy.RECURSIVE) + .call(); + processStopwatch.stopAndLogTimeInMillis(); + return mergeResult.getMergeStatus().name(); + } catch (GitAPIException e) { + // On merge conflicts abort the merge => git merge --abort + git.getRepository().writeMergeCommitMsg(null); + git.getRepository().writeMergeHeads(null); + processStopwatch.stopAndLogTimeInMillis(); + throw new Exception(e); + } + } + }) + .onErrorResume(error -> { + try { + return resetToLastCommit(repoSuffix, destinationBranch).thenReturn(error.getMessage()); + } catch (GitAPIException | IOException e) { + log.error("Error while hard resetting to latest commit {0}", e); + return Mono.error(e); + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } @Override - public Mono<String> fetchRemote(Path repoSuffix, String publicKey, String privateKey, boolean isRepoPath, String branchName, boolean isFetchAll) { - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_FETCH.getEventName()); + public Mono<String> fetchRemote( + Path repoSuffix, + String publicKey, + String privateKey, + boolean isRepoPath, + String branchName, + boolean isFetchAll) { + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_FETCH.getEventName()); Path repoPath = Boolean.TRUE.equals(isRepoPath) ? repoSuffix : createRepoPath(repoSuffix); return Mono.fromCallable(() -> { - TransportConfigCallback config = new SshTransportConfigCallback(privateKey, publicKey); - try (Git git = Git.open(repoPath.toFile())) { - String fetchMessages; - if(Boolean.TRUE.equals(isFetchAll)) { - fetchMessages = git.fetch() - .setRemoveDeletedRefs(true) - .setTransportConfigCallback(config) - .call() - .getMessages(); - } else { - RefSpec ref = new RefSpec("refs/heads/" + branchName +":refs/remotes/origin/" + branchName); - fetchMessages = git.fetch() - .setRefSpecs(ref) - .setRemoveDeletedRefs(true) - .setTransportConfigCallback(config) - .call() - .getMessages(); - } - processStopwatch.stopAndLogTimeInMillis(); - return fetchMessages; - } - }) - .onErrorResume(error -> { - log.error(error.getMessage()); - return Mono.error(error); - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + TransportConfigCallback config = new SshTransportConfigCallback(privateKey, publicKey); + try (Git git = Git.open(repoPath.toFile())) { + String fetchMessages; + if (Boolean.TRUE.equals(isFetchAll)) { + fetchMessages = git.fetch() + .setRemoveDeletedRefs(true) + .setTransportConfigCallback(config) + .call() + .getMessages(); + } else { + RefSpec ref = + new RefSpec("refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); + fetchMessages = git.fetch() + .setRefSpecs(ref) + .setRemoveDeletedRefs(true) + .setTransportConfigCallback(config) + .call() + .getMessages(); + } + processStopwatch.stopAndLogTimeInMillis(); + return fetchMessages; + } + }) + .onErrorResume(error -> { + log.error(error.getMessage()); + return Mono.error(error); + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } @Override public Mono<MergeStatusDTO> isMergeBranch(Path repoSuffix, String sourceBranch, String destinationBranch) { - Stopwatch processStopwatch = StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_MERGE_CHECK.getEventName()); + Stopwatch processStopwatch = + StopwatchHelpers.startStopwatch(repoSuffix, AnalyticsEvents.GIT_MERGE_CHECK.getEventName()); return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": Check mergeability for repo {} with src: {}, dest: {}", repoSuffix, sourceBranch, destinationBranch); + log.debug( + Thread.currentThread().getName() + + ": Check mergeability for repo {} with src: {}, dest: {}", + repoSuffix, + sourceBranch, + destinationBranch); - try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { + try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { + + // checkout the branch on which the merge command is run + try { + git.checkout() + .setName(destinationBranch) + .setCreateBranch(false) + .call(); + } catch (GitAPIException e) { + if (e instanceof CheckoutConflictException) { + MergeStatusDTO mergeStatus = new MergeStatusDTO(); + mergeStatus.setMergeAble(false); + mergeStatus.setConflictingFiles(((CheckoutConflictException) e).getConflictingPaths()); + processStopwatch.stopAndLogTimeInMillis(); + return mergeStatus; + } + } + + MergeResult mergeResult = git.merge() + .include(git.getRepository().findRef(sourceBranch)) + .setFastForward(MergeCommand.FastForwardMode.NO_FF) + .setCommit(false) + .call(); - //checkout the branch on which the merge command is run - try{ - git.checkout().setName(destinationBranch).setCreateBranch(false).call(); - } catch (GitAPIException e) { - if(e instanceof CheckoutConflictException) { MergeStatusDTO mergeStatus = new MergeStatusDTO(); - mergeStatus.setMergeAble(false); - mergeStatus.setConflictingFiles(((CheckoutConflictException) e).getConflictingPaths()); - processStopwatch.stopAndLogTimeInMillis(); + if (mergeResult.getMergeStatus().isSuccessful()) { + mergeStatus.setMergeAble(true); + mergeStatus.setMessage(SUCCESS_MERGE_STATUS); + } else { + // If there aer conflicts add the conflicting file names to the response structure + mergeStatus.setMergeAble(false); + List<String> mergeConflictFiles = + new ArrayList<>(mergeResult.getConflicts().keySet()); + mergeStatus.setConflictingFiles(mergeConflictFiles); + StringBuilder errorMessage = new StringBuilder(); + if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.CONFLICTING)) { + errorMessage.append("Conflicts"); + } else { + errorMessage.append(mergeResult.getMergeStatus().toString()); + } + errorMessage + .append(" while merging branch: ") + .append(destinationBranch) + .append(" <= ") + .append(sourceBranch); + mergeStatus.setMessage(errorMessage.toString()); + mergeStatus.setReferenceDoc(ErrorReferenceDocUrl.GIT_MERGE_CONFLICT.getDocUrl()); + } + mergeStatus.setStatus(mergeResult.getMergeStatus().name()); return mergeStatus; } - } - - MergeResult mergeResult = git.merge() - .include(git.getRepository().findRef(sourceBranch)) - .setFastForward(MergeCommand.FastForwardMode.NO_FF) - .setCommit(false) - .call(); - - MergeStatusDTO mergeStatus = new MergeStatusDTO(); - if(mergeResult.getMergeStatus().isSuccessful()) { - mergeStatus.setMergeAble(true); - mergeStatus.setMessage(SUCCESS_MERGE_STATUS); - } else { - //If there aer conflicts add the conflicting file names to the response structure - mergeStatus.setMergeAble(false); - List<String> mergeConflictFiles = new ArrayList<>(mergeResult.getConflicts().keySet()); - mergeStatus.setConflictingFiles(mergeConflictFiles); - StringBuilder errorMessage = new StringBuilder(); - if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.CONFLICTING)) { - errorMessage.append("Conflicts"); - } else { - errorMessage.append(mergeResult.getMergeStatus().toString()); - } - errorMessage.append(" while merging branch: ").append(destinationBranch).append(" <= ").append(sourceBranch); - mergeStatus.setMessage(errorMessage.toString()); - mergeStatus.setReferenceDoc(ErrorReferenceDocUrl.GIT_MERGE_CONFLICT.getDocUrl()); - } - mergeStatus.setStatus(mergeResult.getMergeStatus().name()); - return mergeStatus; - } - }) - .flatMap(status -> { - try { - // Revert uncommitted changes if any - return resetToLastCommit(repoSuffix, destinationBranch) - .map(ignore -> { + }) + .flatMap(status -> { + try { + // Revert uncommitted changes if any + return resetToLastCommit(repoSuffix, destinationBranch).map(ignore -> { processStopwatch.stopAndLogTimeInMillis(); return status; }); - } catch (GitAPIException | IOException e) { - log.error("Error for hard resetting to latest commit {0}", e); - return Mono.error(e); - } - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + } catch (GitAPIException | IOException e) { + log.error("Error for hard resetting to latest commit {0}", e); + return Mono.error(e); + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } public Mono<String> checkoutRemoteBranch(Path repoSuffix, String branchName) { // We can safely assume that repo has been already initialised either in commit or clone flow and can directly // open the repo return Mono.fromCallable(() -> { - log.debug(Thread.currentThread().getName() + ": Checking out remote branch origin/" + branchName + " for the repo " + repoSuffix); - // open the repo - Path baseRepoPath = createRepoPath(repoSuffix); - try (Git git = Git.open(baseRepoPath.toFile())) { - // Create and checkout to new branch - git.checkout() - .setCreateBranch(Boolean.TRUE) - .setName(branchName) - .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) - .setStartPoint("origin/" + branchName) - .call(); - - StoredConfig config = git.getRepository().getConfig(); - config.setString("branch", branchName, "remote", "origin"); - config.setString("branch", branchName, "merge", "refs/heads/" + branchName); - config.save(); - return git.getRepository().getBranch(); - } - }).timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + log.debug(Thread.currentThread().getName() + ": Checking out remote branch origin/" + branchName + + " for the repo " + repoSuffix); + // open the repo + Path baseRepoPath = createRepoPath(repoSuffix); + try (Git git = Git.open(baseRepoPath.toFile())) { + // Create and checkout to new branch + git.checkout() + .setCreateBranch(Boolean.TRUE) + .setName(branchName) + .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) + .setStartPoint("origin/" + branchName) + .call(); + + StoredConfig config = git.getRepository().getConfig(); + config.setString("branch", branchName, "remote", "origin"); + config.setString("branch", branchName, "merge", "refs/heads/" + branchName); + config.save(); + return git.getRepository().getBranch(); + } + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } @Override public Mono<Boolean> testConnection(String publicKey, String privateKey, String remoteUrl) { return Mono.fromCallable(() -> { - TransportConfigCallback transportConfigCallback = new SshTransportConfigCallback(privateKey, publicKey); - Git.lsRemoteRepository() - .setTransportConfigCallback(transportConfigCallback) - .setRemote(remoteUrl) - .setHeads(true) - .setTags(true) - .call(); - return true; - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + TransportConfigCallback transportConfigCallback = + new SshTransportConfigCallback(privateKey, publicKey); + Git.lsRemoteRepository() + .setTransportConfigCallback(transportConfigCallback) + .setRemote(remoteUrl) + .setHeads(true) + .setTags(true) + .call(); + return true; + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } - private Mono<Ref> resetToLastCommit(Git git) throws GitAPIException { - Stopwatch processStopwatch = StopwatchHelpers - .startStopwatch(git.getRepository().getDirectory().toPath().getParent(), AnalyticsEvents.GIT_RESET.getEventName()); + Stopwatch processStopwatch = StopwatchHelpers.startStopwatch( + git.getRepository().getDirectory().toPath().getParent(), AnalyticsEvents.GIT_RESET.getEventName()); return Mono.fromCallable(() -> { - // Remove tracked files - Ref ref = git.reset().setMode(ResetCommand.ResetType.HARD).call(); - // Remove untracked files - git.clean().setForce(true).setCleanDirectories(true).call(); - processStopwatch.stopAndLogTimeInMillis(); - return ref; - }) - .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .subscribeOn(scheduler); + // Remove tracked files + Ref ref = git.reset().setMode(ResetCommand.ResetType.HARD).call(); + // Remove untracked files + git.clean().setForce(true).setCleanDirectories(true).call(); + processStopwatch.stopAndLogTimeInMillis(); + return ref; + }) + .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) + .subscribeOn(scheduler); } public Mono<Boolean> resetToLastCommit(Path repoSuffix, String branchName) throws GitAPIException, IOException { - try (Git git = Git.open(createRepoPath(repoSuffix).toFile())){ + try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { return this.resetToLastCommit(git) .flatMap(ref -> checkoutToBranch(repoSuffix, branchName)) .flatMap(checkedOut -> { try { - return resetToLastCommit(git) - .thenReturn(true); + return resetToLastCommit(git).thenReturn(true); } catch (GitAPIException e) { log.error(e.getMessage()); return Mono.error(e); @@ -794,7 +855,10 @@ public Mono<Boolean> resetHard(Path repoSuffix, String branchName) { return this.checkoutToBranch(repoSuffix, branchName) .flatMap(aBoolean -> { try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { - Ref ref = git.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD~1").call(); + Ref ref = git.reset() + .setMode(ResetCommand.ResetType.HARD) + .setRef("HEAD~1") + .call(); return Mono.just(true); } catch (GitAPIException | IOException e) { log.error("Error while resetting the commit, {}", e.getMessage()); @@ -809,14 +873,21 @@ public Mono<Boolean> rebaseBranch(Path repoSuffix, String branchName) { return this.checkoutToBranch(repoSuffix, branchName) .flatMap(isCheckedOut -> { try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { - RebaseResult result = git.rebase().setUpstream("origin/" + branchName).call(); + RebaseResult result = + git.rebase().setUpstream("origin/" + branchName).call(); if (result.getStatus().isSuccessful()) { return Mono.just(true); } else { - log.error("Error while rebasing the branch, {}, {}", result.getStatus().name(), result.getConflicts()); - git.rebase().setUpstream("origin/" + branchName).setOperation(RebaseCommand.Operation.ABORT).call(); - return Mono.error(new Exception("Error while rebasing the branch, " + result.getStatus().name())); - + log.error( + "Error while rebasing the branch, {}, {}", + result.getStatus().name(), + result.getConflicts()); + git.rebase() + .setUpstream("origin/" + branchName) + .setOperation(RebaseCommand.Operation.ABORT) + .call(); + return Mono.error(new Exception("Error while rebasing the branch, " + + result.getStatus().name())); } } catch (GitAPIException | IOException e) { log.error("Error while rebasing the branch, {}", e.getMessage()); diff --git a/app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/DSLTransformHelperTest.java b/app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/DSLTransformHelperTest.java index e6ffc14175ab..9762661a9f44 100644 --- a/app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/DSLTransformHelperTest.java +++ b/app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/DSLTransformHelperTest.java @@ -10,8 +10,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -128,7 +126,8 @@ public void testCalculateParentDirectories() { Assertions.assertEquals(expected4, result4); }*/ - // Test case for nested JSON object construction -------------------------------------------------------------------- + // Test case for nested JSON object construction + // -------------------------------------------------------------------- @Test public void testGetNestedDSL_EmptyPageWithNoWidgets() { JSONObject mainContainer = new JSONObject(); @@ -230,7 +229,9 @@ public void testAppendChildren_WithNoExistingChildren() { .put(new JSONObject().put(CommonConstants.WIDGET_NAME, "Child1")) .put(new JSONObject().put(CommonConstants.WIDGET_NAME, "Child2")); - Assertions.assertEquals(expectedChildren.toString(), result.optJSONArray(CommonConstants.CHILDREN).toString()); + Assertions.assertEquals( + expectedChildren.toString(), + result.optJSONArray(CommonConstants.CHILDREN).toString()); } @Test @@ -250,6 +251,8 @@ public void testAppendChildren_WithExistingMultipleChildren() { .put(new JSONObject().put(CommonConstants.WIDGET_NAME, "Child1")) .put(new JSONObject().put(CommonConstants.WIDGET_NAME, "Child2")); - Assertions.assertEquals(expectedChildren.toString(), result.optJSONArray(CommonConstants.CHILDREN).toString()); + Assertions.assertEquals( + expectedChildren.toString(), + result.optJSONArray(CommonConstants.CHILDREN).toString()); } } diff --git a/app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/FileUtilsImplTest.java b/app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/FileUtilsImplTest.java index 06ff39ea3223..f0e0b4bd3235 100644 --- a/app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/FileUtilsImplTest.java +++ b/app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/FileUtilsImplTest.java @@ -11,7 +11,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import reactor.core.publisher.Mono; @@ -32,8 +31,10 @@ @ExtendWith(SpringExtension.class) public class FileUtilsImplTest { private FileUtilsImpl fileUtils; + @MockBean private GitExecutorImpl gitExecutor; + private GitServiceConfig gitServiceConfig; private static final String localTestDirectory = "localTestDirectory"; private static final Path localTestDirectoryPath = Path.of(localTestDirectory); @@ -51,7 +52,8 @@ public void tearDown() { } @Test - public void saveApplicationRef_removeActionAndActionCollectionDirectoryCreatedInV1FileFormat_success() throws GitAPIException, IOException { + public void saveApplicationRef_removeActionAndActionCollectionDirectoryCreatedInV1FileFormat_success() + throws GitAPIException, IOException { Path actionDirectoryPath = localTestDirectoryPath.resolve(ACTION_DIRECTORY); Path actionCollectionDirectoryPath = localTestDirectoryPath.resolve(ACTION_COLLECTION_DIRECTORY); Files.createDirectories(actionDirectoryPath); @@ -68,7 +70,9 @@ public void saveApplicationRef_removeActionAndActionCollectionDirectoryCreatedIn applicationGitReference.setActionCollections(new HashMap<>()); applicationGitReference.setDatasources(new HashMap<>()); applicationGitReference.setJsLibraries(new HashMap<>()); - fileUtils.saveApplicationToGitRepo(Path.of(""), applicationGitReference, "branch").block(); + fileUtils + .saveApplicationToGitRepo(Path.of(""), applicationGitReference, "branch") + .block(); Assertions.assertFalse(actionDirectoryPath.toFile().exists()); Assertions.assertFalse(actionCollectionDirectoryPath.toFile().exists()); @@ -107,8 +111,8 @@ public void testScanAndDeleteDirectoryForDeletedResources() { this.fileUtils.scanAndDeleteDirectoryForDeletedResources(validDirectorySet, pageDirectoryPath); try (Stream<Path> paths = Files.walk(pageDirectoryPath, 1)) { - Set<String> validFSDirectorySet = paths - .filter(path -> Files.isDirectory(path) && !path.equals(pageDirectoryPath)) + Set<String> validFSDirectorySet = paths.filter( + path -> Files.isDirectory(path) && !path.equals(pageDirectoryPath)) .map(Path::getFileName) .map(Path::toString) .collect(Collectors.toSet()); @@ -116,7 +120,6 @@ public void testScanAndDeleteDirectoryForDeletedResources() { } catch (IOException e) { Assertions.fail("Error while scanning directory"); } - } @Test @@ -160,8 +163,7 @@ public void testScanAndDeleteFileForDeletedResources() { this.fileUtils.scanAndDeleteFileForDeletedResources(validActionsSet, actionDirectoryPath); try (Stream<Path> paths = Files.walk(actionDirectoryPath)) { - Set<String> validFSFilesSet = paths - .filter(path -> Files.isRegularFile(path)) + Set<String> validFSFilesSet = paths.filter(path -> Files.isRegularFile(path)) .map(Path::getFileName) .map(Path::toString) .collect(Collectors.toSet()); @@ -169,7 +171,6 @@ public void testScanAndDeleteFileForDeletedResources() { } catch (IOException e) { Assertions.fail("Error while scanning directory"); } - } /** @@ -184,4 +185,4 @@ private void deleteLocalTestDirectoryPath() { } } } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/pom.xml b/app/server/appsmith-interfaces/pom.xml index 3e244f411283..9e1361cf1593 100644 --- a/app/server/appsmith-interfaces/pom.xml +++ b/app/server/appsmith-interfaces/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>integrated</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <artifactId>interfaces</artifactId> <version>1.0-SNAPSHOT</version> @@ -190,7 +189,8 @@ </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> - <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --> + <artifactId>jjwt-jackson</artifactId> + <!-- or jjwt-gson if Gson is preferred --> <version>${jjwt.version}</version> </dependency> @@ -255,9 +255,7 @@ </goals> <configuration> <outputDirectory>target/generated-sources/java</outputDirectory> - <processor> - org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor - </processor> + <processor>org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor</processor> </configuration> </execution> </executions> diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/documenttype/DocumentType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/documenttype/DocumentType.java index eb526398fd52..cc2c1d660216 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/documenttype/DocumentType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/documenttype/DocumentType.java @@ -17,5 +17,4 @@ public @interface DocumentType { public String value() default ""; - -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/documenttype/DocumentTypeMapper.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/documenttype/DocumentTypeMapper.java index 1c3f11f0392c..93c4e0b447bd 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/documenttype/DocumentTypeMapper.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/documenttype/DocumentTypeMapper.java @@ -50,7 +50,8 @@ private void populateTypeMap(List<String> basePackagesToScan) { typeToAliasMap.put(type, alias); } catch (ClassNotFoundException e) { - throw new IllegalStateException(String.format("Class [%s] could not be loaded.", bd.getBeanClassName()), e); + throw new IllegalStateException( + String.format("Class [%s] could not be loaded.", bd.getBeanClassName()), e); } } } @@ -90,7 +91,7 @@ public Builder withBasePackages(String[] basePackages) { return this; } - public Builder withBasePackages(Collection< ? extends String> basePackages) { + public Builder withBasePackages(Collection<? extends String> basePackages) { basePackagesToScan.addAll(basePackages); return this; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/Encrypted.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/Encrypted.java index 3546ceb550ed..8f8c0a4f3cbc 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/Encrypted.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/Encrypted.java @@ -12,5 +12,4 @@ */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) -public @interface Encrypted { -} +public @interface Encrypted {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionHandler.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionHandler.java index b0eb347fd0a9..bd642baa216d 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionHandler.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionHandler.java @@ -17,7 +17,6 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; import java.util.function.UnaryOperator; @Slf4j @@ -55,157 +54,178 @@ List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { - ReflectionUtils.doWithFields(sourceClass, field -> { - if (field.getAnnotation(Encrypted.class) != null) { - CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); - finalCandidateFields.add(candidateField); - } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { - CandidateField candidateField = null; + ReflectionUtils.doWithFields( + sourceClass, + field -> { + if (field.getAnnotation(Encrypted.class) != null) { + CandidateField candidateField = + new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); + finalCandidateFields.add(candidateField); + } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { + CandidateField candidateField = null; - field.setAccessible(true); - Object fieldValue = ReflectionUtils.getField(field, source); - if (fieldValue == null) { - if (this.encryptedFieldsMap.containsKey(field.getType())) { - // If this field is null, but the cache has a non-empty list of candidates already, - // then this is an appsmith field with known annotations - candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); - } else { - // If it is null and the cache is not aware of the field, this is still a prospect, - // but with an unknown type (could also be polymorphic) - candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); - } - } else { - // If an object exists, check if the object type is the same as the field type - CandidateField.Type appsmithFieldType; - if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { - // If they match, then this is going to be an appsmith known field - appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; - } else { - // If not, then this field is polymorphic, - // it will need to be checked for type every time - appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; - } - // Now, go into field type and repeat - List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); + field.setAccessible(true); + Object fieldValue = ReflectionUtils.getField(field, source); + if (fieldValue == null) { + if (this.encryptedFieldsMap.containsKey(field.getType())) { + // If this field is null, but the cache has a non-empty list of candidates already, + // then this is an appsmith field with known annotations + candidateField = + new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); + } else { + // If it is null and the cache is not aware of the field, this is still a prospect, + // but with an unknown type (could also be polymorphic) + candidateField = + new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); + } + } else { + // If an object exists, check if the object type is the same as the field type + CandidateField.Type appsmithFieldType; + if (field.getType() + .getCanonicalName() + .equals(fieldValue.getClass().getCanonicalName())) { + // If they match, then this is going to be an appsmith known field + appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; + } else { + // If not, then this field is polymorphic, + // it will need to be checked for type every time + appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; + } + // Now, go into field type and repeat + List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); - if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) - || !candidateFieldsForType.isEmpty()) { - // This type only qualifies as a candidate if it is polymorphic, - // or has a list of candidates - candidateField = new CandidateField(field, appsmithFieldType); - } - } + if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) + || !candidateFieldsForType.isEmpty()) { + // This type only qualifies as a candidate if it is polymorphic, + // or has a list of candidates + candidateField = new CandidateField(field, appsmithFieldType); + } + } - field.setAccessible(false); - if (candidateField != null) { - // This will only ever be null if the field value is populated, - // and is known to be a non-encryption related field - finalCandidateFields.add(candidateField); - } - } else if (Collection.class.isAssignableFrom(field.getType()) && - field.getGenericType() instanceof ParameterizedType) { - // If this is a collection, check if the Type parameter is an AppsmithDomain - Type[] typeArguments; - ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); - typeArguments = parameterizedType.getActualTypeArguments(); + field.setAccessible(false); + if (candidateField != null) { + // This will only ever be null if the field value is populated, + // and is known to be a non-encryption related field + finalCandidateFields.add(candidateField); + } + } else if (Collection.class.isAssignableFrom(field.getType()) + && field.getGenericType() instanceof ParameterizedType) { + // If this is a collection, check if the Type parameter is an AppsmithDomain + Type[] typeArguments; + ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); + typeArguments = parameterizedType.getActualTypeArguments(); - Class<?> subFieldType; - try { - subFieldType = (Class<?>) typeArguments[0]; - } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { - subFieldType = null; - } - if(subFieldType != null) { - if (this.encryptedFieldsMap.containsKey(subFieldType)) { - // This is a known type, it should necessarily be of AppsmithDomain type - assert AppsmithDomain.class.isAssignableFrom(subFieldType); - final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); - if (!existingSubTypeCandidates.isEmpty()) { - finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); + Class<?> subFieldType; + try { + subFieldType = (Class<?>) typeArguments[0]; + } catch (ClassCastException | ArrayIndexOutOfBoundsException e) { + subFieldType = null; } - } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { - // If the type is not known, then this is either not parsed yet, or has polymorphic implementations + if (subFieldType != null) { + if (this.encryptedFieldsMap.containsKey(subFieldType)) { + // This is a known type, it should necessarily be of AppsmithDomain type + assert AppsmithDomain.class.isAssignableFrom(subFieldType); + final List<CandidateField> existingSubTypeCandidates = + this.encryptedFieldsMap.get(subFieldType); + if (!existingSubTypeCandidates.isEmpty()) { + finalCandidateFields.add(new CandidateField( + field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); + } + } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { + // If the type is not known, then this is either not parsed yet, or has polymorphic + // implementations - field.setAccessible(true); - Object fieldValue = ReflectionUtils.getField(field, source); - Collection<?> collection = (Collection<?>) fieldValue; + field.setAccessible(true); + Object fieldValue = ReflectionUtils.getField(field, source); + Collection<?> collection = (Collection<?>) fieldValue; - if (collection == null || collection.isEmpty()) { - finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); - } else { - for (final Object o : collection) { - if (o == null) { - continue; - } - if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { - final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); - if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { - finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); - } + if (collection == null || collection.isEmpty()) { + finalCandidateFields.add(new CandidateField( + field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { - finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); + for (final Object o : collection) { + if (o == null) { + continue; + } + if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { + final List<CandidateField> candidateFieldsForListMember = + findCandidateFieldsForType(o); + if (candidateFieldsForListMember != null + && !candidateFieldsForListMember.isEmpty()) { + finalCandidateFields.add(new CandidateField( + field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); + } + } else { + finalCandidateFields.add(new CandidateField( + field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); + } + break; + } } - break; + field.setAccessible(false); } } - field.setAccessible(false); + // TODO Add support for nested collections + } else if (Map.class.isAssignableFrom(field.getType()) + && field.getGenericType() instanceof ParameterizedType) { + Type[] typeArguments; + ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); + typeArguments = parameterizedType.getActualTypeArguments(); + Class<?> subFieldType = (Class<?>) typeArguments[1]; - } - } - // TODO Add support for nested collections - } else if (Map.class.isAssignableFrom(field.getType()) && - field.getGenericType() instanceof ParameterizedType) { - Type[] typeArguments; - ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); - typeArguments = parameterizedType.getActualTypeArguments(); - Class<?> subFieldType = (Class<?>) typeArguments[1]; - - if (this.encryptedFieldsMap.containsKey(subFieldType)) { - // This is a known type, it should necessarily be of AppsmithDomain type - assert AppsmithDomain.class.isAssignableFrom(subFieldType); - final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); - if (!existingSubTypeCandidates.isEmpty()) { - finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); - } - } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { - // If the type is not known, then this is either not parsed yet, or has polymorphic implementations - - field.setAccessible(true); - Object fieldValue = ReflectionUtils.getField(field, source); - Map<?, ?> map = (Map<?, ?>) fieldValue; - if (map == null || map.isEmpty()) { - finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); - } else { - for (Map.Entry<?, ?> entry : map.entrySet()) { - final Object value = entry.getValue(); - if (value == null) { - continue; + if (this.encryptedFieldsMap.containsKey(subFieldType)) { + // This is a known type, it should necessarily be of AppsmithDomain type + assert AppsmithDomain.class.isAssignableFrom(subFieldType); + final List<CandidateField> existingSubTypeCandidates = + this.encryptedFieldsMap.get(subFieldType); + if (!existingSubTypeCandidates.isEmpty()) { + finalCandidateFields.add( + new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } - if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { - final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); - if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { - finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); - } + } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { + // If the type is not known, then this is either not parsed yet, or has polymorphic + // implementations + + field.setAccessible(true); + Object fieldValue = ReflectionUtils.getField(field, source); + Map<?, ?> map = (Map<?, ?>) fieldValue; + if (map == null || map.isEmpty()) { + finalCandidateFields.add( + new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { - finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); + for (Map.Entry<?, ?> entry : map.entrySet()) { + final Object value = entry.getValue(); + if (value == null) { + continue; + } + if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { + final List<CandidateField> candidateFieldsForListMember = + findCandidateFieldsForType(value); + if (candidateFieldsForListMember != null + && !candidateFieldsForListMember.isEmpty()) { + finalCandidateFields.add(new CandidateField( + field, CandidateField.Type.APPSMITH_MAP_KNOWN)); + } + } else { + finalCandidateFields.add(new CandidateField( + field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); + } + break; + } } - break; + field.setAccessible(false); } } - field.setAccessible(false); - } - } - - }, field -> field.getAnnotation(Encrypted.class) != null || - AppsmithDomain.class.isAssignableFrom(field.getType()) || - Collection.class.isAssignableFrom(field.getType()) || - Map.class.isAssignableFrom(field.getType())); + }, + field -> field.getAnnotation(Encrypted.class) != null + || AppsmithDomain.class.isAssignableFrom(field.getType()) + || Collection.class.isAssignableFrom(field.getType()) + || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; - } synchronized boolean convertEncryption(Object source, UnaryOperator<String> transformer) { @@ -220,7 +240,8 @@ synchronized boolean convertEncryption(Object source, UnaryOperator<String> tran // if it is a known type, go to sub type and convert // if it is a polymorphic type, go to specific subtype for convert - // if it is an unknown type, go to specific subtype for convert and update the current candidate field with the verdict + // if it is an unknown type, go to specific subtype for convert and update the current candidate field with the + // verdict Iterator<CandidateField> candidateFieldIterator = candidateFields.iterator(); while (candidateFieldIterator.hasNext()) { CandidateField candidateField = candidateFieldIterator.next(); @@ -235,16 +256,16 @@ synchronized boolean convertEncryption(Object source, UnaryOperator<String> tran ReflectionUtils.setField(field, source, transformedValue); } else if (Set.of( - CandidateField.Type.APPSMITH_FIELD_KNOWN, - CandidateField.Type.APPSMITH_FIELD_UNKNOWN, - CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) + CandidateField.Type.APPSMITH_FIELD_KNOWN, + CandidateField.Type.APPSMITH_FIELD_UNKNOWN, + CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) .contains(candidateField.getType())) { // or go into field type if it is not (this is an appsmith field) boolean subTypeHasEncrypted = convertEncryption(fieldValue, transformer); - if (!subTypeHasEncrypted && field - .getType() - .getCanonicalName() - .equals(fieldValue.getClass().getCanonicalName())) { + if (!subTypeHasEncrypted + && field.getType() + .getCanonicalName() + .equals(fieldValue.getClass().getCanonicalName())) { // This is a previously unknown type that is actually irrelevant candidateFieldIterator.remove(); } else { @@ -257,9 +278,9 @@ synchronized boolean convertEncryption(Object source, UnaryOperator<String> tran } else { final Type[] typeNames = ((ParameterizedType) field.getGenericType()).getActualTypeArguments(); if (Set.of( - CandidateField.Type.APPSMITH_COLLECTION_KNOWN, - CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN, - CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC) + CandidateField.Type.APPSMITH_COLLECTION_KNOWN, + CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN, + CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC) .contains(candidateField.getType())) { // This is a collection which will necessarily have elements of AppsmithDomain type boolean subTypeHasEncrypted = false; @@ -270,34 +291,38 @@ synchronized boolean convertEncryption(Object source, UnaryOperator<String> tran } // The following condition will be true for unknown types when: // none of the elements ended up being encrypted, and - // the collection itself was not empty (if it was empty then we never really scanned anything), and + // the collection itself was not empty (if it was empty then we never really scanned anything), + // and // the declared type of the collection was the same as the first element (not polymorphic) - if (!subTypeHasEncrypted && - element != null && - typeNames[0].getTypeName().equals(element.getClass().getCanonicalName())) { + if (!subTypeHasEncrypted + && element != null + && typeNames[0] + .getTypeName() + .equals(element.getClass().getCanonicalName())) { candidateFieldIterator.remove(); } } else if (Set.of( - CandidateField.Type.APPSMITH_MAP_KNOWN, - CandidateField.Type.APPSMITH_MAP_UNKNOWN, - CandidateField.Type.APPSMITH_MAP_POLYMORPHIC) + CandidateField.Type.APPSMITH_MAP_KNOWN, + CandidateField.Type.APPSMITH_MAP_UNKNOWN, + CandidateField.Type.APPSMITH_MAP_POLYMORPHIC) .contains(candidateField.getType())) { // This is a map that will necessarily have element values of AppsmithDomain type boolean subTypeHasEncrypted = false; boolean isPolymorphic = false; final String typeName = typeNames[1].getTypeName(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet()) { - subTypeHasEncrypted = subTypeHasEncrypted || convertEncryption(entry.getValue(), transformer); - isPolymorphic = isPolymorphic || - !typeName.equals(entry.getValue().getClass().getCanonicalName()); + subTypeHasEncrypted = + subTypeHasEncrypted || convertEncryption(entry.getValue(), transformer); + isPolymorphic = isPolymorphic + || !typeName.equals( + entry.getValue().getClass().getCanonicalName()); } // The following condition will be true for unknown types when: // none of the elements ended up being encrypted, and // the map was not empty (if it was empty then we never really scanned anything), and - // the declared type of the values in the map was the same as the values in the map (not polymorphic) - if (!subTypeHasEncrypted && - !((Map<?, ?>) fieldValue).isEmpty() && - !isPolymorphic) { + // the declared type of the values in the map was the same as the values in the map (not + // polymorphic) + if (!subTypeHasEncrypted && !((Map<?, ?>) fieldValue).isEmpty() && !isPolymorphic) { candidateFieldIterator.remove(); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionMongoEventListener.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionMongoEventListener.java index e8e5ceb5e48d..7e687582e950 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionMongoEventListener.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionMongoEventListener.java @@ -34,5 +34,4 @@ public void onAfterConvert(AfterConvertEvent<E> event) { encryptionHandler.convertEncryption(source, encryptionService::decryptString); } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java index cedd07d084af..379631c8362e 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java @@ -84,8 +84,7 @@ public enum AnalyticsEvents { DS_TEST_EVENT("Test_Datasource_Clicked"), DS_TEST_EVENT_SUCCESS("Test_Datasource_Success"), - DS_TEST_EVENT_FAILED("Test_Datasource_Failed") - ; + DS_TEST_EVENT_FAILED("Test_Datasource_Failed"); private final String eventName; @@ -100,5 +99,4 @@ public enum AnalyticsEvents { public String getEventName() { return eventName; } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/Assets.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/Assets.java index 400d9a7dc975..f1593125a5b4 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/Assets.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/Assets.java @@ -1,5 +1,6 @@ package com.appsmith.external.constants; public class Assets { - public static final String GIT_DISCARD_DOC_URL = "https://docs.appsmith.com/core-concepts/version-control-with-git/pull-and-sync#discard-and-pull-changes"; + public static final String GIT_DISCARD_DOC_URL = + "https://docs.appsmith.com/core-concepts/version-control-with-git/pull-and-sync#discard-and-pull-changes"; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/CommonFieldName.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/CommonFieldName.java index 47fa24be387f..d4b2158f3daf 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/CommonFieldName.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/CommonFieldName.java @@ -16,6 +16,6 @@ public class CommonFieldName { public static final String FILE_TYPE = "FILE"; public static final String REDACTED_DATA = "<redacted>"; - public static final String PREPARED_STATEMENT= "preparedStatement"; + public static final String PREPARED_STATEMENT = "preparedStatement"; public static final String BODY = "body"; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/DataType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/DataType.java index 6f6044974c9b..6c6fdceee779 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/DataType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/DataType.java @@ -1,10 +1,10 @@ package com.appsmith.external.constants; /* - There are a lot of occurrences where DataType enum is used. We already do have so many classes to define data types - e.g. ClientDataType, AppsmithType, DataType. Removing all the dependencies from the DataType enum might require a dedicated effort. - Let's consider this a tech-debt and we should pay back before it's too late. - */ + There are a lot of occurrences where DataType enum is used. We already do have so many classes to define data types + e.g. ClientDataType, AppsmithType, DataType. Removing all the dependencies from the DataType enum might require a dedicated effort. + Let's consider this a tech-debt and we should pay back before it's too late. +*/ public enum DataType { INTEGER, LONG, @@ -25,4 +25,4 @@ public enum DataType { BSON_SPECIAL_DATA_TYPES, BIGDECIMAL, NULL_ARRAY -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/ErrorReferenceDocUrl.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/ErrorReferenceDocUrl.java index 47bd3ca4e454..e834fb09f349 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/ErrorReferenceDocUrl.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/ErrorReferenceDocUrl.java @@ -1,14 +1,13 @@ package com.appsmith.external.constants; -import lombok.Getter; - public enum ErrorReferenceDocUrl { - GIT_MERGE_CONFLICT("https://docs.appsmith.com/core-concepts/version-control-with-git/merging-branches"), GIT_PULL_CONFLICT("https://docs.appsmith.com/core-concepts/version-control-with-git/pull-and-sync"), - GIT_DEPLOY_KEY("https://docs.appsmith.com/core-concepts/version-control-with-git/connecting-to-git-repository#generating-a-deploy-key"), + GIT_DEPLOY_KEY( + "https://docs.appsmith.com/core-concepts/version-control-with-git/connecting-to-git-repository#generating-a-deploy-key"), FILE_PATH_NOT_SET("https://docs.appsmith.com/core-concepts/version-control-with-git/updating-local-file-path"), - GIT_UPSTREAM_CHANGES("https://docs.appsmith.com/core-concepts/version-control-with-git/working-with-branches#syncing-local-with-remote-branch"), + GIT_UPSTREAM_CHANGES( + "https://docs.appsmith.com/core-concepts/version-control-with-git/working-with-branches#syncing-local-with-remote-branch"), DEPLOY_KEY_DOC_URL("https://docs.github.com/en/developers/overview/managing-deploy-keys"); private final String docUrl; @@ -17,5 +16,7 @@ public enum ErrorReferenceDocUrl { this.docUrl = docUrl; } - public String getDocUrl() { return this.docUrl;} + public String getDocUrl() { + return this.docUrl; + } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/GitConstants.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/GitConstants.java index 30512c8fcba5..690b40ccfbf5 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/GitConstants.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/GitConstants.java @@ -12,12 +12,13 @@ public class GitConstants { public static final String DEFAULT_COMMIT_MESSAGE = "System generated commit, "; public static final String EMPTY_COMMIT_ERROR_MESSAGE = "On current branch nothing to commit, working tree clean"; public static final String MERGE_CONFLICT_BRANCH_NAME = "_mergeConflict"; - public static final String CONFLICTED_SUCCESS_MESSAGE = "branch has been created from conflicted state. Please " + - "resolve merge conflicts in remote and pull again"; + public static final String CONFLICTED_SUCCESS_MESSAGE = "branch has been created from conflicted state. Please " + + "resolve merge conflicts in remote and pull again"; - public static final String GIT_CONFIG_ERROR = "Unable to find the git configuration, please configure your application " + - "with git to use version control service"; + public static final String GIT_CONFIG_ERROR = + "Unable to find the git configuration, please configure your application " + + "with git to use version control service"; - public static final String GIT_PROFILE_ERROR = "Unable to find git author configuration for logged-in user. You can" + - " set up a git profile from the user profile section."; + public static final String GIT_PROFILE_ERROR = "Unable to find git author configuration for logged-in user. You can" + + " set up a git profile from the user profile section."; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/ActionSpan.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/ActionSpan.java index ff9994064340..6eaeff07ef91 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/ActionSpan.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/ActionSpan.java @@ -16,6 +16,4 @@ public final class ActionSpan { public static final String GET_UNPUBLISHED_ACTION = APPSMITH_SPAN_PREFIX + "get.action.unpublished"; public static final String GET_VIEW_MODE_ACTION = APPSMITH_SPAN_PREFIX + "get.action.viewmode"; public static final String GET_ACTION_REPOSITORY_CALL = APPSMITH_SPAN_PREFIX + "get.action.repository.call"; - - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/HttpMethodConverter.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/HttpMethodConverter.java index e736966b6943..8caa3a1dec44 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/HttpMethodConverter.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/HttpMethodConverter.java @@ -19,7 +19,9 @@ public class HttpMethodConverter implements JsonSerializer<HttpMethod>, JsonDeserializer<HttpMethod> { @Override - public HttpMethod deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + public HttpMethod deserialize( + JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) + throws JsonParseException { return HttpMethod.valueOf(jsonElement.getAsString()); } @@ -37,7 +39,8 @@ public HttpMethodModule() { public static class HttpMethodSerializer extends com.fasterxml.jackson.databind.JsonSerializer<HttpMethod> { @Override - public void serialize(HttpMethod httpMethod, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + public void serialize(HttpMethod httpMethod, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) + throws IOException { jsonGenerator.writeString(httpMethod.name()); } } @@ -45,7 +48,8 @@ public void serialize(HttpMethod httpMethod, JsonGenerator jsonGenerator, Serial public static class HttpMethodDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer<HttpMethod> { @Override - public HttpMethod deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { + public HttpMethod deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) + throws IOException { return HttpMethod.valueOf(deserializationContext.readValue(jsonParser, String.class)); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/ISOStringToInstantConverter.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/ISOStringToInstantConverter.java index 964dca7cc260..f5bba2f14ad2 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/ISOStringToInstantConverter.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/ISOStringToInstantConverter.java @@ -15,16 +15,19 @@ import java.time.format.DateTimeFormatter; public class ISOStringToInstantConverter implements JsonSerializer<Instant>, JsonDeserializer<Instant> { - private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX").withZone(ZoneOffset.UTC); + private final DateTimeFormatter formatter = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX").withZone(ZoneOffset.UTC); @Override - public Instant deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + public Instant deserialize( + JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) + throws JsonParseException { if (jsonElement.isJsonNull()) { return null; } if (jsonElement.isJsonPrimitive()) { String jsonString = jsonElement.getAsJsonPrimitive().getAsString(); - if (jsonString.length() == 0) { + if (jsonString.isEmpty()) { return null; } try { diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/AppsmithType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/AppsmithType.java index 5ed7087b7d7c..9036351a42a6 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/AppsmithType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/AppsmithType.java @@ -6,5 +6,6 @@ public interface AppsmithType extends Predicate<String> { String performSmartSubstitution(String value); + DataType type(); } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/ArrayType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/ArrayType.java index 96c1507f8a5a..6902bbbf6a7c 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/ArrayType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/ArrayType.java @@ -9,7 +9,6 @@ import net.minidev.json.parser.JSONParser; import reactor.core.Exceptions; - public class ArrayType implements AppsmithType { private static final ObjectMapper objectMapper = new ObjectMapper(); @@ -29,12 +28,7 @@ public String performSmartSubstitution(String s) { return objectMapper.writeValueAsString(jsonArray); } catch (net.minidev.json.parser.ParseException | JsonProcessingException e) { throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - s, - e.getMessage() - ) - ); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, s, e.getMessage())); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/BigDecimalType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/BigDecimalType.java index dc6b80a379a0..d86cd72f4830 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/BigDecimalType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/BigDecimalType.java @@ -4,7 +4,7 @@ import java.math.BigDecimal; -public class BigDecimalType implements AppsmithType{ +public class BigDecimalType implements AppsmithType { @Override public String performSmartSubstitution(String s) { return s; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/DateType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/DateType.java index 8ef2aac17516..82deacb439eb 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/DateType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/DateType.java @@ -39,12 +39,7 @@ public String performSmartSubstitution(String s) { return Matcher.quoteReplacement(valueAsString); } catch (JsonProcessingException e) { throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - s, - e.getMessage() - ) - ); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, s, e.getMessage())); } } @@ -52,4 +47,4 @@ public String performSmartSubstitution(String s) { public DataType type() { return DataType.DATE; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/DoubleType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/DoubleType.java index 4ea50e14dcd4..2312f07d1a12 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/DoubleType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/DoubleType.java @@ -2,7 +2,7 @@ import com.appsmith.external.constants.DataType; -public class DoubleType implements AppsmithType{ +public class DoubleType implements AppsmithType { @Override public String performSmartSubstitution(String value) { return String.valueOf(value); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/IntegerType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/IntegerType.java index 31028e8f2794..a79b1474a441 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/IntegerType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/IntegerType.java @@ -2,7 +2,7 @@ import com.appsmith.external.constants.DataType; -public class IntegerType implements AppsmithType{ +public class IntegerType implements AppsmithType { @Override public String performSmartSubstitution(String s) { return s; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/JsonObjectType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/JsonObjectType.java index 0f9b44ae3810..01d66d470b7a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/JsonObjectType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/JsonObjectType.java @@ -20,8 +20,7 @@ public class JsonObjectType implements AppsmithType { - private static final TypeAdapter<JsonObject> strictGsonObjectAdapter = - new Gson().getAdapter(JsonObject.class); + private static final TypeAdapter<JsonObject> strictGsonObjectAdapter = new Gson().getAdapter(JsonObject.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private static final JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); @@ -47,12 +46,7 @@ public String performSmartSubstitution(String s) { return Matcher.quoteReplacement(jsonString); } catch (net.minidev.json.parser.ParseException | JsonProcessingException e) { throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - s, - e.getMessage() - ) - ); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, s, e.getMessage())); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/NullArrayType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/NullArrayType.java index 1f5b079bb7ba..bcb772661121 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/NullArrayType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/NullArrayType.java @@ -2,7 +2,6 @@ import com.appsmith.external.constants.DataType; - public class NullArrayType implements AppsmithType { @Override public boolean test(String s) { diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/NullType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/NullType.java index 4b2e8577dd9d..245718e7cbfe 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/NullType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/NullType.java @@ -2,7 +2,6 @@ import com.appsmith.external.constants.DataType; - public class NullType implements AppsmithType { @Override @@ -23,4 +22,4 @@ public String performSmartSubstitution(String s) { public DataType type() { return DataType.NULL; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/StringType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/StringType.java index a36b5f59f0f7..0a0360c87dd8 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/StringType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/StringType.java @@ -25,12 +25,7 @@ public String performSmartSubstitution(String s) { return Matcher.quoteReplacement(valueAsString); } catch (JsonProcessingException e) { throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - s, - e.getMessage() - ) - ); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, s, e.getMessage())); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/TimeType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/TimeType.java index 76a25128bdb1..f8ac884389da 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/TimeType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/TimeType.java @@ -40,12 +40,7 @@ public String performSmartSubstitution(String s) { return Matcher.quoteReplacement(valueAsString); } catch (JsonProcessingException e) { throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - s, - e.getMessage() - ) - ); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, s, e.getMessage())); } } @@ -53,4 +48,4 @@ public String performSmartSubstitution(String s) { public DataType type() { return DataType.TIME; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/TimestampType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/TimestampType.java index dd9a401acf49..7f30772154ad 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/TimestampType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/datatypes/TimestampType.java @@ -38,12 +38,7 @@ public String performSmartSubstitution(String s) { return Matcher.quoteReplacement(valueAsString); } catch (JsonProcessingException e) { throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - s, - e.getMessage() - ) - ); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, s, e.getMessage())); } } @@ -51,4 +46,4 @@ public String performSmartSubstitution(String s) { public DataType type() { return DataType.TIMESTAMP; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/ExecuteActionDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/ExecuteActionDTO.java index 7890daa0875a..dbea5a641b6c 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/ExecuteActionDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/ExecuteActionDTO.java @@ -25,13 +25,13 @@ public class ExecuteActionDTO { Boolean viewMode = false; /* Sample value of paramProperties - "paramProperties": { - "k0": { - "datatype": "string", - "blobIdentifiers": ["blobUrl1", "blobUrl2"] - } - } - */ + "paramProperties": { + "k0": { + "datatype": "string", + "blobIdentifiers": ["blobUrl1", "blobUrl2"] + } + } + */ Map<String, ParamProperty> paramProperties; Map<String, String> parameterMap; // e.g. {"Text1.text": "k1","Table1.data": "k2", "Api1.data": "k3"} @@ -48,11 +48,7 @@ public class ExecuteActionDTO { public void setParameterMap(Map<String, String> parameterMap) { this.parameterMap = parameterMap; - invertParameterMap = parameterMap.entrySet() - .stream() - .collect(Collectors.toMap( - Map.Entry::getValue, - Map.Entry::getKey - )); + invertParameterMap = + parameterMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/GitStatusDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/GitStatusDTO.java index 166f67317afd..693f4df8ac3b 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/GitStatusDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/GitStatusDTO.java @@ -11,47 +11,47 @@ @Data public class GitStatusDTO { - // Name of modified, added and deleted resources in local git repo - Set<String> modified; + // Name of modified, added and deleted resources in local git repo + Set<String> modified; - // Name of added resources to local git repo - Set<String> added; + // Name of added resources to local git repo + Set<String> added; - // Name of deleted resources from local git repo - Set<String> removed; + // Name of deleted resources from local git repo + Set<String> removed; - // Name of conflicting resources - Set<String> conflicting; + // Name of conflicting resources + Set<String> conflicting; - Boolean isClean; + Boolean isClean; - // number of modified custom JS libs - int modifiedJSLibs; + // number of modified custom JS libs + int modifiedJSLibs; - // number of modified pages - int modifiedPages; + // number of modified pages + int modifiedPages; - // number of modified actions - int modifiedQueries; + // number of modified actions + int modifiedQueries; - // number of modified JSObjects - int modifiedJSObjects; + // number of modified JSObjects + int modifiedJSObjects; - // number of modified JSObjects - int modifiedDatasources; + // number of modified JSObjects + int modifiedDatasources; - // number of local commits which are not present in remote repo - Integer aheadCount; + // number of local commits which are not present in remote repo + Integer aheadCount; - // number of remote commits which are not present in local repo - Integer behindCount; + // number of remote commits which are not present in local repo + Integer behindCount; - // Remote tracking branch name - String remoteBranch; + // Remote tracking branch name + String remoteBranch; - // Documentation url for discard and pull functionality - String discardDocUrl = Assets.GIT_DISCARD_DOC_URL; + // Documentation url for discard and pull functionality + String discardDocUrl = Assets.GIT_DISCARD_DOC_URL; - // File Format migration - String migrationMessage = ""; + // File Format migration + String migrationMessage = ""; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/MergeStatusDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/MergeStatusDTO.java index f3af4a5d7e12..86097d62053b 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/MergeStatusDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/MergeStatusDTO.java @@ -10,7 +10,7 @@ @Setter public class MergeStatusDTO { - @JsonProperty(value="isMergeAble") + @JsonProperty(value = "isMergeAble") boolean MergeAble; // Merge status received from JGIT diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/AppsmithErrorAction.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/AppsmithErrorAction.java index 377aa883b97a..a93d74f0c8a4 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/AppsmithErrorAction.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/AppsmithErrorAction.java @@ -4,4 +4,3 @@ public enum AppsmithErrorAction { DEFAULT, LOG_EXTERNALLY } - diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/BaseException.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/BaseException.java index 6f6a03661360..63b76fd928f8 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/BaseException.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/BaseException.java @@ -36,5 +36,4 @@ public String getMessage() { public abstract String getDownstreamErrorCode(); public abstract String getErrorType(); - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java index f1ab6992da09..a78909956432 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java @@ -7,8 +7,7 @@ import java.text.MessageFormat; @Getter -public enum AppsmithPluginError implements BasePluginError{ - +public enum AppsmithPluginError implements BasePluginError { PLUGIN_ERROR( 500, AppsmithPluginErrorCode.GENERIC_PLUGIN_ERROR.getCode(), @@ -17,8 +16,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_GET_STRUCTURE_ERROR( 500, AppsmithPluginErrorCode.PLUGIN_GET_STRUCTURE_ERROR.getCode(), @@ -27,8 +25,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Failed to get datasource structure", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_VALIDATE_DATASOURCE_ERROR( 500, AppsmithPluginErrorCode.PLUGIN_VALIDATE_DATASOURCE_ERROR.getCode(), @@ -37,8 +34,7 @@ public enum AppsmithPluginError implements BasePluginError{ AppsmithPluginErrorCode.PLUGIN_VALIDATE_DATASOURCE_ERROR.getDescription(), ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_QUERY_TIMEOUT_ERROR( 504, AppsmithPluginErrorCode.PLUGIN_QUERY_TIMEOUT_ERROR.getCode(), @@ -47,8 +43,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Timed out on query execution", ErrorType.CONNECTIVITY_ERROR, "{2}", - "{3}" - ), + "{3}"), PLUGIN_GET_STRUCTURE_TIMEOUT_ERROR( 504, AppsmithPluginErrorCode.PLUGIN_GET_STRUCTURE_TIMEOUT_ERROR.getCode(), @@ -57,8 +52,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Timed out when fetching datasource structure", ErrorType.CONNECTIVITY_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_DATASOURCE_ARGUMENT_ERROR( 500, AppsmithPluginErrorCode.PLUGIN_DATASOURCE_ARGUMENT_ERROR.getCode(), @@ -67,8 +61,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Datasource configuration is invalid", ErrorType.DATASOURCE_CONFIGURATION_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_EXECUTE_ARGUMENT_ERROR( 500, AppsmithPluginErrorCode.PLUGIN_EXECUTE_ARGUMENT_ERROR.getCode(), @@ -77,8 +70,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Query configuration is invalid", ErrorType.ACTION_CONFIGURATION_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_JSON_PARSE_ERROR( 500, AppsmithPluginErrorCode.JSON_PROCESSING_ERROR.getCode(), @@ -87,8 +79,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Invalid JSON found", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_DATASOURCE_TEST_GENERIC_ERROR( 500, AppsmithPluginErrorCode.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getCode(), @@ -97,8 +88,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Datasource configuration is invalid", ErrorType.INTERNAL_ERROR, "{0}", - "{1}" - ), + "{1}"), PLUGIN_DATASOURCE_TIMEOUT_ERROR( 504, AppsmithPluginErrorCode.PLUGIN_DATASOURCE_TIMEOUT_ERROR.getCode(), @@ -107,8 +97,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Timed out when connecting to datasource", ErrorType.CONNECTIVITY_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_AUTHENTICATION_ERROR( 401, AppsmithPluginErrorCode.PLUGIN_AUTHENTICATION_ERROR.getCode(), @@ -117,8 +106,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Datasource authentication error", ErrorType.AUTHENTICATION_ERROR, "{0}", - "{1}" - ), + "{1}"), PLUGIN_IN_MEMORY_FILTERING_ERROR( 500, AppsmithPluginErrorCode.PLUGIN_IN_MEMORY_FILTERING_ERROR.getCode(), @@ -127,8 +115,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Appsmith In Memory Filtering Failed", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), PLUGIN_UQI_WHERE_CONDITION_UNKNOWN( 500, AppsmithPluginErrorCode.PLUGIN_UQI_WHERE_CONDITION_UNKNOWN.getCode(), @@ -137,8 +124,7 @@ public enum AppsmithPluginError implements BasePluginError{ "Where condition could not be parsed", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), INCOMPATIBLE_FILE_FORMAT( 400, AppsmithPluginErrorCode.INCOMPATIBLE_FILE_FORMAT.getCode(), @@ -147,8 +133,7 @@ public enum AppsmithPluginError implements BasePluginError{ AppsmithPluginErrorCode.INCOMPATIBLE_FILE_FORMAT.getDescription(), ErrorType.INTERNAL_ERROR, "{0}", - "{1}" - ), + "{1}"), STALE_CONNECTION_ERROR( 500, @@ -158,21 +143,18 @@ public enum AppsmithPluginError implements BasePluginError{ "Connection is stale", ErrorType.CONNECTIVITY_ERROR, "{0}", - "{1}" - ), + "{1}"), SMART_SUBSTITUTION_VALUE_MISSING( 500, AppsmithPluginErrorCode.SMART_SUBSTITUTION_VALUE_MISSING.getCode(), - "Uh oh! This is unexpected. " + - "Did not receive any information for the binding " - + "{0}" + ". Please contact customer support at Appsmith.", + "Uh oh! This is unexpected. " + "Did not receive any information for the binding " + "{0}" + + ". Please contact customer support at Appsmith.", AppsmithErrorAction.LOG_EXTERNALLY, "Smart substitution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; @@ -186,8 +168,15 @@ public enum AppsmithPluginError implements BasePluginError{ private final String downstreamErrorCode; - AppsmithPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + AppsmithPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -202,7 +191,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); @@ -211,5 +202,4 @@ public String getDownstreamErrorMessage(Object... args) { public String getDownstreamErrorCode(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorCode, args); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java index 2d13db7e1a7b..6510babf1563 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java @@ -4,7 +4,7 @@ @Getter public enum AppsmithPluginErrorCode { - //All Appsmith error codes for common plugin errors + // All Appsmith error codes for common plugin errors JSON_PROCESSING_ERROR("PE-JSN-4000", "JSON processing error either at serializing or deserializing"), SMART_SUBSTITUTION_VALUE_MISSING("PE-SST-5000", "Missing required binding parameter's value"), GENERIC_PLUGIN_ERROR("PE-PLG-5000", "A generic plugin error"), @@ -20,9 +20,7 @@ public enum AppsmithPluginErrorCode { PLUGIN_UQI_WHERE_CONDITION_UNKNOWN("PE-UQI-5000", "Where condition could not be parsed"), GENERIC_STALE_CONNECTION("PE-STC-5000", "Secondary stale connection error"), PLUGIN_EXECUTE_ARGUMENT_ERROR("PE-ARG-5000", "Wrong arguments provided"), - PLUGIN_VALIDATE_DATASOURCE_ERROR("PE-DSE-5005", "Failed to validate datasource") - ; - + PLUGIN_VALIDATE_DATASOURCE_ERROR("PE-DSE-5005", "Failed to validate datasource"); private final String code; private final String description; @@ -31,4 +29,4 @@ public enum AppsmithPluginErrorCode { this.code = code; this.description = description; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginException.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginException.java index 326007031209..c4d564f3c7a1 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginException.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginException.java @@ -36,10 +36,14 @@ public AppsmithErrorAction getErrorAction() { return this.error.getErrorAction(); } - public String getTitle() { return this.error.getTitle(); } + public String getTitle() { + return this.error.getTitle(); + } @Override - public String getErrorType() { return this.error.getErrorType(); } + public String getErrorType() { + return this.error.getErrorType(); + } @Override public String getDownstreamErrorMessage() { @@ -52,6 +56,8 @@ public String getDownstreamErrorCode() { } public String getAppErrorCode() { - return this.error == null ? AppsmithPluginErrorCode.GENERIC_PLUGIN_ERROR.getCode() : this.error.getAppErrorCode(); + return this.error == null + ? AppsmithPluginErrorCode.GENERIC_PLUGIN_ERROR.getCode() + : this.error.getAppErrorCode(); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/BasePluginError.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/BasePluginError.java index 35d4203c9e73..bd7d3b2df2e3 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/BasePluginError.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/BasePluginError.java @@ -6,34 +6,34 @@ import java.util.regex.Pattern; public interface BasePluginError { - Integer getHttpErrorCode(); + Integer getHttpErrorCode(); - String getAppErrorCode(); + String getAppErrorCode(); - String getMessage(Object...args); + String getMessage(Object... args); - String getTitle(); + String getTitle(); - AppsmithErrorAction getErrorAction(); + AppsmithErrorAction getErrorAction(); - String getErrorType(); + String getErrorType(); - String getDownstreamErrorMessage(Object...args); + String getDownstreamErrorMessage(Object... args); - String getDownstreamErrorCode(Object...args); + String getDownstreamErrorCode(Object... args); - Pattern errorPlaceholderPattern = Pattern.compile("\\{\\d+\\}"); + Pattern errorPlaceholderPattern = Pattern.compile("\\{\\d+\\}"); - default String replacePlaceholderWithValue(String origin, Object...args) { - if (origin == null) { - return null; - } - String formattedErrorAttribute = new MessageFormat(origin).format(args); - if (errorPlaceholderPattern.matcher(formattedErrorAttribute).matches()) { - return null; - } else if (formattedErrorAttribute.equals("null")) { - return null; - } - return formattedErrorAttribute; - } + default String replacePlaceholderWithValue(String origin, Object... args) { + if (origin == null) { + return null; + } + String formattedErrorAttribute = new MessageFormat(origin).format(args); + if (errorPlaceholderPattern.matcher(formattedErrorAttribute).matches()) { + return null; + } else if (formattedErrorAttribute.equals("null")) { + return null; + } + return formattedErrorAttribute; + } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/BasePluginErrorMessages.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/BasePluginErrorMessages.java index 30561b4a200e..65ac5d5c972f 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/BasePluginErrorMessages.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/BasePluginErrorMessages.java @@ -7,7 +7,7 @@ public abstract class BasePluginErrorMessages { public static final String CONNECTION_POOL_NULL_ERROR_MSG = "Connection pool is null."; public static final String CONNECTION_POOL_CLOSED_ERROR_MSG = "Connection pool is closed."; public static final String CONNECTION_POOL_NOT_RUNNING_ERROR_MSG = "Connection pool is not running."; - public static final String UNKNOWN_CONNECTION_ERROR_MSG = "Unknown connection error. Please reach out to Appsmith " + - "customer support to resolve this."; + public static final String UNKNOWN_CONNECTION_ERROR_MSG = + "Unknown connection error. Please reach out to Appsmith " + "customer support to resolve this."; public static final String JDBC_DRIVER_LOADING_ERROR_MSG = "Error loading JDBC Driver class."; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/FileInterface.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/FileInterface.java index dc2c66be2f35..14c2d734f966 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/FileInterface.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/FileInterface.java @@ -28,9 +28,9 @@ public interface FileInterface { * --page1 * --page2 */ - Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, - ApplicationGitReference applicationGitReference, - String branchName) throws IOException, GitAPIException; + Mono<Path> saveApplicationToGitRepo( + Path baseRepoSuffix, ApplicationGitReference applicationGitReference, String branchName) + throws IOException, GitAPIException; /** * This method will reconstruct the application from the repo @@ -41,10 +41,8 @@ Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, * @param repoName git repo name to access file system * @return application reference from which entire application can be rehydrated */ - Mono<ApplicationGitReference> reconstructApplicationReferenceFromGitRepo(String organisationId, - String defaultApplicationId, - String repoName, - String branchName); + Mono<ApplicationGitReference> reconstructApplicationReferenceFromGitRepo( + String organisationId, String defaultApplicationId, String repoName, String branchName); /** * Once the user connects the existing application to a remote repo, we will initialize the repo with Readme.md - diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java index 27d3f83e02fc..aec1d5881b9e 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java @@ -25,7 +25,13 @@ public interface GitExecutor { * @param doAmend To amend with the previous commit * @return if the commit was successful */ - Mono<String> commitApplication(Path repoPath, String commitMessage, String authorName, String authorEmail, boolean isSuffixedPath, boolean doAmend); + Mono<String> commitApplication( + Path repoPath, + String commitMessage, + String authorName, + String authorEmail, + boolean isSuffixedPath, + boolean doAmend); /** * Method to get the commit history @@ -50,7 +56,8 @@ public interface GitExecutor { * @param privateKey generated by us and specific to the defaultApplication * @return Success message */ - Mono<String> pushApplication(Path branchSuffix, String remoteUrl, String publicKey, String privateKey, String branchName); + Mono<String> pushApplication( + Path branchSuffix, String remoteUrl, String publicKey, String privateKey, String branchName); /** Clone the repo to the file path : container-volume/orgId/defaultAppId/repo/applicationData * @@ -98,17 +105,16 @@ public interface GitExecutor { * @param publicKey generated by us and specific to the defaultApplication * @return success message */ - Mono<MergeStatusDTO> pullApplication(Path repoSuffix, String remoteUrl, String branchName, String privateKey, String publicKey) throws IOException; + Mono<MergeStatusDTO> pullApplication( + Path repoSuffix, String remoteUrl, String branchName, String privateKey, String publicKey) + throws IOException; /** * @param repoSuffix suffixedPath used to generate the base repo path this includes orgId, defaultAppId, repoName * @return List of branches for the application */ - Mono<List<GitBranchDTO>> listBranches(Path repoSuffix, - String remoteUrl, - String privateKey, - String publicKey, - Boolean isDefaultBranchNeeded); + Mono<List<GitBranchDTO>> listBranches( + Path repoSuffix, String remoteUrl, String privateKey, String publicKey, Boolean isDefaultBranchNeeded); /** * This method will handle the git-status functionality @@ -134,8 +140,13 @@ Mono<List<GitBranchDTO>> listBranches(Path repoSuffix, * @param isRepoPath does the repoSuffix contains the complete repoPath or only the suffix * @return messages received after the remote is fetched */ - Mono<String> fetchRemote(Path repoSuffix, String publicKey, String privateKey, boolean isRepoPath, String branchName, boolean isFetchAll); - + Mono<String> fetchRemote( + Path repoSuffix, + String publicKey, + String privateKey, + boolean isRepoPath, + String branchName, + boolean isFetchAll); /** * diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/AppsmithBeanUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/AppsmithBeanUtils.java index 741acdaff451..67402dc9c031 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/AppsmithBeanUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/AppsmithBeanUtils.java @@ -30,7 +30,7 @@ private static String[] getNullPropertyNames(Object source) { return emptyNames.toArray(result); } - //Use Spring BeanUtils to copy and ignore null + // Use Spring BeanUtils to copy and ignore null public static void copyNewFieldValuesIntoOldObject(Object src, Object target) { BeanUtils.copyProperties(src, target, getNullPropertyNames(src)); } @@ -98,7 +98,6 @@ public static void copyProperties(Object src, Object trg, Iterable<String> props BeanWrapper trgWrap = PropertyAccessorFactory.forBeanPropertyAccess(trg); props.forEach(p -> trgWrap.setPropertyValue(p, srcWrap.getPropertyValue(p))); - } public static List<Object> getBeanPropertyValues(Object object) { diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeServiceUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeServiceUtils.java index d53a463447f9..e41018f88d68 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeServiceUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeServiceUtils.java @@ -7,34 +7,27 @@ import java.util.Map; public class DataTypeServiceUtils { - final static Map<ClientDataType, List<AppsmithType>> defaultAppsmithTypes = new HashMap<>(); + static final Map<ClientDataType, List<AppsmithType>> defaultAppsmithTypes = new HashMap<>(); - static { + static { defaultAppsmithTypes.put(ClientDataType.NULL, List.of(new NullType())); defaultAppsmithTypes.put(ClientDataType.ARRAY, List.of(new ArrayType())); defaultAppsmithTypes.put(ClientDataType.BOOLEAN, List.of(new BooleanType())); - defaultAppsmithTypes.put(ClientDataType.NUMBER, List.of( - new IntegerType(), - new LongType(), - new DoubleType(), - new BigDecimalType() - )); + defaultAppsmithTypes.put( + ClientDataType.NUMBER, + List.of(new IntegerType(), new LongType(), new DoubleType(), new BigDecimalType())); /* - JsonObjectType is the preferred server-side data type when the client-side data type is of type OBJECT. - Fallback server-side data type for client-side OBJECT type is String. - */ + JsonObjectType is the preferred server-side data type when the client-side data type is of type OBJECT. + Fallback server-side data type for client-side OBJECT type is String. + */ defaultAppsmithTypes.put(ClientDataType.OBJECT, List.of(new JsonObjectType())); - defaultAppsmithTypes.put(ClientDataType.STRING, List.of( - new TimeType(), - new DateType(), - new TimestampType(), - new StringType() - )); + defaultAppsmithTypes.put( + ClientDataType.STRING, List.of(new TimeType(), new DateType(), new TimestampType(), new StringType())); } /** @@ -48,7 +41,6 @@ public static AppsmithType getAppsmithType(ClientDataType clientDataType, String return getAppsmithType(clientDataType, value, defaultAppsmithTypes); } - /** * <p>Identifies the AppsmithType from the given client-side data type and the evaluated value of the parameter with the help of the provided plugin-specific types</p> * @@ -79,7 +71,8 @@ public static AppsmithType getAppsmithType(ClientDataType clientDataType, String * * @return the corresponding AppsmithType from the clientDataType and the evaluated value */ - public static AppsmithType getAppsmithType(ClientDataType clientDataType, String value, Map<ClientDataType, List<AppsmithType>> pluginSpecificTypes) { + public static AppsmithType getAppsmithType( + ClientDataType clientDataType, String value, Map<ClientDataType, List<AppsmithType>> pluginSpecificTypes) { if (pluginSpecificTypes.get(clientDataType) != null) { for (AppsmithType currentType : pluginSpecificTypes.get(clientDataType)) { if (currentType.test(value)) { @@ -87,9 +80,8 @@ public static AppsmithType getAppsmithType(ClientDataType clientDataType, String } } } - //TODO: Send analytics event to Mixpanel - //Ideally we shouldn't reach here but if we do then we will return the FallbackType + // TODO: Send analytics event to Mixpanel + // Ideally we shouldn't reach here but if we do then we will return the FallbackType return new FallbackType(); } } - diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeStringUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeStringUtils.java index 22cf75d9d8ec..ba1267703100 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeStringUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeStringUtils.java @@ -57,10 +57,11 @@ public class DataTypeStringUtils { private static JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE); - private static final TypeAdapter<JsonObject> strictGsonObjectAdapter = - new Gson().getAdapter(JsonObject.class); + private static final TypeAdapter<JsonObject> strictGsonObjectAdapter = new Gson().getAdapter(JsonObject.class); - @Deprecated(since = "With the implementation of Data Type handling this function is marked as deprecated and is discouraged for further use") + @Deprecated( + since = + "With the implementation of Data Type handling this function is marked as deprecated and is discouraged for further use") public static DataType stringToKnownDataTypeConverter(String input) { if (input == null) { @@ -120,7 +121,7 @@ public static DataType stringToKnownDataTypeConverter(String input) { try { final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder() -// .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")) + // .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")) .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) .toFormatter(); LocalDateTime.parse(input, dateTimeFormatter); @@ -149,7 +150,6 @@ public static DataType stringToKnownDataTypeConverter(String input) { // Not time } - try (JsonReader reader = new JsonReader(new StringReader(input))) { strictGsonObjectAdapter.read(reader); reader.hasNext(); // throws on multiple top level values @@ -169,21 +169,22 @@ public static DataType stringToKnownDataTypeConverter(String input) { * TODO : ASCII, Binary and Bytes Array */ -// // Check if unicode stream also gets handled as part of this since the destination SQL type is the same. -// if(StandardCharsets.US_ASCII.newEncoder().canEncode(input)) { -// return Ascii.class; -// } -// if (isBinary(input)) { -// return Binary.class; -// } - -// try -// { -// input.getBytes("UTF-8"); -// return Byte.class; -// } catch (UnsupportedEncodingException e) { -// // Not byte -// } + // // Check if unicode stream also gets handled as part of this since the destination SQL type is the + // same. + // if(StandardCharsets.US_ASCII.newEncoder().canEncode(input)) { + // return Ascii.class; + // } + // if (isBinary(input)) { + // return Binary.class; + // } + + // try + // { + // input.getBytes("UTF-8"); + // return Byte.class; + // } catch (UnsupportedEncodingException e) { + // // Not byte + // } // default return type if none of the above matches. return DataType.STRING; @@ -202,12 +203,13 @@ public static DataType stringToKnownDataTypeConverter(String input) { * @param param the binding parameter having the clientDataType to be used in the data type identification process * @return */ - public static String jsonSmartReplacementPlaceholderWithValue(String input, - String replacement, - DataType replacementDataType, - List<Map.Entry<String, String>> insertedParams, - SmartSubstitutionInterface smartSubstitutionUtils, - Param param) { + public static String jsonSmartReplacementPlaceholderWithValue( + String input, + String replacement, + DataType replacementDataType, + List<Map.Entry<String, String>> insertedParams, + SmartSubstitutionInterface smartSubstitutionUtils, + Param param) { final DataType dataType; if (replacementDataType == null) { @@ -237,13 +239,8 @@ public static String jsonSmartReplacementPlaceholderWithValue(String input, // Adding Matcher.quoteReplacement so that "/" and "$" in the string are escaped during replacement updatedReplacement = Matcher.quoteReplacement(updatedReplacement); } catch (net.minidev.json.parser.ParseException | JsonProcessingException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - replacement, - e.getMessage() - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, replacement, e.getMessage())); } break; case JSON_OBJECT: @@ -253,13 +250,8 @@ public static String jsonSmartReplacementPlaceholderWithValue(String input, // Adding Matcher.quoteReplacement so that "/" and "$" in the string are escaped during replacement updatedReplacement = Matcher.quoteReplacement(jsonString); } catch (net.minidev.json.parser.ParseException | JsonProcessingException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - replacement, - e.getMessage() - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, replacement, e.getMessage())); } break; case BSON: @@ -285,13 +277,8 @@ public static String jsonSmartReplacementPlaceholderWithValue(String input, String valueAsString = objectMapper.writeValueAsString(replacement); updatedReplacement = Matcher.quoteReplacement(valueAsString); } catch (JsonProcessingException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - replacement, - e.getMessage() - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, replacement, e.getMessage())); } } @@ -318,24 +305,19 @@ private static boolean isBinary(String input) { private static boolean isDisplayTypeTable(Object data) { if (data instanceof List) { // Check if the data is a list of json objects - return ((List) data).stream() - .allMatch(item -> item instanceof Map); - } - else if (data instanceof JsonNode) { + return ((List) data).stream().allMatch(item -> item instanceof Map); + } else if (data instanceof JsonNode) { // Check if the data is an array of json objects try { - objectMapper.convertValue(data, new TypeReference<List<Map<String, Object>>>() { - }); + objectMapper.convertValue(data, new TypeReference<List<Map<String, Object>>>() {}); return true; } catch (IllegalArgumentException e) { return false; } - } - else if (data instanceof String) { + } else if (data instanceof String) { // Check if the data is an array of json objects try { - objectMapper.readValue((String) data, new TypeReference<List<Map<String, Object>>>() { - }); + objectMapper.readValue((String) data, new TypeReference<List<Map<String, Object>>>() {}); return true; } catch (IOException e) { return false; @@ -344,7 +326,7 @@ else if (data instanceof String) { return false; } - + private static boolean isDisplayTypeJson(Object data) { /* * - Any non string non primitive object is converted into a json when serializing. @@ -352,10 +334,9 @@ private static boolean isDisplayTypeJson(Object data) { */ if (!isPrimitiveOrWrapper(data.getClass()) && !(data instanceof String)) { return true; - } - else if (data instanceof String) { + } else if (data instanceof String) { try { - objectMapper.readTree((String)data); + objectMapper.readTree((String) data); return true; } catch (IOException e) { return false; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/MustacheHelper.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/MustacheHelper.java index fc7e74c7a7ee..74d2f739e150 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/MustacheHelper.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/MustacheHelper.java @@ -41,12 +41,13 @@ public class MustacheHelper { * {{JSON.stringify(fetchUsers)}} * This pattern should return ["JSON.stringify", "fetchUsers"] */ - private final static Pattern pattern = Pattern.compile("[a-zA-Z_][a-zA-Z0-9._]*"); + private static final Pattern pattern = Pattern.compile("[a-zA-Z_][a-zA-Z0-9._]*"); /** * Appsmith smart replacement : The regex pattern below looks for '?' or "?". This pattern is later replaced with ? * to fit the requirements of prepared statements. */ private static final String regexQuotesTrimming = "([\"']\\?[\"'])"; + private static final Pattern quoteQuestionPattern = Pattern.compile(regexQuotesTrimming); // The final replacement string of ? for replacing '?' or "?" private static final String postQuoteTrimmingQuestionMark = "\\?"; @@ -57,12 +58,12 @@ public class MustacheHelper { * of JSON smart replacement aka trim the quotes present. */ private static final String regexPlaceholderTrimming = "([\"']" + APPSMITH_SUBSTITUTION_PLACEHOLDER + "[\"'])"; + private static final Pattern placeholderTrimmingPattern = Pattern.compile(regexPlaceholderTrimming); private static final String laxMustacheBindingRegex = "\\{\\{([\\s\\S]*?)}}"; private static final Pattern laxMustacheBindingPattern = Pattern.compile(laxMustacheBindingRegex); - private static final Pattern nestedPathTokenSplitter = Pattern.compile("\\[.*\\]\\.?|\\."); // Possible types of entity references that we want to be filtering @@ -70,7 +71,6 @@ public class MustacheHelper { public static final int ACTION_ENTITY_REFERENCES = 0b01; public static final int WIDGET_ENTITY_REFERENCES = 0b10; - /** * Tokenize a Mustache template string into a list of plain text and Mustache interpolations. * @@ -166,9 +166,7 @@ public static List<MustacheBindingToken> tokenize(String template) { } else { currentToken.append(currentChar); } - } - } if (currentToken.length() > 0) { @@ -193,8 +191,12 @@ public static Set<MustacheBindingToken> extractMustacheKeys(String template) { if (token.getValue().startsWith("{{") && token.getValue().endsWith("}}")) { // Allowing empty tokens to be added, to be compatible with the previous `extractMustacheKeys` method. // Calling `.trim()` before adding because Mustache compiler strips keys in the template before looking - // up a value. Addresses https://www.notion.so/appsmith/Bindings-with-a-space-at-the-start-fail-to-execute-properly-in-the-API-pane-2eb65d5c6064466b9ef059fa01ef3261 - keys.add(new MustacheBindingToken(token.getValue().substring(2, token.getValue().length() - 2), (token.getStartIndex() + 2), false)); + // up a value. Addresses + // https://www.notion.so/appsmith/Bindings-with-a-space-at-the-start-fail-to-execute-properly-in-the-API-pane-2eb65d5c6064466b9ef059fa01ef3261 + keys.add(new MustacheBindingToken( + token.getValue().substring(2, token.getValue().length() - 2), + (token.getStartIndex() + 2), + false)); } } @@ -209,8 +211,14 @@ public static List<MustacheBindingToken> extractMustacheKeysInOrder(String templ if (token.getValue().startsWith("{{") && token.getValue().endsWith("}}")) { // Allowing empty tokens to be added, to be compatible with the previous `extractMustacheKeys` method. // Calling `.trim()` before adding because Mustache compiler strips keys in the template before looking - // up a value. Addresses https://www.notion.so/appsmith/Bindings-with-a-space-at-the-start-fail-to-execute-properly-in-the-API-pane-2eb65d5c6064466b9ef059fa01ef3261 - keys.add(new MustacheBindingToken(token.getValue().substring(2, token.getValue().length() - 2).trim(), (token.getStartIndex() + 2), false)); + // up a value. Addresses + // https://www.notion.so/appsmith/Bindings-with-a-space-at-the-start-fail-to-execute-properly-in-the-API-pane-2eb65d5c6064466b9ef059fa01ef3261 + keys.add(new MustacheBindingToken( + token.getValue() + .substring(2, token.getValue().length() - 2) + .trim(), + (token.getStartIndex() + 2), + false)); } } @@ -246,14 +254,17 @@ public static Set<MustacheBindingToken> extractMustacheKeysFromFields(Object obj } else if (obj instanceof String) { keys.addAll(extractMustacheKeys((String) obj)); - } } return keys; } - private static void clearAndPushToken(StringBuilder tokenBuilder, int tokenStartIndex, List<MustacheBindingToken> tokenList, boolean includesHandleBars) { + private static void clearAndPushToken( + StringBuilder tokenBuilder, + int tokenStartIndex, + List<MustacheBindingToken> tokenList, + boolean includesHandleBars) { if (tokenBuilder.length() > 0) { tokenList.add(new MustacheBindingToken(tokenBuilder.toString(), tokenStartIndex, includesHandleBars)); tokenBuilder.setLength(0); @@ -301,9 +312,10 @@ public static <T> T renderFieldValues(T object, Map<String, String> context) { } else if (object instanceof Map) { Map renderedMap = new HashMap<>(); for (Object entry : ((Map) object).entrySet()) { - renderedMap.put(((Map.Entry) entry).getKey(), // key + renderedMap.put( + ((Map.Entry) entry).getKey(), // key renderFieldValues(((Map.Entry) entry).getValue(), context) // value - ); + ); } return (T) renderedMap; @@ -325,10 +337,13 @@ public static String render(String template, Map<String, String> keyValueMap) { for (MustacheBindingToken token : tokenize(template)) { if (token.getValue().startsWith("{{") && token.getValue().endsWith("}}")) { - //If there is no entry found for the current token in keyValueMap that means the binding is part of the text - //and hence reflecting the value in the rendered string as is. + // If there is no entry found for the current token in keyValueMap that means the binding is part of the + // text + // and hence reflecting the value in the rendered string as is. // Example: {{Input.text}} = "This whole string is the value of Input1.text. Even this {{one}}." - String bindingValue = keyValueMap.get(token.getValue().substring(2, token.getValue().length() - 2).trim()); + String bindingValue = keyValueMap.get(token.getValue() + .substring(2, token.getValue().length() - 2) + .trim()); if (bindingValue != null) { rendered.append(bindingValue); } else { @@ -350,7 +365,8 @@ public static String render(String template, Map<String, String> keyValueMap) { * @param types * @return */ - public static Mono<Map<String, Set<EntityDependencyNode>>> getPossibleEntityParentsMap(Flux<Tuple2<String, Set<String>>> bindingAndPossibleReferencesFlux, int types) { + public static Mono<Map<String, Set<EntityDependencyNode>>> getPossibleEntityParentsMap( + Flux<Tuple2<String, Set<String>>> bindingAndPossibleReferencesFlux, int types) { return bindingAndPossibleReferencesFlux.collect(HashMap::new, (map, tuple) -> { String bindingValue = tuple.getT1(); @@ -390,7 +406,8 @@ public static Set<EntityDependencyNode> getPossibleWidgets(String reference) { if (subStrings.length < 1) { return dependencyNodes; } else { - EntityDependencyNode entityDependencyNode = new EntityDependencyNode(EntityReferenceType.WIDGET, subStrings[0], reference, null, null, null); + EntityDependencyNode entityDependencyNode = + new EntityDependencyNode(EntityReferenceType.WIDGET, subStrings[0], reference, null, null, null); dependencyNodes.add(entityDependencyNode); } @@ -419,7 +436,6 @@ public static Set<EntityDependencyNode> getPossibleActions(String reference) { Set<EntityDependencyNode> dependencyNodes = new HashSet<>(); String key = reference.trim(); - String[] subStrings = nestedPathTokenSplitter.split(key); if (subStrings.length < 1) { @@ -429,19 +445,22 @@ public static Set<EntityDependencyNode> getPossibleActions(String reference) { if (subStrings.length == 2) { // This could qualify if it is a sync JS function call, even if it is called `JsObject1.data()` // For sync JS actions, the entire reference could be a function call - EntityDependencyNode entityDependencyNode = new EntityDependencyNode(EntityReferenceType.JSACTION, key, reference, false, true, null); + EntityDependencyNode entityDependencyNode = + new EntityDependencyNode(EntityReferenceType.JSACTION, key, reference, false, true, null); dependencyNodes.add(entityDependencyNode); if ("data".equals(subStrings[1])) { // This means it is a valid API/query reference // For queries and APIs, the first word is the action name - EntityDependencyNode actionEntityDependencyNode = new EntityDependencyNode(EntityReferenceType.ACTION, subStrings[0], reference, false, false, null); + EntityDependencyNode actionEntityDependencyNode = new EntityDependencyNode( + EntityReferenceType.ACTION, subStrings[0], reference, false, false, null); dependencyNodes.add(actionEntityDependencyNode); } } else if (subStrings.length > 2) { if ("data".equals(subStrings[1])) { // This means it is a valid API/query reference // For queries and APIs, the first word is the action name - EntityDependencyNode actionEntityDependencyNode = new EntityDependencyNode(EntityReferenceType.ACTION, subStrings[0], reference, false, false, null); + EntityDependencyNode actionEntityDependencyNode = new EntityDependencyNode( + EntityReferenceType.ACTION, subStrings[0], reference, false, false, null); dependencyNodes.add(actionEntityDependencyNode); } if ("data".equals(subStrings[2])) { @@ -449,7 +468,13 @@ public static Set<EntityDependencyNode> getPossibleActions(String reference) { // the collection name and the individual action name // We don't know if this is a run for sync or async JS action at this point, // since both would be valid - EntityDependencyNode entityDependencyNode = new EntityDependencyNode(EntityReferenceType.JSACTION, subStrings[0] + "." + subStrings[1], reference, null, false, null); + EntityDependencyNode entityDependencyNode = new EntityDependencyNode( + EntityReferenceType.JSACTION, + subStrings[0] + "." + subStrings[1], + reference, + null, + false, + null); dependencyNodes.add(entityDependencyNode); } } @@ -468,7 +493,6 @@ public static Set<String> getPossibleParentsOld(String mustacheKey) { Set<String> bindingNames = new HashSet<>(); String key = mustacheKey.trim(); - // Extract all the words in the dynamic bindings Matcher matcher = pattern.matcher(key); @@ -484,7 +508,6 @@ public static Set<String> getPossibleParents(String mustacheKey) { Set<String> bindingNames = new HashSet<>(); String key = mustacheKey.trim(); - // Extract all the words in the dynamic bindings Matcher matcher = pattern.matcher(key); @@ -500,36 +523,42 @@ public static Set<String> getPossibleParents(String mustacheKey) { bindingNames.add(subStrings[0]); if (subStrings.length >= 2) { - // For JS actions, the first two words are the action name since action name consists of the collection name + // For JS actions, the first two words are the action name since action name consists of the collection + // name // and the individual action name bindingNames.add(subStrings[0] + "." + subStrings[1]); } - } return bindingNames; } public static String replaceMustacheWithPlaceholder(String query, List<MustacheBindingToken> mustacheBindings) { - return replaceMustacheUsingPatterns(query, APPSMITH_SUBSTITUTION_PLACEHOLDER, mustacheBindings, placeholderTrimmingPattern, APPSMITH_SUBSTITUTION_PLACEHOLDER); + return replaceMustacheUsingPatterns( + query, + APPSMITH_SUBSTITUTION_PLACEHOLDER, + mustacheBindings, + placeholderTrimmingPattern, + APPSMITH_SUBSTITUTION_PLACEHOLDER); } public static String replaceMustacheWithQuestionMark(String query, List<MustacheBindingToken> mustacheBindings) { - return replaceMustacheUsingPatterns(query, "?", mustacheBindings, quoteQuestionPattern, postQuoteTrimmingQuestionMark); + return replaceMustacheUsingPatterns( + query, "?", mustacheBindings, quoteQuestionPattern, postQuoteTrimmingQuestionMark); } - private static String replaceMustacheUsingPatterns(String query, - String placeholder, - List<MustacheBindingToken> mustacheBindings, - Pattern sanitizePattern, - String replacement) { + private static String replaceMustacheUsingPatterns( + String query, + String placeholder, + List<MustacheBindingToken> mustacheBindings, + Pattern sanitizePattern, + String replacement) { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody(query); Set<MustacheBindingToken> mustacheSet = new HashSet<>(mustacheBindings); - Map<String, String> replaceParamsMap = mustacheSet - .stream() + Map<String, String> replaceParamsMap = mustacheSet.stream() .map(mustacheToken -> mustacheToken.getValue()) .distinct() .collect(Collectors.toMap(k -> k, v -> placeholder)); @@ -560,6 +589,5 @@ public static Set<String> getWordsFromMustache(String mustache) { } return words; - } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/PluginUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/PluginUtils.java index c9d659ef4aa0..06a7cb7b25a3 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/PluginUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/PluginUtils.java @@ -54,8 +54,7 @@ public Type getType() { } }; - public static final TypeReference<Object> OBJECT_TYPE = new TypeReference<>() { - }; + public static final TypeReference<Object> OBJECT_TYPE = new TypeReference<>() {}; // Pattern to match all words in the text private static final Pattern WORD_PATTERN = Pattern.compile("\\w+"); @@ -72,8 +71,7 @@ public Type getType() { public static String MATCH_QUOTED_WORDS_REGEX = "([\\\"'])(?:(?=(\\\\?))\\2.)*?\\1"; public static List<String> getColumnsListForJdbcPlugin(ResultSetMetaData metaData) throws SQLException { - List<String> columnsList = IntStream - .range(1, metaData.getColumnCount()+1) // JDBC column indexes start from 1 + List<String> columnsList = IntStream.range(1, metaData.getColumnCount() + 1) // JDBC column indexes start from 1 .mapToObj(i -> { try { return metaData.getColumnName(i); @@ -93,9 +91,8 @@ public static List<String> getIdenticalColumns(List<String> columnNames) { /* * - Get frequency of each column name */ - Map<String, Long> columnFrequencies = columnNames - .stream() - .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + Map<String, Long> columnFrequencies = + columnNames.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); /* * - Filter only the inputs which have frequency greater than 1 @@ -120,14 +117,17 @@ public static Boolean validConfigurationPresentInFormData(Map<String, Object> fo return getValueSafelyFromFormData(formData, field) != null; } - public static <T> Boolean validDataConfigurationPresentInFormData(Map<String, Object> formData, String field, TypeReference<T> type) { + public static <T> Boolean validDataConfigurationPresentInFormData( + Map<String, Object> formData, String field, TypeReference<T> type) { return getDataValueSafelyFromFormData(formData, field, type) != null; } private static <T> T getDataValueAsTypeFromFormData(Map<String, Object> formDataValueMap, TypeReference<T> type) { assert formDataValueMap != null; final Object formDataValue = formDataValueMap.get("data"); - if (formDataValueMap.containsKey("viewType") && "json".equals(formDataValueMap.get("viewType")) && type != STRING_TYPE) { + if (formDataValueMap.containsKey("viewType") + && "json".equals(formDataValueMap.get("viewType")) + && type != STRING_TYPE) { try { return objectMapper.readValue((String) formDataValue, type); } catch (JsonProcessingException e) { @@ -149,8 +149,8 @@ private static <T> T getDataValueAsTypeFromFormData(Map<String, Object> formData * @param <T> : type parameter to which the obtained value is cast to. * @return : obtained value (post type cast) if non-null, otherwise defaultValue */ - public static <T> T getDataValueSafelyFromFormData(Map<String, Object> formData, String field, TypeReference<T> type, - T defaultValue) { + public static <T> T getDataValueSafelyFromFormData( + Map<String, Object> formData, String field, TypeReference<T> type, T defaultValue) { Map<String, Object> formDataValueMap = (Map<String, Object>) getValueSafelyFromFormData(formData, field); if (formDataValueMap == null) { return defaultValue; @@ -183,7 +183,8 @@ public static String getTrimmedStringDataValueSafelyFromFormData(Map<String, Obj * @param <T> : type parameter to which the obtained value is cast to. * @return : obtained value (post type cast) if non-null, otherwise null. */ - public static <T> T getDataValueSafelyFromFormData(Map<String, Object> formData, String field, TypeReference<T> type) { + public static <T> T getDataValueSafelyFromFormData( + Map<String, Object> formData, String field, TypeReference<T> type) { Map<String, Object> formDataValueMap = (Map<String, Object>) getValueSafelyFromFormData(formData, field); if (formDataValueMap == null) { return null; @@ -191,8 +192,8 @@ public static <T> T getDataValueSafelyFromFormData(Map<String, Object> formData, return getDataValueAsTypeFromFormData(formDataValueMap, type); } - public static <T> T getValueSafelyFromFormData(Map<String, Object> formData, String field, Class<T> type, - T defaultValue) { + public static <T> T getValueSafelyFromFormData( + Map<String, Object> formData, String field, Class<T> type, T defaultValue) { Object value = getValueSafelyFromFormData(formData, field); return value == null ? defaultValue : (T) value; } @@ -226,7 +227,6 @@ public static Object getValueSafelyFromFormData(Map<String, Object> formData, St // This is a top level field. Return the value return formData.getOrDefault(field, null); } - } public static String getValueSafelyFromFormDataAsString(Map<String, Object> formData, String field) { @@ -318,8 +318,7 @@ public static boolean endpointContainsLocalhost(Endpoint endpoint) { localhostUrlIdentifiers.add("127.0.0.1"); String host = endpoint.getHost().toLowerCase(); - return localhostUrlIdentifiers.stream() - .anyMatch(identifier -> host.contains(identifier)); + return localhostUrlIdentifiers.stream().anyMatch(identifier -> host.contains(identifier)); } /** @@ -333,21 +332,18 @@ public static Set<String> getHintMessageForLocalhostUrl(DatasourceConfiguration if (datasourceConfiguration != null) { boolean usingLocalhostUrl = false; - if(!StringUtils.isEmpty(datasourceConfiguration.getUrl())) { + if (!StringUtils.isEmpty(datasourceConfiguration.getUrl())) { usingLocalhostUrl = datasourceConfiguration.getUrl().contains("localhost"); - } - else if(!CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) { - usingLocalhostUrl = datasourceConfiguration - .getEndpoints() - .stream() + } else if (!CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) { + usingLocalhostUrl = datasourceConfiguration.getEndpoints().stream() .anyMatch(endpoint -> endpointContainsLocalhost(endpoint)); } - if(usingLocalhostUrl) { - message.add("You may not be able to access your localhost if Appsmith is running inside a docker " + - "container or on the cloud. To enable access to your localhost you may use ngrok to expose " + - "your local endpoint to the internet. Please check out Appsmith's documentation to understand more" + - "."); + if (usingLocalhostUrl) { + message.add("You may not be able to access your localhost if Appsmith is running inside a docker " + + "container or on the cloud. To enable access to your localhost you may use ngrok to expose " + + "your local endpoint to the internet. Please check out Appsmith's documentation to understand more" + + "."); } } @@ -365,7 +361,8 @@ public static Condition parseWhereClause(Map<String, Object> whereClause) { ConditionalOperator operator; try { - operator = ConditionalOperator.valueOf(((String) unparsedOperator).trim().toUpperCase()); + operator = ConditionalOperator.valueOf( + ((String) unparsedOperator).trim().toUpperCase()); } catch (IllegalArgumentException e) { // The operator could not be cast into a known type. Throw an exception log.error(e.getMessage()); @@ -402,9 +399,11 @@ public static List<String> parseList(String arrayString) throws IOException { return objectMapper.readValue(arrayString, ArrayList.class); } - public static <T> T getValueSafelyFromPropertyList(List<Property> properties, int index, Class<T> type, - T defaultValue) { - if (CollectionUtils.isEmpty(properties) || index > properties.size() - 1 || properties.get(index) == null + public static <T> T getValueSafelyFromPropertyList( + List<Property> properties, int index, Class<T> type, T defaultValue) { + if (CollectionUtils.isEmpty(properties) + || index > properties.size() - 1 + || properties.get(index) == null || properties.get(index).getValue() == null) { return defaultValue; } @@ -424,22 +423,21 @@ public static JSONObject parseStringIntoJSONObject(String body) throws JSONExcep return new JSONObject(body); } - public static void setValueSafelyInPropertyList(List<Property> properties, int index, Object value) throws AppsmithPluginException { + public static void setValueSafelyInPropertyList(List<Property> properties, int index, Object value) + throws AppsmithPluginException { if (properties == null) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_ERROR, - "Appsmith server encountered an unexpected error: property list is null. Please reach out to " + - "our customer support to resolve this." - ); + "Appsmith server encountered an unexpected error: property list is null. Please reach out to " + + "our customer support to resolve this."); } if (index < 0 || index > properties.size() - 1) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_ERROR, - "Appsmith server encountered an unexpected error: index value out or range: index: " + index + - ", property list size: " + properties.size() + ". Please reach out to our customer " + - "support to resolve this." - ); + "Appsmith server encountered an unexpected error: index value out or range: index: " + index + + ", property list size: " + + properties.size() + ". Please reach out to our customer " + "support to resolve this."); } properties.get(index).setValue(value); @@ -455,8 +453,8 @@ public static String replaceMappedColumnInStringValue(Map<String, String> mapped // the column name with user one. Matcher matcher = WORD_PATTERN.matcher(propertyValue.toString()); if (matcher.find()) { - return matcher.replaceAll(key -> - mappedColumns.get(key.group()) == null ? key.group() : mappedColumns.get(key.group())); + return matcher.replaceAll( + key -> mappedColumns.get(key.group()) == null ? key.group() : mappedColumns.get(key.group())); } return propertyValue.toString(); @@ -473,18 +471,18 @@ public static void safelyCloseSingleConnectionFromHikariCP(Connection connection } } - public static ExecuteActionDTO getExecuteDTOForTestWithBindingAndValueAndDataType(LinkedHashMap<String, List> bindingValueDataTypeMap) { + public static ExecuteActionDTO getExecuteDTOForTestWithBindingAndValueAndDataType( + LinkedHashMap<String, List> bindingValueDataTypeMap) { List<Param> params = new ArrayList<>(); - bindingValueDataTypeMap.keySet().stream() - .forEach(bindingName -> { - String bindingValue = (String) (bindingValueDataTypeMap.get(bindingName)).get(0); - ClientDataType clientDataType = (ClientDataType) (bindingValueDataTypeMap.get(bindingName)).get(1); - Param param = new Param(); - param.setKey(bindingName); - param.setValue(bindingValue); - param.setClientDataType(clientDataType); - params.add(param); - }); + bindingValueDataTypeMap.keySet().stream().forEach(bindingName -> { + String bindingValue = (String) (bindingValueDataTypeMap.get(bindingName)).get(0); + ClientDataType clientDataType = (ClientDataType) (bindingValueDataTypeMap.get(bindingName)).get(1); + Param param = new Param(); + param.setKey(bindingName); + param.setValue(bindingValue); + param.setClientDataType(clientDataType); + params.add(param); + }); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/SSLHelper.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/SSLHelper.java index b01116c96d01..731dff2de705 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/SSLHelper.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/SSLHelper.java @@ -27,7 +27,8 @@ public class SSLHelper { private static final String SSL_PROTOCOL = "TLS"; public static SSLContext getSslContext(UploadedFile certificate) - throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException { + throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, + KeyManagementException { final TrustManagerFactory trustManagerFactory = getSslTrustManagerFactory(certificate); @@ -39,11 +40,9 @@ public static SSLContext getSslContext(UploadedFile certificate) public static TrustManagerFactory getSslTrustManagerFactory(UploadedFile certificate) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException { - InputStream certificateIs = - new ByteArrayInputStream(certificate.getDecodedContent()); + InputStream certificateIs = new ByteArrayInputStream(certificate.getDecodedContent()); CertificateFactory certificateFactory = CertificateFactory.getInstance(X_509_TYPE); - X509Certificate caCertificate = - (X509Certificate) certificateFactory.generateCertificate(certificateIs); + X509Certificate caCertificate = (X509Certificate) certificateFactory.generateCertificate(certificateIs); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); @@ -56,18 +55,21 @@ public static TrustManagerFactory getSslTrustManagerFactory(UploadedFile certifi return trustManagerFactory; } - public static Consumer<? super SslProvider.SslContextSpec> sslCheckForHttpClient(DatasourceConfiguration datasourceConfiguration) { + public static Consumer<? super SslProvider.SslContextSpec> sslCheckForHttpClient( + DatasourceConfiguration datasourceConfiguration) { return (sslContextSpec) -> { final DefaultSslContextSpec sslContextSpec1 = DefaultSslContextSpec.forClient(); - if (datasourceConfiguration.getConnection() != null && - datasourceConfiguration.getConnection().getSsl() != null && - datasourceConfiguration.getConnection().getSsl().getAuthType() == SSLDetails.AuthType.SELF_SIGNED_CERTIFICATE) { + if (datasourceConfiguration.getConnection() != null + && datasourceConfiguration.getConnection().getSsl() != null + && datasourceConfiguration.getConnection().getSsl().getAuthType() + == SSLDetails.AuthType.SELF_SIGNED_CERTIFICATE) { sslContextSpec1.configure(sslContextBuilder -> { try { - final UploadedFile certificateFile = datasourceConfiguration.getConnection().getSsl().getCertificateFile(); + final UploadedFile certificateFile = + datasourceConfiguration.getConnection().getSsl().getCertificateFile(); sslContextBuilder.trustManager(SSLHelper.getSslTrustManagerFactory(certificateFile)); } catch (CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException e) { e.printStackTrace(); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/SmartSubstitutionHelper.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/SmartSubstitutionHelper.java index 42d7c1aeed0e..2e485303a80e 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/SmartSubstitutionHelper.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/SmartSubstitutionHelper.java @@ -21,5 +21,4 @@ public static String replaceQuestionMarkWithDollarIndex(String query) { return updatedQuery; } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/APIConnection.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/APIConnection.java index 9ae3cab98046..950df124655a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/APIConnection.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/APIConnection.java @@ -19,4 +19,4 @@ HttpClient getSecuredHttpClient(DatasourceConfiguration datasourceConfiguration) return httpClient; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/APIConnectionFactory.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/APIConnectionFactory.java index 6532c0f5aa82..9847141c4f58 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/APIConnectionFactory.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/APIConnectionFactory.java @@ -2,15 +2,14 @@ import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; +import com.appsmith.external.models.ApiKeyAuth; import com.appsmith.external.models.AuthenticationDTO; import com.appsmith.external.models.BasicAuth; +import com.appsmith.external.models.BearerTokenAuth; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.OAuth2; -import com.appsmith.external.models.ApiKeyAuth; -import com.appsmith.external.models.BearerTokenAuth; import reactor.core.publisher.Mono; - public class APIConnectionFactory { public static Mono<APIConnection> createConnection(DatasourceConfiguration datasourceConfiguration) { @@ -37,4 +36,4 @@ public static Mono<APIConnection> createConnection(DatasourceConfiguration datas return Mono.empty(); } } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/ApiKeyAuthentication.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/ApiKeyAuthentication.java index 7437459ecdb1..d52c6252f833 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/ApiKeyAuthentication.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/ApiKeyAuthentication.java @@ -30,14 +30,12 @@ public class ApiKeyAuthentication extends APIConnection { Type addTo; public static Mono<ApiKeyAuthentication> create(ApiKeyAuth apiKeyAuth) { - return Mono.just( - ApiKeyAuthentication.builder() - .label(apiKeyAuth.getLabel()) - .headerPrefix(apiKeyAuth.getHeaderPrefix()) - .value(apiKeyAuth.getValue()) - .addTo(apiKeyAuth.getAddTo()) - .build() - ); + return Mono.just(ApiKeyAuthentication.builder() + .label(apiKeyAuth.getLabel()) + .headerPrefix(apiKeyAuth.getHeaderPrefix()) + .value(apiKeyAuth.getValue()) + .addTo(apiKeyAuth.getAddTo()) + .build()); } @Override @@ -51,13 +49,10 @@ public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) requestBuilder.headers(header -> header.set(label, this.getHeaderValue())); break; default: - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_ERROR, - "Appsmith server has found an unsupported api key authentication type. Please reach " + - "out to Appsmith customer support to resolve this." - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_ERROR, + "Appsmith server has found an unsupported api key authentication type. Please reach " + + "out to Appsmith customer support to resolve this.")); } return Mono.justOrEmpty(requestBuilder.build()) @@ -79,8 +74,7 @@ private String getHeaderValue() { private URI appendApiKeyParamToUrl(URI oldUrl) { - return UriComponentsBuilder - .newInstance() + return UriComponentsBuilder.newInstance() .scheme(oldUrl.getScheme()) .host(oldUrl.getHost()) .port(oldUrl.getPort()) @@ -91,4 +85,4 @@ private URI appendApiKeyParamToUrl(URI oldUrl) { .build() .toUri(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/BasicAuthentication.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/BasicAuthentication.java index 5133c6bcab40..0c01960ab4d5 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/BasicAuthentication.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/BasicAuthentication.java @@ -22,7 +22,7 @@ public class BasicAuthentication extends APIConnection { private String encodedAuthorizationHeader; - final private static String HEADER_PREFIX = "Basic "; + private static final String HEADER_PREFIX = "Basic "; public static Mono<BasicAuthentication> create(BasicAuth basicAuth) { final BasicAuthentication basicAuthentication = new BasicAuthentication(); @@ -34,12 +34,11 @@ public static Mono<BasicAuthentication> create(BasicAuth basicAuth) { return Mono.just(basicAuthentication); } - @Override public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) { return Mono.justOrEmpty(ClientRequest.from(request) - .headers(headers -> headers.set(AUTHORIZATION_HEADER, getHeaderValue())) - .build()) + .headers(headers -> headers.set(AUTHORIZATION_HEADER, getHeaderValue())) + .build()) // Carry on to next exchange function .flatMap(next::exchange) // Default to next exchange function if something went wrong diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/BearerTokenAuthentication.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/BearerTokenAuthentication.java index 2493997e50e5..d22c2ef8c324 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/BearerTokenAuthentication.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/BearerTokenAuthentication.java @@ -24,18 +24,16 @@ public class BearerTokenAuthentication extends APIConnection { private String bearerToken; public static Mono<BearerTokenAuthentication> create(BearerTokenAuth bearerTokenAuth) { - return Mono.just( - BearerTokenAuthentication.builder() - .bearerToken(bearerTokenAuth.getBearerToken()) - .build() - ); + return Mono.just(BearerTokenAuthentication.builder() + .bearerToken(bearerTokenAuth.getBearerToken()) + .build()); } @Override public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) { return Mono.justOrEmpty(ClientRequest.from(request) - .headers(header -> header.set(AUTHORIZATION_HEADER, getHeaderValue())) - .build()) + .headers(header -> header.set(AUTHORIZATION_HEADER, getHeaderValue())) + .build()) // Carry on to next exchange function .flatMap(next::exchange) // Default to next exchange function if something went wrong @@ -45,4 +43,4 @@ public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) private String getHeaderValue() { return BEARER_HEADER_PREFIX + " " + this.bearerToken; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2AuthorizationCode.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2AuthorizationCode.java index 8edc5d04b1c5..71a63d1e0e6f 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2AuthorizationCode.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2AuthorizationCode.java @@ -81,11 +81,10 @@ public static Mono<OAuth2AuthorizationCode> create(DatasourceConfiguration datas OAuth2AuthorizationCode connection = new OAuth2AuthorizationCode(); if (!isAuthenticationResponseValid(oAuth2)) { - return connection.generateOAuth2Token(datasourceConfiguration) - .flatMap(token -> { - updateConnection(connection, token); - return Mono.just(connection); - }); + return connection.generateOAuth2Token(datasourceConfiguration).flatMap(token -> { + updateConnection(connection, token); + return Mono.just(connection); + }); } updateConnection(connection, oAuth2); @@ -111,8 +110,7 @@ private Mono<OAuth2> generateOAuth2Token(DatasourceConfiguration datasourceConfi // Webclient WebClient.Builder webClientBuilder = WebClientUtils.builder(securedHttpClient) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .exchangeStrategies(ExchangeStrategies - .builder() + .exchangeStrategies(ExchangeStrategies.builder() .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(MAX_IN_MEMORY_SIZE)) .build()); @@ -157,7 +155,8 @@ private Mono<OAuth2> generateOAuth2Token(DatasourceConfiguration datasourceConfi authenticationResponse.setExpiresAt(expiresAt); authenticationResponse.setIssuedAt(issuedAt); if (mappedResponse.containsKey(Authentication.REFRESH_TOKEN)) { - authenticationResponse.setRefreshToken(String.valueOf(mappedResponse.get(Authentication.REFRESH_TOKEN))); + authenticationResponse.setRefreshToken( + String.valueOf(mappedResponse.get(Authentication.REFRESH_TOKEN))); } authenticationResponse.setToken(String.valueOf(mappedResponse.get(Authentication.ACCESS_TOKEN))); oAuth2.setAuthenticationResponse(authenticationResponse); @@ -185,9 +184,10 @@ public Mono<ClientResponse> filter(ClientRequest clientRequest, ExchangeFunction private Mono<ClientRequest> addTokenToRequest(ClientRequest clientRequest) { // Check to see where the token needs to be added if (this.isHeader()) { - final String finalHeaderPrefix = this.getHeaderPrefix() != null && !this.getHeaderPrefix().isBlank() ? - this.getHeaderPrefix().trim() + " " - : ""; + final String finalHeaderPrefix = + this.getHeaderPrefix() != null && !this.getHeaderPrefix().isBlank() + ? this.getHeaderPrefix().trim() + " " + : ""; return Mono.justOrEmpty(ClientRequest.from(clientRequest) .headers(headers -> headers.set("Authorization", finalHeaderPrefix + this.getToken())) .build()); @@ -196,16 +196,16 @@ private Mono<ClientRequest> addTokenToRequest(ClientRequest clientRequest) { .queryParam(Authentication.ACCESS_TOKEN, this.getToken()) .build() .toUri(); - return Mono.justOrEmpty(ClientRequest.from(clientRequest) - .url(url) - .build()); + return Mono.justOrEmpty(ClientRequest.from(clientRequest).url(url).build()); } } private BodyInserters.FormInserter<String> getTokenBody(OAuth2 oAuth2) { - BodyInserters.FormInserter<String> body = BodyInserters - .fromFormData(Authentication.GRANT_TYPE, Authentication.REFRESH_TOKEN) - .with(Authentication.REFRESH_TOKEN, oAuth2.getAuthenticationResponse().getRefreshToken()); + BodyInserters.FormInserter<String> body = BodyInserters.fromFormData( + Authentication.GRANT_TYPE, Authentication.REFRESH_TOKEN) + .with( + Authentication.REFRESH_TOKEN, + oAuth2.getAuthenticationResponse().getRefreshToken()); if (BODY.equals(oAuth2.getRefreshTokenClientCredentialsLocation()) || oAuth2.getRefreshTokenClientCredentialsLocation() == null) { @@ -223,7 +223,8 @@ private BodyInserters.FormInserter<String> getTokenBody(OAuth2 oAuth2) { } // Optionally add scope, if applicable if (!CollectionUtils.isEmpty(oAuth2.getScope()) - && (Boolean.TRUE.equals(oAuth2.getSendScopeWithRefreshToken()) || oAuth2.getSendScopeWithRefreshToken() == null)) { + && (Boolean.TRUE.equals(oAuth2.getSendScopeWithRefreshToken()) + || oAuth2.getSendScopeWithRefreshToken() == null)) { body.with(Authentication.SCOPE, StringUtils.collectionToDelimitedString(oAuth2.getScope(), " ")); } return body; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2ClientCredentials.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2ClientCredentials.java index 1a94a62b09cf..f5be70bd4fb7 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2ClientCredentials.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2ClientCredentials.java @@ -78,7 +78,8 @@ public static Mono<OAuth2ClientCredentials> create(DatasourceConfiguration datas connection.setHeader(token.getIsTokenHeader()); connection.setHeaderPrefix(token.getHeaderPrefix()); connection.setExpiresAt(token.getAuthenticationResponse().getExpiresAt()); - connection.setTokenResponse(token.getAuthenticationResponse().getTokenResponse()); + connection.setTokenResponse( + token.getAuthenticationResponse().getTokenResponse()); return Mono.just(connection); }); } @@ -90,8 +91,7 @@ private Mono<OAuth2> generateOAuth2Token(DatasourceConfiguration datasourceConfi // Webclient final WebClient.Builder webClientBuilder = WebClientUtils.builder(securedHttpClient) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .exchangeStrategies(ExchangeStrategies - .builder() + .exchangeStrategies(ExchangeStrategies.builder() .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(MAX_IN_MEMORY_SIZE)) .build()); @@ -161,9 +161,10 @@ public Mono<ClientResponse> filter(ClientRequest clientRequest, ExchangeFunction private Mono<ClientRequest> addTokenToRequest(ClientRequest clientRequest) { // Check to see where the token needs to be added if (this.isHeader()) { - final String finalHeaderPrefix = this.getHeaderPrefix() != null && !this.getHeaderPrefix().isBlank() ? - this.getHeaderPrefix().trim() + " " - : ""; + final String finalHeaderPrefix = + this.getHeaderPrefix() != null && !this.getHeaderPrefix().isBlank() + ? this.getHeaderPrefix().trim() + " " + : ""; return Mono.justOrEmpty(ClientRequest.from(clientRequest) .headers(headers -> headers.set("Authorization", finalHeaderPrefix + this.getToken())) .build()); @@ -172,15 +173,13 @@ private Mono<ClientRequest> addTokenToRequest(ClientRequest clientRequest) { .queryParam(Authentication.ACCESS_TOKEN, this.getToken()) .build() .toUri(); - return Mono.justOrEmpty(ClientRequest.from(clientRequest) - .url(url) - .build()); + return Mono.justOrEmpty(ClientRequest.from(clientRequest).url(url).build()); } } private BodyInserters.FormInserter<String> clientCredentialsTokenBody(OAuth2 oAuth2) { - BodyInserters.FormInserter<String> body = BodyInserters - .fromFormData(Authentication.GRANT_TYPE, Authentication.CLIENT_CREDENTIALS); + BodyInserters.FormInserter<String> body = + BodyInserters.fromFormData(Authentication.GRANT_TYPE, Authentication.CLIENT_CREDENTIALS); if (Boolean.FALSE.equals(oAuth2.getIsAuthorizationHeader())) { body.with(Authentication.CLIENT_ID, oAuth2.getClientId()) @@ -199,11 +198,11 @@ private BodyInserters.FormInserter<String> clientCredentialsTokenBody(OAuth2 oAu if (!CollectionUtils.isEmpty(oAuth2.getScope())) { body.with(Authentication.SCOPE, StringUtils.collectionToDelimitedString(oAuth2.getScope(), " ")); } - //Custom Token Parameters + // Custom Token Parameters if (oAuth2.getCustomTokenParameters() != null) { - oAuth2.getCustomTokenParameters().forEach(params -> - body.with(params.getKey(), params.getValue().toString()) - ); + oAuth2.getCustomTokenParameters() + .forEach(params -> + body.with(params.getKey(), params.getValue().toString())); } return body; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/constants/ResponseDataType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/constants/ResponseDataType.java index ac6d913a1c33..f7609a79eb8d 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/constants/ResponseDataType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/constants/ResponseDataType.java @@ -1,5 +1,9 @@ package com.appsmith.external.helpers.restApiUtils.constants; public enum ResponseDataType { - BINARY, IMAGE, TEXT, JSON, UNDEFINED + BINARY, + IMAGE, + TEXT, + JSON, + UNDEFINED } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/BodyReceiver.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/BodyReceiver.java index 3d1d81d26e64..248362450431 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/BodyReceiver.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/BodyReceiver.java @@ -54,9 +54,7 @@ private void demandValueFrom(BodyInserter<?, ? extends ReactiveHttpOutputMessage (BodyInserter<Object, MinimalHttpOutputMessage>) bodyInserter; inserter.insert( - MinimalHttpOutputMessage.INSTANCE, - new SingleWriterContext(new WriteToConsumer<>(reference::set)) - ); + MinimalHttpOutputMessage.INSTANCE, new SingleWriterContext(new WriteToConsumer<>(reference::set))); } private Object receivedValue() { @@ -67,8 +65,7 @@ private Object receivedValue() { if (value == DUMMY) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_ERROR, - "Value was not received, check if your inserter worked properly"); + AppsmithPluginError.PLUGIN_ERROR, "Value was not received, check if your inserter worked properly"); } else { validatedValue = value; } @@ -102,8 +99,7 @@ public Mono<Void> write( ResolvableType elementType, MediaType mediaType, ReactiveHttpOutputMessage message, - Map<String, Object> hints - ) { + Map<String, Object> hints) { inputStream.subscribe(new OneValueConsumption<>(consumer)); return Mono.empty(); } @@ -113,8 +109,7 @@ static class MinimalHttpOutputMessage implements ClientHttpRequest { public static final MinimalHttpOutputMessage INSTANCE = new MinimalHttpOutputMessage(); - private MinimalHttpOutputMessage() { - } + private MinimalHttpOutputMessage() {} @Override public HttpHeaders getHeaders() { @@ -127,8 +122,7 @@ public DataBufferFactory bufferFactory() { } @Override - public void beforeCommit(Supplier<? extends Mono<Void>> action) { - } + public void beforeCommit(Supplier<? extends Mono<Void>> action) {} @Override public boolean isCommitted() { diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/BufferingFilter.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/BufferingFilter.java index fc5d614124d5..107b4ce42895 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/BufferingFilter.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/BufferingFilter.java @@ -19,15 +19,10 @@ public class BufferingFilter implements ExchangeFilterFunction { @Override - @NonNull - public Mono<ClientResponse> filter(@NonNull ClientRequest request, ExchangeFunction next) { - return next.exchange( - ClientRequest - .from(request) - .body((message, context) -> request - .body() - .insert(new BufferingRequestDecorator(message), context)) - .build()); + @NonNull public Mono<ClientResponse> filter(@NonNull ClientRequest request, ExchangeFunction next) { + return next.exchange(ClientRequest.from(request) + .body((message, context) -> request.body().insert(new BufferingRequestDecorator(message), context)) + .build()); } private static class BufferingRequestDecorator extends ClientHttpRequestDecorator { @@ -37,15 +32,12 @@ public BufferingRequestDecorator(ClientHttpRequest delegate) { } @Override - @NonNull - public Mono<Void> writeWith(@NonNull Publisher<? extends DataBuffer> body) { - return DataBufferUtils - .join(body) - .flatMap(dataBuffer -> { - int length = dataBuffer.readableByteCount(); - this.getDelegate().getHeaders().setContentLength(length); - return super.writeWith(body); - }); + @NonNull public Mono<Void> writeWith(@NonNull Publisher<? extends DataBuffer> body) { + return DataBufferUtils.join(body).flatMap(dataBuffer -> { + int length = dataBuffer.readableByteCount(); + this.getDelegate().getHeaders().setContentLength(length); + return super.writeWith(body); + }); } } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DataUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DataUtils.java index 790960de2f0e..0a18f815cffb 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DataUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DataUtils.java @@ -99,10 +99,7 @@ public Object parseJsonBody(Object body) { } } catch (JsonSyntaxException | ParseException e) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - body, - "Malformed JSON: " + e.getMessage() - ); + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, body, "Malformed JSON: " + e.getMessage()); } return body; } @@ -131,7 +128,6 @@ public String parseFormData(List<Property> bodyFormData, Boolean encodeParamsTog return key + "=" + value; }) .collect(Collectors.joining("&")); - } public BodyInserter<?, ?> parseMultipartFileData(List<Property> bodyFormData) { @@ -139,114 +135,107 @@ public String parseFormData(List<Property> bodyFormData, Boolean encodeParamsTog return BodyInserters.fromValue(new byte[0]); } - return (BodyInserter<?, ClientHttpRequest>) (outputMessage, context) -> - Mono.defer(() -> { - MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder(); + return (BodyInserter<?, ClientHttpRequest>) (outputMessage, context) -> Mono.defer(() -> { + MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder(); - for (Property property : bodyFormData) { - final String key = property.getKey(); + for (Property property : bodyFormData) { + final String key = property.getKey(); - if (property.getKey() == null) { - continue; - } + if (property.getKey() == null) { + continue; + } - // This condition is for the current scenario, while we wait for client changes to come in - // before the migration can be introduced - if (property.getType() == null) { - bodyBuilder.part(key, property.getValue()); - continue; - } + // This condition is for the current scenario, while we wait for client changes to come in + // before the migration can be introduced + if (property.getType() == null) { + bodyBuilder.part(key, property.getValue()); + continue; + } - final MultipartFormDataType multipartFormDataType = - MultipartFormDataType.valueOf(property.getType().toUpperCase(Locale.ROOT)); + final MultipartFormDataType multipartFormDataType = + MultipartFormDataType.valueOf(property.getType().toUpperCase(Locale.ROOT)); - switch (multipartFormDataType) { - case TEXT: - byte[] valueBytesArray = new byte[0]; - if (StringUtils.hasLength(String.valueOf(property.getValue()))) { - valueBytesArray = String.valueOf(property.getValue()).getBytes(StandardCharsets.ISO_8859_1); - } - bodyBuilder.part(key, valueBytesArray, MediaType.TEXT_PLAIN); - break; - case FILE: - try { - populateFileTypeBodyBuilder(bodyBuilder, property, outputMessage); - } catch (IOException e) { - e.printStackTrace(); - throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - "Unable to parse content. Expected to receive an array or object of multipart data" - ); - } - break; - case ARRAY: - if (property.getValue() instanceof String) { - final String value = (String) property.getValue(); - try { - final JsonNode jsonNode = objectMapper.readTree(value); - if (jsonNode.isArray()) { - for (JsonNode node : jsonNode) { - if (node.isTextual()) bodyBuilder.part(key, node.asText()); - else bodyBuilder.part(key, node); - } - } else { - bodyBuilder.part(key, value); - } - } catch (JsonProcessingException e) { - bodyBuilder.part(key, value); + switch (multipartFormDataType) { + case TEXT: + byte[] valueBytesArray = new byte[0]; + if (StringUtils.hasLength(String.valueOf(property.getValue()))) { + valueBytesArray = + String.valueOf(property.getValue()).getBytes(StandardCharsets.ISO_8859_1); + } + bodyBuilder.part(key, valueBytesArray, MediaType.TEXT_PLAIN); + break; + case FILE: + try { + populateFileTypeBodyBuilder(bodyBuilder, property, outputMessage); + } catch (IOException e) { + e.printStackTrace(); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + "Unable to parse content. Expected to receive an array or object of multipart data"); + } + break; + case ARRAY: + if (property.getValue() instanceof String) { + final String value = (String) property.getValue(); + try { + final JsonNode jsonNode = objectMapper.readTree(value); + if (jsonNode.isArray()) { + for (JsonNode node : jsonNode) { + if (node.isTextual()) bodyBuilder.part(key, node.asText()); + else bodyBuilder.part(key, node); } } else { - bodyBuilder.part(key, property.getValue()); + bodyBuilder.part(key, value); } - break; + } catch (JsonProcessingException e) { + bodyBuilder.part(key, value); + } + } else { + bodyBuilder.part(key, property.getValue()); } - } + break; + } + } - final BodyInserters.MultipartInserter multipartInserter = - BodyInserters - .fromMultipartData(bodyBuilder.build()); - return multipartInserter - .insert(outputMessage, context); - }); + final BodyInserters.MultipartInserter multipartInserter = + BodyInserters.fromMultipartData(bodyBuilder.build()); + return multipartInserter.insert(outputMessage, context); + }); } - private void populateFileTypeBodyBuilder(MultipartBodyBuilder bodyBuilder, Property property, ClientHttpRequest outputMessage) - throws IOException { + private void populateFileTypeBodyBuilder( + MultipartBodyBuilder bodyBuilder, Property property, ClientHttpRequest outputMessage) throws IOException { final String fileValue = (String) property.getValue(); final String key = property.getKey(); List<MultipartFormDataDTO> multipartFormDataDTOs = new ArrayList<>(); - if (fileValue.startsWith("{")) { // Check whether the JSON string is an object - final MultipartFormDataDTO multipartFormDataDTO = objectMapper.readValue( - fileValue, - MultipartFormDataDTO.class); + final MultipartFormDataDTO multipartFormDataDTO = + objectMapper.readValue(fileValue, MultipartFormDataDTO.class); multipartFormDataDTOs.add(multipartFormDataDTO); } else if (fileValue.startsWith("[")) { // Check whether the JSON string is an array - multipartFormDataDTOs = Arrays.asList( - objectMapper.readValue( - fileValue, - MultipartFormDataDTO[].class)); + multipartFormDataDTOs = Arrays.asList(objectMapper.readValue(fileValue, MultipartFormDataDTO[].class)); } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, "Unable to parse content. Expected to receive an array or object of multipart data"); } multipartFormDataDTOs.forEach(multipartFormDataDTO -> { final MultipartFormDataDTO finalMultipartFormDataDTO = multipartFormDataDTO; Flux<DataBuffer> data = DataBufferUtils.readInputStream( - () -> new ByteArrayInputStream(String.valueOf(finalMultipartFormDataDTO.getData()) - .getBytes(StandardCharsets.ISO_8859_1)), + () -> new ByteArrayInputStream( + String.valueOf(finalMultipartFormDataDTO.getData()).getBytes(StandardCharsets.ISO_8859_1)), outputMessage.bufferFactory(), 4096); - bodyBuilder.asyncPart(key, data, DataBuffer.class) + bodyBuilder + .asyncPart(key, data, DataBuffer.class) .filename(multipartFormDataDTO.getName()) .contentType(MediaType.valueOf(multipartFormDataDTO.getType())); }); - } /** @@ -280,17 +269,17 @@ private static Object objectFromJson(String jsonString) throws ParseException { } return parsedJson; - } - public Object getRequestBodyObject(ActionConfiguration actionConfiguration, String reqContentType, - boolean encodeParamsToggle, HttpMethod httpMethod) { + public Object getRequestBodyObject( + ActionConfiguration actionConfiguration, + String reqContentType, + boolean encodeParamsToggle, + HttpMethod httpMethod) { // We will read the request body for all HTTP calls where the apiContentType is NOT "none". // This is irrespective of the content-type header or the HTTP method - String apiContentTypeStr = (String) PluginUtils.getValueSafelyFromFormData( - actionConfiguration.getFormData(), - FIELD_API_CONTENT_TYPE - ); + String apiContentTypeStr = (String) + PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), FIELD_API_CONTENT_TYPE); ApiContentType apiContentType = ApiContentType.getValueFromString(apiContentTypeStr); if (httpMethod.equals(HttpMethod.GET) && (apiContentType == null || apiContentType == ApiContentType.NONE)) { @@ -328,4 +317,4 @@ public Object getRequestBodyObject(ActionConfiguration actionConfiguration, Stri return requestBodyObj; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DatasourceUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DatasourceUtils.java index cd10eb48c75a..5350228b522e 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DatasourceUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DatasourceUtils.java @@ -15,14 +15,13 @@ public class DatasourceUtils { protected static HeaderUtils headerUtils = new HeaderUtils(); - public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration, - boolean isEmbeddedDatasource) { + public Set<String> validateDatasource( + DatasourceConfiguration datasourceConfiguration, boolean isEmbeddedDatasource) { /** * We don't verify whether the URL is in valid format because it can contain mustache template keys, and so * look invalid at this point, but become valid after mustache rendering. So we just check if URL field has * a non-empty value. */ - Set<String> invalids = new HashSet<>(); if (StringUtils.isEmpty(datasourceConfiguration.getUrl())) { @@ -34,11 +33,9 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur * ref: https://theappsmith.slack.com/archives/C040LHZN03V/p1686478370473659?thread_ts=1686300736 * .679729&cid=C040LHZN03V */ - } - else { + } else { invalids.add("Missing URL."); } - } final String contentTypeError = headerUtils.verifyContentType(datasourceConfiguration.getHeaders()); @@ -59,8 +56,8 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur } if (isSendSessionEnabled && (StringUtils.isEmpty(secretKey) || secretKey.length() < 32)) { - invalids.add("Secret key is required when sending session is switched on" + - ", and should be at least 32 characters long."); + invalids.add("Secret key is required when sending session is switched on" + + ", and should be at least 32 characters long."); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DatasourceValidator.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DatasourceValidator.java index f994e4554851..4393c97cdbeb 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DatasourceValidator.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DatasourceValidator.java @@ -11,9 +11,7 @@ public class DatasourceValidator { - private static final String URL_REGEX = - "^https?://" + - "(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+$"; + private static final String URL_REGEX = "^https?://" + "(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+$"; private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/HeaderUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/HeaderUtils.java index 3b14392acc99..13a35c9fb19c 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/HeaderUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/HeaderUtils.java @@ -40,7 +40,8 @@ public void removeEmptyHeaders(ActionConfiguration actionConfiguration) { * We only check for key being empty since an empty value is still a valid header. * Ref: https://stackoverflow.com/questions/12130910/how-to-interpret-empty-http-accept-header */ - if (actionConfiguration.getHeaders() != null && !actionConfiguration.getHeaders().isEmpty()) { + if (actionConfiguration.getHeaders() != null + && !actionConfiguration.getHeaders().isEmpty()) { List<Property> headerList = actionConfiguration.getHeaders().stream() .filter(header -> !org.springframework.util.StringUtils.isEmpty(header.getKey())) .collect(Collectors.toList()); @@ -48,8 +49,8 @@ public void removeEmptyHeaders(ActionConfiguration actionConfiguration) { } } - public String getRequestContentType(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + public String getRequestContentType( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { String reqContentType = ""; /* Get request content type from datasource config */ @@ -120,9 +121,8 @@ public String getSignatureKey(DatasourceConfiguration datasourceConfiguration) t if (StringUtils.isEmpty(secretKey) || secretKey.length() < 32) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - "Secret key is required when sending session details is switched on," + - " and should be at least 32 characters in length." - ); + "Secret key is required when sending session details is switched on," + + " and should be at least 32 characters in length."); } return secretKey; } @@ -131,12 +131,12 @@ public String getSignatureKey(DatasourceConfiguration datasourceConfiguration) t return null; } - public void setHeaderFromAutoGeneratedHeaders(ActionConfiguration actionConfiguration){ - if(isEmpty(actionConfiguration.getAutoGeneratedHeaders())) { + public void setHeaderFromAutoGeneratedHeaders(ActionConfiguration actionConfiguration) { + if (isEmpty(actionConfiguration.getAutoGeneratedHeaders())) { return; } - if(isEmpty(actionConfiguration.getHeaders())) { + if (isEmpty(actionConfiguration.getHeaders())) { actionConfiguration.setHeaders(actionConfiguration.getAutoGeneratedHeaders()); return; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/HintMessageUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/HintMessageUtils.java index 95d9ec2e9321..f61cc77d50a9 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/HintMessageUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/HintMessageUtils.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.OAuth2; import com.appsmith.external.models.Property; -import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.commons.lang.StringUtils; import org.springframework.util.CollectionUtils; @@ -28,19 +27,19 @@ import static com.appsmith.external.constants.Authentication.BEARER_TOKEN; import static com.appsmith.external.constants.Authentication.OAUTH2; import static com.appsmith.external.helpers.PluginUtils.getHintMessageForLocalhostUrl; -import static com.appsmith.external.models.ApiKeyAuth.Type.HEADER; -import static com.appsmith.external.models.ApiKeyAuth.Type.QUERY_PARAMS; import static com.appsmith.external.helpers.restApiUtils.helpers.HintMessageUtils.DUPLICATE_ATTRIBUTE_LOCATION.ACTION_CONFIG_ONLY; import static com.appsmith.external.helpers.restApiUtils.helpers.HintMessageUtils.DUPLICATE_ATTRIBUTE_LOCATION.DATASOURCE_AND_ACTION_CONFIG; import static com.appsmith.external.helpers.restApiUtils.helpers.HintMessageUtils.DUPLICATE_ATTRIBUTE_LOCATION.DATASOURCE_CONFIG_ONLY; +import static com.appsmith.external.models.ApiKeyAuth.Type.HEADER; +import static com.appsmith.external.models.ApiKeyAuth.Type.QUERY_PARAMS; @NoArgsConstructor public class HintMessageUtils { public enum DUPLICATE_ATTRIBUTE_LOCATION { - ACTION_CONFIG_ONLY, // Duplicates found in action configuration only - DATASOURCE_CONFIG_ONLY, // Duplicates found in datasource configuration only - DATASOURCE_AND_ACTION_CONFIG // Duplicates with instance in both datasource and action config + ACTION_CONFIG_ONLY, // Duplicates found in action configuration only + DATASOURCE_CONFIG_ONLY, // Duplicates found in datasource configuration only + DATASOURCE_AND_ACTION_CONFIG // Duplicates with instance in both datasource and action config } protected enum ATTRIBUTE { @@ -48,24 +47,24 @@ protected enum ATTRIBUTE { PARAM } - protected static String HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_DATASOURCE_CONFIG = "API queries linked to this " + - "datasource may not run as expected because this datasource has duplicate definition(s) for {0}(s): {1}." + - " Please remove the duplicate definition(s) to resolve this warning. Please note that some of the " + - "authentication mechanisms also implicitly define a {0}."; + protected static String HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_DATASOURCE_CONFIG = "API queries linked to this " + + "datasource may not run as expected because this datasource has duplicate definition(s) for {0}(s): {1}." + + " Please remove the duplicate definition(s) to resolve this warning. Please note that some of the " + + "authentication mechanisms also implicitly define a {0}."; - protected static String HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_DEFINED_IN_DATASOURCE_CONFIG = "Your API " + - "query may not run as expected because its datasource has duplicate definition(s) for {0}(s): {1}. Please" + - " remove the duplicate definition(s) from the datasource to resolve this warning."; + protected static String HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_DEFINED_IN_DATASOURCE_CONFIG = "Your API " + + "query may not run as expected because its datasource has duplicate definition(s) for {0}(s): {1}. Please" + + " remove the duplicate definition(s) from the datasource to resolve this warning."; - protected static String HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_CONFIG = "Your API query may not run as " + - "expected because it has duplicate definition(s) for {0}(s): {1}. Please remove the duplicate definition" + - "(s) from the ''{2}'' tab to resolve this warning."; + protected static String HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_CONFIG = "Your API query may not run as " + + "expected because it has duplicate definition(s) for {0}(s): {1}. Please remove the duplicate definition" + + "(s) from the ''{2}'' tab to resolve this warning."; protected static String HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_WITH_INSTANCE_ACROSS_ACTION_AND_DATASOURCE_CONFIG = - "Your API query may not run as expected because it has duplicate definition(s) for {0}(s): {1}. Please " + - "remove the duplicate definition(s) from the ''{2}'' section of either the API query or the " + - "datasource. Please note that some of the authentication mechanisms also implicitly define a " + - "{0}."; + "Your API query may not run as expected because it has duplicate definition(s) for {0}(s): {1}. Please " + + "remove the duplicate definition(s) from the ''{2}'' section of either the API query or the " + + "datasource. Please note that some of the authentication mechanisms also implicitly define a " + + "{0}."; public Set<String> getDatasourceHintMessages(DatasourceConfiguration datasourceConfiguration) { Set<String> datasourceHintMessages = new HashSet<>(); @@ -77,27 +76,33 @@ public Set<String> getDatasourceHintMessages(DatasourceConfiguration datasourceC * Get datasource specific hint message for duplicate headers. ActionConfiguration parameter is passed as * `null` so that the hint message that gets generated is only relevant for the datasource. */ - Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateHeadersInDatasource = getAllDuplicateHeaders(null, datasourceConfiguration); + Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateHeadersInDatasource = + getAllDuplicateHeaders(null, datasourceConfiguration); if (!duplicateHeadersInDatasource.get(DATASOURCE_CONFIG_ONLY).isEmpty()) { - datasourceHintMessages.add(MessageFormat.format(HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_DATASOURCE_CONFIG, - ATTRIBUTE.HEADER.name().toLowerCase(), duplicateHeadersInDatasource.get(DATASOURCE_CONFIG_ONLY))); + datasourceHintMessages.add(MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_DATASOURCE_CONFIG, + ATTRIBUTE.HEADER.name().toLowerCase(), + duplicateHeadersInDatasource.get(DATASOURCE_CONFIG_ONLY))); } /** * Get datasource specific hint message for duplicate query params. ActionConfiguration parameter is passed * as `null` so that the hint message that gets generated is only relevant for the datasource. */ - Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateParamsInDatasource = getAllDuplicateParams(null, datasourceConfiguration); + Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateParamsInDatasource = + getAllDuplicateParams(null, datasourceConfiguration); if (!duplicateParamsInDatasource.get(DATASOURCE_CONFIG_ONLY).isEmpty()) { - datasourceHintMessages.add(MessageFormat.format(HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_DATASOURCE_CONFIG, - ATTRIBUTE.PARAM.name().toLowerCase(), duplicateParamsInDatasource.get(DATASOURCE_CONFIG_ONLY))); + datasourceHintMessages.add(MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_DATASOURCE_CONFIG, + ATTRIBUTE.PARAM.name().toLowerCase(), + duplicateParamsInDatasource.get(DATASOURCE_CONFIG_ONLY))); } return datasourceHintMessages; } - public Set<String> getActionHintMessages(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + public Set<String> getActionHintMessages( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { Set<String> actionHintMessages = new HashSet<>(); /** @@ -113,37 +118,29 @@ public Set<String> getActionHintMessages(ActionConfiguration actionConfiguration * configuration apart from the action configuration since an API inherits all the headers defined in its * datasource. */ - Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateHeadersMap = getAllDuplicateHeaders(actionConfiguration, datasourceConfiguration); + Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateHeadersMap = + getAllDuplicateHeaders(actionConfiguration, datasourceConfiguration); if (!duplicateHeadersMap.get(DATASOURCE_CONFIG_ONLY).isEmpty()) { - actionHintMessages.add( - MessageFormat.format( - HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_DEFINED_IN_DATASOURCE_CONFIG, - ATTRIBUTE.HEADER.name().toLowerCase(), - duplicateHeadersMap.get(DATASOURCE_CONFIG_ONLY) - ) - ); + actionHintMessages.add(MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_DEFINED_IN_DATASOURCE_CONFIG, + ATTRIBUTE.HEADER.name().toLowerCase(), + duplicateHeadersMap.get(DATASOURCE_CONFIG_ONLY))); } if (!duplicateHeadersMap.get(ACTION_CONFIG_ONLY).isEmpty()) { - actionHintMessages.add( - MessageFormat.format( - HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_CONFIG, - ATTRIBUTE.HEADER.name().toLowerCase(), - duplicateHeadersMap.get(ACTION_CONFIG_ONLY), - "Headers" - ) - ); + actionHintMessages.add(MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_CONFIG, + ATTRIBUTE.HEADER.name().toLowerCase(), + duplicateHeadersMap.get(ACTION_CONFIG_ONLY), + "Headers")); } if (!duplicateHeadersMap.get(DATASOURCE_AND_ACTION_CONFIG).isEmpty()) { - actionHintMessages.add( - MessageFormat.format( - HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_WITH_INSTANCE_ACROSS_ACTION_AND_DATASOURCE_CONFIG, - ATTRIBUTE.HEADER.name().toLowerCase(), - duplicateHeadersMap.get(DATASOURCE_AND_ACTION_CONFIG), - "Headers" - ) - ); + actionHintMessages.add(MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_WITH_INSTANCE_ACROSS_ACTION_AND_DATASOURCE_CONFIG, + ATTRIBUTE.HEADER.name().toLowerCase(), + duplicateHeadersMap.get(DATASOURCE_AND_ACTION_CONFIG), + "Headers")); } /** @@ -151,44 +148,36 @@ public Set<String> getActionHintMessages(ActionConfiguration actionConfiguration * configuration apart from the action configuration since an API inherits all the params defined in its * datasource. */ - Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateParamsMap = getAllDuplicateParams(actionConfiguration, datasourceConfiguration); + Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateParamsMap = + getAllDuplicateParams(actionConfiguration, datasourceConfiguration); if (!duplicateParamsMap.get(DATASOURCE_CONFIG_ONLY).isEmpty()) { - actionHintMessages.add( - MessageFormat.format( - HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_DEFINED_IN_DATASOURCE_CONFIG, - ATTRIBUTE.PARAM.name().toLowerCase(), - duplicateParamsMap.get(DATASOURCE_CONFIG_ONLY) - ) - ); + actionHintMessages.add(MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_DEFINED_IN_DATASOURCE_CONFIG, + ATTRIBUTE.PARAM.name().toLowerCase(), + duplicateParamsMap.get(DATASOURCE_CONFIG_ONLY))); } if (!duplicateParamsMap.get(ACTION_CONFIG_ONLY).isEmpty()) { - actionHintMessages.add( - MessageFormat.format( - HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_CONFIG, - ATTRIBUTE.PARAM.name().toLowerCase(), - duplicateParamsMap.get(ACTION_CONFIG_ONLY), - "Params" - ) - ); + actionHintMessages.add(MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_IN_ACTION_CONFIG, + ATTRIBUTE.PARAM.name().toLowerCase(), + duplicateParamsMap.get(ACTION_CONFIG_ONLY), + "Params")); } if (!duplicateParamsMap.get(DATASOURCE_AND_ACTION_CONFIG).isEmpty()) { - actionHintMessages.add( - MessageFormat.format( - HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_WITH_INSTANCE_ACROSS_ACTION_AND_DATASOURCE_CONFIG, - ATTRIBUTE.PARAM.name().toLowerCase(), - duplicateParamsMap.get(DATASOURCE_AND_ACTION_CONFIG), - "Params" - ) - ); + actionHintMessages.add(MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_ATTRIBUTE_WITH_INSTANCE_ACROSS_ACTION_AND_DATASOURCE_CONFIG, + ATTRIBUTE.PARAM.name().toLowerCase(), + duplicateParamsMap.get(DATASOURCE_AND_ACTION_CONFIG), + "Params")); } return actionHintMessages; } - public Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> getAllDuplicateHeaders(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + public Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> getAllDuplicateHeaders( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateMap = new HashMap<>(); Set duplicatesInActionConfigOnly = findDuplicates(getActionHeaders(actionConfiguration)); @@ -197,12 +186,12 @@ public Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> getAllDuplicateHeaders(Act Set duplicatesInDsConfigOnly = findDuplicates(getDatasourceHeaders(datasourceConfiguration)); duplicateMap.put(DATASOURCE_CONFIG_ONLY, duplicatesInDsConfigOnly); - Set duplicatesAcrossActionAndDsConfig = findDuplicates(getAllHeaders(actionConfiguration, - datasourceConfiguration)); + Set duplicatesAcrossActionAndDsConfig = + findDuplicates(getAllHeaders(actionConfiguration, datasourceConfiguration)); duplicatesAcrossActionAndDsConfig.removeAll(duplicatesInActionConfigOnly); duplicatesAcrossActionAndDsConfig.removeAll(duplicatesInDsConfigOnly); duplicateMap.put(DATASOURCE_AND_ACTION_CONFIG, duplicatesAcrossActionAndDsConfig); - + return duplicateMap; } @@ -211,20 +200,19 @@ protected Set findDuplicates(List allItems) { Set duplicateItems = new HashSet<String>(); Set uniqueItems = new HashSet<String>(); - allItems.stream() - .forEach(item -> { - if (uniqueItems.contains(item)) { - duplicateItems.add(item); - } + allItems.stream().forEach(item -> { + if (uniqueItems.contains(item)) { + duplicateItems.add(item); + } - uniqueItems.add(item); - }); + uniqueItems.add(item); + }); return duplicateItems; } - protected List getAllHeaders(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + protected List getAllHeaders( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { List allHeaders = new ArrayList<String>(); // Get all headers defined in API query editor page. @@ -252,7 +240,7 @@ protected List getDatasourceHeaders(DatasourceConfiguration datasourceConfigurat if (datasourceConfiguration != null && !CollectionUtils.isEmpty(datasourceConfiguration.getHeaders())) { headers.addAll(getKeyList(datasourceConfiguration.getHeaders())); } - + // Get authentication related headers. headers.addAll(getAuthenticationHeaders(datasourceConfiguration)); @@ -269,28 +257,29 @@ protected Set<String> getAuthenticationHeaders(DatasourceConfiguration datasourc Set<String> headers = new HashSet<>(); // Basic auth or bearer token auth adds a header `Authorization` - if (BASIC.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) || - BEARER_TOKEN.equals(datasourceConfiguration.getAuthentication().getAuthenticationType())) { + if (BASIC.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) + || BEARER_TOKEN.equals( + datasourceConfiguration.getAuthentication().getAuthenticationType())) { headers.add(AUTHORIZATION_HEADER); } // Api key based auth where key is supplied via header - if (API_KEY.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) && - HEADER.equals(((ApiKeyAuth) datasourceConfiguration.getAuthentication()).getAddTo())) { + if (API_KEY.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) + && HEADER.equals(((ApiKeyAuth) datasourceConfiguration.getAuthentication()).getAddTo())) { headers.add(((ApiKeyAuth) datasourceConfiguration.getAuthentication()).getLabel()); } // OAuth2 authentication with token sent via header. - if (OAUTH2.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) && - ((OAuth2) datasourceConfiguration.getAuthentication()).getIsTokenHeader()) { + if (OAUTH2.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) + && ((OAuth2) datasourceConfiguration.getAuthentication()).getIsTokenHeader()) { headers.add(AUTHORIZATION_HEADER); } return headers; } - public Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> getAllDuplicateParams(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + public Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> getAllDuplicateParams( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateMap = new HashMap<>(); Set duplicatesInActionConfigOnly = findDuplicates(getActionParams(actionConfiguration)); @@ -299,8 +288,8 @@ public Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> getAllDuplicateParams(Acti Set duplicatesInDsConfigOnly = findDuplicates(getDatasourceQueryParams(datasourceConfiguration)); duplicateMap.put(DATASOURCE_CONFIG_ONLY, duplicatesInDsConfigOnly); - Set duplicatesAcrossActionAndDsConfig = findDuplicates(getAllParams(actionConfiguration, - datasourceConfiguration)); + Set duplicatesAcrossActionAndDsConfig = + findDuplicates(getAllParams(actionConfiguration, datasourceConfiguration)); duplicatesAcrossActionAndDsConfig.removeAll(duplicatesInActionConfigOnly); duplicatesAcrossActionAndDsConfig.removeAll(duplicatesInDsConfigOnly); duplicateMap.put(DATASOURCE_AND_ACTION_CONFIG, duplicatesAcrossActionAndDsConfig); @@ -315,8 +304,8 @@ protected List getKeyList(List<Property> propertyList) { .collect(Collectors.toList()); } - protected List getAllParams(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + protected List getAllParams( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { List allParams = new ArrayList<String>(); // Get all params defined in API query editor page. @@ -341,8 +330,7 @@ protected List getActionParams(ActionConfiguration actionConfiguration) { protected List getDatasourceQueryParams(DatasourceConfiguration datasourceConfiguration) { List<String> params = new ArrayList<>(); - if (datasourceConfiguration != null && - !CollectionUtils.isEmpty(datasourceConfiguration.getQueryParameters())) { + if (datasourceConfiguration != null && !CollectionUtils.isEmpty(datasourceConfiguration.getQueryParameters())) { params.addAll(getKeyList(datasourceConfiguration.getQueryParameters())); } @@ -361,23 +349,24 @@ protected Set getAuthenticationParams(DatasourceConfiguration datasourceConfigur Set<String> params = new HashSet<>(); // Api key based auth where key is supplied via query param - if (API_KEY.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) && - QUERY_PARAMS.equals(((ApiKeyAuth) datasourceConfiguration.getAuthentication()).getAddTo())) { + if (API_KEY.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) + && QUERY_PARAMS.equals(((ApiKeyAuth) datasourceConfiguration.getAuthentication()).getAddTo())) { params.add(((ApiKeyAuth) datasourceConfiguration.getAuthentication()).getLabel()); } // OAuth2 authentication with token sent via query params. - if (OAUTH2.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) && - !((OAuth2) datasourceConfiguration.getAuthentication()).getIsTokenHeader()) { + if (OAUTH2.equals(datasourceConfiguration.getAuthentication().getAuthenticationType()) + && !((OAuth2) datasourceConfiguration.getAuthentication()).getIsTokenHeader()) { params.add(ACCESS_TOKEN); } return params; } - public Mono<Tuple2<Set<String>, Set<String>>> getHintMessages(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { - return Mono.zip(Mono.just(getDatasourceHintMessages(datasourceConfiguration)), + public Mono<Tuple2<Set<String>, Set<String>>> getHintMessages( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { + return Mono.zip( + Mono.just(getDatasourceHintMessages(datasourceConfiguration)), Mono.just(getActionHintMessages(actionConfiguration, datasourceConfiguration))); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/InitUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/InitUtils.java index d15fd1c68e60..932487650a61 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/InitUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/InitUtils.java @@ -9,8 +9,8 @@ @NoArgsConstructor public class InitUtils { - public String initializeRequestUrl(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration ) { + public String initializeRequestUrl( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { String path = (actionConfiguration.getPath() == null) ? "" : actionConfiguration.getPath(); return datasourceConfiguration.getUrl().trim() + path.trim(); } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RequestCaptureFilter.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RequestCaptureFilter.java index 979d7b678f5d..db7d0bb3b8f1 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RequestCaptureFilter.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RequestCaptureFilter.java @@ -45,13 +45,13 @@ public RequestCaptureFilter(ObjectMapper objectMapper) { } @Override - @NonNull - public Mono<ClientResponse> filter(@NonNull ClientRequest request, ExchangeFunction next) { + @NonNull public Mono<ClientResponse> filter(@NonNull ClientRequest request, ExchangeFunction next) { this.request = request; return next.exchange(request); } - public ActionExecutionRequest populateRequestFields(ActionExecutionRequest existing, boolean isBodySentWithApiRequest) { + public ActionExecutionRequest populateRequestFields( + ActionExecutionRequest existing, boolean isBodySentWithApiRequest) { final ActionExecutionRequest actionExecutionRequest = new ActionExecutionRequest(); if (request == null) { @@ -62,7 +62,8 @@ public ActionExecutionRequest populateRequestFields(ActionExecutionRequest exist actionExecutionRequest.setUrl(request.url().toString()); actionExecutionRequest.setHttpMethod(request.method()); - MultiValueMap<String, String> headers = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); + MultiValueMap<String, String> headers = + CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); AtomicBoolean isMultipart = new AtomicBoolean(false); request.headers().forEach((header, value) -> { if (HttpHeaders.AUTHORIZATION.equalsIgnoreCase(header) || "api_key".equalsIgnoreCase(header)) { @@ -70,7 +71,8 @@ public ActionExecutionRequest populateRequestFields(ActionExecutionRequest exist } else { headers.addAll(header, value); } - if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(header) && MULTIPART_FORM_DATA_VALUE.equalsIgnoreCase(value.get(0))) { + if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(header) + && MULTIPART_FORM_DATA_VALUE.equalsIgnoreCase(value.get(0))) { isMultipart.set(true); } }); @@ -92,10 +94,11 @@ public ActionExecutionRequest populateRequestFields(ActionExecutionRequest exist return actionExecutionRequest; } - public static ActionExecutionRequest populateRequestFields(ActionConfiguration actionConfiguration, - URI uri, - List<Map.Entry<String, String>> insertedParams, - ObjectMapper objectMapper) { + public static ActionExecutionRequest populateRequestFields( + ActionConfiguration actionConfiguration, + URI uri, + List<Map.Entry<String, String>> insertedParams, + ObjectMapper objectMapper) { ActionExecutionRequest actionExecutionRequest = new ActionExecutionRequest(); @@ -108,15 +111,15 @@ public static ActionExecutionRequest populateRequestFields(ActionConfiguration a AtomicReference<String> reqContentType = new AtomicReference<>(); if (actionConfiguration.getHeaders() != null) { - MultiValueMap<String, String> reqMultiMap = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); - - actionConfiguration.getHeaders() - .forEach(header -> { - if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(header.getKey())) { - reqContentType.set((String) header.getValue()); - } - reqMultiMap.put(header.getKey(), Arrays.asList((String) header.getValue())); - }); + MultiValueMap<String, String> reqMultiMap = + CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); + + actionConfiguration.getHeaders().forEach(header -> { + if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(header.getKey())) { + reqContentType.set((String) header.getValue()); + } + reqMultiMap.put(header.getKey(), Arrays.asList((String) header.getValue())); + }); actionExecutionRequest.setHeaders(objectMapper.valueToTree(reqMultiMap)); } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RestAPIActivateUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RestAPIActivateUtils.java index 50ba183e9139..a4c5557dff9a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RestAPIActivateUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/RestAPIActivateUtils.java @@ -54,30 +54,33 @@ public class RestAPIActivateUtils { public static final String RESPONSE_DATA_TYPE = "X-APPSMITH-DATATYPE"; public static final int MAX_REDIRECTS = 5; public static final Set BINARY_DATA_TYPES = Set.of( - "application/zip", - "application/octet-stream", - "application/pdf", - "application/pkcs8", - "application/x-binary" - ); + "application/zip", + "application/octet-stream", + "application/pdf", + "application/pkcs8", + "application/x-binary"); public static HeaderUtils headerUtils = new HeaderUtils(); - public Mono<ActionExecutionResult> triggerApiCall(WebClient client, HttpMethod httpMethod, URI uri, - Object requestBody, - ActionExecutionRequest actionExecutionRequest, - ObjectMapper objectMapper, Set<String> hintMessages, - ActionExecutionResult errorResult, - RequestCaptureFilter requestCaptureFilter) { + public Mono<ActionExecutionResult> triggerApiCall( + WebClient client, + HttpMethod httpMethod, + URI uri, + Object requestBody, + ActionExecutionRequest actionExecutionRequest, + ObjectMapper objectMapper, + Set<String> hintMessages, + ActionExecutionResult errorResult, + RequestCaptureFilter requestCaptureFilter) { return httpCall(client, httpMethod, uri, requestBody, 0) .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) .map(stringResponseEntity -> { HttpHeaders headers = stringResponseEntity.getHeaders(); - /* - Find the media type of the response to parse the body as required. In case the content-type - header is not present in the response then set it to our default i.e. "text/plain" although - the RFC 7231 standard suggests assuming "application/octet-stream" content-type in case - it's not present in response header. - */ + /* + Find the media type of the response to parse the body as required. In case the content-type + header is not present in the response then set it to our default i.e. "text/plain" although + the RFC 7231 standard suggests assuming "application/octet-stream" content-type in case + it's not present in response header. + */ MediaType contentType = headers.getContentType(); if (contentType == null) { contentType = MediaType.TEXT_PLAIN; @@ -89,7 +92,8 @@ public Mono<ActionExecutionResult> triggerApiCall(WebClient client, HttpMethod h // Set the request fields boolean isBodySentWithApiRequest = requestBody == null ? false : true; - result.setRequest(requestCaptureFilter.populateRequestFields(actionExecutionRequest, isBodySentWithApiRequest)); + result.setRequest(requestCaptureFilter.populateRequestFields( + actionExecutionRequest, isBodySentWithApiRequest)); result.setStatusCode(statusCode.toString()); result.setIsExecutionSuccess(statusCode.is2xxSuccessful()); @@ -106,13 +110,8 @@ public Mono<ActionExecutionResult> triggerApiCall(WebClient client, HttpMethod h try { result.setHeaders(objectMapper.readTree(headerInJsonString)); } catch (IOException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - headerInJsonString, - e.getMessage() - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, headerInJsonString, e.getMessage())); } if (body != null) { @@ -134,15 +133,15 @@ public Mono<ActionExecutionResult> triggerApiCall(WebClient client, HttpMethod h result.setBody(bodyString.trim()); // Warn user that the API response is not a valid JSON. - hintMessages.add("The response returned by this API is not a valid JSON. Please " + - "be careful when using the API response anywhere a valid JSON is required" + - ". You may resolve this issue either by modifying the 'Content-Type' " + - "Header to indicate a non-JSON response or by modifying the API response " + - "to return a valid JSON."); + hintMessages.add("The response returned by this API is not a valid JSON. Please " + + "be careful when using the API response anywhere a valid JSON is required" + + ". You may resolve this issue either by modifying the 'Content-Type' " + + "Header to indicate a non-JSON response or by modifying the API response " + + "to return a valid JSON."); } - } else if (MediaType.IMAGE_GIF.equals(contentType) || - MediaType.IMAGE_JPEG.equals(contentType) || - MediaType.IMAGE_PNG.equals(contentType)) { + } else if (MediaType.IMAGE_GIF.equals(contentType) + || MediaType.IMAGE_JPEG.equals(contentType) + || MediaType.IMAGE_PNG.equals(contentType)) { String encode = Base64.encode(body); result.setBody(encode); responseDataType = ResponseDataType.IMAGE; @@ -161,25 +160,20 @@ public Mono<ActionExecutionResult> triggerApiCall(WebClient client, HttpMethod h // Now add a new header which specifies the data type of the response as per Appsmith JsonNode headersJsonNode = result.getHeaders(); ObjectNode headersObjectNode = (ObjectNode) headersJsonNode; - headersObjectNode.putArray(RESPONSE_DATA_TYPE) - .add(String.valueOf(responseDataType)); + headersObjectNode.putArray(RESPONSE_DATA_TYPE).add(String.valueOf(responseDataType)); result.setHeaders(headersObjectNode); - } result.setMessages(hintMessages); return result; }); - } - protected Mono<ClientResponse> httpCall(WebClient webClient, HttpMethod httpMethod, URI uri, Object requestBody, - int iteration) { + protected Mono<ClientResponse> httpCall( + WebClient webClient, HttpMethod httpMethod, URI uri, Object requestBody, int iteration) { if (iteration == MAX_REDIRECTS) { return Mono.error(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_ERROR, - "Exceeded the HTTP redirect limits of " + MAX_REDIRECTS - )); + AppsmithPluginError.PLUGIN_ERROR, "Exceeded the HTTP redirect limits of " + MAX_REDIRECTS)); } /** @@ -197,7 +191,8 @@ protected Mono<ClientResponse> httpCall(WebClient webClient, HttpMethod httpMeth .exchange() .flatMap(response -> { if (response.statusCode().is3xxRedirection()) { - String redirectUrl = response.headers().header("Location").get(0); + String redirectUrl = + response.headers().header("Location").get(0); /** * TODO * In case the redirected URL is not absolute (complete), create the new URL using the relative path @@ -218,10 +213,14 @@ protected Mono<ClientResponse> httpCall(WebClient webClient, HttpMethod httpMeth }); } - public WebClient getWebClient(WebClient.Builder webClientBuilder, APIConnection apiConnection, - String reqContentType, ExchangeStrategies EXCHANGE_STRATEGIES, - RequestCaptureFilter requestCaptureFilter) { - // Right before building the webclient object, we populate it with whatever mutation the APIConnection object demands + public WebClient getWebClient( + WebClient.Builder webClientBuilder, + APIConnection apiConnection, + String reqContentType, + ExchangeStrategies EXCHANGE_STRATEGIES, + RequestCaptureFilter requestCaptureFilter) { + // Right before building the webclient object, we populate it with whatever mutation the APIConnection object + // demands if (apiConnection != null) { webClientBuilder.filter(apiConnection); } @@ -235,8 +234,8 @@ public WebClient getWebClient(WebClient.Builder webClientBuilder, APIConnection return webClientBuilder.exchangeStrategies(EXCHANGE_STRATEGIES).build(); } - public WebClient.Builder getWebClientBuilder(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + public WebClient.Builder getWebClientBuilder( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { HttpClient httpClient = getHttpClient(datasourceConfiguration); WebClient.Builder webClientBuilder = WebClientUtils.builder(httpClient); addAllHeaders(webClientBuilder, actionConfiguration, datasourceConfiguration); @@ -245,8 +244,8 @@ public WebClient.Builder getWebClientBuilder(ActionConfiguration actionConfigura return webClientBuilder; } - protected void addSecretKey(WebClient.Builder webClientBuilder, - DatasourceConfiguration datasourceConfiguration) throws AppsmithPluginException { + protected void addSecretKey(WebClient.Builder webClientBuilder, DatasourceConfiguration datasourceConfiguration) + throws AppsmithPluginException { // If users have chosen to share the Appsmith signature in the header, calculate and add that String secretKey; secretKey = headerUtils.getSignatureKey(datasourceConfiguration); @@ -265,8 +264,10 @@ protected void addSecretKey(WebClient.Builder webClientBuilder, } } - protected void addAllHeaders(WebClient.Builder webClientBuilder, ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + protected void addAllHeaders( + WebClient.Builder webClientBuilder, + ActionConfiguration actionConfiguration, + DatasourceConfiguration datasourceConfiguration) { /** * First, check if headers are defined in API datasource and add them. */ @@ -292,8 +293,7 @@ protected void addHeaders(WebClient.Builder webClientBuilder, List<Property> hea protected HttpClient getHttpClient(DatasourceConfiguration datasourceConfiguration) { // Initializing webClient to be used for http call - final ConnectionProvider provider = ConnectionProvider - .builder("rest-api-provider") + final ConnectionProvider provider = ConnectionProvider.builder("rest-api-provider") .maxIdleTime(Duration.ofSeconds(600)) .maxLifeTime(Duration.ofSeconds(600)) .build(); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/SmartSubstitutionUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/SmartSubstitutionUtils.java index 38cd596933cf..a6add9675f74 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/SmartSubstitutionUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/SmartSubstitutionUtils.java @@ -1,7 +1,6 @@ package com.appsmith.external.helpers.restApiUtils.helpers; import com.appsmith.external.models.Property; -import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.commons.collections.CollectionUtils; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/URIUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/URIUtils.java index 70c9b5af9777..8c857c276161 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/URIUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/URIUtils.java @@ -19,9 +19,12 @@ @NoArgsConstructor public class URIUtils { - public URI createUriWithQueryParams(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration, String url, - boolean encodeParamsToggle) throws URISyntaxException { + public URI createUriWithQueryParams( + ActionConfiguration actionConfiguration, + DatasourceConfiguration datasourceConfiguration, + String url, + boolean encodeParamsToggle) + throws URISyntaxException { String httpUrl = addHttpToUrlWhenPrefixNotPresent(url); ArrayList<Property> allQueryParams = new ArrayList<>(); @@ -47,13 +50,9 @@ public URI addQueryParamsToURI(URI uri, List<Property> allQueryParams, boolean e if (encodeParamsToggle) { uriBuilder.queryParam( URLEncoder.encode(key, StandardCharsets.UTF_8), - URLEncoder.encode((String) queryParam.getValue(), StandardCharsets.UTF_8) - ); + URLEncoder.encode((String) queryParam.getValue(), StandardCharsets.UTF_8)); } else { - uriBuilder.queryParam( - key, - queryParam.getValue() - ); + uriBuilder.queryParam(key, queryParam.getValue()); } } } @@ -68,5 +67,4 @@ protected String addHttpToUrlWhenPrefixNotPresent(String url) { } return "http://" + url; } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionConfiguration.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionConfiguration.java index 9725d326b63f..93cd6d81a685 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionConfiguration.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionConfiguration.java @@ -28,10 +28,10 @@ @NoArgsConstructor @Document public class ActionConfiguration implements AppsmithDomain { - private static final int MIN_TIMEOUT_VALUE = 0; // in Milliseconds + private static final int MIN_TIMEOUT_VALUE = 0; // in Milliseconds private static final int MAX_TIMEOUT_VALUE = 60000; // in Milliseconds - private static final String TIMEOUT_OUT_OF_RANGE_MESSAGE = "'Query timeout' field must be an integer between " - + MIN_TIMEOUT_VALUE + " and " + MAX_TIMEOUT_VALUE; + private static final String TIMEOUT_OUT_OF_RANGE_MESSAGE = + "'Query timeout' field must be an integer between " + MIN_TIMEOUT_VALUE + " and " + MAX_TIMEOUT_VALUE; /* * Any of the fields mentioned below could be represented in mustache * template. If the mustache template is found, it would be replaced @@ -41,10 +41,9 @@ public class ActionConfiguration implements AppsmithDomain { * action execution. */ - @Range(min = MIN_TIMEOUT_VALUE, - max = MAX_TIMEOUT_VALUE, - message = TIMEOUT_OUT_OF_RANGE_MESSAGE) + @Range(min = MIN_TIMEOUT_VALUE, max = MAX_TIMEOUT_VALUE, message = TIMEOUT_OUT_OF_RANGE_MESSAGE) Integer timeoutInMillisecond; + PaginationType paginationType = PaginationType.NONE; // API fields @@ -113,7 +112,8 @@ public void setTimeoutInMillisecond(String timeoutInMillisecond) { } public Integer getTimeoutInMillisecond() { - return (timeoutInMillisecond == null || timeoutInMillisecond <= 0) ? - DEFAULT_ACTION_EXECUTION_TIMEOUT_MS : timeoutInMillisecond; + return (timeoutInMillisecond == null || timeoutInMillisecond <= 0) + ? DEFAULT_ACTION_EXECUTION_TIMEOUT_MS + : timeoutInMillisecond; } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java index c05439d46a89..80ecb8fff63f 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; - import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -69,7 +68,7 @@ public class ActionDTO implements Identifiable { @JsonView(Views.Public.class) ActionConfiguration actionConfiguration; - //this attribute carries error messages while processing the actionCollection + // this attribute carries error messages while processing the actionCollection @JsonProperty(access = JsonProperty.Access.READ_ONLY) @Transient @JsonView(Views.Public.class) @@ -101,7 +100,6 @@ public class ActionDTO implements Identifiable { @JsonView(Views.Public.class) Set<String> messages = new HashSet<>(); - // This is a list of keys that the client whose values the client needs to send during action execution. // These are the Mustache keys that the server will replace before invoking the API @JsonProperty(access = JsonProperty.Access.READ_ONLY) @@ -113,11 +111,11 @@ public class ActionDTO implements Identifiable { @Transient @JsonView(Views.Public.class) - String templateId; //If action is created via a template, store the id here. + String templateId; // If action is created via a template, store the id here. @Transient @JsonView(Views.Public.class) - String providerId; //If action is created via a template, store the template's provider id here. + String providerId; // If action is created via a template, store the template's provider id here. @Transient @JsonView(Views.Public.class) @@ -155,7 +153,8 @@ public class ActionDTO implements Identifiable { @JsonView(Views.Internal.class) DefaultResources defaultResources; - // This field will be used to store analytics data related to this specific domain object. It's been introduced in order to track + // This field will be used to store analytics data related to this specific domain object. It's been introduced in + // order to track // success metrics of modules. Learn more on GitHub issue#24734 @JsonView(Views.Public.class) AnalyticsInfo eventData; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionRequest.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionRequest.java index 9451165c4ba0..b820263340af 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionRequest.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionRequest.java @@ -3,7 +3,6 @@ import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; - import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionResult.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionResult.java index 1f7432559866..8433b6a2d37f 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionResult.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionExecutionResult.java @@ -40,7 +40,6 @@ public class ActionExecutionResult { List<WidgetSuggestionDTO> suggestedWidgets; - PluginErrorDetails pluginErrorDetails; public void setErrorInfo(Throwable error, AppsmithPluginErrorUtils pluginErrorUtils) { @@ -95,4 +94,4 @@ public PluginErrorDetails(AppsmithPluginException appsmithPluginException) { this.downstreamErrorCode = appsmithPluginException.getDownstreamErrorCode(); } } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AnalyticsInfo.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AnalyticsInfo.java index 6f452b0ae514..7a62fe063fa8 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AnalyticsInfo.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AnalyticsInfo.java @@ -13,4 +13,4 @@ @NoArgsConstructor public class AnalyticsInfo { private Map<String, Object> analyticsData; -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiContentType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiContentType.java index e58d580b9b1a..2983c2f9b1a3 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiContentType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiContentType.java @@ -11,13 +11,12 @@ public enum ApiContentType { FORM_URLENCODED("application/x-www-form-urlencoded"), MULTIPART_FORM_DATA("multipart/form-data"), RAW("text/plain"), - GRAPHQL("application/graphql") - ; + GRAPHQL("application/graphql"); private String value; - private static final Map<String, ApiContentType> map = Stream.of(ApiContentType.values()).collect( - Collectors.toMap(ApiContentType::getValue, Function.identity())); + private static final Map<String, ApiContentType> map = + Stream.of(ApiContentType.values()).collect(Collectors.toMap(ApiContentType::getValue, Function.identity())); ApiContentType(String value) { this.value = value; @@ -30,5 +29,4 @@ public String getValue() { public static ApiContentType getValueFromString(String value) { return (value == null) ? null : map.get(value); } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiKeyAuth.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiKeyAuth.java index 7fcf6e174581..a736a20e952d 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiKeyAuth.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiKeyAuth.java @@ -32,6 +32,5 @@ public enum Type { String headerPrefix; @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) - @Encrypted - String value; -} \ No newline at end of file + @Encrypted String value; +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiTemplate.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiTemplate.java index 32c1dec5d2c7..ab2aa60f5200 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiTemplate.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiTemplate.java @@ -14,10 +14,10 @@ public class ApiTemplate extends BaseDomain { // ApiTemplate fields below : - String name; //API name here - String providerId; //Providers, e.g. Salesforce should exist in the db and its id should come here. - String publisher; //e.g. RapidAPI - String packageName; //Plugin package name used to execute the final action created by this template + String name; // API name here + String providerId; // Providers, e.g. Salesforce should exist in the db and its id should come here. + String publisher; // e.g. RapidAPI + String packageName; // Plugin package name used to execute the final action created by this template String versionId; ApiTemplateConfiguration apiTemplateConfiguration; ActionConfiguration actionConfiguration; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiTemplateConfiguration.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiTemplateConfiguration.java index 27a1cf0bfc5c..6bb175e7180a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiTemplateConfiguration.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiTemplateConfiguration.java @@ -10,7 +10,7 @@ @ToString @NoArgsConstructor public class ApiTemplateConfiguration implements AppsmithDomain { - String documentation; //Documentation for this particular API comes here - String documentationUrl; //URL for this particular api's documentation comes here + String documentation; // Documentation for this particular API comes here + String documentationUrl; // URL for this particular api's documentation comes here ActionExecutionResult sampleResponse; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AppsmithDomain.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AppsmithDomain.java index a0efbd59d182..f6203d3c564e 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AppsmithDomain.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AppsmithDomain.java @@ -1,4 +1,3 @@ package com.appsmith.external.models; -public interface AppsmithDomain { -} +public interface AppsmithDomain {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationDTO.java index 9f42124be85c..02d747c6b8ac 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationDTO.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonView; - import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @@ -16,17 +15,13 @@ @Getter @Setter @EqualsAndHashCode -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - visible = true, - property = "authenticationType", - defaultImpl = DBAuth.class) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, visible = true, property = "authenticationType", defaultImpl = DBAuth.class) @JsonSubTypes({ - @JsonSubTypes.Type(value = DBAuth.class, name = Authentication.DB_AUTH), - @JsonSubTypes.Type(value = OAuth2.class, name = Authentication.OAUTH2), - @JsonSubTypes.Type(value = BasicAuth.class, name = Authentication.BASIC), - @JsonSubTypes.Type(value = ApiKeyAuth.class, name = Authentication.API_KEY), - @JsonSubTypes.Type(value = BearerTokenAuth.class, name = Authentication.BEARER_TOKEN) + @JsonSubTypes.Type(value = DBAuth.class, name = Authentication.DB_AUTH), + @JsonSubTypes.Type(value = OAuth2.class, name = Authentication.OAUTH2), + @JsonSubTypes.Type(value = BasicAuth.class, name = Authentication.BASIC), + @JsonSubTypes.Type(value = ApiKeyAuth.class, name = Authentication.API_KEY), + @JsonSubTypes.Type(value = BearerTokenAuth.class, name = Authentication.BEARER_TOKEN) }) public class AuthenticationDTO implements AppsmithDomain { // In principle, this class should've been abstract. However, when this class is abstract, Spring's deserialization @@ -62,5 +57,4 @@ public enum AuthenticationStatus { public Mono<Boolean> hasExpired() { return Mono.just(Boolean.FALSE); } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationResponse.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationResponse.java index 9cf6da9c9aa9..7df764fbd76e 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationResponse.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationResponse.java @@ -19,18 +19,15 @@ @AllArgsConstructor public class AuthenticationResponse implements AppsmithDomain { - @Encrypted - String token; + @Encrypted String token; - @Encrypted - String refreshToken; + @Encrypted String refreshToken; Instant issuedAt; Instant expiresAt; - @Encrypted - Object tokenResponse; + @Encrypted Object tokenResponse; // This field is not returned as response by authorisation server, but is provided by cloud-services server @Transient diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java index a3d52938eccb..1744980ce863 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java @@ -22,7 +22,6 @@ import java.util.HashSet; import java.util.Set; - /** * TODO : * Move BaseDomain back to appsmith-server.domain. This is done temporarily to create templates and providers in the same database as the server diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BasicAuth.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BasicAuth.java index 243ba06fcbd9..d9ce26819d69 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BasicAuth.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BasicAuth.java @@ -21,6 +21,5 @@ public class BasicAuth extends AuthenticationDTO { String username; @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) - @Encrypted - String password; + @Encrypted String password; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BearerTokenAuth.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BearerTokenAuth.java index a025eb79edd6..e550833c8018 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BearerTokenAuth.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BearerTokenAuth.java @@ -19,6 +19,5 @@ public class BearerTokenAuth extends AuthenticationDTO { @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) - @Encrypted - String bearerToken; -} \ No newline at end of file + @Encrypted String bearerToken; +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Category.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Category.java index 7cc3973252b3..fd8e4e8d6746 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Category.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Category.java @@ -15,6 +15,5 @@ public class Category extends BaseDomain { @Indexed(unique = true) - String name; //Category name here - + String name; // Category name here } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/CommandParams.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/CommandParams.java index 0cd5b8ecb6ea..dd13dcd5b4fd 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/CommandParams.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/CommandParams.java @@ -12,4 +12,3 @@ public class CommandParams { List<Param> headerParams; } - diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Condition.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Condition.java index 860b5f8a359f..081290d91720 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Condition.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Condition.java @@ -6,7 +6,6 @@ import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonView; - import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -50,8 +49,7 @@ public Condition(String path, String operator, String value) { public static List<Condition> addValueDataType(List<Condition> conditionList) { - return conditionList - .stream() + return conditionList.stream() .map(condition -> { if (condition.getValue() instanceof String) { String value = (String) condition.getValue(); @@ -72,8 +70,7 @@ public static Condition addValueDataType(Condition condition) { condition.setValueDataType(dataType); } else if (objValue instanceof List) { List<Condition> conditionList = (List<Condition>) objValue; - List<Condition> updatedConditions = conditionList - .stream() + List<Condition> updatedConditions = conditionList.stream() .map(subCondition -> addValueDataType(subCondition)) .collect(Collectors.toList()); condition.setValue(updatedConditions); @@ -90,9 +87,9 @@ public static Condition addValueDataType(Condition condition) { public static Boolean isValid(Condition condition) { // In case the condition does not exist in the first place, mark it as invalid as well - if (condition == null || - (StringUtils.isEmpty(condition.getPath()) && !(condition.getValue() instanceof List)) || - condition.getOperator() == null) { + if (condition == null + || (StringUtils.isEmpty(condition.getPath()) && !(condition.getValue() instanceof List)) + || condition.getOperator() == null) { return false; } @@ -109,19 +106,17 @@ public static Boolean isValid(Condition condition) { public static List<Condition> generateFromConfiguration(List<Object> configurationList) { List<Condition> conditionList = new ArrayList<>(); - for(Object config : configurationList) { + for (Object config : configurationList) { Map<String, String> condition = (Map<String, String>) config; if (condition.entrySet().isEmpty()) { // Its an empty object set by the client for UX. Ignore the same continue; } else if (isColumnOrOperatorEmpty(condition)) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Filtering Condition not configured properly"); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "Filtering Condition not configured properly"); } - conditionList.add(new Condition( - condition.get("path"), - condition.get("operator"), - condition.get("value") - )); + conditionList.add(new Condition(condition.get("path"), condition.get("operator"), condition.get("value"))); } return conditionList; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Connection.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Connection.java index 4202ea8b5ad8..4ca418b24a97 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Connection.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Connection.java @@ -18,11 +18,13 @@ public class Connection implements AppsmithDomain { public enum Mode { - READ_ONLY, READ_WRITE + READ_ONLY, + READ_WRITE } public enum Type { - DIRECT, REPLICA_SET + DIRECT, + REPLICA_SET } Mode mode; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DBAuth.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DBAuth.java index b0785b17652b..09530c5695cb 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DBAuth.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DBAuth.java @@ -19,15 +19,17 @@ public class DBAuth extends AuthenticationDTO { public enum Type { - SCRAM_SHA_1, SCRAM_SHA_256, MONGODB_CR, USERNAME_PASSWORD + SCRAM_SHA_1, + SCRAM_SHA_256, + MONGODB_CR, + USERNAME_PASSWORD } Type authType; String username; - @Encrypted - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Encrypted @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) String password; String databaseName; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java index 2622c6e6603f..ae8c7fb5fa4a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java @@ -41,7 +41,7 @@ public class Datasource extends BranchAwareDomain implements Forkable<Datasource @JsonView(Views.Public.class) String pluginName; - //Organizations migrated to workspaces, kept the field as deprecated to support the old migration + // Organizations migrated to workspaces, kept the field as deprecated to support the old migration @Deprecated @JsonView(Views.Public.class) String organizationId; @@ -60,7 +60,6 @@ public class Datasource extends BranchAwareDomain implements Forkable<Datasource @JsonView(Views.Public.class) Map<String, DatasourceStorageDTO> datasourceStorages = new HashMap<>(); - @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonView(Views.Public.class) Set<String> invalids; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceConfiguration.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceConfiguration.java index 0326ab25596e..2ea4110cc694 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceConfiguration.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceConfiguration.java @@ -1,10 +1,10 @@ package com.appsmith.external.models; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; -import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Setter; import lombok.ToString; import org.springframework.data.mongodb.core.mapping.Document; @@ -42,5 +42,4 @@ public class DatasourceConfiguration implements AppsmithDomain { public boolean isSshProxyEnabled() { return sshProxyEnabled == null ? false : sshProxyEnabled; } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceDTO.java index 6fb4e4861c6b..83f23a916b40 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceDTO.java @@ -1,6 +1,5 @@ package com.appsmith.external.models; -import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; @@ -57,7 +56,6 @@ public class DatasourceDTO { @JsonView(Views.Public.class) Set<String> messages; - /* * This field is introduced as part of git sync feature, for the git import we will need to identify the datasource's * which are not configured. This way user can configure those datasource, which may have been introduced as part of git import. diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java index f4753abd6416..f9ec169703fb 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java @@ -80,12 +80,13 @@ public class DatasourceStorage extends BaseDomain { @Transient Boolean isMock; - public DatasourceStorage(String datasourceId, - String environmentId, - DatasourceConfiguration datasourceConfiguration, - Boolean isConfigured, - Set<String> invalids, - Set<String> messages) { + public DatasourceStorage( + String datasourceId, + String environmentId, + DatasourceConfiguration datasourceConfiguration, + Boolean isConfigured, + Set<String> invalids, + Set<String> messages) { this.datasourceId = datasourceId; this.environmentId = environmentId; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorageDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorageDTO.java index 04f3876710b5..ff152b7249a1 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorageDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorageDTO.java @@ -52,7 +52,8 @@ public DatasourceStorageDTO(DatasourceDTO datasource, String environmentId) { * @param environmentId * @param datasourceConfiguration */ - public DatasourceStorageDTO(String datasourceId, String environmentId, DatasourceConfiguration datasourceConfiguration) { + public DatasourceStorageDTO( + String datasourceId, String environmentId, DatasourceConfiguration datasourceConfiguration) { this.datasourceId = datasourceId; this.environmentId = environmentId; this.datasourceConfiguration = datasourceConfiguration; @@ -98,24 +99,27 @@ public DatasourceStorageDTO fork(Boolean forkWithConfiguration, String toWorkspa } /* - updating the datasource "isConfigured" field, which will be used to return if the forking is a partialImport or not - post forking any application, datasource reconnection modal will appear based on isConfigured property - Ref: getApplicationImportDTO() - */ + updating the datasource "isConfigured" field, which will be used to return if the forking is a partialImport or not + post forking any application, datasource reconnection modal will appear based on isConfigured property + Ref: getApplicationImportDTO() + */ - boolean isConfigured = forkWithConfiguration && - (newDatasourceStorageDTO.getDatasourceConfiguration() != null + boolean isConfigured = forkWithConfiguration + && (newDatasourceStorageDTO.getDatasourceConfiguration() != null && newDatasourceStorageDTO.getDatasourceConfiguration().getAuthentication() != null); if (initialAuth instanceof OAuth2) { /* - This is the case for OAuth2 datasources, for example Google sheets, we don't want to copy the token to the - new workspace as it is user's personal token. Hence, in case of forking to a new workspace the datasource - needs to be re-authorised. - */ + This is the case for OAuth2 datasources, for example Google sheets, we don't want to copy the token to the + new workspace as it is user's personal token. Hence, in case of forking to a new workspace the datasource + needs to be re-authorised. + */ newDatasourceStorageDTO.setIsConfigured(false); if (isConfigured) { - newDatasourceStorageDTO.getDatasourceConfiguration().getAuthentication().setAuthenticationResponse(null); + newDatasourceStorageDTO + .getDatasourceConfiguration() + .getAuthentication() + .setAuthenticationResponse(null); } } else { newDatasourceStorageDTO.setIsConfigured(isConfigured); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorageStructure.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorageStructure.java index 0c63fe052db9..47ace21a648a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorageStructure.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorageStructure.java @@ -22,5 +22,4 @@ public class DatasourceStorageStructure extends BaseDomain { @JsonView(Views.Internal.class) private DatasourceStructure structure; - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStructure.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStructure.java index 37a37ab223b5..0870346c904e 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStructure.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStructure.java @@ -90,6 +90,7 @@ default int compareTo(Key other) { public static class PrimaryKey implements Key { String name; List<String> columnNames; + public String getType() { return "primary key"; } @@ -101,6 +102,7 @@ public static class ForeignKey implements Key { String name; List<String> fromColumns; List<String> toColumns; + public String getType() { return "foreign key"; } @@ -153,10 +155,10 @@ public void setErrorInfo(Throwable error) { this.error.setMessage(error.getMessage()); if (error instanceof BaseException) { - this.error.setCode(((BaseException)error).getAppErrorCode()); + this.error.setCode(((BaseException) error).getAppErrorCode()); } } - + /** * Instance creator is required while de-serialising using Gson as key instance can't be invoked with * no-args constructor @@ -173,5 +175,4 @@ public String getType() { return key; } } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceTestResult.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceTestResult.java index 036ac62d9193..74121a14f840 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceTestResult.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceTestResult.java @@ -30,10 +30,9 @@ public class DatasourceTestResult { */ public DatasourceTestResult(String... invalids) { if (invalids == null) { - invalids = new String[]{AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage()}; + invalids = new String[] {AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage()}; } else { - invalids = Arrays - .stream(invalids) + invalids = Arrays.stream(invalids) .map(x -> x == null ? AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage() : x) .toArray(String[]::new); } @@ -49,5 +48,4 @@ public boolean isSuccess() { // This method exists so that a `"success"` boolean key is present in the JSON response to the frontend. return CollectionUtils.isEmpty(invalids); } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DecryptedSensitiveFields.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DecryptedSensitiveFields.java index 4d41a1fd3291..480c9834efe3 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DecryptedSensitiveFields.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DecryptedSensitiveFields.java @@ -14,25 +14,25 @@ @Setter @NoArgsConstructor public class DecryptedSensitiveFields { - + String password; - + String token; - + String refreshToken; - + Object tokenResponse; - + String authType; - + DBAuth dbAuth; - + BasicAuth basicAuth; - + OAuth2 openAuth2; BearerTokenAuth bearerTokenAuth; - + public DecryptedSensitiveFields(AuthenticationResponse authResponse) { this.token = authResponse.getToken(); this.refreshToken = authResponse.getRefreshToken(); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DefaultResources.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DefaultResources.java index 90666cb05104..6878a16defe7 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DefaultResources.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DefaultResources.java @@ -6,7 +6,6 @@ * This class will be used for connecting resources across branches for git connected application * e.g. Page1 in branch1 will have the same defaultResources.pageId as of Page1 of branch2 */ - @Data public class DefaultResources { String actionId; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Endpoint.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Endpoint.java index ce09a8949333..0dcdcd1c4355 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Endpoint.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Endpoint.java @@ -20,5 +20,4 @@ public class Endpoint { String host; Long port; - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/EntityDependencyNode.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/EntityDependencyNode.java index 28997a4045f1..bda6754789cc 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/EntityDependencyNode.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/EntityDependencyNode.java @@ -30,7 +30,9 @@ public boolean isValidDynamicBinding() { result = false; } } else if (EntityReferenceType.JSACTION.equals(this.entityReferenceType)) { - if (Boolean.TRUE.equals(this.isAsync) && (Boolean.TRUE.equals(this.isFunctionCall) || !this.referenceString.startsWith(this.validEntityName + ".data"))) { + if (Boolean.TRUE.equals(this.isAsync) + && (Boolean.TRUE.equals(this.isFunctionCall) + || !this.referenceString.startsWith(this.validEntityName + ".data"))) { result = false; } @@ -38,12 +40,14 @@ public boolean isValidDynamicBinding() { if (Boolean.TRUE.equals(this.isFunctionCall) && !this.validEntityName.equals(this.referenceString)) { result = false; } - if (Boolean.FALSE.equals(this.isFunctionCall) && !this.referenceString.startsWith(this.validEntityName + ".data")) { + if (Boolean.FALSE.equals(this.isFunctionCall) + && !this.referenceString.startsWith(this.validEntityName + ".data")) { result = false; } } - // TODO: This one feels a little hacky. Should we introduce another property that handles whether the node is coming from a binding or i + // TODO: This one feels a little hacky. Should we introduce another property that handles whether the node + // is coming from a binding or i if (this.isAsync == null && !this.referenceString.startsWith(this.validEntityName + ".data")) { result = false; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ErrorType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ErrorType.java index d7d8e9fc305a..f5254a228293 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ErrorType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ErrorType.java @@ -18,4 +18,3 @@ public enum ErrorType { REPOSITORY_NOT_FOUND, EE_FEATURE_ERROR } - diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/InvisibleActionFields.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/InvisibleActionFields.java index ca39fe057148..7ab4431d16da 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/InvisibleActionFields.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/InvisibleActionFields.java @@ -18,5 +18,4 @@ public class InvisibleActionFields { Boolean unpublishedUserSetOnLoad; Boolean publishedUserSetOnLoad; - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/MustacheBindingToken.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/MustacheBindingToken.java index d73e37b9dfbb..8348c1ff8ae6 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/MustacheBindingToken.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/MustacheBindingToken.java @@ -17,6 +17,7 @@ public class MustacheBindingToken { String value; int startIndex; - // A token can be with or without handlebars in the value. This boolean value represents the state of the current token. + // A token can be with or without handlebars in the value. This boolean value represents the state of the current + // token. boolean includesHandleBars = false; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/OAuth2.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/OAuth2.java index 6b285a4f50f6..16a3f6507136 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/OAuth2.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/OAuth2.java @@ -51,8 +51,7 @@ public enum RefreshTokenClientCredentialsLocation { String clientId; - @Encrypted - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Encrypted @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) String clientSecret; String authorizationUrl; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PEMCertificate.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PEMCertificate.java index 1fd4fafb139c..c14319aeafaf 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PEMCertificate.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PEMCertificate.java @@ -21,8 +21,6 @@ public class PEMCertificate implements AppsmithDomain { UploadedFile file; - @Encrypted - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Encrypted @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) String password; - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PaginationField.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PaginationField.java index 0ccad377ea1e..7013fd0f281b 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PaginationField.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PaginationField.java @@ -1,5 +1,6 @@ package com.appsmith.external.models; public enum PaginationField { - NEXT, PREV + NEXT, + PREV } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PaginationType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PaginationType.java index ab95d2858e7c..4b349039c552 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PaginationType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PaginationType.java @@ -1,5 +1,8 @@ package com.appsmith.external.models; public enum PaginationType { - NONE, PAGE_NO, URL, CURSOR + NONE, + PAGE_NO, + URL, + CURSOR } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Param.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Param.java index 63211264219c..5d9a4d002fd0 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Param.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Param.java @@ -22,14 +22,15 @@ public class Param { ClientDataType clientDataType; - //The type of each array elements are stored in this variable when the clientDataType is of ARRAY type and null otherwise + // The type of each array elements are stored in this variable when the clientDataType is of ARRAY type and null + // otherwise List<ClientDataType> dataTypesOfArrayElements; /* - In execute API the parameter map is sent this way {"Text1.text": "k1","Table1.data": "k2", "Api1.data": "k3"} where the key - is the original name of the binding parameter and value is the pseudo name of the original binding parameter with a view to reducing the size of the payload. - We will store the pseudo binding name in this variable named pseudoBindingName - */ + In execute API the parameter map is sent this way {"Text1.text": "k1","Table1.data": "k2", "Api1.data": "k3"} where the key + is the original name of the binding parameter and value is the pseudo name of the original binding parameter with a view to reducing the size of the payload. + We will store the pseudo binding name in this variable named pseudoBindingName + */ String pseudoBindingName; public Param(String key, String value) { diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PluginType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PluginType.java index 1aba877651a5..6af085161ec1 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PluginType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/PluginType.java @@ -1,5 +1,9 @@ package com.appsmith.external.models; public enum PluginType { - DB, API, JS, SAAS, REMOTE + DB, + API, + JS, + SAAS, + REMOTE } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Policy.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Policy.java index 1f76d68156a4..92a56d365346 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Policy.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Policy.java @@ -1,13 +1,10 @@ package com.appsmith.external.models; - import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; -import lombok.Getter; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.ToString; import java.io.Serializable; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Property.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Property.java index 171dad363aaa..bad41f7618a8 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Property.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Property.java @@ -42,5 +42,4 @@ public Property(String key, Object value) { String maxRange; String[] valueOptions; // This stores the values that are permitted by the api for the given key - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Provider.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Provider.java index 9c5b65a46df7..edac2fd259dc 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Provider.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Provider.java @@ -17,21 +17,21 @@ public class Provider extends BaseDomain { @Indexed(unique = true) - String name; //Provider name here + String name; // Provider name here - String description; //Provider company's description here + String description; // Provider company's description here String url; String imageUrl; - String documentationUrl; //URL which points to the homepage of the documentations here + String documentationUrl; // URL which points to the homepage of the documentations here - String credentialSteps; //How to generate/get the credentials to run the APIs which belong to this provider + String credentialSteps; // How to generate/get the credentials to run the APIs which belong to this provider - List<String> categories; //Category names here + List<String> categories; // Category names here - Statistics statistics; //Cumulative statistics for all the APIs for this provider + Statistics statistics; // Cumulative statistics for all the APIs for this provider DatasourceConfiguration datasourceConfiguration; @@ -45,5 +45,4 @@ public class Provider extends BaseDomain { Boolean isVisible = true; Integer sortOrder = 1000; - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/RequestParamDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/RequestParamDTO.java index a916fadc90f9..53870749f03d 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/RequestParamDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/RequestParamDTO.java @@ -3,7 +3,6 @@ import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonView; - import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSHConnection.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSHConnection.java index 0b83620f91e8..3d7b6b6d1996 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSHConnection.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSHConnection.java @@ -14,7 +14,8 @@ public class SSHConnection implements AppsmithDomain { public enum AuthType { - IDENTITY_FILE, PASSWORD + IDENTITY_FILE, + PASSWORD } String host; @@ -26,5 +27,4 @@ public enum AuthType { AuthType authType; SSHPrivateKey privateKey; - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSHPrivateKey.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSHPrivateKey.java index b209efe7b783..fe6fb77f3aae 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSHPrivateKey.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSHPrivateKey.java @@ -17,8 +17,6 @@ public class SSHPrivateKey implements AppsmithDomain { UploadedFile keyFile; - @Encrypted - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Encrypted @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) String password; - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSLDetails.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSLDetails.java index 8dfc91682733..83fb6714574d 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSLDetails.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSLDetails.java @@ -19,19 +19,28 @@ public class SSLDetails implements AppsmithDomain { public enum AuthType { // Default driver configurations - DEFAULT, NO_SSL, + DEFAULT, + NO_SSL, - //For those drivers that don't have any specific options + // For those drivers that don't have any specific options ENABLED, // Following for Mysql/Postgres Connections. - ALLOW, PREFER, REQUIRE, DISABLE, VERIFY_CA, VERIFY_FULL, + ALLOW, + PREFER, + REQUIRE, + DISABLE, + VERIFY_CA, + VERIFY_FULL, // For MySql Connections - PREFERRED, REQUIRED, DISABLED, + PREFERRED, + REQUIRED, + DISABLED, // Following for MongoDB Connections. - CA_CERTIFICATE, SELF_SIGNED_CERTIFICATE, + CA_CERTIFICATE, + SELF_SIGNED_CERTIFICATE, // For MsSQL, Oracle DB Connections NO_VERIFY diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Statistics.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Statistics.java index ee01ae261ffb..94bee9bca3cb 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Statistics.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Statistics.java @@ -10,7 +10,7 @@ @ToString @NoArgsConstructor public class Statistics { - Long imports; //No of times any of the provider's apis have been imported - Long averageLatency; //Average latency of the APIs provided by this provider in milli second - Double successRate; //Percentage of successful responses. + Long imports; // No of times any of the provider's apis have been imported + Long averageLatency; // Average latency of the APIs provided by this provider in milli second + Double successRate; // Percentage of successful responses. } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/TemplateCollection.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/TemplateCollection.java index 015d28ffac3f..454490decc2d 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/TemplateCollection.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/TemplateCollection.java @@ -2,7 +2,6 @@ import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonView; - import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UQIDataFilterParams.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UQIDataFilterParams.java index ca33ab839dfb..f4b1f62ee3bd 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UQIDataFilterParams.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UQIDataFilterParams.java @@ -8,7 +8,6 @@ import java.util.List; import java.util.Map; - /** * This class is supposed to enclose all the parameters that are required to filter data as per the UQI * specifications. Currently, UQI specifies filtering data on the following parameters: @@ -25,5 +24,5 @@ public class UQIDataFilterParams { Condition condition; // where condition. List<String> projectionColumns; // columns to show to user. List<Map<String, String>> sortBy; // columns to sort by in ascending or descending order. - Map<String, String> paginateBy; // limit and offset + Map<String, String> paginateBy; // limit and offset } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UploadedFile.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UploadedFile.java index 3d54a313d902..f339d9605dc8 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UploadedFile.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UploadedFile.java @@ -4,7 +4,6 @@ import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; - import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -27,8 +26,7 @@ public class UploadedFile implements AppsmithDomain { @JsonView(Views.Public.class) String name; - @Encrypted - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Encrypted @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @JsonView(Views.Public.class) String base64Content; @@ -44,5 +42,4 @@ public byte[] getDecodedContent() { return Base64.getDecoder().decode(base64Content); } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/WidgetType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/WidgetType.java index c33116aa44ee..4797558f80ce 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/WidgetType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/WidgetType.java @@ -19,4 +19,4 @@ public enum WidgetType { public String getMessage() { return this.query; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/BasePlugin.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/BasePlugin.java index 3d38ef6d961f..44fe1a414ef8 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/BasePlugin.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/BasePlugin.java @@ -11,5 +11,4 @@ public abstract class BasePlugin extends Plugin { public BasePlugin(PluginWrapper wrapper) { super(wrapper); } - } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/BaseRestApiPluginExecutor.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/BaseRestApiPluginExecutor.java index 8b1659692adb..4b778e5ad8a7 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/BaseRestApiPluginExecutor.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/BaseRestApiPluginExecutor.java @@ -41,7 +41,6 @@ public class BaseRestApiPluginExecutor implements PluginExecutor<APIConnection>, protected HeaderUtils headerUtils; protected HintMessageUtils hintMessageUtils; - // Setting max content length. This would've been coming from `spring.codec.max-in-memory-size` property if the // `WebClient` instance was loaded as an auto-wired bean. protected ExchangeStrategies EXCHANGE_STRATEGIES; @@ -56,8 +55,7 @@ protected BaseRestApiPluginExecutor(SharedConfig sharedConfig) { this.headerUtils = new HeaderUtils(); this.datasourceUtils = new DatasourceUtils(); this.hintMessageUtils = new HintMessageUtils(); - this.EXCHANGE_STRATEGIES = ExchangeStrategies - .builder() + this.EXCHANGE_STRATEGIES = ExchangeStrategies.builder() .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(sharedConfig.getCodecSize())) .build(); } @@ -73,8 +71,8 @@ public void datasourceDestroy(APIConnection connection) { } @Override - public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration, - boolean isEmbeddedDatasource) { + public Set<String> validateDatasource( + DatasourceConfiguration datasourceConfiguration, boolean isEmbeddedDatasource) { /* Use the default validation routine for REST API based plugins */ return datasourceUtils.validateDatasource(datasourceConfiguration, isEmbeddedDatasource); } @@ -86,9 +84,11 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur * the following variant should be used: * validateDatasource(DatasourceConfiguration datasourceConfiguration, boolean isEmbeddedDatasource) */ - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_VALIDATE_DATASOURCE_ERROR, "This method should " + - "not be used for this plugin as it may have embedded datasource. Please use validateDatasource" + - "(dsConfig, isEmbedded)."); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_VALIDATE_DATASOURCE_ERROR, + "This method should " + + "not be used for this plugin as it may have embedded datasource. Please use validateDatasource" + + "(dsConfig, isEmbedded)."); } @Override @@ -100,16 +100,17 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasou } @Override - public Mono<ActionExecutionResult> execute(APIConnection apiConnection, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + APIConnection apiConnection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Unused function return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, "Unsupported Operation")); } @Override - public Mono<Tuple2<Set<String>, Set<String>>> getHintMessages(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + public Mono<Tuple2<Set<String>, Set<String>>> getHintMessages( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { /* Use the default hint message flow for REST API based plugins */ return hintMessageUtils.getHintMessages(actionConfiguration, datasourceConfiguration); } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/CrudTemplateService.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/CrudTemplateService.java index 5a08b85a22ca..0979d7d91872 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/CrudTemplateService.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/CrudTemplateService.java @@ -18,22 +18,27 @@ public interface CrudTemplateService { * @param mappedColumns column name map from template table to user defined table * @param pluginSpecificTemplateParams plugin specified fields like S3 bucket name etc */ - default void updateCrudTemplateFormData(Map<String, Object> formData, - Map<String, String> mappedColumns, - Map<String, String> pluginSpecificTemplateParams) { - for (Map.Entry<String,Object> property : formData.entrySet()) { + default void updateCrudTemplateFormData( + Map<String, Object> formData, + Map<String, String> mappedColumns, + Map<String, String> pluginSpecificTemplateParams) { + for (Map.Entry<String, Object> property : formData.entrySet()) { if (property.getValue() != null) { - if (property.getKey() != null && !CollectionUtils.isEmpty(pluginSpecificTemplateParams) - && pluginSpecificTemplateParams.get(property.getKey()) != null){ + if (property.getKey() != null + && !CollectionUtils.isEmpty(pluginSpecificTemplateParams) + && pluginSpecificTemplateParams.get(property.getKey()) != null) { property.setValue(pluginSpecificTemplateParams.get(property.getKey())); } else { - // Recursively replace the column names from template table with user provided table using mappedColumns + // Recursively replace the column names from template table with user provided table using + // mappedColumns if (property.getValue() instanceof String) { - final String replacedValue = replaceMappedColumnInStringValue(mappedColumns, property.getValue()); + final String replacedValue = + replaceMappedColumnInStringValue(mappedColumns, property.getValue()); property.setValue(replacedValue); } if (property.getValue() instanceof Map) { - updateCrudTemplateFormData((Map<String, Object>) property.getValue(), mappedColumns, pluginSpecificTemplateParams); + updateCrudTemplateFormData( + (Map<String, Object>) property.getValue(), mappedColumns, pluginSpecificTemplateParams); } } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java index b2398dbd755b..059205809b0a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java @@ -43,7 +43,8 @@ public interface PluginExecutor<C> extends ExtensionPoint, CrudTemplateService { * @param actionConfiguration : These are the configurations which have been used to create an Action from a Datasource. * @return ActionExecutionResult : This object is returned to the user which contains the result values from the execution. */ - Mono<ActionExecutionResult> execute(C connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration); + Mono<ActionExecutionResult> execute( + C connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration); /** * This function is responsible for creating the connection to the data source and returning the connection variable @@ -52,7 +53,7 @@ public interface PluginExecutor<C> extends ExtensionPoint, CrudTemplateService { * @param datasourceConfiguration * @return Connection object */ -// Mono<C> datasourceCreate(DatasourceConfiguration datasourceConfiguration); + // Mono<C> datasourceCreate(DatasourceConfiguration datasourceConfiguration); default Mono<C> datasourceCreate(DatasourceConfiguration datasourceConfiguration) { Properties properties = new Properties(); @@ -71,11 +72,13 @@ default Mono<C> createConnectionClient(DatasourceConfiguration datasourceConfigu return this.datasourceCreate(datasourceConfiguration); } - default Properties addPluginSpecificProperties(DatasourceConfiguration datasourceConfiguration, Properties properties) { + default Properties addPluginSpecificProperties( + DatasourceConfiguration datasourceConfiguration, Properties properties) { return properties; } - default Properties addAuthParamsToConnectionConfig(DatasourceConfiguration datasourceConfiguration, Properties properties) { + default Properties addAuthParamsToConnectionConfig( + DatasourceConfiguration datasourceConfiguration, Properties properties) { return properties; } @@ -110,8 +113,9 @@ default boolean isDatasourceValid(DatasourceConfiguration datasourceConfiguratio * @return Set : The set of invalid strings informing the user of all the invalid fields */ Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration); - default Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration, - boolean isEmbeddedDatasource) { + + default Set<String> validateDatasource( + DatasourceConfiguration datasourceConfiguration, boolean isEmbeddedDatasource) { if (!isEmbeddedDatasource) { return this.validateDatasource(datasourceConfiguration); } @@ -133,18 +137,18 @@ default Set<String> validateDatasource(DatasourceConfiguration datasourceConfigu default Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) { return this.datasourceCreate(datasourceConfiguration) .flatMap(connection -> { - return this.testDatasource(connection) - .doFinally(signal -> this.datasourceDestroy(connection)); + return this.testDatasource(connection).doFinally(signal -> this.datasourceDestroy(connection)); }) .onErrorResume(error -> { // We always expect to have an error object, but the error object may not be well-formed final String errorMessage = error.getMessage() == null ? AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage() : error.getMessage(); - if (error instanceof AppsmithPluginException && - StringUtils.hasLength(((AppsmithPluginException) error).getDownstreamErrorMessage())) { - return Mono.just(new DatasourceTestResult(((AppsmithPluginException) error).getDownstreamErrorMessage(), errorMessage)); - } + if (error instanceof AppsmithPluginException + && StringUtils.hasLength(((AppsmithPluginException) error).getDownstreamErrorMessage())) { + return Mono.just(new DatasourceTestResult( + ((AppsmithPluginException) error).getDownstreamErrorMessage(), errorMessage)); + } return Mono.just(new DatasourceTestResult(errorMessage)); }) .subscribeOn(Schedulers.boundedElastic()); @@ -191,19 +195,21 @@ default Mono<DatasourceStructure> getStructure(C connection, DatasourceConfigura * @param actionConfiguration : These are the configurations which have been used to create an Action from a Datasource. * @return ActionExecutionResult : This object is returned to the user which contains the result values from the execution. */ - default Mono<ActionExecutionResult> executeParameterized(C connection, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + default Mono<ActionExecutionResult> executeParameterized( + C connection, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { prepareConfigurationsForExecution(executeActionDTO, actionConfiguration, datasourceConfiguration); return this.execute(connection, datasourceConfiguration, actionConfiguration); } - default Mono<ActionExecutionResult> executeParameterizedWithMetrics(C connection, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration, - ObservationRegistry observationRegistry) { + default Mono<ActionExecutionResult> executeParameterizedWithMetrics( + C connection, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration, + ObservationRegistry observationRegistry) { return this.executeParameterized(connection, executeActionDTO, datasourceConfiguration, actionConfiguration) .tag("plugin", this.getClass().getName()) .name(ACTION_EXECUTION_PLUGIN_EXECUTION) @@ -217,26 +223,25 @@ default Mono<ActionExecutionResult> executeParameterizedWithMetrics(C connection * @param actionConfiguration * @param datasourceConfiguration */ - default void prepareConfigurationsForExecution(ExecuteActionDTO executeActionDTO, - ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + default void prepareConfigurationsForExecution( + ExecuteActionDTO executeActionDTO, + ActionConfiguration actionConfiguration, + DatasourceConfiguration datasourceConfiguration) { variableSubstitution(actionConfiguration, datasourceConfiguration, executeActionDTO); - } /** * This function replaces the variables in the action and datasource configuration with the actual params */ - default void variableSubstitution(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration, - ExecuteActionDTO executeActionDTO) { - //Do variable substitution - //Do this only if params have been provided in the execute command + default void variableSubstitution( + ActionConfiguration actionConfiguration, + DatasourceConfiguration datasourceConfiguration, + ExecuteActionDTO executeActionDTO) { + // Do variable substitution + // Do this only if params have been provided in the execute command if (executeActionDTO != null && !isEmpty(executeActionDTO.getParams())) { - Map<String, String> replaceParamsMap = executeActionDTO - .getParams() - .stream() + Map<String, String> replaceParamsMap = executeActionDTO.getParams().stream() .collect(Collectors.toMap( // Trimming here for good measure. If the keys have space on either side, // Mustache won't be able to find the key. @@ -246,8 +251,7 @@ default void variableSubstitution(ActionConfiguration actionConfiguration, p -> p.getKey().trim(), // .replaceAll("[\"\n\\\\]", "\\\\$0"), Param::getValue, // In case of a conflict, we pick the older value - (oldValue, newValue) -> oldValue) - ); + (oldValue, newValue) -> oldValue)); MustacheHelper.renderFieldValues(datasourceConfiguration, replaceParamsMap); MustacheHelper.renderFieldValues(actionConfiguration, replaceParamsMap); @@ -268,8 +272,8 @@ default void variableSubstitution(ActionConfiguration actionConfiguration, * @param datasourceConfiguration * @return A tuple of datasource and action configuration related hint messages. */ - default Mono<Tuple2<Set<String>, Set<String>>> getHintMessages(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + default Mono<Tuple2<Set<String>, Set<String>>> getHintMessages( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { Set<String> datasourceHintMessages = new HashSet<>(); Set<String> actionHintMessages = new HashSet<>(); @@ -278,7 +282,8 @@ default Mono<Tuple2<Set<String>, Set<String>>> getHintMessages(ActionConfigurati return Mono.zip(Mono.just(datasourceHintMessages), Mono.just(actionHintMessages)); } - default Mono<TriggerResultDTO> trigger(C connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) { + default Mono<TriggerResultDTO> trigger( + C connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) { return Mono.empty(); } @@ -293,8 +298,7 @@ default Mono<TriggerResultDTO> trigger(C connection, DatasourceConfiguration dat * @param actionConfiguration * @return modified actionConfiguration object after setting the two keys mentioned above in `formData`. */ - default void extractAndSetNativeQueryFromFormData(ActionConfiguration actionConfiguration) { - } + default void extractAndSetNativeQueryFromFormData(ActionConfiguration actionConfiguration) {} /** * This method returns a set of paths that are expected to contain bindings that refer to the same action diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/SmartSubstitutionInterface.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/SmartSubstitutionInterface.java index ab5664085ce3..7bd07bc7682a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/SmartSubstitutionInterface.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/SmartSubstitutionInterface.java @@ -25,24 +25,28 @@ public interface SmartSubstitutionInterface { * @return * @throws AppsmithPluginException */ - default Object smartSubstitutionOfBindings(Object input, - List<MustacheBindingToken> mustacheValuesInOrder, - List<Param> evaluatedParams, - List<Map.Entry<String, String>> insertedParams, - Object... args) throws AppsmithPluginException { + default Object smartSubstitutionOfBindings( + Object input, + List<MustacheBindingToken> mustacheValuesInOrder, + List<Param> evaluatedParams, + List<Map.Entry<String, String>> insertedParams, + Object... args) + throws AppsmithPluginException { if (mustacheValuesInOrder != null && !mustacheValuesInOrder.isEmpty()) { for (int i = 0; i < mustacheValuesInOrder.size(); i++) { String key = mustacheValuesInOrder.get(i).getValue(); - Optional<Param> matchingParam = evaluatedParams.stream().filter(param -> param.getKey().trim().equals(key)).findFirst(); + Optional<Param> matchingParam = evaluatedParams.stream() + .filter(param -> param.getKey().trim().equals(key)) + .findFirst(); // If the evaluated value of the mustache binding is present, set it in the prepared statement if (matchingParam.isPresent()) { String value = matchingParam.get().getValue(); - input = substituteValueInInput(i + 1, key, - value, input, insertedParams, append(args, matchingParam.get())); + input = substituteValueInInput( + i + 1, key, value, input, insertedParams, append(args, matchingParam.get())); } else { throw new AppsmithPluginException(AppsmithPluginError.SMART_SUBSTITUTION_VALUE_MISSING, key); } @@ -53,12 +57,17 @@ default Object smartSubstitutionOfBindings(Object input, // Default implementation does not do any substitution. The plugin doing intelligent substitution is responsible // for overriding this function. - default Object substituteValueInInput(int index, String binding, String value, Object input, - List<Map.Entry<String, String>> insertedParams, Object... args) throws AppsmithPluginException { + default Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) + throws AppsmithPluginException { return input; } - /** * This method is part of the pre-processing of the replacement value before the final substitution that * happens as part of smart substitution process. diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/EncryptionService.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/EncryptionService.java index 844ff2f54f60..4abb39291b7b 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/EncryptionService.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/EncryptionService.java @@ -2,6 +2,4 @@ import com.appsmith.external.services.ce.EncryptionServiceCE; -public interface EncryptionService extends EncryptionServiceCE { - -} +public interface EncryptionService extends EncryptionServiceCE {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/FilterDataService.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/FilterDataService.java index 6f640e958daa..70604fe622fc 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/FilterDataService.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/FilterDataService.java @@ -22,6 +22,4 @@ public static FilterDataService getInstance() { return instance; } - } - diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/IFilterDataService.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/IFilterDataService.java index c1bbb93c26bb..9639bcb4d746 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/IFilterDataService.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/IFilterDataService.java @@ -2,8 +2,4 @@ import com.appsmith.external.services.ce.IFilterDataServiceCE; - -public interface IFilterDataService extends IFilterDataServiceCE { - -} - +public interface IFilterDataService extends IFilterDataServiceCE {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/SharedConfig.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/SharedConfig.java index 76bc46dd0840..9eff39b1018b 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/SharedConfig.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/SharedConfig.java @@ -2,6 +2,4 @@ import com.appsmith.external.services.ce.SharedConfigCE; -public interface SharedConfig extends SharedConfigCE { - -} +public interface SharedConfig extends SharedConfigCE {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/FilterDataServiceCE.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/FilterDataServiceCE.java index 7407d30e319e..f70b2418a250 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/FilterDataServiceCE.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/FilterDataServiceCE.java @@ -42,7 +42,6 @@ import static com.appsmith.external.models.Condition.addValueDataType; import static org.apache.commons.lang3.StringUtils.isBlank; - @Slf4j public class FilterDataServiceCE implements IFilterDataServiceCE { @@ -64,8 +63,7 @@ public class FilterDataServiceCE implements IFilterDataServiceCE { DataType.BOOLEAN, "BOOLEAN", DataType.STRING, "VARCHAR", DataType.DATE, "DATE", - DataType.TIMESTAMP, "TIMESTAMP" - ); + DataType.TIMESTAMP, "TIMESTAMP"); private static final Map<ConditionalOperator, String> SQL_OPERATOR_MAP = Map.of( ConditionalOperator.LT, "<", @@ -76,8 +74,7 @@ public class FilterDataServiceCE implements IFilterDataServiceCE { ConditionalOperator.GTE, ">=", ConditionalOperator.CONTAINS, "LIKE", ConditionalOperator.IN, "IN", - ConditionalOperator.NOT_IN, "NOT IN" - ); + ConditionalOperator.NOT_IN, "NOT IN"); private static final Map<DataType, Set<DataType>> datatypeCompatibilityMap = Map.of( DataType.INTEGER, Set.of(), @@ -85,10 +82,18 @@ public class FilterDataServiceCE implements IFilterDataServiceCE { DataType.FLOAT, Set.of(DataType.INTEGER, DataType.LONG), DataType.DOUBLE, Set.of(DataType.INTEGER, DataType.LONG, DataType.FLOAT), DataType.BOOLEAN, Set.of(), - DataType.STRING, Set.of(DataType.INTEGER, DataType.LONG, DataType.FLOAT, DataType.DOUBLE, DataType.BOOLEAN, DataType.DATE, DataType.TIME, DataType.TIMESTAMP), + DataType.STRING, + Set.of( + DataType.INTEGER, + DataType.LONG, + DataType.FLOAT, + DataType.DOUBLE, + DataType.BOOLEAN, + DataType.DATE, + DataType.TIME, + DataType.TIMESTAMP), DataType.DATE, Set.of(), - DataType.TIMESTAMP, Set.of() - ); + DataType.TIMESTAMP, Set.of()); public FilterDataServiceCE() { @@ -98,7 +103,9 @@ public FilterDataServiceCE() { connection = DriverManager.getConnection(URL); } catch (SQLException e) { log.error(e.getMessage()); - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, "Failed to connect to the in memory database. Unable to perform filtering : " + e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, + "Failed to connect to the in memory database. Unable to perform filtering : " + e.getMessage()); } } @@ -113,7 +120,8 @@ public ArrayNode filterDataNew(ArrayNode items, UQIDataFilterParams uqiDataFilte return this.filterDataNew(items, uqiDataFilterParams, null); } - public ArrayNode filterDataNew(ArrayNode items, UQIDataFilterParams uqiDataFilterParams, Map<DataType, DataType> dataTypeConversionMap) { + public ArrayNode filterDataNew( + ArrayNode items, UQIDataFilterParams uqiDataFilterParams, Map<DataType, DataType> dataTypeConversionMap) { if (items == null || items.size() == 0) { return items; } @@ -131,7 +139,8 @@ public ArrayNode filterDataNew(ArrayNode items, UQIDataFilterParams uqiDataFilte insertAllData(tableName, items, schema, dataTypeConversionMap); // Filter the data - List<Map<String, Object>> finalResults = executeFilterQueryNew(tableName, schema, uqiDataFilterParams, dataTypeConversionMap); + List<Map<String, Object>> finalResults = + executeFilterQueryNew(tableName, schema, uqiDataFilterParams, dataTypeConversionMap); // Now that the data has been filtered. Clean Up. Drop the table dropTable(tableName); @@ -141,9 +150,11 @@ public ArrayNode filterDataNew(ArrayNode items, UQIDataFilterParams uqiDataFilte return finalResultsNode; } - private List<Map<String, Object>> executeFilterQueryNew(String tableName, Map<String, DataType> schema, - UQIDataFilterParams uqiDataFilterParams, - Map<DataType, DataType> dataTypeConversionMap) { + private List<Map<String, Object>> executeFilterQueryNew( + String tableName, + Map<String, DataType> schema, + UQIDataFilterParams uqiDataFilterParams, + Map<DataType, DataType> dataTypeConversionMap) { Condition condition = uqiDataFilterParams.getCondition(); List<String> projectionColumns = uqiDataFilterParams.getProjectionColumns(); @@ -224,9 +235,12 @@ private List<Map<String, Object>> executeFilterQueryNew(String tableName, Map<St // Getting an SQL Exception here means that our generated query is incorrect. Raise an alarm! log.error(e.getMessage()); if (e instanceof JdbcSQLSyntaxErrorException) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, "Filtering failure seen : " + ((JdbcSQLSyntaxErrorException) e).getOriginalMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, + "Filtering failure seen : " + ((JdbcSQLSyntaxErrorException) e).getOriginalMessage()); } - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, "Filtering failure seen : " + e); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, "Filtering failure seen : " + e); } return rowsList; @@ -239,8 +253,8 @@ private List<Map<String, Object>> executeFilterQueryNew(String tableName, Map<St * @param paginateBy - values for limit and offset * @param values - list to hold values to be substituted in prepared statement */ - private void addPaginationCondition(StringBuilder sb, Map<String, String> paginateBy, - List<PreparedStatementValueDTO> values) { + private void addPaginationCondition( + StringBuilder sb, Map<String, String> paginateBy, List<PreparedStatementValueDTO> values) { if (CollectionUtils.isEmpty(paginateBy)) { return; } @@ -274,8 +288,7 @@ private void addPaginationCondition(StringBuilder sb, Map<String, String> pagina private void addProjectionCondition(StringBuilder sb, List<String> projectionColumns, String tableName) { if (!CollectionUtils.isEmpty(projectionColumns)) { sb.append("SELECT"); - projectionColumns.stream() - .forEach(columnName -> sb.append(" `" + columnName + "`,")); + projectionColumns.stream().forEach(columnName -> sb.append(" `" + columnName + "`,")); sb.setLength(sb.length() - 1); sb.append(" FROM " + tableName); @@ -314,11 +327,14 @@ private void addSortCondition(StringBuilder sb, List<Map<String, String>> sortBy String columnName = sortCondition.get(SORT_BY_COLUMN_NAME_KEY); SortType sortType; try { - sortType = SortType.valueOf(sortCondition.get(SORT_BY_TYPE_KEY).toUpperCase()); + sortType = SortType.valueOf( + sortCondition.get(SORT_BY_TYPE_KEY).toUpperCase()); } catch (IllegalArgumentException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, "Appsmith server failed " + - "to parse the type of sort condition. Please reach out to Appsmith customer support " + - "to resolve this."); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_ERROR, + "Appsmith server failed " + + "to parse the type of sort condition. Please reach out to Appsmith customer support " + + "to resolve this."); } sb.append(" `" + columnName + "` " + sortType + ","); }); @@ -336,8 +352,7 @@ private boolean isSortConditionEmpty(List<Map<String, String>> sortBy) { return true; } - return sortBy.stream() - .allMatch(sortCondition -> isBlank(sortCondition.get(SORT_BY_COLUMN_NAME_KEY))); + return sortBy.stream().allMatch(sortCondition -> isBlank(sortCondition.get(SORT_BY_COLUMN_NAME_KEY))); } /** @@ -348,11 +363,16 @@ private boolean isSortConditionEmpty(List<Map<String, String>> sortBy) { * @param schema - The Schema * @param dataTypeConversionMap - A Map to provide custom Datatype against the actual Datatype found. */ - public void insertAllData(String tableName, ArrayNode items, Map<String, DataType> schema, Map<DataType, DataType> dataTypeConversionMap) { + public void insertAllData( + String tableName, + ArrayNode items, + Map<String, DataType> schema, + Map<DataType, DataType> dataTypeConversionMap) { List<String> columnNames = schema.keySet().stream().collect(Collectors.toList()); - List<String> quotedColumnNames = columnNames.stream().map(name -> "\"" + name + "\"").collect(Collectors.toList()); + List<String> quotedColumnNames = + columnNames.stream().map(name -> "\"" + name + "\"").collect(Collectors.toList()); StringBuilder insertQueryBuilder = new StringBuilder("INSERT INTO "); insertQueryBuilder.append(tableName); @@ -381,7 +401,12 @@ public void insertAllData(String tableName, ArrayNode items, Map<String, DataTyp // rows, execute the insert for rows so far and start afresh for the rest of the rows if (counter == 1000) { - insertReadyData(insertQueryBuilder.toString(), valuesMasterBuilder, inOrderValues, columnTypes, dataTypeConversionMap); + insertReadyData( + insertQueryBuilder.toString(), + valuesMasterBuilder, + inOrderValues, + columnTypes, + dataTypeConversionMap); // Reset the values builder and counter for new insert queries. valuesMasterBuilder = new StringBuilder(); counter = 0; @@ -424,7 +449,12 @@ public void insertAllData(String tableName, ArrayNode items, Map<String, DataTyp } if (valuesMasterBuilder.length() > 0) { - insertReadyData(insertQueryBuilder.toString(), valuesMasterBuilder, inOrderValues, columnTypes, dataTypeConversionMap); + insertReadyData( + insertQueryBuilder.toString(), + valuesMasterBuilder, + inOrderValues, + columnTypes, + dataTypeConversionMap); } } @@ -442,7 +472,12 @@ private void executeDbQuery(String query) { } } - private void insertReadyData(String partialInsertQuery, StringBuilder valuesBuilder, List<String> inOrderValues, List<DataType> columnTypes, Map<DataType, DataType> dataTypeConversionMap) { + private void insertReadyData( + String partialInsertQuery, + StringBuilder valuesBuilder, + List<String> inOrderValues, + List<DataType> columnTypes, + Map<DataType, DataType> dataTypeConversionMap) { Connection conn = checkAndGetConnection(); @@ -456,8 +491,15 @@ private void insertReadyData(String partialInsertQuery, StringBuilder valuesBuil int valueCounter = 0; while (valueCounter < inOrderValues.size()) { - for (int columnTypeCounter = 0; columnTypeCounter < columnTypes.size(); columnTypeCounter++, valueCounter++) { - setValueInStatement(preparedStatement, valueCounter + 1, inOrderValues.get(valueCounter), columnTypes.get(columnTypeCounter), dataTypeConversionMap); + for (int columnTypeCounter = 0; + columnTypeCounter < columnTypes.size(); + columnTypeCounter++, valueCounter++) { + setValueInStatement( + preparedStatement, + valueCounter + 1, + inOrderValues.get(valueCounter), + columnTypes.get(columnTypeCounter), + dataTypeConversionMap); } } @@ -465,7 +507,9 @@ private void insertReadyData(String partialInsertQuery, StringBuilder valuesBuil } catch (SQLException e) { e.printStackTrace(); - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, "Error in ingesting the data : " + e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, + "Error in ingesting the data : " + e.getMessage()); } } @@ -475,7 +519,9 @@ private Connection checkAndGetConnection() { connection = DriverManager.getConnection(URL); } } catch (SQLException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, "Failed to connect to the filtering database"); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, + "Failed to connect to the filtering database"); } return connection; @@ -517,7 +563,6 @@ public String generateTable(Map<String, DataType> schema) { sb.append("\"" + fieldName + "\""); sb.append(" "); sb.append(sqlDataType); - } sb.append(");"); @@ -527,7 +572,6 @@ public String generateTable(Map<String, DataType> schema) { executeDbQuery(createTableQuery); return tableName; - } public void dropTable(String tableName) { @@ -571,36 +615,36 @@ public Map<String, DataType> generateSchema(ArrayNode items, Map<DataType, DataT .map(n -> fieldNamesIterator.next()) .map(name -> { if (name.contains("\"") || name.contains("\'")) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "\' or \" are unsupported symbols in column names for filtering. Caused by column name : " + name); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "\' or \" are unsupported symbols in column names for filtering. Caused by column name : " + + name); } return name; }) .collect(Collectors.toMap( - Function.identity(), - name -> { - String value = item.get(name).asText(); - if (StringUtils.isEmpty(value)) { - missingColumnDataTypes.add(name); - // Default to string - return DataType.STRING; - } else { - DataType foundDataType = stringToKnownDataTypeConverter(value); - DataType convertedDataType = foundDataType; - if (!"rowIndex".equals(name) && dataTypeConversionMap != null) { - convertedDataType = dataTypeConversionMap.getOrDefault(foundDataType, foundDataType); - } - return convertedDataType; - } - }, - (u, v) -> { - // This is not possible. - throw new IllegalStateException(String.format("Duplicate key %s", u)); - }, - LinkedHashMap::new - ) - ); - + Function.identity(), + name -> { + String value = item.get(name).asText(); + if (StringUtils.isEmpty(value)) { + missingColumnDataTypes.add(name); + // Default to string + return DataType.STRING; + } else { + DataType foundDataType = stringToKnownDataTypeConverter(value); + DataType convertedDataType = foundDataType; + if (!"rowIndex".equals(name) && dataTypeConversionMap != null) { + convertedDataType = + dataTypeConversionMap.getOrDefault(foundDataType, foundDataType); + } + return convertedDataType; + } + }, + (u, v) -> { + // This is not possible. + throw new IllegalStateException(String.format("Duplicate key %s", u)); + }, + LinkedHashMap::new)); // Try to find the missing data type which has been initialized to String Set<String> columns = new HashSet(); @@ -644,11 +688,16 @@ private void setValueInStatement(PreparedStatement preparedStatement, int index, * @param dataTypeConversionMap - A Map to provide custom Datatype against the actual Datatype found. * @return */ - private PreparedStatement setValueInStatement(PreparedStatement preparedStatement, int index, String value, DataType topRowDataType, Map<DataType, DataType> dataTypeConversionMap) { + private PreparedStatement setValueInStatement( + PreparedStatement preparedStatement, + int index, + String value, + DataType topRowDataType, + Map<DataType, DataType> dataTypeConversionMap) { DataType dataType = topRowDataType; if (dataTypeConversionMap != null) { - //The input datatype will be converted to custom DatType as per implementing dataTypeConversionMap + // The input datatype will be converted to custom DatType as per implementing dataTypeConversionMap dataType = dataTypeConversionMap.getOrDefault(topRowDataType, topRowDataType); } @@ -662,14 +711,18 @@ private PreparedStatement setValueInStatement(PreparedStatement preparedStatemen DataType currentRowDataType = stringToKnownDataTypeConverter(value); DataType inputDataType = currentRowDataType; if (dataTypeConversionMap != null) { - //Datatype of each row be processed, expected to be consistent to column datatype (first row datatype). + // Datatype of each row be processed, expected to be consistent to column datatype (first row datatype). inputDataType = dataTypeConversionMap.getOrDefault(currentRowDataType, currentRowDataType); } if (DataType.NULL.equals(inputDataType)) { dataType = DataType.NULL; } - //We are setting incompatible datatypes of each row to Null, rather allowing it and exit with error. - if (dataTypeConversionMap != null && inputDataType != dataType && !datatypeCompatibilityMap.getOrDefault(dataType, Set.of()).contains(inputDataType)) { + // We are setting incompatible datatypes of each row to Null, rather allowing it and exit with error. + if (dataTypeConversionMap != null + && inputDataType != dataType + && !datatypeCompatibilityMap + .getOrDefault(dataType, Set.of()) + .contains(inputDataType)) { dataType = DataType.NULL; } } @@ -706,35 +759,38 @@ private PreparedStatement setValueInStatement(PreparedStatement preparedStatemen } catch (SQLException e) { // Alarm! This should never fail since appsmith is the creator of the query and supporter of it. Raise // an alarm and fix quickly! - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, "Error while interacting with value " + value + " : " + e.getMessage()); } catch (IllegalArgumentException e) { // The data type recognized does not match the data type of the value being set via Prepared Statement // Add proper handling here. - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, - "Error while interacting with value " + value + " : " + e.getMessage() + - ". The data type value was being parsed to was : " + dataType); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_IN_MEMORY_FILTERING_ERROR, + "Error while interacting with value " + value + " : " + e.getMessage() + + ". The data type value was being parsed to was : " + dataType); } return preparedStatement; } - public boolean validConditionList(List<Condition> conditionList, Map<String, DataType> schema) { - conditionList - .stream() + conditionList.stream() .map(condition -> { if (!Condition.isValid(condition)) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "Condition \" " + condition.getPath() + " " + condition.getOperator().toString() + " " - + condition.getValue() + " \" is incorrect and could not be parsed."); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "Condition \" " + condition.getPath() + " " + + condition.getOperator().toString() + " " + condition.getValue() + + " \" is incorrect and could not be parsed."); } String path = condition.getPath(); if (!schema.containsKey(path)) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, path + " not found in the known column names :" + schema.keySet()); } @@ -747,8 +803,11 @@ public boolean validConditionList(List<Condition> conditionList, Map<String, Dat return true; } - public String generateLogicalExpression(List<Condition> conditions, List<PreparedStatementValueDTO> values, - Map<String, DataType> schema, ConditionalOperator logicOp) { + public String generateLogicalExpression( + List<Condition> conditions, + List<PreparedStatementValueDTO> values, + Map<String, DataType> schema, + ConditionalOperator logicOp) { StringBuilder sb = new StringBuilder(); @@ -780,25 +839,26 @@ public String generateLogicalExpression(List<Condition> conditions, List<Prepare sb.append("\"" + path + "\""); sb.append(" "); if (Set.of( - ConditionalOperator.EQ, - ConditionalOperator.IN, - ConditionalOperator.CONTAINS, - ConditionalOperator.LTE, - ConditionalOperator.LT - ).contains(operator)) { + ConditionalOperator.EQ, + ConditionalOperator.IN, + ConditionalOperator.CONTAINS, + ConditionalOperator.LTE, + ConditionalOperator.LT) + .contains(operator)) { sb.append("IS NULL ) "); } else if (Set.of( - ConditionalOperator.NOT_IN, - ConditionalOperator.NOT_EQ, - ConditionalOperator.GTE, - ConditionalOperator.GT - ).contains(operator)) { + ConditionalOperator.NOT_IN, + ConditionalOperator.NOT_EQ, + ConditionalOperator.GTE, + ConditionalOperator.GT) + .contains(operator)) { sb.append("IS NOT NULL ) "); } } else { String sqlOp = SQL_OPERATOR_MAP.get(operator); if (sqlOp == null) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, operator + " is not supported currently for filtering."); } sb.append(" ( "); @@ -814,17 +874,18 @@ public String generateLogicalExpression(List<Condition> conditions, List<Prepare try { List<Object> arrayValues = objectMapper.readValue(value, List.class); - List<String> updatedStringValues = arrayValues - .stream() + List<String> updatedStringValues = arrayValues.stream() .map(fieldValue -> { - values.add(new PreparedStatementValueDTO(String.valueOf(fieldValue), schema.get(path))); + values.add(new PreparedStatementValueDTO( + String.valueOf(fieldValue), schema.get(path))); return "?"; }) .collect(Collectors.toList()); String finalValues = String.join(",", updatedStringValues); valueBuilder.append(finalValues); } catch (IOException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, value + " could not be parsed into an array"); } @@ -833,8 +894,7 @@ public String generateLogicalExpression(List<Condition> conditions, List<Prepare sb.append(value); } else if (operator == ConditionalOperator.CONTAINS) { - final String escapedLikeValue = value - .replace("!", "!!") + final String escapedLikeValue = value.replace("!", "!!") .replace("%", "!%") .replace("_", "!_") .replace("[", "!["); @@ -850,10 +910,7 @@ public String generateLogicalExpression(List<Condition> conditions, List<Prepare } } } - } return sb.toString(); } - } - diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/IFilterDataServiceCE.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/IFilterDataServiceCE.java index 5372894cd3e8..2e9a6f60dc23 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/IFilterDataServiceCE.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/IFilterDataServiceCE.java @@ -10,14 +10,18 @@ import java.util.List; import java.util.Map; - public interface IFilterDataServiceCE { ArrayNode filterDataNew(ArrayNode items, UQIDataFilterParams uqiDataFilterParams); - ArrayNode filterDataNew(ArrayNode items, UQIDataFilterParams uqiDataFilterParams, Map<DataType, DataType> dataTypeConversionMap); + ArrayNode filterDataNew( + ArrayNode items, UQIDataFilterParams uqiDataFilterParams, Map<DataType, DataType> dataTypeConversionMap); - void insertAllData(String tableName, ArrayNode items, Map<String, DataType> schema, Map<DataType, DataType> dataTypeConversionMap); + void insertAllData( + String tableName, + ArrayNode items, + Map<String, DataType> schema, + Map<DataType, DataType> dataTypeConversionMap); String generateTable(Map<String, DataType> schema); @@ -27,8 +31,9 @@ public interface IFilterDataServiceCE { boolean validConditionList(List<Condition> conditionList, Map<String, DataType> schema); - String generateLogicalExpression(List<Condition> conditions, List<PreparedStatementValueDTO> values, - Map<String, DataType> schema, ConditionalOperator logicOp); - + String generateLogicalExpression( + List<Condition> conditions, + List<PreparedStatementValueDTO> values, + Map<String, DataType> schema, + ConditionalOperator logicOp); } - diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java index d96492e87a2b..5df68082fe8f 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/util/WebClientUtils.java @@ -25,47 +25,37 @@ @Slf4j public class WebClientUtils { - private static final Set<String> DISALLOWED_HOSTS = Set.of( - "169.254.169.254", - "metadata.google.internal" - ); + private static final Set<String> DISALLOWED_HOSTS = Set.of("169.254.169.254", "metadata.google.internal"); public static final String HOST_NOT_ALLOWED = "Host not allowed."; - public static final ExchangeFilterFunction IP_CHECK_FILTER = ExchangeFilterFunction.ofRequestProcessor(request -> - DISALLOWED_HOSTS.contains(request.url().getHost()) + public static final ExchangeFilterFunction IP_CHECK_FILTER = ExchangeFilterFunction.ofRequestProcessor( + request -> DISALLOWED_HOSTS.contains(request.url().getHost()) ? Mono.error(new UnknownHostException(HOST_NOT_ALLOWED)) - : Mono.just(request) - ); + : Mono.just(request)); - private WebClientUtils() { - } + private WebClientUtils() {} public static WebClient create() { - return builder() - .build(); + return builder().build(); } public static WebClient create(ConnectionProvider provider) { - return builder(provider) - .build(); + return builder(provider).build(); } public static WebClient create(String baseUrl) { - return builder() - .baseUrl(baseUrl) - .build(); + return builder().baseUrl(baseUrl).build(); } public static WebClient create(String baseUrl, ConnectionProvider provider) { - return builder(provider) - .baseUrl(baseUrl) - .build(); + return builder(provider).baseUrl(baseUrl).build(); } private static boolean shouldUseSystemProxy() { return "true".equals(System.getProperty("java.net.useSystemProxies")) - && (!System.getProperty("http.proxyHost", "").isEmpty() || !System.getProperty("https.proxyHost", "").isEmpty()); + && (!System.getProperty("http.proxyHost", "").isEmpty() + || !System.getProperty("https.proxyHost", "").isEmpty()); } public static WebClient.Builder builder() { @@ -161,5 +151,4 @@ protected void doResolveAll(String inetHost, Promise<List<InetAddress>> promise) promise.setSuccess(addresses); } } - } diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/annotations/encryption/AppsmithTestSubDomainWithoutEncryption.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/annotations/encryption/AppsmithTestSubDomainWithoutEncryption.java index d84a46ba3c27..d99955d6b102 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/annotations/encryption/AppsmithTestSubDomainWithoutEncryption.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/annotations/encryption/AppsmithTestSubDomainWithoutEncryption.java @@ -1,10 +1,9 @@ package com.appsmith.external.annotations.encryption; import com.appsmith.external.models.AppsmithDomain; - import lombok.Data; @Data -public class AppsmithTestSubDomainWithoutEncryption implements AppsmithDomain { +public class AppsmithTestSubDomainWithoutEncryption implements AppsmithDomain { String notEncryptedInSubDomain; -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/annotations/encryption/EncryptionHandlerTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/annotations/encryption/EncryptionHandlerTest.java index e22afc703894..7baf592c2d74 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/annotations/encryption/EncryptionHandlerTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/annotations/encryption/EncryptionHandlerTest.java @@ -35,84 +35,91 @@ public void testFindCandidateFieldsForType_AllPossibleCombinations() { assertNotNull(candidateFieldsForType); // For encrypted string - final Optional<CandidateField> encryptedString = candidateFieldsForType - .stream() + final Optional<CandidateField> encryptedString = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.ANNOTATED_FIELD)) .findFirst(); assertTrue(encryptedString.isPresent()); assertEquals("encryptedInDomain", encryptedString.get().getField().getName()); // For encrypted subtype when the subtype is null - final Optional<CandidateField> encryptedSubDomainWithoutValue = candidateFieldsForType - .stream() + final Optional<CandidateField> encryptedSubDomainWithoutValue = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_FIELD_UNKNOWN)) .findFirst(); assertTrue(encryptedSubDomainWithoutValue.isPresent()); - assertEquals("encryptedSubDomainWithoutValue", encryptedSubDomainWithoutValue.get().getField().getName()); + assertEquals( + "encryptedSubDomainWithoutValue", + encryptedSubDomainWithoutValue.get().getField().getName()); // For encrypted subtype when the subtype is not null and has encrypted field - final Optional<CandidateField> encryptedSubDomainWithValue = candidateFieldsForType - .stream() + final Optional<CandidateField> encryptedSubDomainWithValue = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_FIELD_KNOWN)) .findFirst(); assertTrue(encryptedSubDomainWithValue.isPresent()); - assertEquals("encryptedSubDomainWithValue", encryptedSubDomainWithValue.get().getField().getName()); + assertEquals( + "encryptedSubDomainWithValue", + encryptedSubDomainWithValue.get().getField().getName()); // For encrypted subtype when the subtype is polymorphic - final Optional<CandidateField> polymorphicSubDomain = candidateFieldsForType - .stream() + final Optional<CandidateField> polymorphicSubDomain = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC)) .findFirst(); assertTrue(polymorphicSubDomain.isPresent()); - assertEquals("polymorphicSubDomain", polymorphicSubDomain.get().getField().getName()); + assertEquals( + "polymorphicSubDomain", polymorphicSubDomain.get().getField().getName()); // For encrypted list - final Optional<CandidateField> testSubDomainListWithElements = candidateFieldsForType - .stream() + final Optional<CandidateField> testSubDomainListWithElements = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_COLLECTION_KNOWN)) .findFirst(); assertTrue(testSubDomainListWithElements.isPresent()); - assertEquals("testSubDomainListWithElements", testSubDomainListWithElements.get().getField().getName()); + assertEquals( + "testSubDomainListWithElements", + testSubDomainListWithElements.get().getField().getName()); // For encrypted list when the list is polymorphic and null - final Optional<CandidateField> polymorphicSubDomainListWithoutElements = candidateFieldsForType - .stream() + final Optional<CandidateField> polymorphicSubDomainListWithoutElements = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)) .findFirst(); assertTrue(polymorphicSubDomainListWithoutElements.isPresent()); - assertEquals("polymorphicSubDomainListWithoutElements", polymorphicSubDomainListWithoutElements.get().getField().getName()); + assertEquals( + "polymorphicSubDomainListWithoutElements", + polymorphicSubDomainListWithoutElements.get().getField().getName()); // For encrypted list when the list is polymorphic and null - final Optional<CandidateField> polymorphicSubDomainListWithElements = candidateFieldsForType - .stream() + final Optional<CandidateField> polymorphicSubDomainListWithElements = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)) .findFirst(); assertTrue(polymorphicSubDomainListWithElements.isPresent()); - assertEquals("polymorphicSubDomainListWithElements", polymorphicSubDomainListWithElements.get().getField().getName()); + assertEquals( + "polymorphicSubDomainListWithElements", + polymorphicSubDomainListWithElements.get().getField().getName()); // For encrypted map - final Optional<CandidateField> testSubDomainMapWithElements = candidateFieldsForType - .stream() + final Optional<CandidateField> testSubDomainMapWithElements = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_MAP_KNOWN)) .findFirst(); assertTrue(testSubDomainMapWithElements.isPresent()); - assertEquals("testSubDomainMapWithElements", testSubDomainMapWithElements.get().getField().getName()); + assertEquals( + "testSubDomainMapWithElements", + testSubDomainMapWithElements.get().getField().getName()); // For encrypted map when the map is polymorphic and null - final Optional<CandidateField> polymorphicSubDomainMapWithoutElements = candidateFieldsForType - .stream() + final Optional<CandidateField> polymorphicSubDomainMapWithoutElements = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_MAP_UNKNOWN)) .findFirst(); assertTrue(polymorphicSubDomainMapWithoutElements.isPresent()); - assertEquals("polymorphicSubDomainMapWithoutElements", polymorphicSubDomainMapWithoutElements.get().getField().getName()); + assertEquals( + "polymorphicSubDomainMapWithoutElements", + polymorphicSubDomainMapWithoutElements.get().getField().getName()); // For encrypted map when the map is polymorphic and not null - final Optional<CandidateField> polymorphicSubDomainMapWithElements = candidateFieldsForType - .stream() + final Optional<CandidateField> polymorphicSubDomainMapWithElements = candidateFieldsForType.stream() .filter(x -> x.getType().equals(CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)) .findFirst(); assertTrue(polymorphicSubDomainMapWithElements.isPresent()); - assertEquals("polymorphicSubDomainMapWithElements", polymorphicSubDomainMapWithElements.get().getField().getName()); + assertEquals( + "polymorphicSubDomainMapWithElements", + polymorphicSubDomainMapWithElements.get().getField().getName()); assertEquals(10, candidateFieldsForType.size()); } @@ -161,13 +168,29 @@ public void testConvertEncryption_AllPossibleCombinations() { assertEquals("Encrypted-String", testDomain.getEncryptedInDomain()); assertEquals("String", testDomain.getNotEncrypted()); assertEquals("String", testDomain.getTestSubDomainWithoutEncryption().getNotEncryptedInSubDomain()); - assertEquals("Encrypted-String", testDomain.getEncryptedSubDomainWithValue().getEncryptedInSubDomain()); - assertEquals("Encrypted-String", ((PolymorphicSubdomain1) testDomain.getPolymorphicSubDomain()).getEncryptedInPolymorphicSubdomain1()); - assertEquals("Encrypted-String", testDomain.getTestSubDomainListWithElements().get(0).getEncryptedInSubDomain()); - assertEquals("Encrypted-String", ((PolymorphicSubdomain1) testDomain.getPolymorphicSubDomainListWithElements().get(0)).getEncryptedInPolymorphicSubdomain1()); - assertEquals("Encrypted-String", testDomain.getTestSubDomainMapWithElements().get("Test1").getEncryptedInSubDomain()); - assertEquals("Encrypted-String", ((PolymorphicSubdomain1) testDomain.getPolymorphicSubDomainMapWithElements().get("Test2")).getEncryptedInPolymorphicSubdomain1()); - + assertEquals( + "Encrypted-String", testDomain.getEncryptedSubDomainWithValue().getEncryptedInSubDomain()); + assertEquals( + "Encrypted-String", + ((PolymorphicSubdomain1) testDomain.getPolymorphicSubDomain()).getEncryptedInPolymorphicSubdomain1()); + assertEquals( + "Encrypted-String", + testDomain.getTestSubDomainListWithElements().get(0).getEncryptedInSubDomain()); + assertEquals( + "Encrypted-String", + ((PolymorphicSubdomain1) testDomain + .getPolymorphicSubDomainListWithElements() + .get(0)) + .getEncryptedInPolymorphicSubdomain1()); + assertEquals( + "Encrypted-String", + testDomain.getTestSubDomainMapWithElements().get("Test1").getEncryptedInSubDomain()); + assertEquals( + "Encrypted-String", + ((PolymorphicSubdomain1) testDomain + .getPolymorphicSubDomainMapWithElements() + .get("Test2")) + .getEncryptedInPolymorphicSubdomain1()); } @Test @@ -179,16 +202,17 @@ public void testConvertEncryption_EmptySetFirstWithNonEncryptedFields() { testDomain.setSet(new HashSet<>()); boolean b = encryptionHandler.convertEncryption(testDomain, "Encrypted-"::concat); - assertTrue(b); //First time field will be detected as APPSMITH_COLLECTION_UNKNOWN + assertTrue(b); // First time field will be detected as APPSMITH_COLLECTION_UNKNOWN - AppsmithTestSubDomainWithoutEncryption testSubDomainWithoutEncryption = new AppsmithTestSubDomainWithoutEncryption(); + AppsmithTestSubDomainWithoutEncryption testSubDomainWithoutEncryption = + new AppsmithTestSubDomainWithoutEncryption(); testSubDomainWithoutEncryption.setNotEncryptedInSubDomain("String"); testDomain.setSet(new HashSet<>()); testDomain.getSet().add(testSubDomainWithoutEncryption); b = encryptionHandler.convertEncryption(testDomain, "Encrypted-"::concat); - assertFalse(b); //Second time field will be removed from cache but returns true + assertFalse(b); // Second time field will be removed from cache but returns true } @Test @@ -197,7 +221,8 @@ public void testConvertEncryption_FilledSetFirstWithNonEncryptedFields() { TestDomainWithSet testDomain = new TestDomainWithSet(); - AppsmithTestSubDomainWithoutEncryption testSubDomainWithoutEncryption = new AppsmithTestSubDomainWithoutEncryption(); + AppsmithTestSubDomainWithoutEncryption testSubDomainWithoutEncryption = + new AppsmithTestSubDomainWithoutEncryption(); testSubDomainWithoutEncryption.setNotEncryptedInSubDomain("String"); testDomain.setSet(new HashSet<>()); @@ -212,8 +237,7 @@ public void testConvertEncryption_FilledSetFirstWithNonEncryptedFields() { static class TestDomain implements AppsmithDomain { // For an annotated field, we should straight up recognize this as an encrypted type - @Encrypted - String encryptedInDomain; + @Encrypted String encryptedInDomain; // For non-Appsmith types that are not annotated, we should skip the fields String notEncrypted; @@ -236,7 +260,8 @@ static class TestDomain implements AppsmithDomain { // For lists of Appsmith types that have encrypted fields, we should recognize it as a known list List<TestSubDomain> testSubDomainListWithElements; - // For lists of Appsmith types (polymorphic or not) that do not have any elements, we should recognize it as unknown list types + // For lists of Appsmith types (polymorphic or not) that do not have any elements, we should recognize it as + // unknown list types List<PolymorphicSubDomain> polymorphicSubDomainListWithoutElements; // For lists of polymorphic Appsmith types that have elements, we should recognize it as polymorphic list types @@ -248,7 +273,8 @@ static class TestDomain implements AppsmithDomain { // For maps of Appsmith types that have encrypted fields, we should recognize it as a known map Map<String, TestSubDomain> testSubDomainMapWithElements; - // For maps of Appsmith types (polymorphic or not) that do not have any elements, we should recognize it as unknown map types + // For maps of Appsmith types (polymorphic or not) that do not have any elements, we should recognize it as + // unknown map types Map<String, PolymorphicSubDomain> polymorphicSubDomainMapWithoutElements; // For maps of polymorphic Appsmith types that have elements, we should recognize it as polymorphic map types @@ -271,7 +297,7 @@ static class TestDomain implements AppsmithDomain { @Getter @Setter static class TestDomainWithSet implements AppsmithDomain { - //this list will be created innitially empty + // this list will be created innitially empty Set<AppsmithTestSubDomainWithoutEncryption> set; } @@ -285,18 +311,15 @@ static class TestSubDomainWithoutEncryption implements AppsmithDomain { @Setter static class TestSubDomain implements AppsmithDomain { - @Encrypted - String encryptedInSubDomain; + @Encrypted String encryptedInSubDomain; } - static abstract class PolymorphicSubDomain implements AppsmithDomain { - } + abstract static class PolymorphicSubDomain implements AppsmithDomain {} @Getter @Setter static class PolymorphicSubdomain1 extends PolymorphicSubDomain { - @Encrypted - String encryptedInPolymorphicSubdomain1; + @Encrypted String encryptedInPolymorphicSubdomain1; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/ApiKeyAuthenticationTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/ApiKeyAuthenticationTest.java index 3ffc94736b1e..7bf146fd4f83 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/ApiKeyAuthenticationTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/ApiKeyAuthenticationTest.java @@ -25,4 +25,4 @@ public void testCreateMethodWithQueryParamsLabel() { }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/BasicAuthenticationTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/BasicAuthenticationTest.java index 7457a8215df0..fb1d1e071f3b 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/BasicAuthenticationTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/BasicAuthenticationTest.java @@ -24,4 +24,4 @@ public void testCreate_validCredentials_ReturnsWithEncodedValue() { Base64.getEncoder().encodeToString("test:password".getBytes(StandardCharsets.UTF_8)), connection.getEncodedAuthorizationHeader()); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/BearerTokenAuthenticationTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/BearerTokenAuthenticationTest.java index c46da681a113..181e4a4b9fea 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/BearerTokenAuthenticationTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/BearerTokenAuthenticationTest.java @@ -23,4 +23,4 @@ public void testCreateMethod() { }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/OAuth2ClientCredentialsTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/OAuth2ClientCredentialsTest.java index 45df948f8afb..d9793b99da56 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/OAuth2ClientCredentialsTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/connections/OAuth2ClientCredentialsTest.java @@ -62,7 +62,8 @@ public void testValidConnection() { authenticationResponse.setToken("SomeToken"); authenticationResponse.setExpiresAt(Instant.now().plusSeconds(1200)); oAuth2.setAuthenticationResponse(authenticationResponse); - OAuth2ClientCredentials connection = OAuth2ClientCredentials.create(datasourceConfiguration).block(Duration.ofMillis(100)); + OAuth2ClientCredentials connection = + OAuth2ClientCredentials.create(datasourceConfiguration).block(Duration.ofMillis(100)); assertThat(connection).isNotNull(); assertThat(connection.getExpiresAt()).isEqualTo(authenticationResponse.getExpiresAt()); assertThat(connection.getToken()).isEqualTo("SomeToken"); @@ -78,13 +79,14 @@ public void testStaleFilter() { authenticationResponse.setToken("SomeToken"); authenticationResponse.setExpiresAt(Instant.now().plusSeconds(1200)); oAuth2.setAuthenticationResponse(authenticationResponse); - OAuth2ClientCredentials connection = OAuth2ClientCredentials.create(datasourceConfiguration).block(Duration.ofMillis(100)); + OAuth2ClientCredentials connection = + OAuth2ClientCredentials.create(datasourceConfiguration).block(Duration.ofMillis(100)); connection.setExpiresAt(Instant.now()); - Mono<ClientResponse> response = connection.filter(Mockito.mock(ClientRequest.class), Mockito.mock(ExchangeFunction.class)); + Mono<ClientResponse> response = + connection.filter(Mockito.mock(ClientRequest.class), Mockito.mock(ExchangeFunction.class)); - StepVerifier.create(response) - .expectError(StaleConnectionException.class); + StepVerifier.create(response).expectError(StaleConnectionException.class); } @Test @@ -100,12 +102,10 @@ public void testCreate_withIsAuthorizationHeaderTrue_sendsCredentialsInHeader() oAuth2.setClientId("testId"); oAuth2.setClientSecret("testSecret"); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); - final OAuth2ClientCredentials response = OAuth2ClientCredentials.create(datasourceConfiguration).block(); + final OAuth2ClientCredentials response = + OAuth2ClientCredentials.create(datasourceConfiguration).block(); final RecordedRequest recordedRequest = mockEndpoint.takeRequest(30, TimeUnit.SECONDS); final String authorizationHeader = recordedRequest.getHeader("Authorization"); @@ -114,7 +114,8 @@ public void testCreate_withIsAuthorizationHeaderTrue_sendsCredentialsInHeader() } @Test - public void testCreate_withIsAuthorizationHeaderFalse_sendsCredentialsInBody() throws InterruptedException, EOFException { + public void testCreate_withIsAuthorizationHeaderFalse_sendsCredentialsInBody() + throws InterruptedException, EOFException { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); final DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); @@ -125,12 +126,10 @@ public void testCreate_withIsAuthorizationHeaderFalse_sendsCredentialsInBody() t oAuth2.setClientId("testId"); oAuth2.setClientSecret("testSecret"); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); - final OAuth2ClientCredentials response = OAuth2ClientCredentials.create(datasourceConfiguration).block(); + final OAuth2ClientCredentials response = + OAuth2ClientCredentials.create(datasourceConfiguration).block(); final RecordedRequest recordedRequest = mockEndpoint.takeRequest(30, TimeUnit.SECONDS); final String authorizationHeader = recordedRequest.getHeader("Authorization"); diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/AppsmithBeanUtilsTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/AppsmithBeanUtilsTest.java index 4fd7df6cc7d0..ab2e75f12ab1 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/AppsmithBeanUtilsTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/AppsmithBeanUtilsTest.java @@ -28,7 +28,8 @@ static class Person { } enum Gender { - Male, Female + Male, + Female } @Test @@ -36,14 +37,7 @@ public void copyProperties() { Person source = new Person(); source.setAge(30); - Person target = new Person( - "Luke", - 25, - true, - LocalDate.of(2000, 1, 1), - Gender.Male, - null - ); + Person target = new Person("Luke", 25, true, LocalDate.of(2000, 1, 1), Gender.Male, null); AppsmithBeanUtils.copyNestedNonNullProperties(source, target); assertThat(target.getName()).isEqualTo("Luke"); @@ -65,15 +59,7 @@ public void copyNestedProperty() { true, LocalDate.of(2000, 1, 1), Gender.Male, - new Person( - "Leia", - 25, - true, - LocalDate.of(2000, 1, 1), - Gender.Male, - null - ) - ); + new Person("Leia", 25, true, LocalDate.of(2000, 1, 1), Gender.Male, null)); AppsmithBeanUtils.copyNestedNonNullProperties(source, target); assertThat(target.getName()).isEqualTo("Luke"); @@ -87,14 +73,7 @@ public void copyNestedPropertyWithTargetNull() { mentor.setName("The new mentor name"); source.setMentor(mentor); - Person target = new Person( - "Luke", - 25, - true, - LocalDate.of(2000, 1, 1), - Gender.Male, - null - ); + Person target = new Person("Luke", 25, true, LocalDate.of(2000, 1, 1), Gender.Male, null); AppsmithBeanUtils.copyNestedNonNullProperties(source, target); assertThat(target.getName()).isEqualTo("Luke"); @@ -106,14 +85,7 @@ public void copyEnumValue() { Person source = new Person(); source.setGender(Gender.Female); - Person target = new Person( - "Luke", - 25, - true, - LocalDate.of(2000, 1, 1), - Gender.Male, - null - ); + Person target = new Person("Luke", 25, true, LocalDate.of(2000, 1, 1), Gender.Male, null); AppsmithBeanUtils.copyNestedNonNullProperties(source, target); assertThat(target.getName()).isEqualTo("Luke"); @@ -122,5 +94,4 @@ public void copyEnumValue() { assertThat(target.getJoinDate()).isEqualTo(LocalDate.of(2000, 1, 1)); assertThat(target.getGender()).isEqualTo(Gender.Female); } - } diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataTypeStringUtilsTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataTypeStringUtilsTest.java index e43e5e860a11..ff1a5aa60f7f 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataTypeStringUtilsTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataTypeStringUtilsTest.java @@ -19,7 +19,6 @@ import static com.appsmith.external.helpers.DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue; import static org.assertj.core.api.Assertions.assertThat; - public class DataTypeStringUtilsTest { @Test @@ -79,17 +78,16 @@ public void checkSimpleArrayDataType() { @Test public void checkArrayOfObjectsDataType() { - String arrayData = "[\n" + - " {\n" + - " \"key1\": \"value\"\n" + - " },\n" + - " {\n" + - " \"key2\": \"value\"\n" + - " },\n" + - " {\n" + - " \"key3\": \"value\"\n" + - " }\n" + - "]"; + String arrayData = "[\n" + " {\n" + + " \"key1\": \"value\"\n" + + " },\n" + + " {\n" + + " \"key2\": \"value\"\n" + + " },\n" + + " {\n" + + " \"key3\": \"value\"\n" + + " }\n" + + "]"; AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, arrayData); DataType dataType = appsmithType.type(); @@ -98,9 +96,7 @@ public void checkArrayOfObjectsDataType() { @Test public void checkJsonDataType() { - String jsonData = "{\n" + - " \"key1\": \"value\"\n" + - "}"; + String jsonData = "{\n" + " \"key1\": \"value\"\n" + "}"; AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, jsonData); DataType dataType = appsmithType.type(); @@ -120,45 +116,94 @@ public void checkNullDataType() { public void testJsonStrictParsing() { // https://static.javadoc.io/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html#setLenient-boolean- // Streams that start with the non-execute prefix, ")]}'\n". - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"){}").type()); - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"]{}").type()); - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"}{}").type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "){}") + .type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "]{}") + .type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "}{}") + .type()); // Top-level values of any type. With strict parsing, the top-level value must be an object or an array. - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"").type()); - assertThat(DataType.NULL).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.NULL,"null").type()); - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"Abracadabra").type()); - assertThat(DataType.INTEGER).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER,"13").type()); - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"\"literal\"").type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "") + .type()); + assertThat(DataType.NULL) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.NULL, "null") + .type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "Abracadabra") + .type()); + assertThat(DataType.INTEGER) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, "13") + .type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "\"literal\"") + .type()); // End of line comments starting with // or # and ending with a newline character. - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"{//comment\n}").type()); - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"{#comment\n}").type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{//comment\n}") + .type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{#comment\n}") + .type()); // C-style comments starting with /* and ending with */. Such comments may not be nested. - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"{/*comment*/}").type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{/*comment*/}") + .type()); // Strings that are unquoted or 'single quoted'. - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"{\"a\": str}").type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\": str}") + .type()); // Array elements separated by ; instead of ,. - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"{\"a\": [1;2]}").type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\": [1;2]}") + .type()); // Unnecessary array separators. These are interpreted as if null was the omitted value. // Names and values separated by = or => instead of :. - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"{\"a\" = 13}").type()); - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"{\"a\" => 13}").type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\" = 13}") + .type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\" => 13}") + .type()); // Name/value pairs separated by ; instead of ,. - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING,"{\"a\": 1; \"b\": 2}").type()); - - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\": }").type()); - assertThat(DataType.STRING).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\": ,}").type()); - - assertThat(DataType.JSON_OBJECT).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{} ").type()); - assertThat(DataType.JSON_OBJECT).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": null} \n \n").type()); - assertThat(DataType.JSON_OBJECT).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": 0}").type()); - assertThat(DataType.JSON_OBJECT).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": \"\"}").type()); - assertThat(DataType.JSON_OBJECT).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": []}").type()); - assertThat(DataType.ARRAY).isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, "[]").type()); + assertThat(DataType.STRING) + .isEqualByComparingTo( + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\": 1; \"b\": 2}") + .type()); + + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\": }") + .type()); + assertThat(DataType.STRING) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, "{\"a\": ,}") + .type()); + + assertThat(DataType.JSON_OBJECT) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{} ") + .type()); + assertThat(DataType.JSON_OBJECT) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": null} \n \n") + .type()); + assertThat(DataType.JSON_OBJECT) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": 0}") + .type()); + assertThat(DataType.JSON_OBJECT) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": \"\"}") + .type()); + assertThat(DataType.JSON_OBJECT) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": []}") + .type()); + assertThat(DataType.ARRAY) + .isEqualByComparingTo(DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, "[]") + .type()); } @Test @@ -173,7 +218,8 @@ public void testGetDisplayDataTypes_withNestedObjectsInList_returnsWithTable() { data.add(objectMap); final List<ParsedDataType> displayDataTypes = getDisplayDataTypes(data); - assertThat(displayDataTypes).anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE)); + assertThat(displayDataTypes) + .anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE)); } @Test @@ -188,7 +234,8 @@ public void testGetDisplayDataTypes_withNestedObjectsInArrayNode_returnsWithTabl data.add(objectNode); final List<ParsedDataType> displayDataTypes = getDisplayDataTypes(data); - assertThat(displayDataTypes).anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE)); + assertThat(displayDataTypes) + .anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE)); } @Test @@ -203,24 +250,20 @@ public void testGetDisplayDataTypes_withNestedObjectsInString_returnsWithTable() data.add(objectNode); final List<ParsedDataType> displayDataTypes = getDisplayDataTypes(data.toString()); - assertThat(displayDataTypes).anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE)); + assertThat(displayDataTypes) + .anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE)); } @Test - public void testJsonSmartReplacementPlaceholderWithValue_withReplacementDataTypeArray_returnsCorrectMultilineString() { + public void + testJsonSmartReplacementPlaceholderWithValue_withReplacementDataTypeArray_returnsCorrectMultilineString() { final String input = "#_appsmith_placeholder#"; final String replacement = "[{\"Address\":\"Line1.\\nLine2.\\nLine3\"}]"; List<Map.Entry<String, String>> insertedParams = (List) new ArrayList<>(); final String replacedValue = jsonSmartReplacementPlaceholderWithValue( - input, - replacement, - DataType.ARRAY, - insertedParams, - null, - null - ); + input, replacement, DataType.ARRAY, insertedParams, null, null); final String expectedValue = "[{\"Address\":\"Line1.\\nLine2.\\nLine3\"}]"; assertThat(expectedValue).isEqualTo(replacedValue); } diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataUtilsTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataUtilsTest.java index f00c9055a310..7ab815f9d246 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataUtilsTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataUtilsTest.java @@ -47,7 +47,6 @@ public class DataUtilsTest { private Map<String, Object> hints; - @BeforeEach public void createContext() { final List<HttpMessageWriter<?>> messageWriters = new ArrayList<>(); @@ -122,18 +121,16 @@ public void testParseMultipartFileData_withValidTextList_returnsExpectedBody() { dataBuffer.read(resultBytes); DataBufferUtils.release(dataBuffer); String content = new String(resultBytes, StandardCharsets.UTF_8); - assertTrue(content.contains( - "Content-Disposition: form-data; name=\"nullType\"\r\n" + - "Content-Type: text/plain;charset=UTF-8\r\n" + - "Content-Length: 8\r\n" + - "\r\n" + - "textData")); + assertTrue(content.contains("Content-Disposition: form-data; name=\"nullType\"\r\n" + + "Content-Type: text/plain;charset=UTF-8\r\n" + + "Content-Length: 8\r\n" + + "\r\n" + + "textData")); assertTrue(content.contains("Content-Type: text/plain")); assertTrue(content.contains( - "Content-Disposition: form-data; name=\"textType\"\r\n" + - "Content-Length: 8\r\n" + - "\r\n" + - "textData")); + "Content-Disposition: form-data; name=\"textType\"\r\n" + "Content-Length: 8\r\n" + + "\r\n" + + "textData")); }) .expectComplete() .verify(); @@ -142,7 +139,8 @@ public void testParseMultipartFileData_withValidTextList_returnsExpectedBody() { @Test public void testParseMultipartFileData_withValidFileList_returnsExpectedBody() { List<Property> properties = new ArrayList<>(); - final Property p1 = new Property("fileType", "{\"name\": \"test.json\", \"type\": \"application/json\", \"data\" : {}}"); + final Property p1 = + new Property("fileType", "{\"name\": \"test.json\", \"type\": \"application/json\", \"data\" : {}}"); p1.setType("file"); properties.add(p1); @@ -159,10 +157,10 @@ public void testParseMultipartFileData_withValidFileList_returnsExpectedBody() { DataBufferUtils.release(dataBuffer); String content = new String(resultBytes, StandardCharsets.UTF_8); assertTrue(content.contains( - "Content-Disposition: form-data; name=\"fileType\"; filename=\"test.json\"\r\n" + - "Content-Type: application/json\r\n" + - "\r\n" + - "{}")); + "Content-Disposition: form-data; name=\"fileType\"; filename=\"test.json\"\r\n" + + "Content-Type: application/json\r\n" + + "\r\n" + + "{}")); }) .expectComplete() .verify(); @@ -171,7 +169,9 @@ public void testParseMultipartFileData_withValidFileList_returnsExpectedBody() { @Test public void testParseMultipartFileData_withValidMultipleFileList_returnsExpectedBody() { List<Property> properties = new ArrayList<>(); - final Property p1 = new Property("fileType", "[{\"name\": \"test1.json\", \"type\": \"application/json\", \"data\" : {}}, {\"name\": \"test2.json\", \"type\": \"application/json\", \"data\" : {}}]"); + final Property p1 = new Property( + "fileType", + "[{\"name\": \"test1.json\", \"type\": \"application/json\", \"data\" : {}}, {\"name\": \"test2.json\", \"type\": \"application/json\", \"data\" : {}}]"); p1.setType("file"); properties.add(p1); @@ -188,25 +188,25 @@ public void testParseMultipartFileData_withValidMultipleFileList_returnsExpected DataBufferUtils.release(dataBuffer); String content = new String(resultBytes, StandardCharsets.UTF_8); assertTrue(content.contains( - "Content-Disposition: form-data; name=\"fileType\"; filename=\"test1.json\"\r\n" + - "Content-Type: application/json\r\n" + - "\r\n" + - "{}")); + "Content-Disposition: form-data; name=\"fileType\"; filename=\"test1.json\"\r\n" + + "Content-Type: application/json\r\n" + + "\r\n" + + "{}")); assertTrue(content.contains( - "Content-Disposition: form-data; name=\"fileType\"; filename=\"test2.json\"\r\n" + - "Content-Type: application/json\r\n" + - "\r\n" + - "{}")); + "Content-Disposition: form-data; name=\"fileType\"; filename=\"test2.json\"\r\n" + + "Content-Type: application/json\r\n" + + "\r\n" + + "{}")); }) .expectComplete() .verify(); } @Test - public void testParseFormData_withEncodingParamsToggleTrue_returnsEncodedString() throws UnsupportedEncodingException { - final String encoded_value = dataUtils.parseFormData(List.of(new Property("key", "valüe")), - true); + public void testParseFormData_withEncodingParamsToggleTrue_returnsEncodedString() + throws UnsupportedEncodingException { + final String encoded_value = dataUtils.parseFormData(List.of(new Property("key", "valüe")), true); String expected_value = null; try { expected_value = "key=" + URLEncoder.encode("valüe", StandardCharsets.UTF_8.toString()); @@ -217,9 +217,9 @@ public void testParseFormData_withEncodingParamsToggleTrue_returnsEncodedString( } @Test - public void testParseFormData_withoutEncodingParamsToggleTrue_returnsEncodedString() throws UnsupportedEncodingException { - final String encoded_value = dataUtils.parseFormData(List.of(new Property("key", "valüe")), - false); + public void testParseFormData_withoutEncodingParamsToggleTrue_returnsEncodedString() + throws UnsupportedEncodingException { + final String encoded_value = dataUtils.parseFormData(List.of(new Property("key", "valüe")), false); String expected_value; try { expected_value = "key=" + URLEncoder.encode("valüe", StandardCharsets.UTF_8.toString()); @@ -231,8 +231,8 @@ public void testParseFormData_withoutEncodingParamsToggleTrue_returnsEncodedStri @Test public void testParseFormData_withNullKeys_skipsNullProperty() { - final String encoded_value = dataUtils.parseFormData(List.of(new Property(null, "v1"), new Property("k2", "v2")), - false); + final String encoded_value = + dataUtils.parseFormData(List.of(new Property(null, "v1"), new Property("k2", "v2")), false); assertEquals("k2=v2", encoded_value); } @@ -289,25 +289,24 @@ public void testParseMultipartArrayDataWorks() { dataBuffer.read(resultBytes); DataBufferUtils.release(dataBuffer); String content = new String(resultBytes, StandardCharsets.UTF_8); - Assertions.assertThat(content).containsSubsequence( - "Content-Disposition: form-data; name=\"arrayOne\"", - "1", - "Content-Disposition: form-data; name=\"arrayOne\"", - "2", - "Content-Disposition: form-data; name=\"arrayOne\"", - "3", - "Content-Disposition: form-data; name=\"listOne\"", - "four", - "Content-Disposition: form-data; name=\"listOne\"", - "five", - "Content-Disposition: form-data; name=\"listTwo\"", - "6", - "Content-Disposition: form-data; name=\"listTwo\"", - "7" - ); + Assertions.assertThat(content) + .containsSubsequence( + "Content-Disposition: form-data; name=\"arrayOne\"", + "1", + "Content-Disposition: form-data; name=\"arrayOne\"", + "2", + "Content-Disposition: form-data; name=\"arrayOne\"", + "3", + "Content-Disposition: form-data; name=\"listOne\"", + "four", + "Content-Disposition: form-data; name=\"listOne\"", + "five", + "Content-Disposition: form-data; name=\"listTwo\"", + "6", + "Content-Disposition: form-data; name=\"listTwo\"", + "7"); }) .expectComplete() .verify(); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/MustacheHelperTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/MustacheHelperTest.java index a263afcd3553..04c62cfb5617 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/MustacheHelperTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/MustacheHelperTest.java @@ -26,9 +26,9 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings( - // Disabling this so we may use `Arrays.asList` with single argument, which is easier to refactor, just for tests. - "ArraysAsListWithZeroOrOneArgument" -) + // Disabling this so we may use `Arrays.asList` with single argument, which is easier to refactor, just for + // tests. + "ArraysAsListWithZeroOrOneArgument") public class MustacheHelperTest { private void checkTokens(String template, List<MustacheBindingToken> expected) { @@ -39,7 +39,8 @@ private void checkKeys(String template, Set<MustacheBindingToken> expected) { assertThat(extractMustacheKeys(template)).isEqualTo(expected); } - private void check(String template, List<MustacheBindingToken> expectedTokens, Set<MustacheBindingToken> expectedKeys) { + private void check( + String template, List<MustacheBindingToken> expectedTokens, Set<MustacheBindingToken> expectedKeys) { if (expectedTokens != null) { checkTokens(template, expectedTokens); } @@ -48,8 +49,12 @@ private void check(String template, List<MustacheBindingToken> expectedTokens, S } } - private AbstractCollectionAssert<?, Collection<? extends MustacheBindingToken>, MustacheBindingToken, ObjectAssert<MustacheBindingToken>> - assertKeys(Object object) { + private AbstractCollectionAssert< + ?, + Collection<? extends MustacheBindingToken>, + MustacheBindingToken, + ObjectAssert<MustacheBindingToken>> + assertKeys(Object object) { return assertThat(extractMustacheKeysFromFields(object)); } @@ -86,29 +91,23 @@ public void realWorldText1() { new MustacheBindingToken(", the status for your order id ", 6, false), new MustacheBindingToken("{{orderId}}", 54, true), new MustacheBindingToken(" is ", 54, false), - new MustacheBindingToken("{{status}}", 69, true) - ) - ); + new MustacheBindingToken("{{status}}", 69, true))); checkKeys( "Hello {{Customer.Name}}, the status for your order id {{orderId}} is {{status}}", Set.of( new MustacheBindingToken("Customer.Name", 8, false), new MustacheBindingToken("orderId", 56, false), - new MustacheBindingToken("status", 71, false) - ) - ); + new MustacheBindingToken("status", 71, false))); } @Test public void realWorldText2() { checkTokens( "{{data.map(datum => {return {id: datum}})}}", - Arrays.asList(new MustacheBindingToken("{{data.map(datum => {return {id: datum}})}}", 0, true)) - ); + Arrays.asList(new MustacheBindingToken("{{data.map(datum => {return {id: datum}})}}", 0, true))); checkKeys( "{{data.map(datum => {return {id: datum}})}}", - Set.of(new MustacheBindingToken("data.map(datum => {return {id: datum}})", 2, false)) - ); + Set.of(new MustacheBindingToken("data.map(datum => {return {id: datum}})", 2, false))); } @Test @@ -119,17 +118,21 @@ public void braceDances1() { new MustacheBindingToken("{{}}", 0, true), new MustacheBindingToken("{{}}", 4, true), new MustacheBindingToken("}", 4, false)), - Set.of(new MustacheBindingToken("", 2, false), - new MustacheBindingToken("", 6, false)) - ); + Set.of(new MustacheBindingToken("", 2, false), new MustacheBindingToken("", 6, false))); - check("{{{}}", Arrays.asList(new MustacheBindingToken("{{{}}", 0, false)), Set.of(new MustacheBindingToken("{", 2, false))); + check( + "{{{}}", + Arrays.asList(new MustacheBindingToken("{{{}}", 0, false)), + Set.of(new MustacheBindingToken("{", 2, false))); check("{{ {{", Arrays.asList(new MustacheBindingToken("{{ {{", 0, false)), Set.of()); check("}} }}", Arrays.asList(new MustacheBindingToken("}} }}", 0, false)), Set.of()); - check("}} {{", Arrays.asList(new MustacheBindingToken("}} ", 0, false), new MustacheBindingToken("{{", 3, false)), Set.of()); + check( + "}} {{", + Arrays.asList(new MustacheBindingToken("}} ", 0, false), new MustacheBindingToken("{{", 3, false)), + Set.of()); } @Test @@ -137,18 +140,15 @@ public void quotedStrings() { check( "{{ 'abc def'.toUpperCase() }}", Arrays.asList(new MustacheBindingToken("{{ 'abc def'.toUpperCase() }}", 0, true)), - Set.of(new MustacheBindingToken(" 'abc def'.toUpperCase() ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'abc def'.toUpperCase() ", 2, false))); check( "{{ \"abc def\".toUpperCase() }}", Arrays.asList(new MustacheBindingToken("{{ \"abc def\".toUpperCase() }}", 0, true)), - Set.of(new MustacheBindingToken(" \"abc def\".toUpperCase() ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"abc def\".toUpperCase() ", 2, false))); check( "{{ `abc def`.toUpperCase() }}", Arrays.asList(new MustacheBindingToken("{{ `abc def`.toUpperCase() }}", 0, true)), - Set.of(new MustacheBindingToken(" `abc def`.toUpperCase() ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `abc def`.toUpperCase() ", 2, false))); } @Test @@ -156,38 +156,31 @@ public void singleQuotedStringsWithBraces() { check( "{{ 'The { char is a brace' }}", Arrays.asList(new MustacheBindingToken("{{ 'The { char is a brace' }}", 0, true)), - Set.of(new MustacheBindingToken(" 'The { char is a brace' ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'The { char is a brace' ", 2, false))); check( "{{ 'I have {{ two braces' }}", Arrays.asList(new MustacheBindingToken("{{ 'I have {{ two braces' }}", 0, true)), - Set.of(new MustacheBindingToken(" 'I have {{ two braces' ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'I have {{ two braces' ", 2, false))); check( "{{ 'I have {{{ three braces' }}", Arrays.asList(new MustacheBindingToken("{{ 'I have {{{ three braces' }}", 0, true)), - Set.of(new MustacheBindingToken(" 'I have {{{ three braces' ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'I have {{{ three braces' ", 2, false))); check( "{{ 'The } char is a brace' }}", Arrays.asList(new MustacheBindingToken("{{ 'The } char is a brace' }}", 0, true)), - Set.of(new MustacheBindingToken(" 'The } char is a brace' ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'The } char is a brace' ", 2, false))); check( "{{ 'I have }} two braces' }}", Arrays.asList(new MustacheBindingToken("{{ 'I have }} two braces' }}", 0, true)), - Set.of(new MustacheBindingToken(" 'I have }} two braces' ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'I have }} two braces' ", 2, false))); check( "{{ 'I have }}} three braces' }}", Arrays.asList(new MustacheBindingToken("{{ 'I have }}} three braces' }}", 0, true)), - Set.of(new MustacheBindingToken(" 'I have }}} three braces' ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'I have }}} three braces' ", 2, false))); check( "{{ 'Interpolation uses {{ and }} delimiters' }}", Arrays.asList(new MustacheBindingToken("{{ 'Interpolation uses {{ and }} delimiters' }}", 0, true)), - Set.of(new MustacheBindingToken(" 'Interpolation uses {{ and }} delimiters' ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'Interpolation uses {{ and }} delimiters' ", 2, false))); } @Test @@ -195,38 +188,31 @@ public void doubleQuotedStringsWithBraces() { check( "{{ \"The { char is a brace\" }}", Arrays.asList(new MustacheBindingToken("{{ \"The { char is a brace\" }}", 0, true)), - Set.of(new MustacheBindingToken(" \"The { char is a brace\" ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"The { char is a brace\" ", 2, false))); check( "{{ \"I have {{ two braces\" }}", Arrays.asList(new MustacheBindingToken("{{ \"I have {{ two braces\" }}", 0, true)), - Set.of(new MustacheBindingToken(" \"I have {{ two braces\" ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"I have {{ two braces\" ", 2, false))); check( "{{ \"I have {{{ three braces\" }}", Arrays.asList(new MustacheBindingToken("{{ \"I have {{{ three braces\" }}", 0, true)), - Set.of(new MustacheBindingToken(" \"I have {{{ three braces\" ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"I have {{{ three braces\" ", 2, false))); check( "{{ \"The } char is a brace\" }}", Arrays.asList(new MustacheBindingToken("{{ \"The } char is a brace\" }}", 0, true)), - Set.of(new MustacheBindingToken(" \"The } char is a brace\" ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"The } char is a brace\" ", 2, false))); check( "{{ \"I have }} two braces\" }}", Arrays.asList(new MustacheBindingToken("{{ \"I have }} two braces\" }}", 0, true)), - Set.of(new MustacheBindingToken(" \"I have }} two braces\" ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"I have }} two braces\" ", 2, false))); check( "{{ \"I have }}} three braces\" }}", Arrays.asList(new MustacheBindingToken("{{ \"I have }}} three braces\" }}", 0, true)), - Set.of(new MustacheBindingToken(" \"I have }}} three braces\" ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"I have }}} three braces\" ", 2, false))); check( "{{ \"Interpolation uses {{ and }} delimiters\" }}", Arrays.asList(new MustacheBindingToken("{{ \"Interpolation uses {{ and }} delimiters\" }}", 0, true)), - Set.of(new MustacheBindingToken(" \"Interpolation uses {{ and }} delimiters\" ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"Interpolation uses {{ and }} delimiters\" ", 2, false))); } @Test @@ -234,38 +220,31 @@ public void backQuotedStringsWithBraces() { check( "{{ `The { char is a brace` }}", Arrays.asList(new MustacheBindingToken("{{ `The { char is a brace` }}", 0, true)), - Set.of(new MustacheBindingToken(" `The { char is a brace` ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `The { char is a brace` ", 2, false))); check( "{{ `I have {{ two braces` }}", Arrays.asList(new MustacheBindingToken("{{ `I have {{ two braces` }}", 0, true)), - Set.of(new MustacheBindingToken(" `I have {{ two braces` ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `I have {{ two braces` ", 2, false))); check( "{{ `I have {{{ three braces` }}", Arrays.asList(new MustacheBindingToken("{{ `I have {{{ three braces` }}", 0, true)), - Set.of(new MustacheBindingToken(" `I have {{{ three braces` ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `I have {{{ three braces` ", 2, false))); check( "{{ `The } char is a brace` }}", Arrays.asList(new MustacheBindingToken("{{ `The } char is a brace` }}", 0, true)), - Set.of(new MustacheBindingToken(" `The } char is a brace` ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `The } char is a brace` ", 2, false))); check( "{{ `I have }} two braces` }}", Arrays.asList(new MustacheBindingToken("{{ `I have }} two braces` }}", 0, true)), - Set.of(new MustacheBindingToken(" `I have }} two braces` ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `I have }} two braces` ", 2, false))); check( "{{ `I have }}} three braces` }}", Arrays.asList(new MustacheBindingToken("{{ `I have }}} three braces` }}", 0, true)), - Set.of(new MustacheBindingToken(" `I have }}} three braces` ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `I have }}} three braces` ", 2, false))); check( "{{ `Interpolation uses {{ and }} delimiters` }}", Arrays.asList(new MustacheBindingToken("{{ `Interpolation uses {{ and }} delimiters` }}", 0, true)), - Set.of(new MustacheBindingToken(" `Interpolation uses {{ and }} delimiters` ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `Interpolation uses {{ and }} delimiters` ", 2, false))); } @Test @@ -273,18 +252,15 @@ public void quotedStringsWithExtras() { check( "{{ 2 + ' hello ' + 3 }}", Arrays.asList(new MustacheBindingToken("{{ 2 + ' hello ' + 3 }}", 0, true)), - Set.of(new MustacheBindingToken(" 2 + ' hello ' + 3 ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 2 + ' hello ' + 3 ", 2, false))); check( "{{ 2 + \" hello \" + 3 }}", Arrays.asList(new MustacheBindingToken("{{ 2 + \" hello \" + 3 }}", 0, true)), - Set.of(new MustacheBindingToken(" 2 + \" hello \" + 3 ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 2 + \" hello \" + 3 ", 2, false))); check( "{{ 2 + ` hello ` + 3 }}", Arrays.asList(new MustacheBindingToken("{{ 2 + ` hello ` + 3 }}", 0, true)), - Set.of(new MustacheBindingToken(" 2 + ` hello ` + 3 ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 2 + ` hello ` + 3 ", 2, false))); } @Test @@ -292,18 +268,15 @@ public void quotedStringsWithEscapes() { check( "{{ 'Escaped \\' character' }}", Arrays.asList(new MustacheBindingToken("{{ 'Escaped \\' character' }}", 0, true)), - Set.of(new MustacheBindingToken(" 'Escaped \\' character' ", 2, false)) - ); + Set.of(new MustacheBindingToken(" 'Escaped \\' character' ", 2, false))); check( "{{ \"Escaped \\\" character\" }}", Arrays.asList(new MustacheBindingToken("{{ \"Escaped \\\" character\" }}", 0, true)), - Set.of(new MustacheBindingToken(" \"Escaped \\\" character\" ", 2, false)) - ); + Set.of(new MustacheBindingToken(" \"Escaped \\\" character\" ", 2, false))); check( "{{ `Escaped \\` character` }}", Arrays.asList(new MustacheBindingToken("{{ `Escaped \\` character` }}", 0, true)), - Set.of(new MustacheBindingToken(" `Escaped \\` character` ", 2, false)) - ); + Set.of(new MustacheBindingToken(" `Escaped \\` character` ", 2, false))); } @Test @@ -313,8 +286,7 @@ public void conditionalExpression() { Arrays.asList( new MustacheBindingToken("Conditional: ", 0, false), new MustacheBindingToken("{{ 2 + 4 ? trueVal : falseVal }}", 13, true)), - Set.of(new MustacheBindingToken(" 2 + 4 ? trueVal : falseVal ", 15, false)) - ); + Set.of(new MustacheBindingToken(" 2 + 4 ? trueVal : falseVal ", 15, false))); } @Test @@ -322,8 +294,7 @@ public void jsonInMustache() { check( "{{{\"foo\": \"bar\"}}}", Arrays.asList(new MustacheBindingToken("{{{\"foo\": \"bar\"}}}", 0, true)), - Set.of(new MustacheBindingToken("{\"foo\": \"bar\"}", 2, false)) - ); + Set.of(new MustacheBindingToken("{\"foo\": \"bar\"}", 2, false))); } @Test @@ -336,20 +307,13 @@ public void allDatasourceConfigurationFields() { configuration.setUrl("{{ url }}"); - configuration.setHeaders(List.of( - new Property("header1", "{{ headerValue1 }}"), - new Property("header2", "{{ headerValue2 }}") - )); + configuration.setHeaders( + List.of(new Property("header1", "{{ headerValue1 }}"), new Property("header2", "{{ headerValue2 }}"))); - configuration.setEndpoints(List.of( - new Endpoint("{{ host1 }}", 2000L), - new Endpoint("{{ host2 }}", 2000L) - )); + configuration.setEndpoints(List.of(new Endpoint("{{ host1 }}", 2000L), new Endpoint("{{ host2 }}", 2000L))); configuration.setProperties(Arrays.asList( - new Property("name1", "{{ propertyValue1 }}!"), - new Property("name2", "{{ propertyValue2 }}!") - )); + new Property("name1", "{{ propertyValue1 }}!"), new Property("name2", "{{ propertyValue2 }}!"))); Map<String, String> context = Map.of( " dbName ", "rendered dbName", @@ -359,10 +323,12 @@ public void allDatasourceConfigurationFields() { " host1 ", "rendered host1", " host2 ", "rendered host2", " propertyValue1 ", "rendered propertyValue1", - " propertyValue2 ", "rendered propertyValue2" - ); + " propertyValue2 ", "rendered propertyValue2"); - assertKeys(configuration).hasSameElementsAs(context.keySet().stream().map(keys -> new MustacheBindingToken(keys, 2, false)).collect(Collectors.toSet())); + assertKeys(configuration) + .hasSameElementsAs(context.keySet().stream() + .map(keys -> new MustacheBindingToken(keys, 2, false)) + .collect(Collectors.toSet())); Map<String, String> context2 = Map.of( "dbName", "rendered dbName", @@ -372,28 +338,25 @@ public void allDatasourceConfigurationFields() { "host1", "rendered host1", "host2", "rendered host2", "propertyValue1", "rendered propertyValue1", - "propertyValue2", "rendered propertyValue2" - ); + "propertyValue2", "rendered propertyValue2"); renderFieldValues(configuration, context2); assertThat(configuration.getConnection().getDefaultDatabaseName()).isEqualTo("rendered dbName"); assertThat(configuration.getUrl()).isEqualTo("rendered url"); - assertThat(configuration.getHeaders()).containsOnly( - new Property("header1", "rendered headerValue1"), - new Property("header2", "rendered headerValue2") - ); + assertThat(configuration.getHeaders()) + .containsOnly( + new Property("header1", "rendered headerValue1"), + new Property("header2", "rendered headerValue2")); - assertThat(configuration.getEndpoints()).containsOnly( - new Endpoint("rendered host1", 2000L), - new Endpoint("rendered host2", 2000L) - ); + assertThat(configuration.getEndpoints()) + .containsOnly(new Endpoint("rendered host1", 2000L), new Endpoint("rendered host2", 2000L)); - assertThat(configuration.getProperties()).containsOnly( - new Property("name1", "rendered propertyValue1!"), - new Property("name2", "rendered propertyValue2!") - ); + assertThat(configuration.getProperties()) + .containsOnly( + new Property("name1", "rendered propertyValue1!"), + new Property("name2", "rendered propertyValue2!")); } @Test @@ -404,27 +367,20 @@ public void allActionConfigurationFields() { configuration.setPath("{{ path }}"); configuration.setNext("{{ next }}"); - configuration.setHeaders(List.of( - new Property("header1", "{{ headerValue1 }}"), - new Property("header2", "{{ headerValue2 }}") - )); + configuration.setHeaders( + List.of(new Property("header1", "{{ headerValue1 }}"), new Property("header2", "{{ headerValue2 }}"))); - configuration.setBodyFormData(List.of( - new Property("param1", "{{ bodyParam1 }}"), - new Property("param2", "{{ bodyParam2 }}") - )); + configuration.setBodyFormData( + List.of(new Property("param1", "{{ bodyParam1 }}"), new Property("param2", "{{ bodyParam2 }}"))); - configuration.setQueryParameters(List.of( - new Property("param1", "{{ queryParam1 }}"), - new Property("param2", "{{ queryParam2 }}") - )); + configuration.setQueryParameters( + List.of(new Property("param1", "{{ queryParam1 }}"), new Property("param2", "{{ queryParam2 }}"))); configuration.setPluginSpecifiedTemplates(Arrays.asList( null, new Property("prop1", "{{ pluginSpecifiedProp1 }}"), null, - new Property("prop2", "{{ pluginSpecifiedProp2 }}") - )); + new Property("prop2", "{{ pluginSpecifiedProp2 }}"))); final Map<String, String> context = new HashMap<>(Map.of( " body ", "rendered body", @@ -435,18 +391,14 @@ public void allActionConfigurationFields() { " bodyParam1 ", "rendered bodyParam1", " bodyParam2 ", "rendered bodyParam2", " queryParam1 ", "rendered queryParam1", - " queryParam2 ", "rendered queryParam2" - )); + " queryParam2 ", "rendered queryParam2")); context.putAll(Map.of( " pluginSpecifiedProp1 ", "rendered pluginSpecifiedProp1", - " pluginSpecifiedProp2 ", "rendered pluginSpecifiedProp2" - )); + " pluginSpecifiedProp2 ", "rendered pluginSpecifiedProp2")); assertKeys(configuration) - .hasSameElementsAs(context - .keySet() - .stream() + .hasSameElementsAs(context.keySet().stream() .map(keys -> new MustacheBindingToken(keys, 2, false)) .collect(Collectors.toSet())); @@ -459,39 +411,35 @@ public void allActionConfigurationFields() { "bodyParam1", "rendered bodyParam1", "bodyParam2", "rendered bodyParam2", "queryParam1", "rendered queryParam1", - "queryParam2", "rendered queryParam2" - )); + "queryParam2", "rendered queryParam2")); context2.putAll(Map.of( "pluginSpecifiedProp1", "rendered pluginSpecifiedProp1", - "pluginSpecifiedProp2", "rendered pluginSpecifiedProp2" - )); + "pluginSpecifiedProp2", "rendered pluginSpecifiedProp2")); renderFieldValues(configuration, context2); assertThat(configuration.getBody()).isEqualTo("rendered body"); assertThat(configuration.getPath()).isEqualTo("rendered path"); assertThat(configuration.getNext()).isEqualTo("rendered next"); - assertThat(configuration.getHeaders()).containsOnly( - new Property("header1", "rendered headerValue1"), - new Property("header2", "rendered headerValue2") - ); + assertThat(configuration.getHeaders()) + .containsOnly( + new Property("header1", "rendered headerValue1"), + new Property("header2", "rendered headerValue2")); - assertThat(configuration.getBodyFormData()).containsOnly( - new Property("param1", "rendered bodyParam1"), - new Property("param2", "rendered bodyParam2") - ); + assertThat(configuration.getBodyFormData()) + .containsOnly( + new Property("param1", "rendered bodyParam1"), new Property("param2", "rendered bodyParam2")); - assertThat(configuration.getQueryParameters()).containsOnly( - new Property("param1", "rendered queryParam1"), - new Property("param2", "rendered queryParam2") - ); + assertThat(configuration.getQueryParameters()) + .containsOnly( + new Property("param1", "rendered queryParam1"), new Property("param2", "rendered queryParam2")); - assertThat(configuration.getPluginSpecifiedTemplates()).containsExactly( - null, - new Property("prop1", "rendered pluginSpecifiedProp1"), - null, - new Property("prop2", "rendered pluginSpecifiedProp2") - ); + assertThat(configuration.getPluginSpecifiedTemplates()) + .containsExactly( + null, + new Property("prop1", "rendered pluginSpecifiedProp1"), + null, + new Property("prop2", "rendered pluginSpecifiedProp2")); } @Test @@ -522,7 +470,8 @@ public void objectWithJavascriptStringWithNewline() { // The `\n` should be interpreted by Javascript, not Java. So we put an extra `\` before it. property.setValue("Hello {{ \"line 1\" + \"\\n\" + \"line 2\" }}!"); configuration.setProperties(Arrays.asList(property)); - assertKeys(configuration).containsExactlyInAnyOrder(new MustacheBindingToken(" \"line 1\" + \"\\n\" + \"line 2\" ", 8, false)); + assertKeys(configuration) + .containsExactlyInAnyOrder(new MustacheBindingToken(" \"line 1\" + \"\\n\" + \"line 2\" ", 8, false)); } @Test @@ -556,14 +505,18 @@ public void bodyWithTabInMustaches() { public void bodyWithMultilineJavascriptInMustaches() { ActionConfiguration configuration = new ActionConfiguration(); configuration.setBody("outside {{\n\ttrue\n\t\t? \"yes\\n\"\n\t\t: \"no\\n\"\n}} outside"); - assertKeys(configuration).containsExactlyInAnyOrder(new MustacheBindingToken("\n\ttrue\n\t\t? \"yes\\n\"\n\t\t: \"no\\n\"\n", 10, false)); + assertKeys(configuration) + .containsExactlyInAnyOrder( + new MustacheBindingToken("\n\ttrue\n\t\t? \"yes\\n\"\n\t\t: \"no\\n\"\n", 10, false)); } @Test public void renderBodyWithMultilineJavascriptInMustaches() { ActionConfiguration configuration = new ActionConfiguration(); configuration.setBody("outside {{\n\ttrue\n\t\t \"yes\\n\"\n\t\t \"no\\n\"\n}} outside"); - assertKeys(configuration).containsExactlyInAnyOrder(new MustacheBindingToken("\n\ttrue\n\t\t \"yes\\n\"\n\t\t \"no\\n\"\n", 10, false)); + assertKeys(configuration) + .containsExactlyInAnyOrder( + new MustacheBindingToken("\n\ttrue\n\t\t \"yes\\n\"\n\t\t \"no\\n\"\n", 10, false)); renderFieldValues(configuration, Map.of("true\n\t\t \"yes\\n\"\n\t\t \"no\\n\"", "{\"more\": \"json\"}")); assertThat(configuration.getBody()).isEqualTo("outside {\"more\": \"json\"} outside"); @@ -571,78 +524,43 @@ public void renderBodyWithMultilineJavascriptInMustaches() { @Test public void renderSingleKey() { - final String rendered = render( - "{{key1}}", - Map.of( - "key1", "value1" - ) - ); + final String rendered = render("{{key1}}", Map.of("key1", "value1")); assertThat(rendered).isEqualTo("value1"); } @Test public void renderSingleKeyWithLeading() { - final String rendered = render( - "leading content {{key1}}", - Map.of( - "key1", "value1" - ) - ); + final String rendered = render("leading content {{key1}}", Map.of("key1", "value1")); assertThat(rendered).isEqualTo("leading content value1"); } @Test public void renderSingleKeyWithTailing() { - final String rendered = render( - "{{key1}} tailing content", - Map.of( - "key1", "value1" - ) - ); + final String rendered = render("{{key1}} tailing content", Map.of("key1", "value1")); assertThat(rendered).isEqualTo("value1 tailing content"); } @Test public void renderSingleKeyWithLeadingAndTailing() { - final String rendered = render( - "leading content {{key1}} tailing content", - Map.of( - "key1", "value1" - ) - ); + final String rendered = render("leading content {{key1}} tailing content", Map.of("key1", "value1")); assertThat(rendered).isEqualTo("leading content value1 tailing content"); } @Test public void renderMustacheComment() { - final String rendered = render( - "leading content {{!key1}} tailing content", - Map.of( - "!key1", "value1" - ) - ); + final String rendered = render("leading content {{!key1}} tailing content", Map.of("!key1", "value1")); assertThat(rendered).isEqualTo("leading content value1 tailing content"); } @Test public void renderMustacheCondition() { - final String rendered = render( - "leading content {{#key1}} tailing content", - Map.of( - "#key1", "value1" - ) - ); + final String rendered = render("leading content {{#key1}} tailing content", Map.of("#key1", "value1")); assertThat(rendered).isEqualTo("leading content value1 tailing content"); } @Test public void renderMustacheSubSection() { - final String rendered = render( - "leading content {{>key1}} tailing content", - Map.of( - ">key1", "value1" - ) - ); + final String rendered = render("leading content {{>key1}} tailing content", Map.of(">key1", "value1")); assertThat(rendered).isEqualTo("leading content value1 tailing content"); } @@ -652,9 +570,7 @@ public void renderMultipleKeys() { "leading {{key1}} and then {{key2}} tailing.", Map.of( "key1", "value1", - "key2", "value2" - ) - ); + "key2", "value2")); assertThat(rendered).isEqualTo("leading value1 and then value2 tailing."); } @@ -664,9 +580,7 @@ public void renderMultipleKeysWithSpaces() { "leading {{ key1 }} and then {{ key2 }} tailing.", Map.of( "key1", "value1", - "key2", "value2" - ) - ); + "key2", "value2")); assertThat(rendered).isEqualTo("leading value1 and then value2 tailing."); } @@ -674,11 +588,7 @@ public void renderMultipleKeysWithSpaces() { public void whenBindingFoundWithoutValue_doNotReplaceWithNull() { final String rendered = render( "HL7 Result: CODE 5 - {{severity}} - {{institution}} {{accessionNumber}}", - Map.of( - "severity", "CRITICAL VALUE" - ) - ); + Map.of("severity", "CRITICAL VALUE")); assertThat(rendered).isEqualTo("HL7 Result: CODE 5 - CRITICAL VALUE - {{institution}} {{accessionNumber}}"); } - } diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/PluginUtilsTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/PluginUtilsTest.java index 83f0504b8679..85a6de2f280f 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/PluginUtilsTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/PluginUtilsTest.java @@ -29,48 +29,47 @@ public class PluginUtilsTest { @Test public void parseWhereClauseTest() { - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"i\",\n" + - " \"condition\": \"GTE\",\n" + - " \"value\": \"u\"\n" + - " },\n" + - " {\n" + - " \"condition\": \"AND\",\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"d\",\n" + - " \"condition\": \"LTE\",\n" + - " \"value\": \"w\"\n" + - " },\n" + - " {\n" + - " \"condition\": \"AND\",\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"a\",\n" + - " \"condition\": \"LTE\",\n" + - " \"value\": \"s\"\n" + - " }\n" + - " ]\n" + - " }\n" + - " ]\n" + - " },\n" + - " {\n" + - " \"condition\": \"AND\",\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"u\",\n" + - " \"condition\": \"LTE\",\n" + - " \"value\": \"me\"\n" + - " }\n" + - " ]\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"i\",\n" + + " \"condition\": \"GTE\",\n" + + " \"value\": \"u\"\n" + + " },\n" + + " {\n" + + " \"condition\": \"AND\",\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"d\",\n" + + " \"condition\": \"LTE\",\n" + + " \"value\": \"w\"\n" + + " },\n" + + " {\n" + + " \"condition\": \"AND\",\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"a\",\n" + + " \"condition\": \"LTE\",\n" + + " \"value\": \"s\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " },\n" + + " {\n" + + " \"condition\": \"AND\",\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"u\",\n" + + " \"condition\": \"LTE\",\n" + + " \"value\": \"me\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { Map<String, Object> whereClause = objectMapper.readValue(whereJson, HashMap.class); Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); @@ -104,12 +103,8 @@ public void parseWhereClauseTest() { @Test public void parseWhereClauseEmptyChildrenArrayTest() { - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String whereJson = + "{\n" + " \"where\": {\n" + " \"children\": [],\n" + " \"condition\": \"AND\"\n" + " }\n" + "}"; try { Map<String, Object> whereClause = objectMapper.readValue(whereJson, HashMap.class); Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); @@ -126,12 +121,10 @@ public void parseWhereClauseEmptyChildrenArrayTest() { @Test public void testGetDataValueAsTypeFromFormData_withFormMode_doesNotConvertToList() { - final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "component", - "data", "[\"value\"]")); + final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "component", "data", "[\"value\"]")); try { - PluginUtils.getDataValueSafelyFromFormData(dataMap, "key", new TypeReference<List<String>>() { - }); + PluginUtils.getDataValueSafelyFromFormData(dataMap, "key", new TypeReference<List<String>>() {}); } catch (Exception e) { assertTrue(e instanceof ClassCastException); } @@ -139,8 +132,7 @@ public void testGetDataValueAsTypeFromFormData_withFormMode_doesNotConvertToList @Test public void testGetDataValueAsTypeFromFormData_withFormMode_doesNotConvert() { - final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "component", - "data", "[\"value\"]")); + final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "component", "data", "[\"value\"]")); final String data = PluginUtils.getDataValueSafelyFromFormData(dataMap, "key", STRING_TYPE); @@ -149,19 +141,17 @@ public void testGetDataValueAsTypeFromFormData_withFormMode_doesNotConvert() { @Test public void testGetDataValueAsTypeFromFormData_withJsonMode_doesConvertToList() { - final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "json", - "data", "[\"value\"]")); + final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "json", "data", "[\"value\"]")); - final List<String> data = PluginUtils.getDataValueSafelyFromFormData(dataMap, "key", new TypeReference<List<String>>() { - }); + final List<String> data = + PluginUtils.getDataValueSafelyFromFormData(dataMap, "key", new TypeReference<List<String>>() {}); assertEquals(List.of("value"), data); } @Test public void testGetDataValueAsTypeFromFormData_withJsonMode_doesConvertToObject() { - final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "json", - "data", "[\"value\"]")); + final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "json", "data", "[\"value\"]")); final Object data = PluginUtils.getDataValueSafelyFromFormData(dataMap, "key", OBJECT_TYPE); @@ -170,15 +160,13 @@ public void testGetDataValueAsTypeFromFormData_withJsonMode_doesConvertToObject( @Test public void testGetDataValueAsTypeFromFormData_withJsonMode_doesConvertToMap() { - final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "json", - "data", "{\"k\":\"value\"}")); + final Map<String, Object> dataMap = Map.of("key", Map.of("viewType", "json", "data", "{\"k\":\"value\"}")); - final Map<String, String> data = PluginUtils.getDataValueSafelyFromFormData(dataMap, "key", new TypeReference<Map<String, String>>() { - }); + final Map<String, String> data = + PluginUtils.getDataValueSafelyFromFormData(dataMap, "key", new TypeReference<Map<String, String>>() {}); assertEquals(Map.of("k", "value"), data); } - @Test public void testGetValueSafelyInFormData_IncorrectParsingByCaller() { @@ -212,6 +200,10 @@ public void testSetDataValueSafelyInFormData_withNestedPath_createsInnermostData @Test public void verifyUniquenessOfCommonPluginErrorCode() { - assert (Arrays.stream(AppsmithPluginError.values()).map(AppsmithPluginError::getAppErrorCode).distinct().count() == AppsmithPluginError.values().length); + assert (Arrays.stream(AppsmithPluginError.values()) + .map(AppsmithPluginError::getAppErrorCode) + .distinct() + .count() + == AppsmithPluginError.values().length); } } diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/models/DatasourceTestResultTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/models/DatasourceTestResultTest.java index 559a4f2f5a59..47d21ea6c0b8 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/models/DatasourceTestResultTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/models/DatasourceTestResultTest.java @@ -12,10 +12,14 @@ public class DatasourceTestResultTest { public void testNewDatasourceTestResult_NullInvalidArray() { DatasourceTestResult nullInvalidsResult = new DatasourceTestResult((String) null); assertNotNull(nullInvalidsResult); - assertTrue(nullInvalidsResult.getInvalids().contains(AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage())); + assertTrue(nullInvalidsResult + .getInvalids() + .contains(AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage())); - nullInvalidsResult = new DatasourceTestResult(new String[]{null}); + nullInvalidsResult = new DatasourceTestResult(new String[] {null}); assertNotNull(nullInvalidsResult); - assertTrue(nullInvalidsResult.getInvalids().contains(AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage())); + assertTrue(nullInvalidsResult + .getInvalids() + .contains(AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage())); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/services/FilterDataServiceTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/services/FilterDataServiceTest.java index 9a499a52eb06..fb25d83bc90a 100644 --- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/services/FilterDataServiceTest.java +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/services/FilterDataServiceTest.java @@ -40,8 +40,7 @@ public void testGenerateTable() { Map<String, DataType> schema = Map.of( "id", DataType.INTEGER, "name", DataType.STRING, - "status", DataType.BOOLEAN - ); + "status", DataType.BOOLEAN); String table = filterDataService.generateTable(schema); @@ -51,75 +50,73 @@ public void testGenerateTable() { @Test public void generateLogicalOperatorTest() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"i\",\n" + - " \"condition\": \"GTE\",\n" + - " \"value\": \"u\"\n" + - " },\n" + - " {\n" + - " \"condition\": \"AND\",\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"d\",\n" + - " \"condition\": \"LTE\",\n" + - " \"value\": \"w\"\n" + - " },\n" + - " {\n" + - " \"condition\": \"AND\",\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"a\",\n" + - " \"condition\": \"LTE\",\n" + - " \"value\": \"s\"\n" + - " }\n" + - " ]\n" + - " }\n" + - " ]\n" + - " },\n" + - " {\n" + - " \"condition\": \"AND\",\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"u\",\n" + - " \"condition\": \"LTE\",\n" + - " \"value\": \"me\"\n" + - " }\n" + - " ]\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"i\",\n" + + " \"condition\": \"GTE\",\n" + + " \"value\": \"u\"\n" + + " },\n" + + " {\n" + + " \"condition\": \"AND\",\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"d\",\n" + + " \"condition\": \"LTE\",\n" + + " \"value\": \"w\"\n" + + " },\n" + + " {\n" + + " \"condition\": \"AND\",\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"a\",\n" + + " \"condition\": \"LTE\",\n" + + " \"value\": \"s\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " },\n" + + " {\n" + + " \"condition\": \"AND\",\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"u\",\n" + + " \"condition\": \"LTE\",\n" + + " \"value\": \"me\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { @@ -133,8 +130,11 @@ public void generateLogicalOperatorTest() { ConditionalOperator operator = condition.getOperator(); List<Condition> conditions = (List<Condition>) condition.getValue(); - String expression = filterDataService.generateLogicalExpression(conditions, new ArrayList<>(), schema, operator); - assertThat(expression).isEqualTo(" ( \"i\" >= ? ) and ( ( \"d\" <= ? ) and ( ( \"a\" <= ? ) ) ) and ( ( \"u\" <= ? ) ) "); + String expression = + filterDataService.generateLogicalExpression(conditions, new ArrayList<>(), schema, operator); + assertThat(expression) + .isEqualTo( + " ( \"i\" >= ? ) and ( ( \"d\" <= ? ) and ( ( \"a\" <= ? ) ) ) and ( ( \"u\" <= ? ) ) "); } catch (IOException e) { e.printStackTrace(); @@ -144,45 +144,43 @@ public void generateLogicalOperatorTest() { @Test public void testFilterSingleConditionWithWhereJson() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -191,8 +189,8 @@ public void testFilterSingleConditionWithWhereJson() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 2); @@ -204,58 +202,56 @@ public void testFilterSingleConditionWithWhereJson() { @Test public void testFilterMultipleConditionsNew() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"anotherKey\": 20,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"anotherKey\": 12,\n" + - " \"orderStatus\": \"NOT READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"anotherKey\": 20,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " },\n" + - " {\n" + - " \"key\": \"anotherKey\",\n" + - " \"condition\": \"GT\",\n" + - " \"value\": \"15\"\n" + - " },\n" + - " {\n" + - " \"key\": \"orderStatus\",\n" + - " \"condition\": \"EQ\",\n" + - " \"value\": \"READY\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"anotherKey\": 20,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"anotherKey\": 12,\n" + + " \"orderStatus\": \"NOT READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"anotherKey\": 20,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " },\n" + + " {\n" + + " \"key\": \"anotherKey\",\n" + + " \"condition\": \"GT\",\n" + + " \"value\": \"15\"\n" + + " },\n" + + " {\n" + + " \"key\": \"orderStatus\",\n" + + " \"condition\": \"EQ\",\n" + + " \"value\": \"READY\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -264,12 +260,11 @@ public void testFilterMultipleConditionsNew() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 1); - } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); @@ -278,50 +273,48 @@ public void testFilterMultipleConditionsNew() { @Test public void testFilterInConditionForStringsNew() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"NOT READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " },\n" + - " {\n" + - " \"key\": \"orderStatus\",\n" + - " \"condition\": \"IN\",\n" + - " \"value\": \"[\\\"READY\\\", \\\"NOT READY\\\"]\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"NOT READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " },\n" + + " {\n" + + " \"key\": \"orderStatus\",\n" + + " \"condition\": \"IN\",\n" + + " \"value\": \"[\\\"READY\\\", \\\"NOT READY\\\"]\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -330,12 +323,11 @@ public void testFilterInConditionForStringsNew() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 2); - } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); @@ -344,50 +336,48 @@ public void testFilterInConditionForStringsNew() { @Test public void testFilterInConditionForNumbersNew() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"NOT READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " },\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"IN\",\n" + - " \"value\": \"[4.99, 19.99]\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"NOT READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " },\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"IN\",\n" + + " \"value\": \"[4.99, 19.99]\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -396,8 +386,8 @@ public void testFilterInConditionForNumbersNew() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 1); @@ -409,50 +399,48 @@ public void testFilterInConditionForNumbersNew() { @Test public void testFilterNotInConditionForNumbersNew() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"NOT READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " },\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"NOT_IN\",\n" + - " \"value\": \"[5.99, 19.00]\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"NOT READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " },\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"NOT_IN\",\n" + + " \"value\": \"[5.99, 19.00]\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -461,12 +449,11 @@ public void testFilterNotInConditionForNumbersNew() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 2); - } catch (IOException e) { e.printStackTrace(); } @@ -474,45 +461,43 @@ public void testFilterNotInConditionForNumbersNew() { @Test public void testMultiWordColumnNamesNew() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -521,8 +506,8 @@ public void testMultiWordColumnNamesNew() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 2); @@ -533,7 +518,9 @@ public void testMultiWordColumnNamesNew() { .map(n -> fieldNamesIterator.next()) .collect(Collectors.toList()); - assertThat(columnNames).containsExactlyInAnyOrder("id", "email id", "userName", "productName", "orderAmount", "orderStatus"); + assertThat(columnNames) + .containsExactlyInAnyOrder( + "id", "email id", "userName", "productName", "orderAmount", "orderStatus"); } catch (IOException e) { e.printStackTrace(); @@ -543,45 +530,43 @@ public void testMultiWordColumnNamesNew() { @Test public void testEmptyValuesInSomeColumnsNew() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -590,12 +575,11 @@ public void testEmptyValuesInSomeColumnsNew() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 2); - } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); @@ -604,48 +588,46 @@ public void testEmptyValuesInSomeColumnsNew() { @Test public void testValuesOfUnsupportedDataTypeNew() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"date\": \"2021-09-01\",\n" + - " \"datetime\": \"2021-09-01T00:01:00.000Z\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"date\": \"2021-09-01\",\n" + - " \"datetime\": \"2021-09-01T00:01:00.000Z\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"date\": \"2021-09-01\",\n" + - " \"datetime\": \"2021-09-01T00:01:00.000Z\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"date\": \"2021-09-01\",\n" + + " \"datetime\": \"2021-09-01T00:01:00.000Z\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"date\": \"2021-09-01\",\n" + + " \"datetime\": \"2021-09-01T00:01:00.000Z\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"date\": \"2021-09-01\",\n" + + " \"datetime\": \"2021-09-01T00:01:00.000Z\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -654,12 +636,11 @@ public void testValuesOfUnsupportedDataTypeNew() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 2); - } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); @@ -668,45 +649,43 @@ public void testValuesOfUnsupportedDataTypeNew() { @Test public void testConditionTypeMismatch() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"String here where number is expected\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"String here where number is expected\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -716,7 +695,8 @@ public void testConditionTypeMismatch() { Condition condition = parseWhereClause(unparsedWhereClause); // Since the data type expected for orderAmount is float, but the value given is String, assert exception - assertThrows(AppsmithPluginException.class, + assertThrows( + AppsmithPluginException.class, () -> filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null))); } catch (IOException e) { @@ -727,39 +707,34 @@ public void testConditionTypeMismatch() { @Test public void testEmptyConditions() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": \"USD 4.99\",\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": \"USD 4.99\",\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " }\n" + + "]"; + + String whereJson = + "{\n" + " \"where\": {\n" + " \"children\": [],\n" + " \"condition\": \"AND\"\n" + " }\n" + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -768,8 +743,8 @@ public void testEmptyConditions() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null), new HashMap<>()); + ArrayNode filteredData = filterDataService.filterDataNew( + items, new UQIDataFilterParams(condition, null, null, null), new HashMap<>()); assertEquals(3, filteredData.size()); assertEquals("USD 4.99", filteredData.get(0).get("orderAmount").asText()); @@ -783,45 +758,43 @@ public void testEmptyConditions() { @Test public void testConditionNullValueMatch() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"EQ\",\n" + - " \"value\": \"null\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"EQ\",\n" + + " \"value\": \"null\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -830,8 +803,8 @@ public void testConditionNullValueMatch() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); // Since there are no null orderAmounts, the filtered data would be empty. assertEquals(filteredData.size(), 0); @@ -844,45 +817,43 @@ public void testConditionNullValueMatch() { @Test public void testDateCondition() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"date\": \"2021-09-01\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"date\": \"2021-09-02\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"date\": \"2021-09-03\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"date\",\n" + - " \"condition\": \"GTE\",\n" + - " \"value\": \"2021-09-02\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"date\": \"2021-09-01\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"date\": \"2021-09-02\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"date\": \"2021-09-03\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"date\",\n" + + " \"condition\": \"GTE\",\n" + + " \"value\": \"2021-09-02\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -891,8 +862,8 @@ public void testDateCondition() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 2); @@ -904,45 +875,43 @@ public void testDateCondition() { @Test public void testFilterDataNew_withTimestampClause_returnsCorrectValues() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email id\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"date\": \"2021-09-01 00:01:00\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"date\": \"2021-09-02 00:02:00\"\n" + - " },\n" + - " {\n" + - " \"id\": \"\",\n" + - " \"email id\": \"\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"date\": \"2021-09-03 00:03:00\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"date\",\n" + - " \"condition\": \"GTE\",\n" + - " \"value\": \"2021-09-02 00:02:00\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email id\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"date\": \"2021-09-01 00:01:00\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"date\": \"2021-09-02 00:02:00\"\n" + + " },\n" + + " {\n" + + " \"id\": \"\",\n" + + " \"email id\": \"\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"date\": \"2021-09-03 00:03:00\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"date\",\n" + + " \"condition\": \"GTE\",\n" + + " \"value\": \"2021-09-02 00:02:00\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -951,8 +920,8 @@ public void testFilterDataNew_withTimestampClause_returnsCorrectValues() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 2); @@ -964,45 +933,43 @@ public void testFilterDataNew_withTimestampClause_returnsCorrectValues() { @Test public void testProjection() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -1011,8 +978,8 @@ public void testProjection() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, - List.of("id", "email"), null, null)); + ArrayNode filteredData = filterDataService.filterDataNew( + items, new UQIDataFilterParams(condition, List.of("id", "email"), null, null)); assertEquals(filteredData.size(), 2); @@ -1028,45 +995,43 @@ public void testProjection() { @Test public void testSortBy() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -1085,8 +1050,8 @@ public void testSortBy() { sortCondition2.put(SORT_BY_TYPE_KEY, VALUE_DESCENDING); sortBy.add(sortCondition2); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - sortBy, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, sortBy, null)); assertEquals(filteredData.size(), 2); @@ -1103,45 +1068,43 @@ public void testSortBy() { @Test public void testPagination() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"25\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"25\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -1154,8 +1117,8 @@ public void testPagination() { paginateBy.put(PAGINATE_LIMIT_KEY, "2"); paginateBy.put(PAGINATE_OFFSET_KEY, "1"); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - null, paginateBy)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, paginateBy)); assertEquals(filteredData.size(), 2); @@ -1172,45 +1135,43 @@ public void testPagination() { @Test public void testProjectionSortingAndPaginationTogether() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"20\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"20\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -1231,8 +1192,8 @@ public void testProjectionSortingAndPaginationTogether() { paginateBy.put(PAGINATE_LIMIT_KEY, "1"); paginateBy.put(PAGINATE_OFFSET_KEY, "1"); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, - projectColumns, sortBy, paginateBy)); + ArrayNode filteredData = filterDataService.filterDataNew( + items, new UQIDataFilterParams(condition, projectColumns, sortBy, paginateBy)); assertEquals(filteredData.size(), 1); @@ -1247,45 +1208,43 @@ public void testProjectionSortingAndPaginationTogether() { @Test public void testSortByWithEmptyColumnNameOnly() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"Tuna Salad\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"Beef steak\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderAmount\",\n" + - " \"condition\": \"LT\",\n" + - " \"value\": \"15\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"Tuna Salad\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"Beef steak\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderAmount\",\n" + + " \"condition\": \"LT\",\n" + + " \"value\": \"15\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -1300,8 +1259,8 @@ public void testSortByWithEmptyColumnNameOnly() { sortCondition1.put(SORT_BY_TYPE_KEY, VALUE_DESCENDING); sortBy.add(sortCondition1); - ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, - sortBy, null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, sortBy, null)); assertEquals(filteredData.size(), 2); @@ -1318,49 +1277,47 @@ public void testSortByWithEmptyColumnNameOnly() { @Test public void testFilterEmptyAndNonEmptyCondition() { - String data = "[\n" + - " {\n" + - " \"id\": 2381224,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Michael Lawson\",\n" + - " \"productName\": \"Chicken Sandwich\",\n" + - " \"orderAmount\": 4.99,\n" + - " \"orderStatus\": \"READY\"\n" + - " },\n" + - " {\n" + - " \"id\": 2736212,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Lindsay Ferguson\",\n" + - " \"productName\": \"\",\n" + - " \"orderAmount\": 9.99,\n" + - " \"orderStatus\": \"\"\n" + - " },\n" + - " {\n" + - " \"id\": 6788734,\n" + - " \"email\": \"[email protected]\",\n" + - " \"userName\": \"Tobias Funke\",\n" + - " \"productName\": \"\",\n" + - " \"orderAmount\": 19.99,\n" + - " \"orderStatus\": \"NOT READY\"\n" + - " }\n" + - "]"; - - String whereJson = "{\n" + - " \"where\": {\n" + - " \"children\": [\n" + - " {\n" + - " \"key\": \"orderStatus\",\n" + - " \"condition\": \"EQ\",\n" + - " \"value\": \"\"\n" + - " },\n" + - " {\n" + - " \"key\": \"productName\",\n" + - " \"condition\": \"EQ\"\n" + - " }\n" + - " ],\n" + - " \"condition\": \"AND\"\n" + - " }\n" + - "}"; + String data = "[\n" + " {\n" + + " \"id\": 2381224,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Michael Lawson\",\n" + + " \"productName\": \"Chicken Sandwich\",\n" + + " \"orderAmount\": 4.99,\n" + + " \"orderStatus\": \"READY\"\n" + + " },\n" + + " {\n" + + " \"id\": 2736212,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Lindsay Ferguson\",\n" + + " \"productName\": \"\",\n" + + " \"orderAmount\": 9.99,\n" + + " \"orderStatus\": \"\"\n" + + " },\n" + + " {\n" + + " \"id\": 6788734,\n" + + " \"email\": \"[email protected]\",\n" + + " \"userName\": \"Tobias Funke\",\n" + + " \"productName\": \"\",\n" + + " \"orderAmount\": 19.99,\n" + + " \"orderStatus\": \"NOT READY\"\n" + + " }\n" + + "]"; + + String whereJson = "{\n" + " \"where\": {\n" + + " \"children\": [\n" + + " {\n" + + " \"key\": \"orderStatus\",\n" + + " \"condition\": \"EQ\",\n" + + " \"value\": \"\"\n" + + " },\n" + + " {\n" + + " \"key\": \"productName\",\n" + + " \"condition\": \"EQ\"\n" + + " }\n" + + " ],\n" + + " \"condition\": \"AND\"\n" + + " }\n" + + "}"; try { ArrayNode items = (ArrayNode) objectMapper.readTree(data); @@ -1369,13 +1326,8 @@ public void testFilterEmptyAndNonEmptyCondition() { Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where"); Condition condition = parseWhereClause(unparsedWhereClause); - ArrayNode filteredData = filterDataService.filterDataNew( - items, - new UQIDataFilterParams( - condition, - null, - null, - null)); + ArrayNode filteredData = + filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)); assertEquals(filteredData.size(), 1); diff --git a/app/server/appsmith-plugins/amazons3Plugin/pom.xml b/app/server/appsmith-plugins/amazons3Plugin/pom.xml index b2284236a5c9..3567fc1de1c5 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/pom.xml +++ b/app/server/appsmith-plugins/amazons3Plugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>amazons3Plugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -54,10 +53,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java index c6e75a930388..771452cc331a 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java @@ -144,8 +144,7 @@ ArrayList<String> getFilenamesFromObjectListing(ObjectListing objectListing) thr if (objectListing == null) { throw new AppsmithPluginException( S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, - S3ErrorMessages.FILE_CONTENT_FETCHING_ERROR_MSG - ); + S3ErrorMessages.FILE_CONTENT_FETCHING_ERROR_MSG); } ArrayList<String> result = new ArrayList<>(); @@ -160,14 +159,11 @@ ArrayList<String> getFilenamesFromObjectListing(ObjectListing objectListing) thr /* * - Exception thrown by this method is expected to be handled by the caller. */ - ArrayList<String> listAllFilesInBucket(AmazonS3 connection, - String bucketName, - String prefix) throws AppsmithPluginException { + ArrayList<String> listAllFilesInBucket(AmazonS3 connection, String bucketName, String prefix) + throws AppsmithPluginException { if (connection == null) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.CONNECTIVITY_ERROR_MSG - ); + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.CONNECTIVITY_ERROR_MSG); } if (bucketName == null) { @@ -176,9 +172,7 @@ ArrayList<String> listAllFilesInBucket(AmazonS3 connection, * execute function already. */ throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.EMPTY_BUCKET_ERROR_MSG - ); + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.EMPTY_BUCKET_ERROR_MSG); } if (prefix == null) { @@ -187,9 +181,7 @@ ArrayList<String> listAllFilesInBucket(AmazonS3 connection, * execute function already. */ throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.EMPTY_PREFIX_ERROR_MSG - ); + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.EMPTY_PREFIX_ERROR_MSG); } ObjectListing result = connection.listObjects(bucketName, prefix); @@ -203,15 +195,13 @@ ArrayList<String> listAllFilesInBucket(AmazonS3 connection, return fileList; } - ArrayList<String> getSignedUrls(AmazonS3 connection, - String bucketName, - ArrayList<String> listOfFiles, - Date expiryDateTime) { + ArrayList<String> getSignedUrls( + AmazonS3 connection, String bucketName, ArrayList<String> listOfFiles, Date expiryDateTime) { ArrayList<String> urlList = new ArrayList<>(); for (String filePath : listOfFiles) { - GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, - filePath) + GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest( + bucketName, filePath) .withMethod(HttpMethod.GET) .withExpiration(expiryDateTime); @@ -226,32 +216,29 @@ ArrayList<String> getSignedUrls(AmazonS3 connection, * - Throws exception on upload failure. * - Returns signed url of the created file on success. */ - String uploadFileFromBody(AmazonS3 connection, - String bucketName, - String path, - String body, - Boolean usingFilePicker, - Date expiryDateTime) + String uploadFileFromBody( + AmazonS3 connection, + String bucketName, + String path, + String body, + Boolean usingFilePicker, + Date expiryDateTime) throws InterruptedException, AppsmithPluginException { byte[] payload; MultipartFormDataDTO multipartFormDataDTO; try { - multipartFormDataDTO = objectMapper.readValue( - body, - MultipartFormDataDTO.class); + multipartFormDataDTO = objectMapper.readValue(body, MultipartFormDataDTO.class); } catch (IOException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.UNPARSABLE_CONTENT_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } if (multipartFormDataDTO == null) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.UNPARSABLE_CONTENT_ERROR_MSG - ); + S3ErrorMessages.UNPARSABLE_CONTENT_ERROR_MSG); } if (Boolean.TRUE.equals(usingFilePicker)) { @@ -272,11 +259,11 @@ String uploadFileFromBody(AmazonS3 connection, } catch (IllegalArgumentException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.UNEXPECTED_ENCODING_IN_FILE_CONTENT_ERROR_MSG - ); + S3ErrorMessages.UNEXPECTED_ENCODING_IN_FILE_CONTENT_ERROR_MSG); } } else { - payload = getEncodedPayloadFromMultipartDTO(multipartFormDataDTO).getBytes(); + payload = + getEncodedPayloadFromMultipartDTO(multipartFormDataDTO).getBytes(); } uploadFileInS3(payload, connection, multipartFormDataDTO, bucketName, path); @@ -285,9 +272,7 @@ String uploadFileFromBody(AmazonS3 connection, ArrayList<String> listOfUrls = getSignedUrls(connection, bucketName, listOfFiles, expiryDateTime); if (listOfUrls.size() != 1) { throw new AppsmithPluginException( - S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, - S3ErrorMessages.SIGNED_URL_FETCHING_ERROR_MSG - ); + S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, S3ErrorMessages.SIGNED_URL_FETCHING_ERROR_MSG); } String signedUrl = listOfUrls.get(0); @@ -298,26 +283,23 @@ String uploadFileFromBody(AmazonS3 connection, * - Throws exception on upload failure. * - Returns signed url of the created file on success. */ - List<String> uploadMultipleFilesFromBody(AmazonS3 connection, - String bucketName, - String path, - String body, - Boolean usingFilePicker, - Date expiryDateTime) + List<String> uploadMultipleFilesFromBody( + AmazonS3 connection, + String bucketName, + String path, + String body, + Boolean usingFilePicker, + Date expiryDateTime) throws AppsmithPluginException { - List<MultipartFormDataDTO> multipartFormDataDTOs; try { - multipartFormDataDTOs = Arrays.asList(objectMapper.readValue( - body, - MultipartFormDataDTO[].class)); + multipartFormDataDTOs = Arrays.asList(objectMapper.readValue(body, MultipartFormDataDTO[].class)); } catch (IOException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.UNPARSABLE_CONTENT_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } ArrayList<String> listOfFiles = new ArrayList<>(); @@ -343,11 +325,11 @@ List<String> uploadMultipleFilesFromBody(AmazonS3 connection, throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.UNEXPECTED_ENCODING_IN_FILE_CONTENT_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } } else { - payload = getEncodedPayloadFromMultipartDTO(multipartFormDataDTO).getBytes(); + payload = getEncodedPayloadFromMultipartDTO(multipartFormDataDTO) + .getBytes(); } try { @@ -356,8 +338,7 @@ List<String> uploadMultipleFilesFromBody(AmazonS3 connection, throw new AppsmithPluginException( S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, S3ErrorMessages.FILE_UPLOAD_INTERRUPTED_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } listOfFiles.add(filePath); @@ -385,25 +366,29 @@ String readFile(AmazonS3 connection, String bucketName, String path, Boolean enc } @Override - public Mono<ActionExecutionResult> execute(AmazonS3 connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + AmazonS3 connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Unused function - return Mono.error(new AppsmithPluginException(S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, "Unsupported Operation")); + return Mono.error(new AppsmithPluginException( + S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, "Unsupported Operation")); } @Override - public Mono<ActionExecutionResult> executeParameterized(AmazonS3 connection, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { - + public Mono<ActionExecutionResult> executeParameterized( + AmazonS3 connection, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final Map<String, Object> formData = actionConfiguration.getFormData(); List<Map.Entry<String, String>> parameters = new ArrayList<>(); Boolean smartJsonSubstitution = TRUE; - Object smartSubstitutionObject = getDataValueSafelyFromFormData(formData, SMART_SUBSTITUTION, OBJECT_TYPE, - TRUE); + Object smartSubstitutionObject = + getDataValueSafelyFromFormData(formData, SMART_SUBSTITUTION, OBJECT_TYPE, TRUE); if (smartSubstitutionObject instanceof Boolean) { smartJsonSubstitution = (Boolean) smartSubstitutionObject; @@ -422,13 +407,10 @@ public Mono<ActionExecutionResult> executeParameterized(AmazonS3 connection, // Replace all the bindings with a placeholder String updatedValue = MustacheHelper.replaceMustacheWithPlaceholder(body, mustacheKeysInOrder); - updatedValue = (String) smartSubstitutionOfBindings(updatedValue, - mustacheKeysInOrder, - executeActionDTO.getParams(), - parameters); + updatedValue = (String) smartSubstitutionOfBindings( + updatedValue, mustacheKeysInOrder, executeActionDTO.getParams(), parameters); setDataValueSafelyInFormData(formData, BODY, updatedValue); - } } catch (AppsmithPluginException e) { // Initializing object for error condition @@ -443,9 +425,10 @@ public Mono<ActionExecutionResult> executeParameterized(AmazonS3 connection, return this.executeCommon(connection, datasourceConfiguration, actionConfiguration); } - private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + private Mono<ActionExecutionResult> executeCommon( + AmazonS3 connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final String[] query = new String[1]; Map<String, Object> requestProperties = new HashMap<>(); @@ -463,49 +446,38 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, } if (actionConfiguration == null) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.MANDATORY_FIELD_MISSING_ERROR_MSG - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + S3ErrorMessages.MANDATORY_FIELD_MISSING_ERROR_MSG)); } Map<String, Object> formData = actionConfiguration.getFormData(); String command = getDataValueSafelyFromFormData(formData, COMMAND, STRING_TYPE); if (StringUtils.isNullOrEmpty(command)) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.MANDATORY_PARAMETER_COMMAND_MISSING_ERROR_MSG - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + S3ErrorMessages.MANDATORY_PARAMETER_COMMAND_MISSING_ERROR_MSG)); } AmazonS3Action s3Action = AmazonS3Action.valueOf(command); query[0] = s3Action.name(); - requestParams.add(new RequestParamDTO(COMMAND, - command, null, null, null)); + requestParams.add(new RequestParamDTO(COMMAND, command, null, null, null)); - final String bucketName = (s3Action == AmazonS3Action.LIST_BUCKETS) ? - null : getDataValueSafelyFromFormData(formData, BUCKET, STRING_TYPE); + final String bucketName = (s3Action == AmazonS3Action.LIST_BUCKETS) + ? null + : getDataValueSafelyFromFormData(formData, BUCKET, STRING_TYPE); // If the action_type is LIST_BUCKET, remove the bucket name requirement - if (s3Action != AmazonS3Action.LIST_BUCKETS - && StringUtils.isNullOrEmpty(bucketName)) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.MANDATORY_PARAMETER_BUCKET_MISSING_ERROR_MSG - ) - ); + if (s3Action != AmazonS3Action.LIST_BUCKETS && StringUtils.isNullOrEmpty(bucketName)) { + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + S3ErrorMessages.MANDATORY_PARAMETER_BUCKET_MISSING_ERROR_MSG)); } requestProperties.put(BUCKET, bucketName == null ? "" : bucketName); - requestParams.add(new RequestParamDTO(BUCKET, - bucketName, null, null, null)); + requestParams.add(new RequestParamDTO(BUCKET, bucketName, null, null, null)); /* * - Allow users to upload empty file. Hence, only check for null value. @@ -514,56 +486,50 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, requestProperties.put("content", body == null ? "null" : body); if (s3Action == AmazonS3Action.UPLOAD_FILE_FROM_BODY && body == null) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.MANDATORY_PARAMETER_CONTENT_MISSING_ERROR_MSG - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + S3ErrorMessages.MANDATORY_PARAMETER_CONTENT_MISSING_ERROR_MSG)); } final String path = getDataValueSafelyFromFormData(formData, PATH, STRING_TYPE, ""); requestProperties.put(PATH, path); - if ((s3Action == AmazonS3Action.UPLOAD_FILE_FROM_BODY || s3Action == AmazonS3Action.READ_FILE || - s3Action == AmazonS3Action.DELETE_FILE) && StringUtils.isNullOrEmpty(path)) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - S3ErrorMessages.MANDATORY_PARAMETER_FILE_PATH_MISSING_ERROR_MSG - ) - ); + if ((s3Action == AmazonS3Action.UPLOAD_FILE_FROM_BODY + || s3Action == AmazonS3Action.READ_FILE + || s3Action == AmazonS3Action.DELETE_FILE) + && StringUtils.isNullOrEmpty(path)) { + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + S3ErrorMessages.MANDATORY_PARAMETER_FILE_PATH_MISSING_ERROR_MSG)); } Object actionResult; switch (s3Action) { case LIST: String prefix = getDataValueSafelyFromFormData(formData, LIST_PREFIX, STRING_TYPE, ""); - requestParams.add(new RequestParamDTO(LIST_PREFIX, - prefix, null, null, null)); + requestParams.add(new RequestParamDTO(LIST_PREFIX, prefix, null, null, null)); ArrayList<String> listOfFiles = listAllFilesInBucket(connection, bucketName, prefix); - Boolean isSignedUrl = YES.equals(getDataValueSafelyFromFormData(formData, LIST_SIGNED_URL, STRING_TYPE)); + Boolean isSignedUrl = YES.equals( + getDataValueSafelyFromFormData(formData, LIST_SIGNED_URL, STRING_TYPE)); if (isSignedUrl) { - requestParams.add(new RequestParamDTO(LIST_SIGNED_URL, YES, null, - null, null)); + requestParams.add(new RequestParamDTO(LIST_SIGNED_URL, YES, null, null, null)); int durationInMinutes; try { - durationInMinutes = Integer.parseInt(getDataValueSafelyFromFormData(formData, - LIST_EXPIRY, STRING_TYPE, DEFAULT_URL_EXPIRY_IN_MINUTES)); + durationInMinutes = Integer.parseInt(getDataValueSafelyFromFormData( + formData, LIST_EXPIRY, STRING_TYPE, DEFAULT_URL_EXPIRY_IN_MINUTES)); } catch (NumberFormatException e) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.EXPIRY_DURATION_NOT_A_NUMBER_ERROR_MSG, - e.getMessage() - )); + e.getMessage())); } - requestParams.add(new RequestParamDTO(LIST_EXPIRY, - durationInMinutes, null, null, null)); + requestParams.add( + new RequestParamDTO(LIST_EXPIRY, durationInMinutes, null, null, null)); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, durationInMinutes); @@ -571,15 +537,12 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, DateFormat dateTimeFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS z"); String expiryDateTimeString = dateTimeFormat.format(expiryDateTime); - ArrayList<String> listOfSignedUrls = getSignedUrls(connection, - bucketName, - listOfFiles, - expiryDateTime); + ArrayList<String> listOfSignedUrls = + getSignedUrls(connection, bucketName, listOfFiles, expiryDateTime); if (listOfFiles.size() != listOfSignedUrls.size()) { return Mono.error(new AppsmithPluginException( S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, - S3ErrorMessages.ACTION_LIST_OF_FILE_FETCHING_ERROR_MSG - )); + S3ErrorMessages.ACTION_LIST_OF_FILE_FETCHING_ERROR_MSG)); } actionResult = new ArrayList<>(); @@ -591,8 +554,7 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, ((ArrayList<Object>) actionResult).add(fileInfo); } } else { - requestParams.add(new RequestParamDTO(LIST_SIGNED_URL, - "", null, null, null)); + requestParams.add(new RequestParamDTO(LIST_SIGNED_URL, "", null, null, null)); actionResult = new ArrayList<>(); for (int i = 0; i < listOfFiles.size(); i++) { HashMap<String, Object> fileInfo = new HashMap<>(); @@ -601,26 +563,26 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, } } - String isUnsignedUrl = getDataValueSafelyFromFormData(formData, LIST_UNSIGNED_URL, STRING_TYPE); + String isUnsignedUrl = + getDataValueSafelyFromFormData(formData, LIST_UNSIGNED_URL, STRING_TYPE); if (YES.equals(isUnsignedUrl)) { - requestParams.add(new RequestParamDTO(LIST_UNSIGNED_URL, YES, null, - null, null)); - ((ArrayList<Object>) actionResult).stream() - .forEach(item -> ((Map) item) - .put( - "url", // key - connection.getUrl(bucketName, (String) ((Map) item).get("fileName")).toString() // value - ) - ); + requestParams.add(new RequestParamDTO(LIST_UNSIGNED_URL, YES, null, null, null)); + ((ArrayList<Object>) actionResult).stream().forEach(item -> ((Map) item) + .put( + "url", // key + connection + .getUrl(bucketName, (String) ((Map) item).get("fileName")) + .toString() // value + )); } else { - requestParams.add(new RequestParamDTO(LIST_UNSIGNED_URL, NO, null, - null, null)); + requestParams.add(new RequestParamDTO(LIST_UNSIGNED_URL, NO, null, null, null)); } // Check if where condition is configured - Object whereFormObject = getDataValueSafelyFromFormData(formData, LIST_WHERE, OBJECT_TYPE); + Object whereFormObject = + getDataValueSafelyFromFormData(formData, LIST_WHERE, OBJECT_TYPE); Condition condition = null; if (whereFormObject != null) { @@ -628,33 +590,32 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, condition = parseWhereClause(whereForm); } - List<Map<String, String>> sortBy = - getDataValueSafelyFromFormData(formData, LIST_SORT, new TypeReference<List<Map<String, String>>>() { - }); + List<Map<String, String>> sortBy = getDataValueSafelyFromFormData( + formData, LIST_SORT, new TypeReference<List<Map<String, String>>>() {}); - Map<String, String> paginateBy = - getDataValueSafelyFromFormData(formData, LIST_PAGINATE, new TypeReference<Map<String, String>>() { - }); + Map<String, String> paginateBy = getDataValueSafelyFromFormData( + formData, LIST_PAGINATE, new TypeReference<Map<String, String>>() {}); ArrayNode preFilteringResponse = objectMapper.valueToTree(actionResult); - actionResult = filterDataService.filterDataNew(preFilteringResponse, + actionResult = filterDataService.filterDataNew( + preFilteringResponse, new UQIDataFilterParams(condition, null, sortBy, paginateBy)); break; case UPLOAD_FILE_FROM_BODY: { - requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); + requestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); int durationInMinutes; try { - durationInMinutes = Integer.parseInt(getDataValueSafelyFromFormData(formData, - CREATE_EXPIRY, STRING_TYPE, DEFAULT_URL_EXPIRY_IN_MINUTES)); + durationInMinutes = Integer.parseInt(getDataValueSafelyFromFormData( + formData, CREATE_EXPIRY, STRING_TYPE, DEFAULT_URL_EXPIRY_IN_MINUTES)); } catch (NumberFormatException e) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.EXPIRY_DURATION_NOT_A_NUMBER_ERROR_MSG, - e.getMessage() - )); + e.getMessage())); } requestProperties.put("expiry duration in minutes", String.valueOf(durationInMinutes)); @@ -667,38 +628,42 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, String signedUrl; - String dataType = getDataValueSafelyFromFormData(formData, CREATE_DATATYPE, STRING_TYPE); + String dataType = + getDataValueSafelyFromFormData(formData, CREATE_DATATYPE, STRING_TYPE); if (YES.equals(dataType)) { - requestParams.add(new RequestParamDTO(CREATE_DATATYPE, "Base64", - null, null, null)); - signedUrl = uploadFileFromBody(connection, bucketName, path, body, true, expiryDateTime); + requestParams.add(new RequestParamDTO(CREATE_DATATYPE, "Base64", null, null, null)); + signedUrl = uploadFileFromBody( + connection, bucketName, path, body, true, expiryDateTime); } else { - requestParams.add(new RequestParamDTO(CREATE_DATATYPE, - "Text / Binary", null, null, null)); - signedUrl = uploadFileFromBody(connection, bucketName, path, body, false, expiryDateTime); + requestParams.add( + new RequestParamDTO(CREATE_DATATYPE, "Text / Binary", null, null, null)); + signedUrl = uploadFileFromBody( + connection, bucketName, path, body, false, expiryDateTime); } actionResult = new HashMap<String, Object>(); ((HashMap<String, Object>) actionResult).put("signedUrl", signedUrl); ((HashMap<String, Object>) actionResult).put("urlExpiryDate", expiryDateTimeString); - requestParams.add(new RequestParamDTO(CREATE_EXPIRY, expiryDateTimeString, null, null, null)); - requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, body, null, null, null)); + requestParams.add( + new RequestParamDTO(CREATE_EXPIRY, expiryDateTimeString, null, null, null)); + requestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_BODY, body, null, null, null)); break; } case UPLOAD_MULTIPLE_FILES_FROM_BODY: { - requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); + requestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); int durationInMinutes; try { - durationInMinutes = Integer.parseInt(getDataValueSafelyFromFormData(formData, - CREATE_EXPIRY, STRING_TYPE, DEFAULT_URL_EXPIRY_IN_MINUTES)); + durationInMinutes = Integer.parseInt(getDataValueSafelyFromFormData( + formData, CREATE_EXPIRY, STRING_TYPE, DEFAULT_URL_EXPIRY_IN_MINUTES)); } catch (NumberFormatException e) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.EXPIRY_DURATION_NOT_A_NUMBER_ERROR_MSG, - e.getMessage() - )); + e.getMessage())); } requestProperties.put("expiry duration in minutes", String.valueOf(durationInMinutes)); @@ -711,46 +676,49 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, List<String> signedUrls; - String dataType = getDataValueSafelyFromFormData(formData, CREATE_DATATYPE, STRING_TYPE); + String dataType = + getDataValueSafelyFromFormData(formData, CREATE_DATATYPE, STRING_TYPE); if (YES.equals(dataType)) { - requestParams.add(new RequestParamDTO(CREATE_DATATYPE, "Base64", - null, null, null)); - signedUrls = uploadMultipleFilesFromBody(connection, bucketName, path, body, true, expiryDateTime); + requestParams.add(new RequestParamDTO(CREATE_DATATYPE, "Base64", null, null, null)); + signedUrls = uploadMultipleFilesFromBody( + connection, bucketName, path, body, true, expiryDateTime); } else { - requestParams.add(new RequestParamDTO(CREATE_DATATYPE, - "Text / Binary", null, null, null)); - signedUrls = uploadMultipleFilesFromBody(connection, bucketName, path, body, false, expiryDateTime); + requestParams.add( + new RequestParamDTO(CREATE_DATATYPE, "Text / Binary", null, null, null)); + signedUrls = uploadMultipleFilesFromBody( + connection, bucketName, path, body, false, expiryDateTime); } actionResult = new HashMap<String, Object>(); ((HashMap<String, Object>) actionResult).put("signedUrls", signedUrls); ((HashMap<String, Object>) actionResult).put("urlExpiryDate", expiryDateTimeString); - requestParams.add(new RequestParamDTO(CREATE_EXPIRY, - expiryDateTimeString, null, null, null)); - requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, body, null, null, null)); + requestParams.add( + new RequestParamDTO(CREATE_EXPIRY, expiryDateTimeString, null, null, null)); + requestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_BODY, body, null, null, null)); break; } case READ_FILE: - requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); + requestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); String result; String isBase64 = getDataValueSafelyFromFormData(formData, READ_DATATYPE, STRING_TYPE); if (YES.equals(isBase64)) { - requestParams.add(new RequestParamDTO(READ_DATATYPE, - YES, null, null, null)); + requestParams.add(new RequestParamDTO(READ_DATATYPE, YES, null, null, null)); result = readFile(connection, bucketName, path, true); } else { - requestParams.add(new RequestParamDTO(READ_DATATYPE, - NO, null, null, null)); + requestParams.add(new RequestParamDTO(READ_DATATYPE, NO, null, null, null)); result = readFile(connection, bucketName, path, false); } actionResult = Map.of("fileData", result); break; case DELETE_FILE: - requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); + requestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); /* * - If attempting to delete an object that does not exist, Amazon S3 returns a success message @@ -760,30 +728,30 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, actionResult = Map.of("status", "File deleted successfully"); break; case DELETE_MULTIPLE_FILES: - requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); + requestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); deleteMultipleObjects(connection, bucketName, path); actionResult = Map.of("status", "All files deleted successfully"); break; - /** - * Commenting out this code section since we have not decided to expose this action to users - * as of now. In the future, if we do decide to expose this action to the users, just uncommenting this - * code should take care of gathering the list of buckets. Hence, leaving this commented but - * intact for future use. - - case LIST_BUCKETS: - List<String> bucketNames = connection.listBuckets() - .stream() - .map(Bucket::getName) - .collect(Collectors.toList()); - actionResult = Map.of("bucketList", bucketNames); - break; - */ + /** + * Commenting out this code section since we have not decided to expose this action to users + * as of now. In the future, if we do decide to expose this action to the users, just uncommenting this + * code should take care of gathering the list of buckets. Hence, leaving this commented but + * intact for future use. + * + * case LIST_BUCKETS: + * List<String> bucketNames = connection.listBuckets() + * .stream() + * .map(Bucket::getName) + * .collect(Collectors.toList()); + * actionResult = Map.of("bucketList", bucketNames); + * break; + */ default: return Mono.error(new AppsmithPluginException( S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, - String.format(S3ErrorMessages.UNSUPPORTED_ACTION_ERROR_MSG, query[0]) - )); + String.format(S3ErrorMessages.UNSUPPORTED_ACTION_ERROR_MSG, query[0]))); } return Mono.just(actionResult); }) @@ -802,11 +770,13 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, if (e instanceof StaleConnectionException) { return Mono.error(e); } else if (!(e instanceof AppsmithPluginException)) { - e = new AppsmithPluginException(e, S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, S3ErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG); + e = new AppsmithPluginException( + e, + S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, + S3ErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG); } result.setErrorInfo(e, amazonS3ErrorUtils); return Mono.just(result); - }) // Now set the request in the result to be returned to the server .map(actionExecutionResult -> { @@ -820,7 +790,8 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection, .subscribeOn(scheduler); } - private void deleteMultipleObjects(AmazonS3 connection, String bucketName, String path) throws AppsmithPluginException { + private void deleteMultipleObjects(AmazonS3 connection, String bucketName, String path) + throws AppsmithPluginException { List<String> listOfFiles; try { listOfFiles = parseList(path); @@ -828,8 +799,7 @@ private void deleteMultipleObjects(AmazonS3 connection, String bucketName, Strin throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, S3ErrorMessages.LIST_OF_FILE_PARSING_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } DeleteObjectsRequest deleteObjectsRequest = getDeleteObjectsRequest(bucketName, listOfFiles); @@ -839,8 +809,7 @@ private void deleteMultipleObjects(AmazonS3 connection, String bucketName, Strin throw new AppsmithPluginException( S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, S3ErrorMessages.FILE_CANNOT_BE_DELETED_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } } @@ -857,31 +826,25 @@ public Mono<AmazonS3> datasourceCreate(DatasourceConfiguration datasourceConfigu try { Class.forName(S3_DRIVER); } catch (ClassNotFoundException e) { - return Mono.error( - new AppsmithPluginException( - S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, - S3ErrorMessages.S3_DRIVER_LOADING_ERROR_MSG, - e.getMessage() - ) - ); + return Mono.error(new AppsmithPluginException( + S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, + S3ErrorMessages.S3_DRIVER_LOADING_ERROR_MSG, + e.getMessage())); } - return Mono.fromCallable(() -> getS3ClientBuilder(datasourceConfiguration).build()) + return Mono.fromCallable( + () -> getS3ClientBuilder(datasourceConfiguration).build()) .flatMap(client -> Mono.just(client)) .onErrorResume(e -> { - if (e instanceof AppsmithPluginException) { - return Mono.error(e); - } + if (e instanceof AppsmithPluginException) { + return Mono.error(e); + } - return Mono.error( - new AppsmithPluginException( - S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, - S3ErrorMessages.CONNECTIVITY_ERROR_MSG, - e.getMessage() - ) - ); - } - ) + return Mono.error(new AppsmithPluginException( + S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED, + S3ErrorMessages.CONNECTIVITY_ERROR_MSG, + e.getMessage())); + }) .subscribeOn(scheduler); } @@ -928,18 +891,22 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur */ if (properties == null || properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX) == null - || StringUtils.isNullOrEmpty((String) properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX).getValue())) { + || StringUtils.isNullOrEmpty((String) + properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX).getValue())) { invalids.add(S3ErrorMessages.DS_S3_SERVICE_PROVIDER_PROPERTIES_FETCHING_ERROR_MSG); } boolean usingAWSS3ServiceProvider = false; if (properties != null && properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX) != null) { - usingAWSS3ServiceProvider = - AWS_S3_SERVICE_PROVIDER.equals(properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX).getValue()); + usingAWSS3ServiceProvider = AWS_S3_SERVICE_PROVIDER.equals( + properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX).getValue()); } if (!usingAWSS3ServiceProvider && (CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints()) - || datasourceConfiguration.getEndpoints().get(CUSTOM_ENDPOINT_INDEX) == null - || StringUtils.isNullOrEmpty(datasourceConfiguration.getEndpoints().get(CUSTOM_ENDPOINT_INDEX).getHost()))) { + || datasourceConfiguration.getEndpoints().get(CUSTOM_ENDPOINT_INDEX) == null + || StringUtils.isNullOrEmpty(datasourceConfiguration + .getEndpoints() + .get(CUSTOM_ENDPOINT_INDEX) + .getHost()))) { invalids.add(S3ErrorMessages.DS_MANDATORY_PARAMETER_ENDPOINT_URL_MISSING_ERROR_MSG); } @@ -957,7 +924,8 @@ public Mono<DatasourceTestResult> testDatasource(AmazonS3 connection) { connection.listBuckets(); return new DatasourceTestResult(); }) - .onErrorResume(error -> Mono.just(new DatasourceTestResult(amazonS3ErrorUtils.getReadableError(error)))); + .onErrorResume( + error -> Mono.just(new DatasourceTestResult(amazonS3ErrorUtils.getReadableError(error)))); } /** @@ -965,27 +933,30 @@ public Mono<DatasourceTestResult> testDatasource(AmazonS3 connection) { * structure. */ @Override - public Mono<DatasourceStructure> getStructure(AmazonS3 connection, DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + AmazonS3 connection, DatasourceConfiguration datasourceConfiguration) { return Mono.fromSupplier(() -> { List<DatasourceStructure.Table> tableList; try { - tableList = connection.listBuckets() - .stream() + tableList = connection.listBuckets().stream() /* Get name of each bucket */ .map(Bucket::getName) /* Get command templates and use it to create Table object */ - .map(bucketName -> new DatasourceStructure.Table(DatasourceStructure.TableType.BUCKET, "", - bucketName, new ArrayList<>(), new ArrayList<>(), getTemplates(bucketName, - DEFAULT_FILE_NAME))) + .map(bucketName -> new DatasourceStructure.Table( + DatasourceStructure.TableType.BUCKET, + "", + bucketName, + new ArrayList<>(), + new ArrayList<>(), + getTemplates(bucketName, DEFAULT_FILE_NAME))) /* Collect all Table objects in a list */ .collect(Collectors.toList()); } catch (SdkClientException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, S3ErrorMessages.LIST_OF_BUCKET_FETCHING_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } catch (IllegalStateException e) { throw new StaleConnectionException(e.getMessage()); } @@ -1007,38 +978,49 @@ private String getOneFileNameOrDefault(AmazonS3 connection, String bucketName, S } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) { String jsonBody = (String) input; Param param = (Param) args[0]; - return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue(jsonBody, value, null, insertedParams, null, param); + return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue( + jsonBody, value, null, insertedParams, null, param); } private String getEncodedPayloadFromMultipartDTO(MultipartFormDataDTO multipartFormDataDTO) { String encodedPayload; if (multipartFormDataDTO.getData() instanceof LinkedHashMap) { - encodedPayload = ((LinkedHashMap<?, ?>) multipartFormDataDTO.getData()).get("data").toString(); + encodedPayload = ((LinkedHashMap<?, ?>) multipartFormDataDTO.getData()) + .get("data") + .toString(); } else { encodedPayload = (String) multipartFormDataDTO.getData(); } return encodedPayload; } - void uploadFileInS3(byte[] payload, AmazonS3 connection, MultipartFormDataDTO multipartFormDataDTO, - String bucketName, String path) throws InterruptedException { + void uploadFileInS3( + byte[] payload, + AmazonS3 connection, + MultipartFormDataDTO multipartFormDataDTO, + String bucketName, + String path) + throws InterruptedException { InputStream inputStream = new ByteArrayInputStream(payload); - TransferManager transferManager = TransferManagerBuilder.standard().withS3Client(connection).build(); + TransferManager transferManager = + TransferManagerBuilder.standard().withS3Client(connection).build(); final ObjectMetadata objectMetadata = new ObjectMetadata(); // Only add content type if the user has mentioned it in the body if (multipartFormDataDTO.getType() != null) { objectMetadata.setContentType(multipartFormDataDTO.getType()); } - transferManager.upload(bucketName, path, inputStream, objectMetadata).waitForUploadResult(); + transferManager + .upload(bucketName, path, inputStream, objectMetadata) + .waitForUploadResult(); } - } } diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/constants/FieldName.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/constants/FieldName.java index a8a575198de2..103610a82aa5 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/constants/FieldName.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/constants/FieldName.java @@ -37,4 +37,3 @@ public class FieldName { public static final String LIST_PAGINATE = LIST + "." + PAGINATE; public static final String SMART_SUBSTITUTION = "smartSubstitution"; } - diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/exceptions/S3ErrorMessages.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/exceptions/S3ErrorMessages.java index a980544788f8..aefb7e796bbf 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/exceptions/S3ErrorMessages.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/exceptions/S3ErrorMessages.java @@ -6,99 +6,124 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) // To prevent instantiation public class S3ErrorMessages extends BasePluginErrorMessages { - public static final String FILE_CONTENT_FETCHING_ERROR_MSG = "Appsmith server has encountered an unexpected error when fetching file " + - "content from AWS S3 server. Please reach out to Appsmith customer support to resolve this."; + public static final String FILE_CONTENT_FETCHING_ERROR_MSG = + "Appsmith server has encountered an unexpected error when fetching file " + + "content from AWS S3 server. Please reach out to Appsmith customer support to resolve this."; - public static final String CONNECTIVITY_ERROR_MSG = "Appsmith server has encountered an unexpected error when establishing " + - "connection with AWS S3 server. Please reach out to Appsmith customer support to resolve this."; + public static final String CONNECTIVITY_ERROR_MSG = + "Appsmith server has encountered an unexpected error when establishing " + + "connection with AWS S3 server. Please reach out to Appsmith customer support to resolve this."; - public static final String EMPTY_BUCKET_ERROR_MSG = "Appsmith has encountered an unexpected error when getting bucket name. Please reach out to " + - "Appsmith customer support to resolve this."; + public static final String EMPTY_BUCKET_ERROR_MSG = + "Appsmith has encountered an unexpected error when getting bucket name. Please reach out to " + + "Appsmith customer support to resolve this."; - public static final String EMPTY_PREFIX_ERROR_MSG = "Appsmith has encountered an unexpected error when getting path prefix. Please reach out to " + - "Appsmith customer support to resolve this."; + public static final String EMPTY_PREFIX_ERROR_MSG = + "Appsmith has encountered an unexpected error when getting path prefix. Please reach out to " + + "Appsmith customer support to resolve this."; - public static final String UNPARSABLE_CONTENT_ERROR_MSG = "Unable to parse content. Expected to receive an object with `data` and `type`."; + public static final String UNPARSABLE_CONTENT_ERROR_MSG = + "Unable to parse content. Expected to receive an object with `data` and `type`."; - public static final String UNEXPECTED_ENCODING_IN_FILE_CONTENT_ERROR_MSG = "File content is not base64 encoded. File content needs to be base64 encoded when the " + - "'File data type: Base64/Text' field is selected 'Yes'."; + public static final String UNEXPECTED_ENCODING_IN_FILE_CONTENT_ERROR_MSG = + "File content is not base64 encoded. File content needs to be base64 encoded when the " + + "'File data type: Base64/Text' field is selected 'Yes'."; - public static final String SIGNED_URL_FETCHING_ERROR_MSG = "Appsmith has encountered an unexpected error while fetching url from AmazonS3 after file " + - "creation. Please reach out to Appsmith customer support to resolve this."; + public static final String SIGNED_URL_FETCHING_ERROR_MSG = + "Appsmith has encountered an unexpected error while fetching url from AmazonS3 after file " + + "creation. Please reach out to Appsmith customer support to resolve this."; public static final String FILE_UPLOAD_INTERRUPTED_ERROR_MSG = "File upload interrupted."; - public static final String MANDATORY_FIELD_MISSING_ERROR_MSG = "At least one of the mandatory fields in S3 query creation form is empty - 'Action'/" + - "'Bucket name'/'File path'/'Content'. Please fill all the mandatory fields and try " + - "again."; + public static final String MANDATORY_FIELD_MISSING_ERROR_MSG = + "At least one of the mandatory fields in S3 query creation form is empty - 'Action'/" + + "'Bucket name'/'File path'/'Content'. Please fill all the mandatory fields and try " + + "again."; - public static final String MANDATORY_PARAMETER_COMMAND_MISSING_ERROR_MSG = "Mandatory parameter 'Command' is missing. Did you forget to select one of the commands" + - " from the Command dropdown ?"; + public static final String MANDATORY_PARAMETER_COMMAND_MISSING_ERROR_MSG = + "Mandatory parameter 'Command' is missing. Did you forget to select one of the commands" + + " from the Command dropdown ?"; - public static final String MANDATORY_PARAMETER_BUCKET_MISSING_ERROR_MSG = "Mandatory parameter 'Bucket name' is missing. Did you forget to edit the 'Bucket " + - "Name' field in the query form ?"; + public static final String MANDATORY_PARAMETER_BUCKET_MISSING_ERROR_MSG = + "Mandatory parameter 'Bucket name' is missing. Did you forget to edit the 'Bucket " + + "Name' field in the query form ?"; - public static final String MANDATORY_PARAMETER_CONTENT_MISSING_ERROR_MSG = "Mandatory parameter 'Content' is missing. Did you forget to edit the 'Content' " + - "field in the query form ?"; + public static final String MANDATORY_PARAMETER_CONTENT_MISSING_ERROR_MSG = + "Mandatory parameter 'Content' is missing. Did you forget to edit the 'Content' " + + "field in the query form ?"; - public static final String MANDATORY_PARAMETER_FILE_PATH_MISSING_ERROR_MSG = "Required parameter 'File path' is missing. Did you forget to edit the 'File path' field " + - "in the query form ? This field cannot be left empty with the chosen action."; + public static final String MANDATORY_PARAMETER_FILE_PATH_MISSING_ERROR_MSG = + "Required parameter 'File path' is missing. Did you forget to edit the 'File path' field " + + "in the query form ? This field cannot be left empty with the chosen action."; - public static final String EXPIRY_DURATION_NOT_A_NUMBER_ERROR_MSG = "Parameter 'Expiry Duration of Signed URL' is NOT a number. Please ensure that the " + - "input to 'Expiry Duration of Signed URL' field is a valid number - i.e. " + - "any non-negative integer. Please note that the maximum expiry " + - "duration supported by Amazon S3 is 7 days i.e. 10080 minutes."; + public static final String EXPIRY_DURATION_NOT_A_NUMBER_ERROR_MSG = + "Parameter 'Expiry Duration of Signed URL' is NOT a number. Please ensure that the " + + "input to 'Expiry Duration of Signed URL' field is a valid number - i.e. " + + "any non-negative integer. Please note that the maximum expiry " + + "duration supported by Amazon S3 is 7 days i.e. 10080 minutes."; - public static final String ACTION_LIST_OF_FILE_FETCHING_ERROR_MSG = "Appsmith server has encountered an unexpected error when getting " + - "list of files from AWS S3 server. Please reach out to Appsmith customer " + - "support to resolve this."; + public static final String ACTION_LIST_OF_FILE_FETCHING_ERROR_MSG = + "Appsmith server has encountered an unexpected error when getting " + + "list of files from AWS S3 server. Please reach out to Appsmith customer " + + "support to resolve this."; - public static final String UNSUPPORTED_ACTION_ERROR_MSG = "It seems that the query has requested an unsupported action: %s" + - ". Please reach out to Appsmith customer support to resolve this."; + public static final String UNSUPPORTED_ACTION_ERROR_MSG = + "It seems that the query has requested an unsupported action: %s" + + ". Please reach out to Appsmith customer support to resolve this."; - public static final String LIST_OF_BUCKET_FETCHING_ERROR_MSG = "Appsmith server has failed to fetch list of buckets from database. Please check if \" +\n" + - " \"the database credentials are valid and/or you have the required permissions."; + public static final String LIST_OF_BUCKET_FETCHING_ERROR_MSG = + "Appsmith server has failed to fetch list of buckets from database. Please check if \" +\n" + + " \"the database credentials are valid and/or you have the required permissions."; - public static final String S3_SERVICE_PROVIDER_IDENTIFICATION_ERROR_MSG = "Appsmith S3 plugin service has " + - "failed to identify the S3 service provider type. Please reach out to Appsmith customer support" + - " to resolve this."; + public static final String S3_SERVICE_PROVIDER_IDENTIFICATION_ERROR_MSG = "Appsmith S3 plugin service has " + + "failed to identify the S3 service provider type. Please reach out to Appsmith customer support" + + " to resolve this."; - public static final String AWS_CREDENTIALS_PARSING_ERROR_MSG = "Appsmith server has encountered an error when parsing AWS credentials from datasource."; + public static final String AWS_CREDENTIALS_PARSING_ERROR_MSG = + "Appsmith server has encountered an error when parsing AWS credentials from datasource."; - public static final String INCORRECT_S3_ENDPOINT_URL_ERROR_MSG = "Your S3 endpoint" + - " URL seems to be incorrect for the selected S3 service provider. Please check your endpoint URL " + - "and the selected S3 service provider."; + public static final String INCORRECT_S3_ENDPOINT_URL_ERROR_MSG = "Your S3 endpoint" + + " URL seems to be incorrect for the selected S3 service provider. Please check your endpoint URL " + + "and the selected S3 service provider."; public static final String FILE_CANNOT_BE_DELETED_ERROR_MSG = "One or more files could not be deleted."; - public static final String S3_DRIVER_LOADING_ERROR_MSG = "Appsmith server has failed to load AWS S3 driver class. Please reach out to Appsmith " + - "customer support to resolve this."; + public static final String S3_DRIVER_LOADING_ERROR_MSG = + "Appsmith server has failed to load AWS S3 driver class. Please reach out to Appsmith " + + "customer support to resolve this."; - public static final String LIST_OF_FILE_PARSING_ERROR_MSG = "Appsmith server failed to parse the list of files. Please provide the list of files in the " + - "correct format e.g. [\"file1\", \"file2\"]."; + public static final String LIST_OF_FILE_PARSING_ERROR_MSG = + "Appsmith server failed to parse the list of files. Please provide the list of files in the " + + "correct format e.g. [\"file1\", \"file2\"]."; - public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Your S3 query failed to execute. To know more please check the error details."; + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = + "Your S3 query failed to execute. To know more please check the error details."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ - public static final String DS_AT_LEAST_ONE_MANDATORY_PARAMETER_MISSING_ERROR_MSG = "At least one of the mandatory fields in S3 datasource creation form is empty - " + - "'Access key'/'Secret key'/'Region'. Please fill all the mandatory fields and try again."; - - public static final String DS_MANDATORY_PARAMETER_ACCESS_KEY_MISSING_ERROR_MSG = "Mandatory parameter 'Access key' is empty. Did you forget to edit the 'Access key' " + - "field in the datasource creation form ? You need to fill it with your AWS Access " + - "Key."; - - public static final String DS_MANDATORY_PARAMETER_SECRET_KEY_MISSING_ERROR_MSG = "Mandatory parameter 'Secret key' is empty. Did you forget to edit the 'Secret key' " + - "field in the datasource creation form ? You need to fill it with your AWS Secret " + - "Key."; - - public static final String DS_S3_SERVICE_PROVIDER_PROPERTIES_FETCHING_ERROR_MSG = "Appsmith has failed to fetch the 'S3 service provider' field properties. Please " + - "reach out to Appsmith customer support to resolve this."; - - public static final String DS_MANDATORY_PARAMETER_ENDPOINT_URL_MISSING_ERROR_MSG = "Required parameter 'Endpoint URL' is empty. Did you forget to edit the 'Endpoint" + - " URL' field in the datasource creation form ? You need to fill it with " + - "the endpoint URL of your S3 instance."; + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ + public static final String DS_AT_LEAST_ONE_MANDATORY_PARAMETER_MISSING_ERROR_MSG = + "At least one of the mandatory fields in S3 datasource creation form is empty - " + + "'Access key'/'Secret key'/'Region'. Please fill all the mandatory fields and try again."; + + public static final String DS_MANDATORY_PARAMETER_ACCESS_KEY_MISSING_ERROR_MSG = + "Mandatory parameter 'Access key' is empty. Did you forget to edit the 'Access key' " + + "field in the datasource creation form ? You need to fill it with your AWS Access " + + "Key."; + + public static final String DS_MANDATORY_PARAMETER_SECRET_KEY_MISSING_ERROR_MSG = + "Mandatory parameter 'Secret key' is empty. Did you forget to edit the 'Secret key' " + + "field in the datasource creation form ? You need to fill it with your AWS Secret " + + "Key."; + + public static final String DS_S3_SERVICE_PROVIDER_PROPERTIES_FETCHING_ERROR_MSG = + "Appsmith has failed to fetch the 'S3 service provider' field properties. Please " + + "reach out to Appsmith customer support to resolve this."; + + public static final String DS_MANDATORY_PARAMETER_ENDPOINT_URL_MISSING_ERROR_MSG = + "Required parameter 'Endpoint URL' is empty. Did you forget to edit the 'Endpoint" + + " URL' field in the datasource creation form ? You need to fill it with " + + "the endpoint URL of your S3 instance."; } diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/exceptions/S3PluginError.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/exceptions/S3PluginError.java index 0b2e860f7976..bbc91320bac7 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/exceptions/S3PluginError.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/exceptions/S3PluginError.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum S3PluginError implements BasePluginError { AMAZON_S3_QUERY_EXECUTION_FAILED( @@ -16,8 +15,7 @@ public enum S3PluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; @@ -31,8 +29,15 @@ public enum S3PluginError implements BasePluginError { private final String downstreamErrorCode; - S3PluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + S3PluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -59,5 +64,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/AmazonS3ErrorUtils.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/AmazonS3ErrorUtils.java index 3d816ceee6b8..7a736551bd33 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/AmazonS3ErrorUtils.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/AmazonS3ErrorUtils.java @@ -4,14 +4,11 @@ import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.plugins.AppsmithPluginErrorUtils; - - public class AmazonS3ErrorUtils extends AppsmithPluginErrorUtils { private static AmazonS3ErrorUtils amazonS3ErrorUtils; - - private AmazonS3ErrorUtils () throws InstantiationException { + private AmazonS3ErrorUtils() throws InstantiationException { /** * Prevention of creating any other new object by using constructor */ @@ -31,7 +28,7 @@ protected Object clone() throws CloneNotSupportedException { public static AmazonS3ErrorUtils getInstance() throws InstantiationException { if (amazonS3ErrorUtils == null) { synchronized (AmazonS3ErrorUtils.class) { - if (amazonS3ErrorUtils == null){ + if (amazonS3ErrorUtils == null) { amazonS3ErrorUtils = new AmazonS3ErrorUtils(); } } @@ -53,8 +50,7 @@ public String getReadableError(Throwable error) { return error.getMessage(); } externalError = ((AppsmithPluginException) error).getExternalError(); - } - else { + } else { externalError = error; } @@ -69,7 +65,6 @@ public String getReadableError(Throwable error) { * InvalidAccessPoint * Return string: InvalidAccessPoint: The specified access point name or account is not valid. */ - return amazonServiceException.getErrorCode() + ": " + amazonServiceException.getErrorMessage(); } @@ -80,8 +75,6 @@ public String getReadableError(Throwable error) { * Return String * An unescaped quote was found while parsing the CSV file. To allow quoted record delimiters, set AllowQuotedRecordDelimiter to 'TRUE'. **/ - return error.getMessage(); } } - diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/DatasourceUtils.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/DatasourceUtils.java index b169a1523923..ed9147189373 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/DatasourceUtils.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/DatasourceUtils.java @@ -32,6 +32,7 @@ public class DatasourceUtils { * Group 2 match: de-fra1 */ public static String UPCLOUD_URL_ENDPOINT_PATTERN = "^([^\\.]+)\\.([^\\.]+)\\.upcloudobjects\\.com$"; + public static int UPCLOUD_REGION_GROUP_INDEX = 2; /** @@ -39,6 +40,7 @@ public class DatasourceUtils { * Group 2 match: ap-northeast-2 */ public static String WASABI_URL_ENDPOINT_PATTERN = "^([^\\.]+)\\.([^\\.]+)\\.wasabisys\\.com$"; + public static int WASABI_REGION_GROUP_INDEX = 2; /** @@ -46,6 +48,7 @@ public class DatasourceUtils { * Group 1 match: fra1 */ public static String DIGITAL_OCEAN_URL_ENDPOINT_PATTERN = "^([^\\.]+)\\.digitaloceanspaces\\.com$"; + public static int DIGITAL_OCEAN_REGION_GROUP_INDEX = 1; /** @@ -53,17 +56,18 @@ public class DatasourceUtils { * Group 1 match: us-east-1 */ public static String DREAM_OBJECTS_URL_ENDPOINT_PATTERN = "^objects-([^\\.]+)\\.dream\\.io$"; + public static int DREAM_OBJECTS_REGION_GROUP_INDEX = 1; /* This enum lists various types of S3 service providers that we support. */ public enum S3ServiceProvider { - AMAZON ("amazon-s3"), - UPCLOUD ("upcloud"), - WASABI ("wasabi"), - DIGITAL_OCEAN_SPACES ("digital-ocean-spaces"), - DREAM_OBJECTS ("dream-objects"), - MINIO ("minio"), - OTHER ("other"); + AMAZON("amazon-s3"), + UPCLOUD("upcloud"), + WASABI("wasabi"), + DIGITAL_OCEAN_SPACES("digital-ocean-spaces"), + DREAM_OBJECTS("dream-objects"), + MINIO("minio"), + OTHER("other"); private String name; @@ -78,7 +82,9 @@ public static S3ServiceProvider fromString(String name) throws AppsmithPluginExc } } - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, S3ErrorMessages.S3_SERVICE_PROVIDER_IDENTIFICATION_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + S3ErrorMessages.S3_SERVICE_PROVIDER_IDENTIFICATION_ERROR_MSG); } } @@ -91,7 +97,7 @@ public static S3ServiceProvider fromString(String name) throws AppsmithPluginExc * @throws AppsmithPluginException when (1) there is an error with parsing credentials (2) required * datasourceConfiguration properties are missing (3) endpoint URL is found incorrect. */ - public static AmazonS3ClientBuilder getS3ClientBuilder (DatasourceConfiguration datasourceConfiguration) + public static AmazonS3ClientBuilder getS3ClientBuilder(DatasourceConfiguration datasourceConfiguration) throws AppsmithPluginException { DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); @@ -104,14 +110,12 @@ public static AmazonS3ClientBuilder getS3ClientBuilder (DatasourceConfiguration throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, S3ErrorMessages.AWS_CREDENTIALS_PARSING_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } /* Set credentials in client builder. */ - AmazonS3ClientBuilder s3ClientBuilder = AmazonS3ClientBuilder - .standard() - .withCredentials(new AWSStaticCredentialsProvider(awsCreds)); + AmazonS3ClientBuilder s3ClientBuilder = + AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds)); List<Property> properties = datasourceConfiguration.getProperties(); @@ -123,15 +127,15 @@ public static AmazonS3ClientBuilder getS3ClientBuilder (DatasourceConfiguration */ if (properties == null || properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX) == null - || StringUtils.isEmpty((String) properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX).getValue())) { + || StringUtils.isEmpty((String) + properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX).getValue())) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - S3ErrorMessages.DS_S3_SERVICE_PROVIDER_PROPERTIES_FETCHING_ERROR_MSG - ); + S3ErrorMessages.DS_S3_SERVICE_PROVIDER_PROPERTIES_FETCHING_ERROR_MSG); } - S3ServiceProvider s3ServiceProvider = - S3ServiceProvider.fromString((String) properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX).getValue()); + S3ServiceProvider s3ServiceProvider = S3ServiceProvider.fromString( + (String) properties.get(S3_SERVICE_PROVIDER_PROPERTY_INDEX).getValue()); /** * AmazonS3 provides an attribute `forceGlobalBucketAccessEnabled` that automatically routes the request to a @@ -151,38 +155,38 @@ public static AmazonS3ClientBuilder getS3ClientBuilder (DatasourceConfiguration * explicitly provided. */ if (s3ServiceProvider.equals(AMAZON)) { - s3ClientBuilder = s3ClientBuilder - .withRegion(DEFAULT_REGION) - .enableForceGlobalBucketAccess(); - } - else { - String endpoint = datasourceConfiguration.getEndpoints().get(CUSTOM_ENDPOINT_INDEX).getHost(); + s3ClientBuilder = s3ClientBuilder.withRegion(DEFAULT_REGION).enableForceGlobalBucketAccess(); + } else { + String endpoint = datasourceConfiguration + .getEndpoints() + .get(CUSTOM_ENDPOINT_INDEX) + .getHost(); String region = ""; - switch(s3ServiceProvider) { + switch (s3ServiceProvider) { case AMAZON: /* This case can never be reached because of the if condition above. Just adding for sake of completeness. */ break; case UPCLOUD: - region = getRegionFromEndpointPattern(endpoint, UPCLOUD_URL_ENDPOINT_PATTERN, - UPCLOUD_REGION_GROUP_INDEX); + region = getRegionFromEndpointPattern( + endpoint, UPCLOUD_URL_ENDPOINT_PATTERN, UPCLOUD_REGION_GROUP_INDEX); break; case WASABI: - region = getRegionFromEndpointPattern(endpoint, WASABI_URL_ENDPOINT_PATTERN, - WASABI_REGION_GROUP_INDEX); + region = getRegionFromEndpointPattern( + endpoint, WASABI_URL_ENDPOINT_PATTERN, WASABI_REGION_GROUP_INDEX); break; case DIGITAL_OCEAN_SPACES: - region = getRegionFromEndpointPattern(endpoint, DIGITAL_OCEAN_URL_ENDPOINT_PATTERN, - DIGITAL_OCEAN_REGION_GROUP_INDEX); + region = getRegionFromEndpointPattern( + endpoint, DIGITAL_OCEAN_URL_ENDPOINT_PATTERN, DIGITAL_OCEAN_REGION_GROUP_INDEX); break; case DREAM_OBJECTS: - region = getRegionFromEndpointPattern(endpoint, DREAM_OBJECTS_URL_ENDPOINT_PATTERN, - DREAM_OBJECTS_REGION_GROUP_INDEX); + region = getRegionFromEndpointPattern( + endpoint, DREAM_OBJECTS_URL_ENDPOINT_PATTERN, DREAM_OBJECTS_REGION_GROUP_INDEX); break; case MINIO: @@ -211,12 +215,12 @@ public static AmazonS3ClientBuilder getS3ClientBuilder (DatasourceConfiguration break; default: - region = getValueSafelyFromPropertyList(properties, CUSTOM_ENDPOINT_REGION_PROPERTY_INDEX, - String.class, ""); + region = getValueSafelyFromPropertyList( + properties, CUSTOM_ENDPOINT_REGION_PROPERTY_INDEX, String.class, ""); } - s3ClientBuilder = s3ClientBuilder - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, region)); + s3ClientBuilder = s3ClientBuilder.withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration(endpoint, region)); } return s3ClientBuilder; @@ -240,7 +244,9 @@ private static String getRegionFromEndpointPattern(String endpoint, String regex /* endpoint is expected to be non-null at this point */ if (!endpoint.matches(regex)) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, S3ErrorMessages.INCORRECT_S3_ENDPOINT_URL_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + S3ErrorMessages.INCORRECT_S3_ENDPOINT_URL_ERROR_MSG); } Pattern pattern = Pattern.compile(regex); @@ -250,6 +256,8 @@ private static String getRegionFromEndpointPattern(String endpoint, String regex } /* Code flow is never expected to reach here. */ - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, S3ErrorMessages.INCORRECT_S3_ENDPOINT_URL_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + S3ErrorMessages.INCORRECT_S3_ENDPOINT_URL_ERROR_MSG); } } diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/TemplateUtils.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/TemplateUtils.java index f2dac0cd832c..4fba9709baf8 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/TemplateUtils.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/TemplateUtils.java @@ -131,9 +131,11 @@ private static Template getListFilesTemplate(String bucketName) { setDataValueSafelyInFormData(configMap, BUCKET, bucketName); setDataValueSafelyInFormData(configMap, LIST_SIGNED_URL, NO); setDataValueSafelyInFormData(configMap, LIST_UNSIGNED_URL, YES); - setDataValueSafelyInFormData(configMap, LIST_WHERE, new HashMap<String, Object>() {{ - put("condition", "AND"); - }}); + setDataValueSafelyInFormData(configMap, LIST_WHERE, new HashMap<String, Object>() { + { + put("condition", "AND"); + } + }); return new Template(LIST_FILES_TEMPLATE_NAME, configMap); } diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/plugins/AmazonS3PluginTest.java b/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/plugins/AmazonS3PluginTest.java index ae3b68c50e60..81102b2019c0 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/plugins/AmazonS3PluginTest.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/plugins/AmazonS3PluginTest.java @@ -31,8 +31,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.node.ArrayNode; import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mockito; import reactor.core.publisher.Mono; @@ -101,11 +101,10 @@ public class AmazonS3PluginTest { @BeforeAll public static void setUp() { - accessKey = "access_key"; - secretKey = "secret_key"; - region = "ap-south-1"; + accessKey = "access_key"; + secretKey = "secret_key"; + region = "ap-south-1"; serviceProvider = "amazon-s3"; - } private DatasourceConfiguration createDatasourceConfiguration() { @@ -168,7 +167,9 @@ public void testValidateDatasourceWithMissingSecretKey() { assertNotEquals(0, res.size()); List<String> errorList = new ArrayList<>(res); - assertTrue(errorList.get(0).equals(S3ErrorMessages.DS_MANDATORY_PARAMETER_SECRET_KEY_MISSING_ERROR_MSG)); + assertTrue(errorList + .get(0) + .equals(S3ErrorMessages.DS_MANDATORY_PARAMETER_SECRET_KEY_MISSING_ERROR_MSG)); }) .verifyComplete(); } @@ -222,7 +223,9 @@ public void testValidateDatasourceWithMissingUrlWithNonAmazonProvider() { assertNotEquals(0, res.size()); List<String> errorList = new ArrayList<>(res); - assertTrue(errorList.get(0).equals(S3ErrorMessages.DS_MANDATORY_PARAMETER_ENDPOINT_URL_MISSING_ERROR_MSG)); + assertTrue(errorList + .get(0) + .equals(S3ErrorMessages.DS_MANDATORY_PARAMETER_ENDPOINT_URL_MISSING_ERROR_MSG)); }) .verifyComplete(); } @@ -236,12 +239,13 @@ public void testTestDatasourceWithFalseCredentials() { assertNotEquals(0, datasourceTestResult.getInvalids().size()); List<String> errorList = new ArrayList<>(datasourceTestResult.getInvalids()); - assertTrue(errorList.get(0).contains("The AWS Access Key Id you provided does not exist in our records")); + assertTrue(errorList + .get(0) + .contains("The AWS Access Key Id you provided does not exist in our records")); }) .verifyComplete(); } - @Test public void testStaleConnectionExceptionFromExecuteMethod() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); @@ -249,19 +253,13 @@ public void testStaleConnectionExceptionFromExecuteMethod() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setFormData(new HashMap<>()); Mono<AmazonS3Plugin.S3PluginExecutor> pluginExecutorMono = Mono.just(new AmazonS3Plugin.S3PluginExecutor()); - Mono<ActionExecutionResult> resultMono = pluginExecutorMono - .flatMap(executor -> { - return executor.executeParameterized( - null, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); - }); + Mono<ActionExecutionResult> resultMono = pluginExecutorMono.flatMap(executor -> { + return executor.executeParameterized(null, executeActionDTO, datasourceConfiguration, actionConfiguration); + }); - StepVerifier.create(resultMono) - .verifyError(StaleConnectionException.class); + StepVerifier.create(resultMono).verifyError(StaleConnectionException.class); } - + @Test public void testListFilesInBucketWithNoUrl() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); @@ -297,10 +295,7 @@ public void testListFilesInBucketWithNoUrl() { when(mockObjectListing.getObjectSummaries()).thenReturn(mockS3ObjectSummaryList); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -310,13 +305,7 @@ public void testListFilesInBucketWithNoUrl() { ArrayList<String> resultFilenamesArray = new ArrayList<>(); resultFilenamesArray.add(node.get(0).get("fileName").asText()); resultFilenamesArray.add(node.get(1).get("fileName").asText()); - assertArrayEquals( - new String[]{ - dummyKey1, - dummyKey2 - }, - resultFilenamesArray.toArray() - ); + assertArrayEquals(new String[] {dummyKey1, dummyKey2}, resultFilenamesArray.toArray()); }) .verifyComplete(); } @@ -333,7 +322,6 @@ public void testCreateFileFromBodyWithFalseCredentialsAndNonNullDuration() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); AmazonS3Plugin.S3PluginExecutor pluginExecutor = new AmazonS3Plugin.S3PluginExecutor(); - ActionConfiguration actionConfiguration = new ActionConfiguration(); Map<String, Object> configMap = new HashMap<>(); @@ -346,19 +334,17 @@ public void testCreateFileFromBodyWithFalseCredentialsAndNonNullDuration() { actionConfiguration.setFormData(configMap); - AmazonS3 connection = pluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + pluginExecutor.datasourceCreate(datasourceConfiguration).block(); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String message = result.getPluginErrorDetails().getDownstreamErrorMessage(); - assertTrue(message.contains("The AWS Access Key Id you provided does not exist in " + - "our records")); + assertTrue( + message.contains("The AWS Access Key Id you provided does not exist in " + "our records")); assertEquals(S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED.getTitle(), result.getTitle()); }) .verifyComplete(); @@ -387,19 +373,17 @@ public void testFileUploadFromBodyWithMissingDuration() { actionConfiguration.setFormData(configMap); - AmazonS3 connection = pluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + pluginExecutor.datasourceCreate(datasourceConfiguration).block(); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String message = result.getPluginErrorDetails().getDownstreamErrorMessage(); - assertTrue(message.contains("The AWS Access Key Id you provided does not exist in " + - "our records")); + assertTrue( + message.contains("The AWS Access Key Id you provided does not exist in " + "our records")); assertEquals(S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED.getTitle(), result.getTitle()); }) .verifyComplete(); @@ -408,7 +392,7 @@ public void testFileUploadFromBodyWithMissingDuration() { /* * - This method tests the create file program flow till the point where an actual call is made by the AmazonS3 * connection to upload a file. - * - If this test fails, the point of failure is expected to be the logic for smart substitution + * - If this test fails, the point of failure is expected to be the logic for smart substitution * - If everything goes well, then only expected exception is the one thrown by AmazonS3 connection * regarding false credentials. */ @@ -433,19 +417,17 @@ public void testSmartSubstitutionJSONBody() { actionConfiguration.setFormData(configMap); - AmazonS3 connection = pluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + pluginExecutor.datasourceCreate(datasourceConfiguration).block(); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String message = result.getPluginErrorDetails().getDownstreamErrorMessage(); - assertTrue(message.contains("The AWS Access Key Id you provided does not exist in " + - "our records")); + assertTrue( + message.contains("The AWS Access Key Id you provided does not exist in " + "our records")); assertEquals(S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED.getTitle(), result.getTitle()); }) .verifyComplete(); @@ -469,20 +451,18 @@ public void testFileUploadFromBody_withMalformedBody_returnsErrorMessage() { actionConfiguration.setFormData(configMap); - AmazonS3 connection = pluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + pluginExecutor.datasourceCreate(datasourceConfiguration).block(); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String message = (String) result.getBody(); - assertTrue(message.contains("Unrecognized token 'erroneousBody': was expecting " + - "(JSON String, Number, Array, Object or token 'null', 'true' or 'false')\n" + - " at [Source: (String)\"erroneousBody\"; line: 1, column: 14]")); + assertTrue(message.contains("Unrecognized token 'erroneousBody': was expecting " + + "(JSON String, Number, Array, Object or token 'null', 'true' or 'false')\n" + + " at [Source: (String)\"erroneousBody\"; line: 1, column: 14]")); assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); /* @@ -490,14 +470,17 @@ public void testFileUploadFromBody_withMalformedBody_returnsErrorMessage() { * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(COMMAND, - "UPLOAD_FILE_FROM_BODY", null, null, null)); // Action - expectedRequestParams.add(new RequestParamDTO(BUCKET, "bucket_name", - null, null, null)); // Bucket name - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, "path", null, null, null)); // Path - expectedRequestParams.add(new RequestParamDTO(CREATE_DATATYPE, "Base64", null, - null, null)); // File data type - assertEquals(expectedRequestParams.toString(), result.getRequest().getRequestParams().toString()); + expectedRequestParams.add( + new RequestParamDTO(COMMAND, "UPLOAD_FILE_FROM_BODY", null, null, null)); // Action + expectedRequestParams.add( + new RequestParamDTO(BUCKET, "bucket_name", null, null, null)); // Bucket name + expectedRequestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, "path", null, null, null)); // Path + expectedRequestParams.add( + new RequestParamDTO(CREATE_DATATYPE, "Base64", null, null, null)); // File data type + assertEquals( + expectedRequestParams.toString(), + result.getRequest().getRequestParams().toString()); }) .verifyComplete(); } @@ -520,20 +503,18 @@ public void testFileUploadFromBodyWithFilepickerAndNonBase64() { actionConfiguration.setFormData(configMap); - AmazonS3 connection = pluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + pluginExecutor.datasourceCreate(datasourceConfiguration).block(); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String message = (String) result.getBody(); - assertTrue(message.contains("File content is not base64 encoded. " + - "File content needs to be base64 encoded when the " + - "'File data type: Base64/Text' field is selected 'Yes'.")); + assertTrue(message.contains( + "File content is not base64 encoded. " + "File content needs to be base64 encoded when the " + + "'File data type: Base64/Text' field is selected 'Yes'.")); assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); /* @@ -541,14 +522,17 @@ public void testFileUploadFromBodyWithFilepickerAndNonBase64() { * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(COMMAND, - "UPLOAD_FILE_FROM_BODY", null, null, null)); // Action - expectedRequestParams.add(new RequestParamDTO(BUCKET, "bucket_name", - null, null, null)); // Bucket name - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, "path", null, null, null)); // Path - expectedRequestParams.add(new RequestParamDTO(CREATE_DATATYPE, "Base64", null, - null, null)); // File data type - assertEquals(expectedRequestParams.toString(), result.getRequest().getRequestParams().toString()); + expectedRequestParams.add( + new RequestParamDTO(COMMAND, "UPLOAD_FILE_FROM_BODY", null, null, null)); // Action + expectedRequestParams.add( + new RequestParamDTO(BUCKET, "bucket_name", null, null, null)); // Bucket name + expectedRequestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, "path", null, null, null)); // Path + expectedRequestParams.add( + new RequestParamDTO(CREATE_DATATYPE, "Base64", null, null, null)); // File data type + assertEquals( + expectedRequestParams.toString(), + result.getRequest().getRequestParams().toString()); }) .verifyComplete(); } @@ -577,19 +561,17 @@ public void testCreateMultipleFilesFromBodyWithFalseCredentialsAndNonNullDuratio actionConfiguration.setFormData(configMap); - AmazonS3 connection = pluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + pluginExecutor.datasourceCreate(datasourceConfiguration).block(); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String message = result.getPluginErrorDetails().getDownstreamErrorMessage(); - assertTrue(message.contains("The AWS Access Key Id you provided does not exist in " + - "our records")); + assertTrue( + message.contains("The AWS Access Key Id you provided does not exist in " + "our records")); assertEquals(S3PluginError.AMAZON_S3_QUERY_EXECUTION_FAILED.getTitle(), result.getTitle()); }) .verifyComplete(); @@ -622,10 +604,7 @@ public void testReadFileFromPathWithoutBase64Encoding() { when(mockS3Object.getObjectContent()).thenReturn(dummyS3ObjectInputStream); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -663,10 +642,7 @@ public void testReadFileFromPathWithBase64Encoding() { when(mockS3Object.getObjectContent()).thenReturn(dummyS3ObjectInputStream); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -679,14 +655,16 @@ public void testReadFileFromPathWithBase64Encoding() { * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(COMMAND, "READ_FILE", - null, null, null)); // Action - expectedRequestParams.add(new RequestParamDTO(BUCKET, "bucket_name", - null, null, null)); // Bucket name - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, "path", null, null, null)); // Path - expectedRequestParams.add(new RequestParamDTO(READ_DATATYPE, "YES", null, - null, null)); // Base64 encode file - assertEquals(expectedRequestParams.toString(), result.getRequest().getRequestParams().toString()); + expectedRequestParams.add(new RequestParamDTO(COMMAND, "READ_FILE", null, null, null)); // Action + expectedRequestParams.add( + new RequestParamDTO(BUCKET, "bucket_name", null, null, null)); // Bucket name + expectedRequestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, "path", null, null, null)); // Path + expectedRequestParams.add( + new RequestParamDTO(READ_DATATYPE, "YES", null, null, null)); // Base64 encode file + assertEquals( + expectedRequestParams.toString(), + result.getRequest().getRequestParams().toString()); }) .verifyComplete(); } @@ -711,10 +689,7 @@ public void testDeleteFile() { doNothing().when(mockConnection).deleteObject(anyString(), anyString()); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -727,12 +702,14 @@ public void testDeleteFile() { * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(COMMAND, "DELETE_FILE", - null, null, null)); // Action - expectedRequestParams.add(new RequestParamDTO(BUCKET, "bucket_name", - null, null, null)); // Bucket name - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, "path", null, null, null)); // Path - assertEquals(expectedRequestParams.toString(), result.getRequest().getRequestParams().toString()); + expectedRequestParams.add(new RequestParamDTO(COMMAND, "DELETE_FILE", null, null, null)); // Action + expectedRequestParams.add( + new RequestParamDTO(BUCKET, "bucket_name", null, null, null)); // Bucket name + expectedRequestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, "path", null, null, null)); // Path + assertEquals( + expectedRequestParams.toString(), + result.getRequest().getRequestParams().toString()); }) .verifyComplete(); } @@ -772,10 +749,7 @@ public void testListFilesWithPrefix() { when(mockObjectListing.getObjectSummaries()).thenReturn(mockS3ObjectSummaryList); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -785,13 +759,7 @@ public void testListFilesWithPrefix() { ArrayList<String> resultFilenamesArray = new ArrayList<>(); resultFilenamesArray.add(node.get(0).get("fileName").asText()); resultFilenamesArray.add(node.get(1).get("fileName").asText()); - assertArrayEquals( - new String[]{ - dummyKey1, - dummyKey2 - }, - resultFilenamesArray.toArray() - ); + assertArrayEquals(new String[] {dummyKey1, dummyKey2}, resultFilenamesArray.toArray()); }) .verifyComplete(); } @@ -834,13 +802,12 @@ public void testListFilesWithUnsignedUrl() throws MalformedURLException { URL dummyUrl1 = new URL("http", "dummy_url_1", ""); URL dummyUrl2 = new URL("http", "dummy_url_1", ""); - when(mockConnection.getUrl(anyString(), anyString())).thenReturn(dummyUrl1).thenReturn(dummyUrl2); + when(mockConnection.getUrl(anyString(), anyString())) + .thenReturn(dummyUrl1) + .thenReturn(dummyUrl2); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -850,24 +817,13 @@ public void testListFilesWithUnsignedUrl() throws MalformedURLException { ArrayList<String> resultFilenamesArray = new ArrayList<>(); resultFilenamesArray.add(node.get(0).get("fileName").asText()); resultFilenamesArray.add(node.get(1).get("fileName").asText()); - assertArrayEquals( - new String[]{ - dummyKey1, - dummyKey2 - }, - resultFilenamesArray.toArray() - ); + assertArrayEquals(new String[] {dummyKey1, dummyKey2}, resultFilenamesArray.toArray()); ArrayList<String> resultUrlArray = new ArrayList<>(); resultUrlArray.add(node.get(0).get("url").asText()); resultUrlArray.add(node.get(1).get("url").asText()); assertArrayEquals( - new String[]{ - dummyUrl1.toString(), - dummyUrl2.toString() - }, - resultUrlArray.toArray() - ); + new String[] {dummyUrl1.toString(), dummyUrl2.toString()}, resultUrlArray.toArray()); }) .verifyComplete(); } @@ -913,10 +869,7 @@ public void testListFilesWithSignedUrl() throws MalformedURLException { when(mockConnection.generatePresignedUrl(any())).thenReturn(dummyUrl1).thenReturn(dummyUrl2); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -926,24 +879,13 @@ public void testListFilesWithSignedUrl() throws MalformedURLException { ArrayList<String> resultFilenamesArray = new ArrayList<>(); resultFilenamesArray.add(node.get(0).get("fileName").asText()); resultFilenamesArray.add(node.get(1).get("fileName").asText()); - assertArrayEquals( - new String[]{ - dummyKey1, - dummyKey2 - }, - resultFilenamesArray.toArray() - ); + assertArrayEquals(new String[] {dummyKey1, dummyKey2}, resultFilenamesArray.toArray()); ArrayList<String> resultUrlArray = new ArrayList<>(); resultUrlArray.add(node.get(0).get("signedUrl").asText()); resultUrlArray.add(node.get(1).get("signedUrl").asText()); assertArrayEquals( - new String[]{ - dummyUrl1.toString(), - dummyUrl2.toString() - }, - resultUrlArray.toArray() - ); + new String[] {dummyUrl1.toString(), dummyUrl2.toString()}, resultUrlArray.toArray()); assertNotNull(node.get(0).get("urlExpiryDate")); assertNotNull(node.get(1).get("urlExpiryDate")); @@ -991,10 +933,7 @@ public void testListFilesWithSignedUrlAndNullDuration() throws MalformedURLExcep when(mockConnection.generatePresignedUrl(any())).thenReturn(dummyUrl1).thenReturn(dummyUrl2); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1004,24 +943,13 @@ public void testListFilesWithSignedUrlAndNullDuration() throws MalformedURLExcep ArrayList<String> resultFilenamesArray = new ArrayList<>(); resultFilenamesArray.add(node.get(0).get("fileName").asText()); resultFilenamesArray.add(node.get(1).get("fileName").asText()); - assertArrayEquals( - new String[]{ - dummyKey1, - dummyKey2 - }, - resultFilenamesArray.toArray() - ); + assertArrayEquals(new String[] {dummyKey1, dummyKey2}, resultFilenamesArray.toArray()); ArrayList<String> resultUrlArray = new ArrayList<>(); resultUrlArray.add(node.get(0).get("signedUrl").asText()); resultUrlArray.add(node.get(1).get("signedUrl").asText()); assertArrayEquals( - new String[]{ - dummyUrl1.toString(), - dummyUrl2.toString() - }, - resultUrlArray.toArray() - ); + new String[] {dummyUrl1.toString(), dummyUrl2.toString()}, resultUrlArray.toArray()); assertNotNull(node.get(0).get("urlExpiryDate")); assertNotNull(node.get(1).get("urlExpiryDate")); @@ -1031,19 +959,19 @@ public void testListFilesWithSignedUrlAndNullDuration() throws MalformedURLExcep * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(COMMAND, "LIST", null - , null, null)); // Action - expectedRequestParams.add(new RequestParamDTO(BUCKET, "bucket_name", - null, null, null)); // Bucket name - expectedRequestParams.add(new RequestParamDTO(LIST_PREFIX, "", null, - null, null)); // Prefix - expectedRequestParams.add(new RequestParamDTO(LIST_SIGNED_URL, "YES", null, - null, null)); // Generate signed URL - expectedRequestParams.add(new RequestParamDTO(LIST_EXPIRY, "5", null, - null, null)); // Expiry duration - expectedRequestParams.add(new RequestParamDTO(LIST_UNSIGNED_URL, "NO", null, - null, null)); // Generate unsigned URL - assertEquals(expectedRequestParams.toString(), result.getRequest().getRequestParams().toString()); + expectedRequestParams.add(new RequestParamDTO(COMMAND, "LIST", null, null, null)); // Action + expectedRequestParams.add( + new RequestParamDTO(BUCKET, "bucket_name", null, null, null)); // Bucket name + expectedRequestParams.add(new RequestParamDTO(LIST_PREFIX, "", null, null, null)); // Prefix + expectedRequestParams.add( + new RequestParamDTO(LIST_SIGNED_URL, "YES", null, null, null)); // Generate signed URL + expectedRequestParams.add( + new RequestParamDTO(LIST_EXPIRY, "5", null, null, null)); // Expiry duration + expectedRequestParams.add( + new RequestParamDTO(LIST_UNSIGNED_URL, "NO", null, null, null)); // Generate unsigned URL + assertEquals( + expectedRequestParams.toString(), + result.getRequest().getRequestParams().toString()); }) .verifyComplete(); } @@ -1062,73 +990,127 @@ public void testGetStructure() { StepVerifier.create(pluginExecutor.getStructure(mockConnection, datasourceConfiguration)) .assertNext(datasourceStructure -> { String expectedBucketName = "dummy_bucket_1"; - assertEquals(expectedBucketName, datasourceStructure.getTables().get(0).getName()); + assertEquals( + expectedBucketName, + datasourceStructure.getTables().get(0).getName()); - List<Template> templates = datasourceStructure.getTables().get(0).getTemplates(); + List<Template> templates = + datasourceStructure.getTables().get(0).getTemplates(); // Check list files template Template listFilesTemplate = templates.get(0); assertEquals(LIST_FILES_TEMPLATE_NAME, listFilesTemplate.getTitle()); - Map<String, Object> listFilesConfig = (Map<String, Object>) listFilesTemplate.getConfiguration(); - assertEquals(AmazonS3Action.LIST.name(), PluginUtils.getDataValueSafelyFromFormData(listFilesConfig, COMMAND, STRING_TYPE)); - assertEquals(expectedBucketName, PluginUtils.getDataValueSafelyFromFormData(listFilesConfig, BUCKET, STRING_TYPE)); - assertEquals(NO, PluginUtils.getDataValueSafelyFromFormData(listFilesConfig, LIST_SIGNED_URL, STRING_TYPE)); - assertEquals(YES, PluginUtils.getDataValueSafelyFromFormData(listFilesConfig, LIST_UNSIGNED_URL, STRING_TYPE)); - assertEquals(new HashMap<String, Object>() {{ - put("condition", "AND"); - }}, - PluginUtils.getDataValueSafelyFromFormData(listFilesConfig, LIST_WHERE, new TypeReference<HashMap<String, Object>>() { - })); + assertEquals( + AmazonS3Action.LIST.name(), + PluginUtils.getDataValueSafelyFromFormData(listFilesConfig, COMMAND, STRING_TYPE)); + assertEquals( + expectedBucketName, + PluginUtils.getDataValueSafelyFromFormData(listFilesConfig, BUCKET, STRING_TYPE)); + assertEquals( + NO, + PluginUtils.getDataValueSafelyFromFormData(listFilesConfig, LIST_SIGNED_URL, STRING_TYPE)); + assertEquals( + YES, + PluginUtils.getDataValueSafelyFromFormData( + listFilesConfig, LIST_UNSIGNED_URL, STRING_TYPE)); + assertEquals( + new HashMap<String, Object>() { + { + put("condition", "AND"); + } + }, + PluginUtils.getDataValueSafelyFromFormData( + listFilesConfig, LIST_WHERE, new TypeReference<HashMap<String, Object>>() {})); // Check read file template Template readFileTemplate = templates.get(1); assertEquals(READ_FILE_TEMPLATE_NAME, readFileTemplate.getTitle()); Map<String, Object> readFileConfig = (Map<String, Object>) readFileTemplate.getConfiguration(); - assertEquals(DEFAULT_FILE_NAME, PluginUtils.getDataValueSafelyFromFormData(readFileConfig, PATH, STRING_TYPE)); - assertEquals(AmazonS3Action.READ_FILE.name(), PluginUtils.getDataValueSafelyFromFormData(readFileConfig, COMMAND, STRING_TYPE)); - assertEquals(expectedBucketName, PluginUtils.getDataValueSafelyFromFormData(readFileConfig, BUCKET, STRING_TYPE)); - assertEquals(YES, PluginUtils.getDataValueSafelyFromFormData(readFileConfig, READ_DATATYPE, STRING_TYPE)); - assertEquals(DEFAULT_URL_EXPIRY_IN_MINUTES, PluginUtils.getDataValueSafelyFromFormData(readFileConfig, READ_EXPIRY, STRING_TYPE)); + assertEquals( + DEFAULT_FILE_NAME, + PluginUtils.getDataValueSafelyFromFormData(readFileConfig, PATH, STRING_TYPE)); + assertEquals( + AmazonS3Action.READ_FILE.name(), + PluginUtils.getDataValueSafelyFromFormData(readFileConfig, COMMAND, STRING_TYPE)); + assertEquals( + expectedBucketName, + PluginUtils.getDataValueSafelyFromFormData(readFileConfig, BUCKET, STRING_TYPE)); + assertEquals( + YES, + PluginUtils.getDataValueSafelyFromFormData(readFileConfig, READ_DATATYPE, STRING_TYPE)); + assertEquals( + DEFAULT_URL_EXPIRY_IN_MINUTES, + PluginUtils.getDataValueSafelyFromFormData(readFileConfig, READ_EXPIRY, STRING_TYPE)); // Check create file template Template createFileTemplate = templates.get(2); assertEquals(CREATE_FILE_TEMPLATE_NAME, createFileTemplate.getTitle()); Map<String, Object> createFileConfig = (Map<String, Object>) createFileTemplate.getConfiguration(); - assertEquals(DEFAULT_FILE_NAME, PluginUtils.getDataValueSafelyFromFormData(createFileConfig, PATH, STRING_TYPE)); - assertEquals(FILE_PICKER_DATA_EXPRESSION, PluginUtils.getDataValueSafelyFromFormData(createFileConfig, BODY, STRING_TYPE)); - assertEquals(AmazonS3Action.UPLOAD_FILE_FROM_BODY.name(), + assertEquals( + DEFAULT_FILE_NAME, + PluginUtils.getDataValueSafelyFromFormData(createFileConfig, PATH, STRING_TYPE)); + assertEquals( + FILE_PICKER_DATA_EXPRESSION, + PluginUtils.getDataValueSafelyFromFormData(createFileConfig, BODY, STRING_TYPE)); + assertEquals( + AmazonS3Action.UPLOAD_FILE_FROM_BODY.name(), PluginUtils.getDataValueSafelyFromFormData(createFileConfig, COMMAND, STRING_TYPE)); - assertEquals(expectedBucketName, PluginUtils.getDataValueSafelyFromFormData(createFileConfig, BUCKET, STRING_TYPE)); - assertEquals(YES, PluginUtils.getDataValueSafelyFromFormData(createFileConfig, CREATE_DATATYPE, STRING_TYPE)); - assertEquals(DEFAULT_URL_EXPIRY_IN_MINUTES, PluginUtils.getDataValueSafelyFromFormData(createFileConfig, CREATE_EXPIRY, STRING_TYPE)); + assertEquals( + expectedBucketName, + PluginUtils.getDataValueSafelyFromFormData(createFileConfig, BUCKET, STRING_TYPE)); + assertEquals( + YES, + PluginUtils.getDataValueSafelyFromFormData(createFileConfig, CREATE_DATATYPE, STRING_TYPE)); + assertEquals( + DEFAULT_URL_EXPIRY_IN_MINUTES, + PluginUtils.getDataValueSafelyFromFormData(createFileConfig, CREATE_EXPIRY, STRING_TYPE)); // Check create multiple files template Template createMultipleFilesTemplate = templates.get(3); assertEquals(CREATE_MULTIPLE_FILES_TEMPLATE_NAME, createMultipleFilesTemplate.getTitle()); - Map<String, Object> createMultipleFilesConfig = (Map<String, Object>) createMultipleFilesTemplate.getConfiguration(); - assertEquals(DEFAULT_DIR, PluginUtils.getDataValueSafelyFromFormData(createMultipleFilesConfig, PATH, STRING_TYPE)); - assertEquals(FILE_PICKER_MULTIPLE_FILES_DATA_EXPRESSION, + Map<String, Object> createMultipleFilesConfig = + (Map<String, Object>) createMultipleFilesTemplate.getConfiguration(); + assertEquals( + DEFAULT_DIR, + PluginUtils.getDataValueSafelyFromFormData(createMultipleFilesConfig, PATH, STRING_TYPE)); + assertEquals( + FILE_PICKER_MULTIPLE_FILES_DATA_EXPRESSION, PluginUtils.getDataValueSafelyFromFormData(createMultipleFilesConfig, BODY, STRING_TYPE)); - assertEquals(AmazonS3Action.UPLOAD_MULTIPLE_FILES_FROM_BODY.name(), - PluginUtils.getDataValueSafelyFromFormData(createMultipleFilesConfig, COMMAND, STRING_TYPE)); - assertEquals(expectedBucketName, PluginUtils.getDataValueSafelyFromFormData(createMultipleFilesConfig, BUCKET, STRING_TYPE)); - assertEquals(YES, PluginUtils.getDataValueSafelyFromFormData(createMultipleFilesConfig, CREATE_DATATYPE, STRING_TYPE)); - assertEquals(DEFAULT_URL_EXPIRY_IN_MINUTES, PluginUtils.getDataValueSafelyFromFormData(createMultipleFilesConfig, CREATE_EXPIRY, STRING_TYPE)); + assertEquals( + AmazonS3Action.UPLOAD_MULTIPLE_FILES_FROM_BODY.name(), + PluginUtils.getDataValueSafelyFromFormData( + createMultipleFilesConfig, COMMAND, STRING_TYPE)); + assertEquals( + expectedBucketName, + PluginUtils.getDataValueSafelyFromFormData(createMultipleFilesConfig, BUCKET, STRING_TYPE)); + assertEquals( + YES, + PluginUtils.getDataValueSafelyFromFormData( + createMultipleFilesConfig, CREATE_DATATYPE, STRING_TYPE)); + assertEquals( + DEFAULT_URL_EXPIRY_IN_MINUTES, + PluginUtils.getDataValueSafelyFromFormData( + createMultipleFilesConfig, CREATE_EXPIRY, STRING_TYPE)); // Check delete file template Template deleteFileTemplate = templates.get(4); assertEquals(DELETE_FILE_TEMPLATE_NAME, deleteFileTemplate.getTitle()); Map<String, Object> deleteFileConfig = (Map<String, Object>) deleteFileTemplate.getConfiguration(); - assertEquals(DEFAULT_FILE_NAME, PluginUtils.getDataValueSafelyFromFormData(deleteFileConfig, PATH, STRING_TYPE)); - assertEquals(AmazonS3Action.DELETE_FILE.name(), PluginUtils.getDataValueSafelyFromFormData(deleteFileConfig, - COMMAND, STRING_TYPE)); - assertEquals(expectedBucketName, PluginUtils.getDataValueSafelyFromFormData(deleteFileConfig, BUCKET, STRING_TYPE)); + assertEquals( + DEFAULT_FILE_NAME, + PluginUtils.getDataValueSafelyFromFormData(deleteFileConfig, PATH, STRING_TYPE)); + assertEquals( + AmazonS3Action.DELETE_FILE.name(), + PluginUtils.getDataValueSafelyFromFormData(deleteFileConfig, COMMAND, STRING_TYPE)); + assertEquals( + expectedBucketName, + PluginUtils.getDataValueSafelyFromFormData(deleteFileConfig, BUCKET, STRING_TYPE)); // Check delete multiple files template Template deleteMultipleFilesTemplate = templates.get(5); @@ -1136,10 +1118,16 @@ public void testGetStructure() { Map<String, Object> deleteMultipleFilesConfig = (Map<String, Object>) deleteMultipleFilesTemplate.getConfiguration(); - assertEquals(LIST_OF_FILES_STRING, PluginUtils.getDataValueSafelyFromFormData(deleteMultipleFilesConfig, PATH, STRING_TYPE)); - assertEquals(AmazonS3Action.DELETE_MULTIPLE_FILES.name(), - PluginUtils.getDataValueSafelyFromFormData(deleteMultipleFilesConfig, COMMAND, STRING_TYPE)); - assertEquals(expectedBucketName, PluginUtils.getDataValueSafelyFromFormData(deleteMultipleFilesConfig, BUCKET, STRING_TYPE)); + assertEquals( + LIST_OF_FILES_STRING, + PluginUtils.getDataValueSafelyFromFormData(deleteMultipleFilesConfig, PATH, STRING_TYPE)); + assertEquals( + AmazonS3Action.DELETE_MULTIPLE_FILES.name(), + PluginUtils.getDataValueSafelyFromFormData( + deleteMultipleFilesConfig, COMMAND, STRING_TYPE)); + assertEquals( + expectedBucketName, + PluginUtils.getDataValueSafelyFromFormData(deleteMultipleFilesConfig, BUCKET, STRING_TYPE)); }) .verifyComplete(); } @@ -1187,8 +1175,8 @@ public void testExtractRegionFromEndpointWithBadEndpointFormat() { StepVerifier.create(Mono.fromCallable(() -> getS3ClientBuilder(datasourceConfiguration))) .expectErrorSatisfies(error -> { - String expectedErrorMessage = "Your S3 endpoint URL seems to be incorrect for the selected S3 " + - "service provider. Please check your endpoint URL and the selected S3 service provider."; + String expectedErrorMessage = "Your S3 endpoint URL seems to be incorrect for the selected S3 " + + "service provider. Please check your endpoint URL and the selected S3 service provider."; assertEquals(expectedErrorMessage, error.getMessage()); }) .verify(); @@ -1216,10 +1204,7 @@ public void testDeleteMultipleFiles() { when(mockConnection.deleteObjects(any())).thenReturn(new DeleteObjectsResult(new ArrayList<>())); Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( - mockConnection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + mockConnection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -1232,18 +1217,22 @@ public void testDeleteMultipleFiles() { * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(COMMAND, "DELETE_MULTIPLE_FILES", - null, null, null)); // Action - expectedRequestParams.add(new RequestParamDTO(BUCKET, "bucket_name", - null, null, null)); // Bucket name - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, dummyPath, null, null, null)); // Path - assertEquals(expectedRequestParams.toString(), result.getRequest().getRequestParams().toString()); + expectedRequestParams.add( + new RequestParamDTO(COMMAND, "DELETE_MULTIPLE_FILES", null, null, null)); // Action + expectedRequestParams.add( + new RequestParamDTO(BUCKET, "bucket_name", null, null, null)); // Bucket name + expectedRequestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, dummyPath, null, null, null)); // Path + assertEquals( + expectedRequestParams.toString(), + result.getRequest().getRequestParams().toString()); }) .verifyComplete(); } @Test - public void testExecuteCommonForAmazonS3Exception() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + public void testExecuteCommonForAmazonS3Exception() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String errorMessage = "The requested range is not valid for the request. Try another range."; String errorCode = "InvalidRange"; @@ -1253,44 +1242,39 @@ public void testExecuteCommonForAmazonS3Exception() throws NoSuchMethodException DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); AmazonS3Plugin.S3PluginExecutor pluginExecutor = new AmazonS3Plugin.S3PluginExecutor(); AmazonS3 mockConnection = Mockito.mock(AmazonS3.class); - Method executeCommon = AmazonS3Plugin.S3PluginExecutor.class - .getDeclaredMethod("executeCommon", AmazonS3.class, - DatasourceConfiguration.class, ActionConfiguration.class); + Method executeCommon = AmazonS3Plugin.S3PluginExecutor.class.getDeclaredMethod( + "executeCommon", AmazonS3.class, DatasourceConfiguration.class, ActionConfiguration.class); executeCommon.setAccessible(true); ActionConfiguration mockAction = Mockito.mock(ActionConfiguration.class); when(mockAction.getFormData()).thenThrow(amazonS3Exception); - Mono<ActionExecutionResult> invoke = (Mono<ActionExecutionResult>) executeCommon - .invoke(pluginExecutor, mockConnection, datasourceConfiguration, mockAction); + Mono<ActionExecutionResult> invoke = (Mono<ActionExecutionResult>) + executeCommon.invoke(pluginExecutor, mockConnection, datasourceConfiguration, mockAction); ActionExecutionResult actionExecutionResult = invoke.block(); - assertEquals(actionExecutionResult.getReadableError(),errorCode+": "+errorMessage); - + assertEquals(actionExecutionResult.getReadableError(), errorCode + ": " + errorMessage); } @Test - public void testExecuteCommonForIllegalStateException() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + public void testExecuteCommonForIllegalStateException() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); ActionConfiguration mockActionConfiguration = mock(ActionConfiguration.class); Mockito.when(mockActionConfiguration.getFormData()).thenCallRealMethod().thenThrow(new IllegalStateException()); Mono<AmazonS3Plugin.S3PluginExecutor> pluginExecutorMono = Mono.just(new AmazonS3Plugin.S3PluginExecutor()); - Mono<ActionExecutionResult> resultMono = pluginExecutorMono - .flatMap(executor -> { - return executor.executeParameterized( - null, - executeActionDTO, - datasourceConfiguration, - mockActionConfiguration); - }); + Mono<ActionExecutionResult> resultMono = pluginExecutorMono.flatMap(executor -> { + return executor.executeParameterized( + null, executeActionDTO, datasourceConfiguration, mockActionConfiguration); + }); - StepVerifier.create(resultMono) - .verifyError(StaleConnectionException.class); + StepVerifier.create(resultMono).verifyError(StaleConnectionException.class); } @Test - public void testExecuteCommonForAmazonServiceException() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { - String errorMessage = "The version ID specified in the request does not match an existing version."; + public void testExecuteCommonForAmazonServiceException() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + String errorMessage = "The version ID specified in the request does not match an existing version."; String errorCode = "NoSuchVersion"; AmazonServiceException amazonServiceException = new AmazonServiceException(errorMessage); amazonServiceException.setErrorCode(errorCode); @@ -1298,18 +1282,16 @@ public void testExecuteCommonForAmazonServiceException() throws NoSuchMethodExce DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); AmazonS3Plugin.S3PluginExecutor pluginExecutor = new AmazonS3Plugin.S3PluginExecutor(); AmazonS3 mockConnection = Mockito.mock(AmazonS3.class); - Method executeCommon = AmazonS3Plugin.S3PluginExecutor.class - .getDeclaredMethod("executeCommon", AmazonS3.class, - DatasourceConfiguration.class, ActionConfiguration.class); + Method executeCommon = AmazonS3Plugin.S3PluginExecutor.class.getDeclaredMethod( + "executeCommon", AmazonS3.class, DatasourceConfiguration.class, ActionConfiguration.class); executeCommon.setAccessible(true); ActionConfiguration mockAction = Mockito.mock(ActionConfiguration.class); when(mockAction.getFormData()).thenThrow(amazonServiceException); - Mono<ActionExecutionResult> invoke = (Mono<ActionExecutionResult>) executeCommon - .invoke(pluginExecutor, mockConnection, datasourceConfiguration, mockAction); + Mono<ActionExecutionResult> invoke = (Mono<ActionExecutionResult>) + executeCommon.invoke(pluginExecutor, mockConnection, datasourceConfiguration, mockAction); ActionExecutionResult actionExecutionResult = invoke.block(); - assertEquals(actionExecutionResult.getReadableError(),errorCode+": "+errorMessage); - + assertEquals(actionExecutionResult.getReadableError(), errorCode + ": " + errorMessage); } @Test @@ -1321,10 +1303,12 @@ public void uploadsSingleFileWithFilePicker() throws InterruptedException { ActionConfiguration actionConfiguration = new ActionConfiguration(); Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - "\t\"type\":\"text/plain\",\n" + - "\t\"data\": \"data:text/plain;base64,SGVsbG8gV29ybGQhCg==\"\n" + - "}"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + "\t\"type\":\"text/plain\",\n" + + "\t\"data\": \"data:text/plain;base64,SGVsbG8gV29ybGQhCg==\"\n" + + "}"); setDataValueSafelyInFormData(configMap, PATH, "path"); setDataValueSafelyInFormData(configMap, COMMAND, "UPLOAD_FILE_FROM_BODY"); setDataValueSafelyInFormData(configMap, BUCKET, "bucket_name"); @@ -1333,22 +1317,19 @@ public void uploadsSingleFileWithFilePicker() throws InterruptedException { actionConfiguration.setFormData(configMap); - AmazonS3 connection = spyS3PluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + spyS3PluginExecutor.datasourceCreate(datasourceConfiguration).block(); ArrayList<String> signedURLS = new ArrayList<>(); signedURLS.add("https://example.signed.url"); - doNothing().when(spyS3PluginExecutor).uploadFileInS3(any(),any(),any(),anyString(),anyString()); - doReturn(signedURLS).when(spyS3PluginExecutor).getSignedUrls(any(), anyString(),any(), any()); + doNothing().when(spyS3PluginExecutor).uploadFileInS3(any(), any(), any(), anyString(), anyString()); + doReturn(signedURLS).when(spyS3PluginExecutor).getSignedUrls(any(), anyString(), any(), any()); Mono<ActionExecutionResult> resultMono = spyS3PluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertEquals(((HashMap) result.getBody()).get("signedUrl"), signedURLS.get(0)); - }) .verifyComplete(); } @@ -1362,7 +1343,10 @@ public void uploadsMultipleFilesWithFilePicker() throws InterruptedException { ActionConfiguration actionConfiguration = new ActionConfiguration(); Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, BODY, "[{\"data\":\"data:application/json;base64,ewogICAgIm1vc3QiOiAic2ltcGxlIgp9Cg==\",\"size\":25,\"dataFormat\":\"Base64\",\"name\":\"testfile.json\",\"id\":\"uppy-testfile/json-1e-application/json-25-1661283894345\",\"type\":\"application/json\"},{\"data\":\"data:text/plain;base64,SGVsbG8gV29ybGQhCg==\",\"size\":13,\"dataFormat\":\"Base64\",\"name\":\"testFile.txt\",\"id\":\"uppy-testfile/txt-1e-text/plain-13-1659676685242\",\"type\":\"text/plain\"}]"); + setDataValueSafelyInFormData( + configMap, + BODY, + "[{\"data\":\"data:application/json;base64,ewogICAgIm1vc3QiOiAic2ltcGxlIgp9Cg==\",\"size\":25,\"dataFormat\":\"Base64\",\"name\":\"testfile.json\",\"id\":\"uppy-testfile/json-1e-application/json-25-1661283894345\",\"type\":\"application/json\"},{\"data\":\"data:text/plain;base64,SGVsbG8gV29ybGQhCg==\",\"size\":13,\"dataFormat\":\"Base64\",\"name\":\"testFile.txt\",\"id\":\"uppy-testfile/txt-1e-text/plain-13-1659676685242\",\"type\":\"text/plain\"}]"); setDataValueSafelyInFormData(configMap, PATH, "path"); setDataValueSafelyInFormData(configMap, COMMAND, "UPLOAD_MULTIPLE_FILES_FROM_BODY"); setDataValueSafelyInFormData(configMap, BUCKET, "bucket_name"); @@ -1371,26 +1355,23 @@ public void uploadsMultipleFilesWithFilePicker() throws InterruptedException { actionConfiguration.setFormData(configMap); - AmazonS3 connection = spyS3PluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + spyS3PluginExecutor.datasourceCreate(datasourceConfiguration).block(); ArrayList<String> signedURLS = new ArrayList<>(); signedURLS.add("https://example.signed.url1"); signedURLS.add("https://example.signed.url2"); - doNothing().when(spyS3PluginExecutor).uploadFileInS3(any(),any(),any(),anyString(),anyString()); - doReturn(signedURLS).when(spyS3PluginExecutor).getSignedUrls(any(), anyString(),any(), any()); + doNothing().when(spyS3PluginExecutor).uploadFileInS3(any(), any(), any(), anyString(), anyString()); + doReturn(signedURLS).when(spyS3PluginExecutor).getSignedUrls(any(), anyString(), any(), any()); Mono<ActionExecutionResult> resultMono = spyS3PluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); ArrayList<String> x = (ArrayList<String>) ((HashMap) result.getBody()).get("signedUrls"); - assertEquals(x.size() , signedURLS.size()); + assertEquals(x.size(), signedURLS.size()); assertEquals(x.get(0), signedURLS.get(0)); assertEquals(x.get(1), signedURLS.get(1)); - }) .verifyComplete(); } @@ -1404,10 +1385,12 @@ public void uploadsSingleFileWithoutFilePicker() throws InterruptedException { ActionConfiguration actionConfiguration = new ActionConfiguration(); Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"type\": \"text/json\",\n" + - " \"data\": {\"data\":\"{\\n \\\"most\\\": \\\"simple\\\"\\n}\\n\",\"size\":25,\"dataFormat\":\"Text\",\"name\":\"testfile.json\",\"id\":\"uppy-testfile/json-1e-application/json-25-1661283894345\",\"type\":\"application/json\"}\n" + - "}"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " \"type\": \"text/json\",\n" + + " \"data\": {\"data\":\"{\\n \\\"most\\\": \\\"simple\\\"\\n}\\n\",\"size\":25,\"dataFormat\":\"Text\",\"name\":\"testfile.json\",\"id\":\"uppy-testfile/json-1e-application/json-25-1661283894345\",\"type\":\"application/json\"}\n" + + "}"); setDataValueSafelyInFormData(configMap, PATH, "path"); setDataValueSafelyInFormData(configMap, COMMAND, "UPLOAD_FILE_FROM_BODY"); setDataValueSafelyInFormData(configMap, BUCKET, "bucket_name"); @@ -1416,22 +1399,19 @@ public void uploadsSingleFileWithoutFilePicker() throws InterruptedException { actionConfiguration.setFormData(configMap); - AmazonS3 connection = spyS3PluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + spyS3PluginExecutor.datasourceCreate(datasourceConfiguration).block(); ArrayList<String> signedURLS = new ArrayList<>(); signedURLS.add("https://example.signed.url"); - doNothing().when(spyS3PluginExecutor).uploadFileInS3(any(),any(),any(),anyString(),anyString()); - doReturn(signedURLS).when(spyS3PluginExecutor).getSignedUrls(any(), anyString(),any(), any()); + doNothing().when(spyS3PluginExecutor).uploadFileInS3(any(), any(), any(), anyString(), anyString()); + doReturn(signedURLS).when(spyS3PluginExecutor).getSignedUrls(any(), anyString(), any(), any()); Mono<ActionExecutionResult> resultMono = spyS3PluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertEquals(((HashMap) result.getBody()).get("signedUrl"), signedURLS.get(0)); - }) .verifyComplete(); } @@ -1445,7 +1425,10 @@ public void uploadsMultipleFilesWithoutFilePicker() throws InterruptedException ActionConfiguration actionConfiguration = new ActionConfiguration(); Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, BODY, "[{\"data\":\"data:application/json;base64,ewogICAgIm1vc3QiOiAic2ltcGxlIgp9Cg==\",\"size\":25,\"dataFormat\":\"Base64\",\"name\":\"testfile.json\",\"id\":\"uppy-testfile/json-1e-application/json-25-1661283894345\",\"type\":\"application/json\"},{\"data\":\"data:text/plain;base64,SGVsbG8gV29ybGQhCg==\",\"size\":13,\"dataFormat\":\"Base64\",\"name\":\"testFile.txt\",\"id\":\"uppy-testfile/txt-1e-text/plain-13-1659676685242\",\"type\":\"text/plain\"}]"); + setDataValueSafelyInFormData( + configMap, + BODY, + "[{\"data\":\"data:application/json;base64,ewogICAgIm1vc3QiOiAic2ltcGxlIgp9Cg==\",\"size\":25,\"dataFormat\":\"Base64\",\"name\":\"testfile.json\",\"id\":\"uppy-testfile/json-1e-application/json-25-1661283894345\",\"type\":\"application/json\"},{\"data\":\"data:text/plain;base64,SGVsbG8gV29ybGQhCg==\",\"size\":13,\"dataFormat\":\"Base64\",\"name\":\"testFile.txt\",\"id\":\"uppy-testfile/txt-1e-text/plain-13-1659676685242\",\"type\":\"text/plain\"}]"); setDataValueSafelyInFormData(configMap, PATH, "path"); setDataValueSafelyInFormData(configMap, COMMAND, "UPLOAD_MULTIPLE_FILES_FROM_BODY"); setDataValueSafelyInFormData(configMap, BUCKET, "bucket_name"); @@ -1454,37 +1437,40 @@ public void uploadsMultipleFilesWithoutFilePicker() throws InterruptedException actionConfiguration.setFormData(configMap); - AmazonS3 connection = spyS3PluginExecutor.datasourceCreate(datasourceConfiguration).block(); + AmazonS3 connection = + spyS3PluginExecutor.datasourceCreate(datasourceConfiguration).block(); ArrayList<String> signedURLS = new ArrayList<>(); signedURLS.add("https://example.signed.url1"); signedURLS.add("https://example.signed.url2"); - doNothing().when(spyS3PluginExecutor).uploadFileInS3(any(),any(),any(),anyString(),anyString()); - doReturn(signedURLS).when(spyS3PluginExecutor).getSignedUrls(any(), anyString(),any(), any()); + doNothing().when(spyS3PluginExecutor).uploadFileInS3(any(), any(), any(), anyString(), anyString()); + doReturn(signedURLS).when(spyS3PluginExecutor).getSignedUrls(any(), anyString(), any(), any()); Mono<ActionExecutionResult> resultMono = spyS3PluginExecutor.executeParameterized( - connection, - executeActionDTO, - datasourceConfiguration, - actionConfiguration); + connection, executeActionDTO, datasourceConfiguration, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); ArrayList<String> x = (ArrayList<String>) ((HashMap) result.getBody()).get("signedUrls"); - assertEquals(x.size() , signedURLS.size()); + assertEquals(x.size(), signedURLS.size()); assertEquals(x.get(0), signedURLS.get(0)); assertEquals(x.get(1), signedURLS.get(1)); - }) .verifyComplete(); } @Test public void verifyUniquenessOfAmazonS3PluginErrorCode() { - assert (Arrays.stream(S3PluginError.values()).map(S3PluginError::getAppErrorCode).distinct().count() == S3PluginError.values().length); - - assert (Arrays.stream(S3PluginError.values()).map(S3PluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-AS3")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(S3PluginError.values()) + .map(S3PluginError::getAppErrorCode) + .distinct() + .count() + == S3PluginError.values().length); + + assert (Arrays.stream(S3PluginError.values()) + .map(S3PluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-AS3")) + .collect(Collectors.toList()) + .size() + == 0); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/utils/AmazonS3ErrorUtilsTest.java b/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/utils/AmazonS3ErrorUtilsTest.java index 86076c63a03e..72ccadd6057a 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/utils/AmazonS3ErrorUtilsTest.java +++ b/app/server/appsmith-plugins/amazons3Plugin/src/test/java/com/external/utils/AmazonS3ErrorUtilsTest.java @@ -9,7 +9,6 @@ public class AmazonS3ErrorUtilsTest { - @Test public void getReadableErrorWithAmazonServiceException() throws InstantiationException { String errorMessage = "The specified access point name or account is not valid."; @@ -19,8 +18,7 @@ public void getReadableErrorWithAmazonServiceException() throws InstantiationExc AmazonS3ErrorUtils errorUtil = AmazonS3ErrorUtils.getInstance(); String returnedErrorMessage = errorUtil.getReadableError(amazonServiceException); assertNotNull(returnedErrorMessage); - assertEquals(returnedErrorMessage,errorCode+": "+errorMessage); - + assertEquals(returnedErrorMessage, errorCode + ": " + errorMessage); } @Test @@ -32,8 +30,6 @@ public void getReadableErrorWithAmazonS3Exception() throws InstantiationExceptio AmazonS3ErrorUtils errorUtil = AmazonS3ErrorUtils.getInstance(); String returnedErrorMessage = errorUtil.getReadableError(amazonS3Exception); assertNotNull(returnedErrorMessage); - assertEquals(returnedErrorMessage,errorCode+": "+errorMessage); - + assertEquals(returnedErrorMessage, errorCode + ": " + errorMessage); } - } diff --git a/app/server/appsmith-plugins/arangoDBPlugin/pom.xml b/app/server/appsmith-plugins/arangoDBPlugin/pom.xml index 068bff6bc7c4..ae0cec6a4314 100644 --- a/app/server/appsmith-plugins/arangoDBPlugin/pom.xml +++ b/app/server/appsmith-plugins/arangoDBPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>arangodbPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -64,10 +63,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/ArangoDBPlugin.java b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/ArangoDBPlugin.java index b9037bc20068..7ee937795c02 100644 --- a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/ArangoDBPlugin.java +++ b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/ArangoDBPlugin.java @@ -79,24 +79,22 @@ public static class ArangoDBPluginExecutor implements PluginExecutor<ArangoDatab public static AppsmithPluginErrorUtils arangoDBErrorUtils = ArangoDBErrorUtils.getInstance(); @Override - public Mono<ActionExecutionResult> execute(ArangoDatabase db, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + ArangoDatabase db, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { if (!isConnectionValid(db)) { return Mono.error(new StaleConnectionException(CONNECTION_INVALID_ERROR_MSG)); } String query = actionConfiguration.getBody(); - List<RequestParamDTO> requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - query, null, null, null)); + List<RequestParamDTO> requestParams = + List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null)); if (StringUtils.isNullOrEmpty(query)) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ArangoDBErrorMessages.MISSING_QUERY_ERROR_MSG - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ArangoDBErrorMessages.MISSING_QUERY_ERROR_MSG)); } return Mono.fromCallable(() -> { @@ -108,8 +106,10 @@ public Mono<ActionExecutionResult> execute(ArangoDatabase db, if (isUpdateQuery(query)) { Map<String, Long> updateCount = new HashMap<>(); - updateCount.put(WRITES_EXECUTED_KEY, cursor.getStats().getWritesExecuted()); - updateCount.put(WRITES_IGNORED_KEY, cursor.getStats().getWritesIgnored()); + updateCount.put( + WRITES_EXECUTED_KEY, cursor.getStats().getWritesExecuted()); + updateCount.put( + WRITES_IGNORED_KEY, cursor.getStats().getWritesIgnored()); docList.add(updateCount); } else { docList.addAll(cursor.asListRemaining()); @@ -122,8 +122,11 @@ public Mono<ActionExecutionResult> execute(ArangoDatabase db, .onErrorResume(error -> { ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(ArangoDBPluginError.QUERY_EXECUTION_FAILED, ArangoDBErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error); + if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + ArangoDBPluginError.QUERY_EXECUTION_FAILED, + ArangoDBErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error); } result.setErrorInfo(error); return Mono.just(result); @@ -169,30 +172,28 @@ private boolean isConnectionValid(ArangoDatabase db) { return true; } - @Override public Mono<ArangoDatabase> datasourceCreate(DatasourceConfiguration datasourceConfiguration) { return (Mono<ArangoDatabase>) Mono.fromCallable(() -> { - List<Endpoint> nonEmptyEndpoints = datasourceConfiguration.getEndpoints().stream() .filter(endpoint -> isNonEmptyEndpoint(endpoint)) .collect(Collectors.toList()); DBAuth auth = (DBAuth) datasourceConfiguration.getAuthentication(); Builder dbBuilder = getBasicBuilder(auth); - nonEmptyEndpoints.stream() - .forEach(endpoint -> { - String host = endpoint.getHost(); - int port = (int) (long) ObjectUtils.defaultIfNull(endpoint.getPort(), DEFAULT_PORT); - dbBuilder.host(host, port); - }); + nonEmptyEndpoints.stream().forEach(endpoint -> { + String host = endpoint.getHost(); + int port = (int) (long) ObjectUtils.defaultIfNull(endpoint.getPort(), DEFAULT_PORT); + dbBuilder.host(host, port); + }); /** * - datasource.connection, datasource.connection.ssl, datasource.connection.ssl.authType objects * are never expected to be null because form.json always assigns a default value to authType object. */ - SSLDetails.AuthType sslAuthType = datasourceConfiguration.getConnection().getSsl().getAuthType(); + SSLDetails.AuthType sslAuthType = + datasourceConfiguration.getConnection().getSsl().getAuthType(); try { setSSLParam(dbBuilder, sslAuthType); } catch (AppsmithPluginException e) { @@ -263,19 +264,15 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur DBAuth auth = (DBAuth) datasourceConfiguration.getAuthentication(); if (isAuthenticationMissing(auth)) { - invalids.add( - ArangoDBErrorMessages.DS_MISSING_AUTHENTICATION_DETAILS_ERROR_MSG - ); + invalids.add(ArangoDBErrorMessages.DS_MISSING_AUTHENTICATION_DETAILS_ERROR_MSG); } if (!isEndpointAvailable(datasourceConfiguration.getEndpoints())) { - invalids.add( - ArangoDBErrorMessages.DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG - ); + invalids.add(ArangoDBErrorMessages.DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG); } - SSLDetails.CACertificateType caCertificateType = datasourceConfiguration.getConnection().getSsl() - .getCaCertificateType(); + SSLDetails.CACertificateType caCertificateType = + datasourceConfiguration.getConnection().getSsl().getCaCertificateType(); if (!SSLDetails.CACertificateType.NONE.equals(caCertificateType) && !isCaCertificateAvailable(datasourceConfiguration)) { invalids.add(ArangoDBErrorMessages.DS_CA_CERT_NOT_FOUND_ERROR_MSG); @@ -315,12 +312,14 @@ public Mono<DatasourceTestResult> testDatasource(ArangoDatabase connection) { log.error("Error when testing ArangoDB datasource.", error); return Mono.just(new DatasourceTestResult(arangoDBErrorUtils.getReadableError(error))); }) - .timeout(Duration.ofSeconds(TEST_DATASOURCE_TIMEOUT_SECONDS), + .timeout( + Duration.ofSeconds(TEST_DATASOURCE_TIMEOUT_SECONDS), Mono.just(new DatasourceTestResult(DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG))); } @Override - public Mono<DatasourceStructure> getStructure(ArangoDatabase db, DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + ArangoDatabase db, DatasourceConfiguration datasourceConfiguration) { final DatasourceStructure structure = new DatasourceStructure(); List<DatasourceStructure.Table> tables = new ArrayList<>(); structure.setTables(tables); @@ -331,13 +330,10 @@ public Mono<DatasourceStructure> getStructure(ArangoDatabase db, DatasourceConfi try { collections = db.getCollections(options); } catch (ArangoDBException e) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, - ArangoDBErrorMessages.GET_STRUCTURE_ERROR_MSG, - e.getErrorMessage() - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + ArangoDBErrorMessages.GET_STRUCTURE_ERROR_MSG, + e.getErrorMessage())); } return Flux.fromIterable(collections) @@ -346,16 +342,13 @@ public Mono<DatasourceStructure> getStructure(ArangoDatabase db, DatasourceConfi final ArrayList<DatasourceStructure.Column> columns = new ArrayList<>(); final ArrayList<DatasourceStructure.Template> templates = new ArrayList<>(); final String collectionName = collectionEntity.getName(); - tables.add( - new DatasourceStructure.Table( - DatasourceStructure.TableType.COLLECTION, - null, - collectionName, - columns, - new ArrayList<>(), - templates - ) - ); + tables.add(new DatasourceStructure.Table( + DatasourceStructure.TableType.COLLECTION, + null, + collectionName, + columns, + new ArrayList<>(), + templates)); ArangoCursor<Map> cursor = db.query(getOneDocumentQuery(collectionName), null, null, Map.class); Map document = new HashMap(); @@ -368,8 +361,7 @@ public Mono<DatasourceStructure> getStructure(ArangoDatabase db, DatasourceConfi Mono.just(columns), Mono.just(templates), Mono.just(collectionName), - Mono.just(document) - ); + Mono.just(document)); }) .flatMap(tuple -> { final ArrayList<DatasourceStructure.Column> columns = tuple.getT1(); diff --git a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/exceptions/ArangoDBErrorMessages.java b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/exceptions/ArangoDBErrorMessages.java index 5ec02396df69..6acf39f8deab 100644 --- a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/exceptions/ArangoDBErrorMessages.java +++ b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/exceptions/ArangoDBErrorMessages.java @@ -8,32 +8,38 @@ public class ArangoDBErrorMessages extends BasePluginErrorMessages { public static final String MISSING_QUERY_ERROR_MSG = "Missing required parameter: Query."; - public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Your query failed to execute. Please check more information in the error details."; + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = + "Your query failed to execute. Please check more information in the error details."; - public static final String UNEXPECTED_SSL_OPTION_ERROR_MSG = "Appsmith server has found an unexpected SSL option: %s. Please reach " + - "out to Appsmith customer support to resolve this."; + public static final String UNEXPECTED_SSL_OPTION_ERROR_MSG = + "Appsmith server has found an unexpected SSL option: %s. Please reach " + + "out to Appsmith customer support to resolve this."; - public static final String SSL_CONTEXT_FETCHING_ERROR_MSG = "Appsmith server encountered an error when getting ssl context. Please contact Appsmith " + - "customer support to resolve this."; + public static final String SSL_CONTEXT_FETCHING_ERROR_MSG = + "Appsmith server encountered an error when getting ssl context. Please contact Appsmith " + + "customer support to resolve this."; - public static final String UNEXPECTED_CA_CERT_OPTION_ERROR_MSG = "Appsmith server has found an unexpected CA certificate option: %s. " + - "Please reach out to Appsmith customer support to resolve this."; + public static final String UNEXPECTED_CA_CERT_OPTION_ERROR_MSG = + "Appsmith server has found an unexpected CA certificate option: %s. " + + "Please reach out to Appsmith customer support to resolve this."; - public static final String GET_STRUCTURE_ERROR_MSG = "Appsmith server has failed to fetch list of collections from database. Please check " + - "if the database credentials are valid and/or you have the required permissions."; + public static final String GET_STRUCTURE_ERROR_MSG = + "Appsmith server has failed to fetch list of collections from database. Please check " + + "if the database credentials are valid and/or you have the required permissions."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ - public static final String DS_MISSING_AUTHENTICATION_DETAILS_ERROR_MSG = "Could not find required authentication info. At least one of 'Username', 'Password', " + - "'Database name' fields is missing. Please edit the 'Username', 'Password' and " + - "'Database name' fields to provide authentication info."; - - public static final String DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG = "Could not find host address. Please edit " + - "the 'Host Address' and/or the 'Port' field to provide the desired endpoint."; - - public static final String DS_CA_CERT_NOT_FOUND_ERROR_MSG = "Could not find CA certificate. Please provide a CA certificate."; - + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ + public static final String DS_MISSING_AUTHENTICATION_DETAILS_ERROR_MSG = + "Could not find required authentication info. At least one of 'Username', 'Password', " + + "'Database name' fields is missing. Please edit the 'Username', 'Password' and " + + "'Database name' fields to provide authentication info."; + + public static final String DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG = "Could not find host address. Please edit " + + "the 'Host Address' and/or the 'Port' field to provide the desired endpoint."; + + public static final String DS_CA_CERT_NOT_FOUND_ERROR_MSG = + "Could not find CA certificate. Please provide a CA certificate."; } diff --git a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/exceptions/ArangoDBPluginError.java b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/exceptions/ArangoDBPluginError.java index 5dc1a24e5abd..22b959767cf0 100644 --- a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/exceptions/ArangoDBPluginError.java +++ b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/exceptions/ArangoDBPluginError.java @@ -17,8 +17,7 @@ public enum ArangoDBPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; private final String appErrorCode; @@ -31,8 +30,15 @@ public enum ArangoDBPluginError implements BasePluginError { private final String downstreamErrorCode; - ArangoDBPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + ArangoDBPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -47,7 +53,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/ArangoDBErrorUtils.java b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/ArangoDBErrorUtils.java index 5572a074f5fa..e98c8eaab60c 100644 --- a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/ArangoDBErrorUtils.java +++ b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/ArangoDBErrorUtils.java @@ -67,5 +67,4 @@ public String getReadableError(Throwable error) { */ return CollectionUtils.lastElement(Arrays.asList(error.getMessage().split(":"))); } - } diff --git a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/SSLUtils.java b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/SSLUtils.java index 2ace0f18c554..7c3eef320fa6 100644 --- a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/SSLUtils.java +++ b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/SSLUtils.java @@ -21,8 +21,11 @@ public static boolean isCaCertificateAvailable(DatasourceConfiguration datasourc if (datasourceConfiguration.getConnection() != null && datasourceConfiguration.getConnection().getSsl() != null && datasourceConfiguration.getConnection().getSsl().getCaCertificateFile() != null - && StringUtils.isNotNullOrEmpty(datasourceConfiguration.getConnection().getSsl() - .getCaCertificateFile().getBase64Content())) { + && StringUtils.isNotNullOrEmpty(datasourceConfiguration + .getConnection() + .getSsl() + .getCaCertificateFile() + .getBase64Content())) { return true; } @@ -46,15 +49,14 @@ public static void setSSLParam(Builder builder, SSLDetails.AuthType authType) { default: throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - String.format(ArangoDBErrorMessages.UNEXPECTED_SSL_OPTION_ERROR_MSG, authType) - ); + String.format(ArangoDBErrorMessages.UNEXPECTED_SSL_OPTION_ERROR_MSG, authType)); } } public static void setSSLContext(Builder builder, DatasourceConfiguration datasourceConfiguration) { - SSLDetails.CACertificateType caCertificateType = datasourceConfiguration.getConnection().getSsl() - .getCaCertificateType(); + SSLDetails.CACertificateType caCertificateType = + datasourceConfiguration.getConnection().getSsl().getCaCertificateType(); switch (caCertificateType) { case NONE: @@ -64,22 +66,24 @@ public static void setSSLContext(Builder builder, DatasourceConfiguration dataso case FILE: case BASE64_STRING: try { - builder.sslContext(SSLHelper.getSslContext(datasourceConfiguration.getConnection().getSsl().getCaCertificateFile())); - } catch (CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException + builder.sslContext(SSLHelper.getSslContext( + datasourceConfiguration.getConnection().getSsl().getCaCertificateFile())); + } catch (CertificateException + | KeyStoreException + | IOException + | NoSuchAlgorithmException | KeyManagementException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, ArangoDBErrorMessages.SSL_CONTEXT_FETCHING_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } break; default: throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - String.format(ArangoDBErrorMessages.UNEXPECTED_CA_CERT_OPTION_ERROR_MSG, caCertificateType) - ); + String.format(ArangoDBErrorMessages.UNEXPECTED_CA_CERT_OPTION_ERROR_MSG, caCertificateType)); } } } diff --git a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/StructureUtils.java b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/StructureUtils.java index 829bd0ba90e0..0000da5763c1 100644 --- a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/StructureUtils.java +++ b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/utils/StructureUtils.java @@ -15,10 +15,11 @@ public class StructureUtils { - public static void generateTemplatesAndStructureForACollection(String collectionName, - Map document, - ArrayList<DatasourceStructure.Column> columns, - ArrayList<DatasourceStructure.Template> templates) { + public static void generateTemplatesAndStructureForACollection( + String collectionName, + Map document, + ArrayList<DatasourceStructure.Column> columns, + ArrayList<DatasourceStructure.Template> templates) { Set<String> autogenerateKeys = Set.of("_id", "_key", "_rev"); for (Object entry : document.entrySet()) { @@ -48,7 +49,7 @@ public static void generateTemplatesAndStructureForACollection(String collection } if (autogenerateKeys.contains(name)) { - isAutogenerated = true; + isAutogenerated = true; } columns.add(new DatasourceStructure.Column(name, type, null, isAutogenerated)); @@ -78,29 +79,18 @@ private static DatasourceStructure.Template generateSelectTemplate(Map<String, O String filterKey = "_key"; String filterValue = sampleValues.get("_key"); - String rawQuery = "FOR document IN " + collectionName + "\n" + - "FILTER " + "document." + filterKey + " == \"" + filterValue + "\"\n" + - "RETURN document"; + String rawQuery = "FOR document IN " + collectionName + "\n" + "FILTER " + "document." + filterKey + " == \"" + + filterValue + "\"\n" + "RETURN document"; - return new DatasourceStructure.Template( - "Select", - rawQuery - ); + return new DatasourceStructure.Template("Select", rawQuery); } private static DatasourceStructure.Template generateCreateTemplate(Map<String, Object> templateConfiguration) { String collectionName = (String) templateConfiguration.get("collectionName"); - String rawQuery = "INSERT \n" + - "{\n" + - " insertKey: \"insertValue\"\n" + - "}\n" + - "INTO " + collectionName; + String rawQuery = "INSERT \n" + "{\n" + " insertKey: \"insertValue\"\n" + "}\n" + "INTO " + collectionName; - return new DatasourceStructure.Template( - "Create", - rawQuery - ); + return new DatasourceStructure.Template("Create", rawQuery); } private static DatasourceStructure.Template generateUpdateTemplate(Map<String, Object> templateConfiguration) { @@ -109,20 +99,17 @@ private static DatasourceStructure.Template generateUpdateTemplate(Map<String, O String filterKey = "_key"; String filterValue = sampleValues.get("_key"); - String rawQuery = "UPDATE\n" + - "{\n" + - " " + filterKey + ": \"" + filterValue + "\"\n" + - "}\n" + - "WITH\n" + - "{\n" + - " updateKey: \"updateVal\"\n" + - "}\n" + - "IN " + collectionName; - - return new DatasourceStructure.Template( - "Update", - rawQuery - ); + String rawQuery = "UPDATE\n" + "{\n" + + " " + + filterKey + ": \"" + filterValue + "\"\n" + "}\n" + + "WITH\n" + + "{\n" + + " updateKey: \"updateVal\"\n" + + "}\n" + + "IN " + + collectionName; + + return new DatasourceStructure.Template("Update", rawQuery); } private static DatasourceStructure.Template generateRemoveTemplate(Map<String, Object> templateConfiguration) { @@ -132,14 +119,10 @@ private static DatasourceStructure.Template generateRemoveTemplate(Map<String, O String rawQuery = "REMOVE \"" + filterValue + "\" IN " + collectionName; - return new DatasourceStructure.Template( - "Delete", - rawQuery - ); + return new DatasourceStructure.Template("Delete", rawQuery); } public static String getOneDocumentQuery(String collectionName) { return "for doc in " + collectionName + " limit 1 return doc"; } - } diff --git a/app/server/appsmith-plugins/arangoDBPlugin/src/test/java/com/external/plugins/ArangoDBPluginTest.java b/app/server/appsmith-plugins/arangoDBPlugin/src/test/java/com/external/plugins/ArangoDBPluginTest.java index 512ec99c18cb..2da1b0f450d5 100644 --- a/app/server/appsmith-plugins/arangoDBPlugin/src/test/java/com/external/plugins/ArangoDBPluginTest.java +++ b/app/server/appsmith-plugins/arangoDBPlugin/src/test/java/com/external/plugins/ArangoDBPluginTest.java @@ -66,13 +66,12 @@ public class ArangoDBPluginTest { .withExposedPorts(8529) .waitingFor(Wait.forHttp("/")); - @BeforeAll public static void setUp() { address = container.getContainerIpAddress(); port = container.getFirstMappedPort(); - //connect + // connect arangoDB = new ArangoDB.Builder() .host(address, port) .user(user) @@ -81,64 +80,62 @@ public static void setUp() { .useProtocol(Protocol.HTTP_VPACK) .build(); - arangoDB.createDatabase(dbName); ArangoDatabase arangoDatabase = arangoDB.db(dbName); - //create collection + // create collection CollectionSchema schema = new CollectionSchema(); - schema.setRule("{\n" + - " \"message\": \"\",\n" + - " \"level\": \"strict\",\n" + - " \"rule\": {\n" + - " \"properties\": {\n" + - " \"name\": {\n" + - " \"type\": \"string\"\n" + - " },\n" + - " \"dob\": {\n" + - " \"required\": [\n" + - " \"day\",\n" + - " \"month\",\n" + - " \"year\"\n" + - " ],\n" + - " \"type\": \"object\",\n" + - " \"properties\": {\n" + - " \"year\": {\n" + - " \"type\": \"integer\"\n" + - " },\n" + - " \"month\": {\n" + - " \"type\": \"integer\"\n" + - " },\n" + - " \"day\": {\n" + - " \"type\": \"integer\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"netWorth\": {\n" + - " \"type\": \"string\"\n" + - " },\n" + - " \"age\": {\n" + - " \"type\": \"integer\"\n" + - " },\n" + - " \"gender\": {\n" + - " \"type\": \"string\"\n" + - " },\n" + - " \"luckyNumber\": {\n" + - " \"type\": \"integer\"\n" + - " }\n" + - " },\n" + - " \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" + - " \"type\": \"object\",\n" + - " \"required\": [\n" + - " \"age\",\n" + - " \"dob\",\n" + - " \"gender\",\n" + - " \"luckyNumber\",\n" + - " \"name\",\n" + - " \"netWorth\"\n" + - " ]\n" + - " }\n" + - "}"); + schema.setRule("{\n" + " \"message\": \"\",\n" + + " \"level\": \"strict\",\n" + + " \"rule\": {\n" + + " \"properties\": {\n" + + " \"name\": {\n" + + " \"type\": \"string\"\n" + + " },\n" + + " \"dob\": {\n" + + " \"required\": [\n" + + " \"day\",\n" + + " \"month\",\n" + + " \"year\"\n" + + " ],\n" + + " \"type\": \"object\",\n" + + " \"properties\": {\n" + + " \"year\": {\n" + + " \"type\": \"integer\"\n" + + " },\n" + + " \"month\": {\n" + + " \"type\": \"integer\"\n" + + " },\n" + + " \"day\": {\n" + + " \"type\": \"integer\"\n" + + " }\n" + + " }\n" + + " },\n" + + " \"netWorth\": {\n" + + " \"type\": \"string\"\n" + + " },\n" + + " \"age\": {\n" + + " \"type\": \"integer\"\n" + + " },\n" + + " \"gender\": {\n" + + " \"type\": \"string\"\n" + + " },\n" + + " \"luckyNumber\": {\n" + + " \"type\": \"integer\"\n" + + " }\n" + + " },\n" + + " \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" + + " \"type\": \"object\",\n" + + " \"required\": [\n" + + " \"age\",\n" + + " \"dob\",\n" + + " \"gender\",\n" + + " \"luckyNumber\",\n" + + " \"name\",\n" + + " \"netWorth\"\n" + + " ]\n" + + " }\n" + + "}"); schema.setMessage(""); schema.setLevel(CollectionSchema.Level.NONE); CollectionCreateOptions options = new CollectionCreateOptions(); @@ -152,19 +149,23 @@ public static void setUp() { arangoDatabase.createCollection(collectionName, options); collection.grantAccess(user, Permissions.RW); - //insert test documents - collection.insertDocuments( - List.of(Map.of( - "name", "Cierra Vega", - "gender", "F", - "age", 20, - "luckyNumber", 987654321L, - "dob", LocalDate.of(2018, 12, 31), - "netWorth", new BigDecimal("123456.789012") - ), - Map.of("name", "Alden Cantrell", "gender", "M", "age", 30), - Map.of("name", "Kierra Gentry", "gender", "F", "age", 40) - )); + // insert test documents + collection.insertDocuments(List.of( + Map.of( + "name", + "Cierra Vega", + "gender", + "F", + "age", + 20, + "luckyNumber", + 987654321L, + "dob", + LocalDate.of(2018, 12, 31), + "netWorth", + new BigDecimal("123456.789012")), + Map.of("name", "Alden Cantrell", "gender", "M", "age", 30), + Map.of("name", "Kierra Gentry", "gender", "F", "age", 40))); } private DatasourceConfiguration createDatasourceConfiguration() { @@ -212,14 +213,11 @@ public void testExecuteReadQuery() { Mono<ArangoDatabase> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("FOR user IN users" + - " FILTER user.age > 30" + - " SORT user.id ASC" + - " LIMIT 10" + - " RETURN user"); + actionConfiguration.setBody( + "FOR user IN users" + " FILTER user.age > 30" + " SORT user.id ASC" + " LIMIT 10" + " RETURN user"); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> - pluginExecutor.execute(conn, dsConfig, actionConfiguration)); + Mono<Object> executeMono = + dsConnectionMono.flatMap(conn -> pluginExecutor.execute(conn, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -246,14 +244,14 @@ public void testExecuteWriteQuery() { Mono<ArangoDatabase> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("INSERT {" + - " name: 'John Smith'," + - " email: ['[email protected]](mailto:%[email protected])']," + - " gender: 'M'," + - " testKeyWord: ' Return '," + - " age: 50" + - " } INTO users"); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.execute(conn, dsConfig, actionConfiguration)); + actionConfiguration.setBody("INSERT {" + " name: 'John Smith'," + + " email: ['[email protected]](mailto:%[email protected])']," + + " gender: 'M'," + + " testKeyWord: ' Return '," + + " age: 50" + + " } INTO users"); + Mono<Object> executeMono = + dsConnectionMono.flatMap(conn -> pluginExecutor.execute(conn, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -272,7 +270,8 @@ public void testExecuteWriteQuery() { @Test public void testStructure() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<DatasourceStructure> structureMono = pluginExecutor.datasourceCreate(dsConfig) + Mono<DatasourceStructure> structureMono = pluginExecutor + .datasourceCreate(dsConfig) .flatMap(connection -> pluginExecutor.getStructure(connection, dsConfig)); StepVerifier.create(structureMono) @@ -280,41 +279,45 @@ public void testStructure() { assertNotNull(structure); assertEquals(1, structure.getTables().size()); - final DatasourceStructure.Table possessionsTable = structure.getTables().get(0); + final DatasourceStructure.Table possessionsTable = + structure.getTables().get(0); assertEquals("users", possessionsTable.getName()); assertEquals(DatasourceStructure.TableType.COLLECTION, possessionsTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("_id", "String", null, true), - new DatasourceStructure.Column("_key", "String", null, true), - new DatasourceStructure.Column("_rev", "String", null, true), - new DatasourceStructure.Column("age", "Long", null, false), - new DatasourceStructure.Column("dob", "Object", null, false), - new DatasourceStructure.Column("gender", "String", null, false), - new DatasourceStructure.Column("luckyNumber", "Long", null, false), - new DatasourceStructure.Column("name", "String", null, false), - new DatasourceStructure.Column("netWorth", "String", null, false), + new DatasourceStructure.Column[] { + new DatasourceStructure.Column("_id", "String", null, true), + new DatasourceStructure.Column("_key", "String", null, true), + new DatasourceStructure.Column("_rev", "String", null, true), + new DatasourceStructure.Column("age", "Long", null, false), + new DatasourceStructure.Column("dob", "Object", null, false), + new DatasourceStructure.Column("gender", "String", null, false), + new DatasourceStructure.Column("luckyNumber", "Long", null, false), + new DatasourceStructure.Column("name", "String", null, false), + new DatasourceStructure.Column("netWorth", "String", null, false), }, - possessionsTable.getColumns().toArray() - ); + possessionsTable.getColumns().toArray()); assertArrayEquals( - new DatasourceStructure.Key[]{}, - possessionsTable.getKeys().toArray() - ); - + new DatasourceStructure.Key[] {}, + possessionsTable.getKeys().toArray()); }) .verifyComplete(); } @Test public void verifyUniquenessOfArangoDBPluginErrorCode() { - assert (Arrays.stream(ArangoDBPluginError.values()).map(ArangoDBPluginError::getAppErrorCode).distinct().count() == ArangoDBPluginError.values().length); - - assert (Arrays.stream(ArangoDBPluginError.values()).map(ArangoDBPluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-ARN")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(ArangoDBPluginError.values()) + .map(ArangoDBPluginError::getAppErrorCode) + .distinct() + .count() + == ArangoDBPluginError.values().length); + + assert (Arrays.stream(ArangoDBPluginError.values()) + .map(ArangoDBPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-ARN")) + .collect(Collectors.toList()) + .size() + == 0); } @Test @@ -325,7 +328,8 @@ public void testErrorMessageOnBadHostAddress() { StepVerifier.create(testDsResult) .assertNext(dsTestResult -> { assertEquals(1, dsTestResult.getInvalids().size()); - assertEquals(DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG, + assertEquals( + DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG, dsTestResult.getInvalids().stream().toList().get(0)); }) .verifyComplete(); @@ -335,14 +339,15 @@ public void testErrorMessageOnBadHostAddress() { public void testErrorMessageOnTestDatasourceTimeout() { ArangoDatabase mockConnection = mock(ArangoDatabase.class); when(mockConnection.getVersion()).thenAnswer((Answer<String>) invocation -> { - Thread.sleep(30*1000); + Thread.sleep(30 * 1000); return "test_version"; }); Mono<DatasourceTestResult> testDsResult = pluginExecutor.testDatasource(mockConnection); StepVerifier.create(testDsResult) .assertNext(dsTestResult -> { assertEquals(1, dsTestResult.getInvalids().size()); - assertEquals(DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG, + assertEquals( + DS_HOSTNAME_MISSING_OR_INVALID_ERROR_MSG, dsTestResult.getInvalids().stream().toList().get(0)); }) .verifyComplete(); diff --git a/app/server/appsmith-plugins/dynamoPlugin/pom.xml b/app/server/appsmith-plugins/dynamoPlugin/pom.xml index 1a62c9961362..54e544bc7a13 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/pom.xml +++ b/app/server/appsmith-plugins/dynamoPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>dynamoPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -45,10 +44,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java index f6094e5b9137..964e9a993f6e 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java +++ b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java @@ -85,7 +85,6 @@ public DynamoPlugin(PluginWrapper wrapper) { * DynamoDB actions and parameters reference: * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations_Amazon_DynamoDB.html */ - @Extension public static class DynamoPluginExecutor implements PluginExecutor<DynamoDbClient> { @@ -93,17 +92,15 @@ public static class DynamoPluginExecutor implements PluginExecutor<DynamoDbClien public Object extractValue(Object rawItem) { - if (!(rawItem instanceof List) - && !(rawItem instanceof Map)) { + if (!(rawItem instanceof List) && !(rawItem instanceof Map)) { return rawItem; } if (rawItem instanceof List) { return ((List<Object>) rawItem) - .stream() - .map(item -> extractValue(item)) - .collect(Collectors.toList()); - } else { /* map type */ + .stream().map(item -> extractValue(item)).collect(Collectors.toList()); + } else { + /* map type */ Map<String, Object> extractedValueMap = new HashMap<>(); Map<String, Object> rawItemAsMap = (Map<String, Object>) rawItem; for (Map.Entry<String, Object> entry : rawItemAsMap.entrySet()) { @@ -132,8 +129,7 @@ public Object extractValue(Object rawItem) { */ List<Object> rawValueAsList = (List<Object>) entry.getValue(); if (rawValueAsList.size() > 0) { - return rawValueAsList - .stream() + return rawValueAsList.stream() .map(listItem -> extractValue(listItem)) .collect(Collectors.toList()); } @@ -145,9 +141,7 @@ public Object extractValue(Object rawItem) { */ Map<String, Object> rawValueAsMap = (Map<String, Object>) entry.getValue(); if (rawValueAsMap.size() > 0) { - return rawValueAsMap - .entrySet() - .stream() + return rawValueAsMap.entrySet().stream() .map(item -> Map.entry(item.getKey(), extractValue(item.getValue()))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @@ -166,8 +160,8 @@ public Object extractValue(Object rawItem) { * - Transform response for easy consumption. For details please visit * https://github.com/appsmithorg/appsmith/issues/3010 */ - public Object getTransformedResponse(Map<String, Object> rawResponse, - String action) throws AppsmithPluginException { + public Object getTransformedResponse(Map<String, Object> rawResponse, String action) + throws AppsmithPluginException { Map<String, Object> transformedResponse = new HashMap<>(); for (Map.Entry<String, Object> responseEntry : rawResponse.entrySet()) { @@ -186,9 +180,10 @@ public Object getTransformedResponse(Map<String, Object> rawResponse, } @Override - public Mono<ActionExecutionResult> execute(DynamoDbClient ddb, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + DynamoDbClient ddb, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final Map<String, Object> requestData = new HashMap<>(); final String body = actionConfiguration.getBody(); @@ -198,11 +193,10 @@ public Mono<ActionExecutionResult> execute(DynamoDbClient ddb, ActionExecutionResult result = new ActionExecutionResult(); final String action = actionConfiguration.getPath(); - if (! StringUtils.hasLength(action)) { + if (!StringUtils.hasLength(action)) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - DynamoErrorMessages.MISSING_ACTION_NAME_ERROR_MSG - ); + DynamoErrorMessages.MISSING_ACTION_NAME_ERROR_MSG); } requestData.put("action", action); requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, action, null, null, null)); @@ -216,37 +210,44 @@ public Mono<ActionExecutionResult> execute(DynamoDbClient ddb, } catch (IOException e) { final String message = "Error parsing the JSON body: " + e.getMessage(); log.warn(message, e); - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, body, e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, body, e.getMessage()); } requestData.put("parameters", parameters); final Class<?> requestClass; try { - requestClass = Class.forName("software.amazon.awssdk.services.dynamodb.model." + action + "Request"); + requestClass = Class.forName( + "software.amazon.awssdk.services.dynamodb.model." + action + "Request"); } catch (ClassNotFoundException e) { throw new AppsmithPluginException( DynamoPluginError.UNKNOWN_ACTION_NAME, String.format(DynamoErrorMessages.UNKNOWN_ACTION_NAME_ERROR_MSG, action), - e.getMessage() - ); + e.getMessage()); } try { final Method actionExecuteMethod = DynamoDbClient.class.getMethod( - // Convert `ListTables` to `listTables`, which is the name of the method to execute this action. - toLowerCamelCase(action), - requestClass - ); + // Convert `ListTables` to `listTables`, which is the name of the method to execute + // this action. + toLowerCamelCase(action), requestClass); final Object sdkValue = plainToSdk(parameters, requestClass); - final DynamoDbResponse response = (DynamoDbResponse) actionExecuteMethod.invoke(ddb, sdkValue); + final DynamoDbResponse response = + (DynamoDbResponse) actionExecuteMethod.invoke(ddb, sdkValue); Object rawResponse = sdkToPlain(response); - Object transformedResponse = getTransformedResponse((Map<String, Object>) rawResponse, action); + Object transformedResponse = + getTransformedResponse((Map<String, Object>) rawResponse, action); result.setBody(transformedResponse); - } catch (InvocationTargetException | IllegalAccessException | - NoSuchMethodException | ClassNotFoundException e) { + } catch (InvocationTargetException + | IllegalAccessException + | NoSuchMethodException + | ClassNotFoundException e) { final String errorMessage = (e.getCause() == null ? e : e.getCause()).getMessage(); log.warn("Error executing the DynamoDB Action: {}", errorMessage, e); - throw new AppsmithPluginException(DynamoPluginError.QUERY_EXECUTION_FAILED, DynamoErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, errorMessage); + throw new AppsmithPluginException( + DynamoPluginError.QUERY_EXECUTION_FAILED, + DynamoErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + errorMessage); } result.setIsExecutionSuccess(true); @@ -256,8 +257,11 @@ public Mono<ActionExecutionResult> execute(DynamoDbClient ddb, .onErrorResume(error -> { ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(DynamoPluginError.QUERY_EXECUTION_FAILED, DynamoErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error.getMessage()); + if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + DynamoPluginError.QUERY_EXECUTION_FAILED, + DynamoErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error.getMessage()); } result.setErrorInfo(error); return Mono.just(result); @@ -281,23 +285,23 @@ public Mono<DynamoDbClient> datasourceCreate(DatasourceConfiguration datasourceC final DynamoDbClientBuilder builder = DynamoDbClient.builder(); if (!CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) { - final Endpoint endpoint = datasourceConfiguration.getEndpoints().get(0); - builder.endpointOverride(URI.create("http://" + endpoint.getHost() + ":" + endpoint.getPort())); + final Endpoint endpoint = + datasourceConfiguration.getEndpoints().get(0); + builder.endpointOverride( + URI.create("http://" + endpoint.getHost() + ":" + endpoint.getPort())); } final DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); - if (authentication == null || ! StringUtils.hasLength(authentication.getDatabaseName())) { + if (authentication == null || !StringUtils.hasLength(authentication.getDatabaseName())) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - DynamoErrorMessages.MISSING_REGION_ERROR_MSG - ); + DynamoErrorMessages.MISSING_REGION_ERROR_MSG); } builder.region(Region.of(authentication.getDatabaseName())); - builder.credentialsProvider(StaticCredentialsProvider.create( - AwsBasicCredentials.create(authentication.getUsername(), authentication.getPassword()) - )); + builder.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create( + authentication.getUsername(), authentication.getPassword()))); return builder.build(); }) @@ -348,27 +352,26 @@ public Mono<DatasourceTestResult> testDatasource(DynamoDbClient connection) { } @Override - public Mono<DatasourceStructure> getStructure(DynamoDbClient ddb, DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + DynamoDbClient ddb, DatasourceConfiguration datasourceConfiguration) { return Mono.fromCallable(() -> { - final ListTablesResponse listTablesResponse = ddb.listTables(); - - List<DatasourceStructure.Table> tables = new ArrayList<>(); - for (final String tableName : listTablesResponse.tableNames()) { - tables.add(new DatasourceStructure.Table( - DatasourceStructure.TableType.TABLE, - null, - tableName, - Collections.emptyList(), - Collections.emptyList(), - Collections.emptyList() - )); - } - - return new DatasourceStructure(tables); + final ListTablesResponse listTablesResponse = ddb.listTables(); + + List<DatasourceStructure.Table> tables = new ArrayList<>(); + for (final String tableName : listTablesResponse.tableNames()) { + tables.add(new DatasourceStructure.Table( + DatasourceStructure.TableType.TABLE, + null, + tableName, + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList())); + } - }).subscribeOn(scheduler); + return new DatasourceStructure(tables); + }) + .subscribeOn(scheduler); } - } private static String toLowerCamelCase(String action) { @@ -389,8 +392,8 @@ private static String toLowerCamelCase(String action) { * @throws ClassNotFoundException Thrown if any of the builder class could not be found corresponding to the action class. */ public static <T> T plainToSdk(Map<String, Object> mapping, Class<T> type) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, - AppsmithPluginException, ClassNotFoundException { + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, AppsmithPluginException, + ClassNotFoundException { final Class<?> builderType = Class.forName(type.getName() + "$Builder"); @@ -408,13 +411,13 @@ public static <T> T plainToSdk(Map<String, Object> mapping, Class<T> type) final Method setterMethod = findMethod(builderType, method -> { final Class<?>[] parameterTypes = method.getParameterTypes(); return method.getName().equals(setterName) - && (SdkBytes.class.isAssignableFrom(parameterTypes[0]) || String.class.isAssignableFrom(parameterTypes[0])); + && (SdkBytes.class.isAssignableFrom(parameterTypes[0]) + || String.class.isAssignableFrom(parameterTypes[0])); }); if (setterMethod == null) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - String.format(DynamoErrorMessages.INVALID_ATTRIBUTE_ERROR_MSG, entry.getKey()) - ); + String.format(DynamoErrorMessages.INVALID_ATTRIBUTE_ERROR_MSG, entry.getKey())); } if (SdkBytes.class.isAssignableFrom(setterMethod.getParameterTypes()[0])) { value = SdkBytes.fromUtf8String((String) value); @@ -432,7 +435,8 @@ public static <T> T plainToSdk(Map<String, Object> mapping, Class<T> type) } else if (value instanceof Map) { // For maps, we go recursive, applying this transformation to each value, and replacing with the // result in the map. Generic types in the setter method's signature are used to convert the values. - final Method setterMethod = findMethod(builderType, m -> m.getName().equals(setterName)); + final Method setterMethod = + findMethod(builderType, m -> m.getName().equals(setterName)); final Type parameterType = setterMethod.getGenericParameterTypes()[0]; if (parameterType instanceof ParameterizedType) { final ParameterizedType valueType = (ParameterizedType) parameterType; @@ -440,13 +444,15 @@ public static <T> T plainToSdk(Map<String, Object> mapping, Class<T> type) for (final Map.Entry<String, Object> innerEntry : ((Map<String, Object>) value).entrySet()) { Object innerValue = innerEntry.getValue(); if (innerValue instanceof Map) { - innerValue = plainToSdk((Map) innerValue, (Class<?>) valueType.getActualTypeArguments()[1]); + innerValue = plainToSdk( + (Map) innerValue, (Class<?>) valueType.getActualTypeArguments()[1]); } transformedMap.put(innerEntry.getKey(), innerValue); } value = transformedMap; if (!Map.class.isAssignableFrom((Class<?>) valueType.getRawType())) { - // Some setters don't take a plain map. For example, some require an `AttributeValue` instance + // Some setters don't take a plain map. For example, some require an `AttributeValue` + // instance // for objects that are just maps in JSON. So, we make that conversion here. value = plainToSdk((Map) value, (Class<T>) valueType.getRawType()); } @@ -459,17 +465,23 @@ public static <T> T plainToSdk(Map<String, Object> mapping, Class<T> type) // For linear collections, the process is similar to that of maps. final Collection<Object> valueAsCollection = (Collection) value; // Find method by name and exclude the varargs version of the method. - final Method setterMethod = findMethod(builderType, m -> m.getName().equals(setterName) && !m.getParameterTypes()[0].getName().startsWith("[L")); - Type valueType = ((ParameterizedType) setterMethod.getGenericParameterTypes()[0]).getActualTypeArguments()[0]; + final Method setterMethod = findMethod( + builderType, + m -> m.getName().equals(setterName) + && !m.getParameterTypes()[0].getName().startsWith("[L")); + Type valueType = ((ParameterizedType) setterMethod.getGenericParameterTypes()[0]) + .getActualTypeArguments()[0]; if (valueType instanceof WildcardType) { - // This occurs when the method's parameter is typed as `Collection<? extends Map<...>>`. Example op: `BatchGetItem`. + // This occurs when the method's parameter is typed as `Collection<? extends Map<...>>`. Example + // op: `BatchGetItem`. valueType = ((WildcardType) valueType).getUpperBounds()[0]; } final Collection<Object> reTypedList = new ArrayList<>(); for (final Object innerValue : valueAsCollection) { if (innerValue instanceof Map) { reTypedList.add(plainToSdk((Map) innerValue, valueType)); - } else if (innerValue instanceof String && SdkBytes.class.isAssignableFrom((Class<?>) valueType)) { + } else if (innerValue instanceof String + && SdkBytes.class.isAssignableFrom((Class<?>) valueType)) { reTypedList.add(SdkBytes.fromUtf8String((String) innerValue)); } else { reTypedList.add(innerValue); @@ -480,9 +492,9 @@ public static <T> T plainToSdk(Map<String, Object> mapping, Class<T> type) } else { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - String.format(DynamoErrorMessages.UNKNOWN_TYPE_DURING_DESERIALIZATION_ERROR_MSG, value.getClass().getName()) - ); - + String.format( + DynamoErrorMessages.UNKNOWN_TYPE_DURING_DESERIALIZATION_ERROR_MSG, + value.getClass().getName())); } } } @@ -492,7 +504,7 @@ public static <T> T plainToSdk(Map<String, Object> mapping, Class<T> type) public static Object plainToSdk(Map<String, Object> mapping, Type type) throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, AppsmithPluginException, - IllegalAccessException { + IllegalAccessException { if (mapping == null) { return null; @@ -507,15 +519,16 @@ public static Object plainToSdk(Map<String, Object> mapping, Type type) if (Map.class.equals(ptype.getRawType())) { final Map<String, Object> convertedMap = new HashMap<>(); for (final Map.Entry<String, Object> entry : mapping.entrySet()) { - convertedMap.put(entry.getKey(), plainToSdk((Map) entry.getValue(), (Class<?>) ptype.getActualTypeArguments()[1])); + convertedMap.put(entry.getKey(), plainToSdk((Map) entry.getValue(), (Class<?>) + ptype.getActualTypeArguments()[1])); } return convertedMap; } throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - String.format(DynamoErrorMessages.UNKNOWN_TYPE_FOUND_TO_CONVERT_TO_SDK_STYLE_ERROR_MSG, type.getTypeName()) - ); + String.format( + DynamoErrorMessages.UNKNOWN_TYPE_FOUND_TO_CONVERT_TO_SDK_STYLE_ERROR_MSG, type.getTypeName())); } private static Method findMethod(Class<?> builderType, Predicate<Method> predicate) { @@ -590,5 +603,4 @@ private static boolean isUpperCase(String s) { } return true; } - } diff --git a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/exceptions/DynamoErrorMessages.java b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/exceptions/DynamoErrorMessages.java index 7be8f9a2da82..cf850e6fe763 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/exceptions/DynamoErrorMessages.java +++ b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/exceptions/DynamoErrorMessages.java @@ -6,9 +6,11 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) // To prevent instantiation public class DynamoErrorMessages extends BasePluginErrorMessages { - public static final String MISSING_ACTION_NAME_ERROR_MSG = "Missing action name (like `ListTables`, `GetItem` etc.)."; + public static final String MISSING_ACTION_NAME_ERROR_MSG = + "Missing action name (like `ListTables`, `GetItem` etc.)."; - public static final String UNKNOWN_ACTION_NAME_ERROR_MSG = "Unknown action: `%s`. Note that action names are case-sensitive."; + public static final String UNKNOWN_ACTION_NAME_ERROR_MSG = + "Unknown action: `%s`. Note that action names are case-sensitive."; public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Error occurred while executing DynamoDB query."; @@ -16,7 +18,9 @@ public class DynamoErrorMessages extends BasePluginErrorMessages { public static final String INVALID_ATTRIBUTE_ERROR_MSG = "Invalid attribute/value by name %s"; - public static final String UNKNOWN_TYPE_DURING_DESERIALIZATION_ERROR_MSG = "Unknown value type while deserializing: %s"; + public static final String UNKNOWN_TYPE_DURING_DESERIALIZATION_ERROR_MSG = + "Unknown value type while deserializing: %s"; - public static final String UNKNOWN_TYPE_FOUND_TO_CONVERT_TO_SDK_STYLE_ERROR_MSG = "Unknown type to convert to SDK style %s"; + public static final String UNKNOWN_TYPE_FOUND_TO_CONVERT_TO_SDK_STYLE_ERROR_MSG = + "Unknown type to convert to SDK style %s"; } diff --git a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/exceptions/DynamoPluginError.java b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/exceptions/DynamoPluginError.java index 4dc3c6c8db8d..c3ed29a16299 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/exceptions/DynamoPluginError.java +++ b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/exceptions/DynamoPluginError.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum DynamoPluginError implements BasePluginError { QUERY_EXECUTION_FAILED( @@ -16,8 +15,7 @@ public enum DynamoPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), UNKNOWN_ACTION_NAME( 500, "PE-DYN-5001", @@ -26,8 +24,7 @@ public enum DynamoPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; @@ -41,8 +38,15 @@ public enum DynamoPluginError implements BasePluginError { private final String downstreamErrorCode; - DynamoPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + DynamoPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -69,5 +73,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/dynamoPlugin/src/test/java/com/external/plugins/DynamoPluginTest.java b/app/server/appsmith-plugins/dynamoPlugin/src/test/java/com/external/plugins/DynamoPluginTest.java index dde30f1cfcda..ff5b428fd9cb 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/src/test/java/com/external/plugins/DynamoPluginTest.java +++ b/app/server/appsmith-plugins/dynamoPlugin/src/test/java/com/external/plugins/DynamoPluginTest.java @@ -33,11 +33,11 @@ import java.net.URI; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Arrays; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; @@ -52,23 +52,22 @@ @Testcontainers public class DynamoPluginTest { - private final static DynamoPlugin.DynamoPluginExecutor pluginExecutor = new DynamoPlugin.DynamoPluginExecutor(); + private static final DynamoPlugin.DynamoPluginExecutor pluginExecutor = new DynamoPlugin.DynamoPluginExecutor(); @SuppressWarnings("rawtypes") @Container - public static GenericContainer container = new GenericContainer(CompletableFuture.completedFuture("amazon/dynamodb-local")) - .withExposedPorts(8000); + public static GenericContainer container = + new GenericContainer(CompletableFuture.completedFuture("amazon/dynamodb-local")).withExposedPorts(8000); - private final static DatasourceConfiguration dsConfig = new DatasourceConfiguration(); + private static final DatasourceConfiguration dsConfig = new DatasourceConfiguration(); @BeforeAll public static void setUp() { final String host = "localhost"; final Integer port = container.getMappedPort(8000); - final StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create( - AwsBasicCredentials.create("dummy", "dummy") - ); + final StaticCredentialsProvider credentialsProvider = + StaticCredentialsProvider.create(AwsBasicCredentials.create("dummy", "dummy")); DynamoDbClient ddb = DynamoDbClient.builder() .region(Region.AP_SOUTH_1) @@ -78,44 +77,48 @@ public static void setUp() { ddb.createTable(CreateTableRequest.builder() .tableName("cities") - .attributeDefinitions( - AttributeDefinition.builder().attributeName("Id").attributeType(ScalarAttributeType.S).build() - ) - .keySchema( - KeySchemaElement.builder().attributeName("Id").keyType(KeyType.HASH).build() - ) - .provisionedThroughput( - ProvisionedThroughput.builder().readCapacityUnits(5L).writeCapacityUnits(5L).build() - ) + .attributeDefinitions(AttributeDefinition.builder() + .attributeName("Id") + .attributeType(ScalarAttributeType.S) + .build()) + .keySchema(KeySchemaElement.builder() + .attributeName("Id") + .keyType(KeyType.HASH) + .build()) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(5L) + .writeCapacityUnits(5L) + .build()) .build()); ddb.putItem(PutItemRequest.builder() .tableName("cities") .item(Map.of( "Id", AttributeValue.builder().s("1").build(), - "City", AttributeValue.builder().s("New Delhi").build() - )) + "City", AttributeValue.builder().s("New Delhi").build())) .build()); ddb.putItem(PutItemRequest.builder() .tableName("cities") .item(Map.of( "Id", AttributeValue.builder().s("2").build(), - "City", AttributeValue.builder().s("Bangalore").build() - )) + "City", AttributeValue.builder().s("Bangalore").build())) .build()); ddb.createTable(CreateTableRequest.builder() .tableName("allTypes") - .attributeDefinitions( - AttributeDefinition.builder().attributeName("Id").attributeType(ScalarAttributeType.N).build() - ) - .keySchema( - KeySchemaElement.builder().attributeName("Id").keyType(KeyType.HASH).build() - ) - .provisionedThroughput( - ProvisionedThroughput.builder().readCapacityUnits(5L).writeCapacityUnits(5L).build() - ) + .attributeDefinitions(AttributeDefinition.builder() + .attributeName("Id") + .attributeType(ScalarAttributeType.N) + .build()) + .keySchema(KeySchemaElement.builder() + .attributeName("Id") + .keyType(KeyType.HASH) + .build()) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(5L) + .writeCapacityUnits(5L) + .build()) .build()); String testPayload1 = "payload1"; @@ -133,12 +136,21 @@ public static void setUp() { "BooleanType", AttributeValue.builder().bool(true).build(), "BinaryType", AttributeValue.builder().b(bytesValue1).build(), "NullType", AttributeValue.builder().nul(true).build(), - "StringSetType", AttributeValue.builder().ss("str1", "str2").build(), + "StringSetType", + AttributeValue.builder().ss("str1", "str2").build(), "NumberSetType", AttributeValue.builder().ns("1", "2").build(), - "BinarySetType", AttributeValue.builder().bs(bytesValue1, bytesValue2).build(), - "MapType", AttributeValue.builder().m(Map.of("mapKey", mapValue)).build(), - "ListType", AttributeValue.builder().l(listValue1, listValue2).build() - )) + "BinarySetType", + AttributeValue.builder() + .bs(bytesValue1, bytesValue2) + .build(), + "MapType", + AttributeValue.builder() + .m(Map.of("mapKey", mapValue)) + .build(), + "ListType", + AttributeValue.builder() + .l(listValue1, listValue2) + .build())) .build()); Endpoint endpoint = new Endpoint(); @@ -175,8 +187,12 @@ public void testListTables() { expectedTables.add("allTypes"); HashSet<String> actualTables = new HashSet<>(); - actualTables.add(((Map<String, ArrayList<String>>) result.getBody()).get("TableNames").get(0)); - actualTables.add(((Map<String, ArrayList<String>>) result.getBody()).get("TableNames").get(1)); + actualTables.add(((Map<String, ArrayList<String>>) result.getBody()) + .get("TableNames") + .get(0)); + actualTables.add(((Map<String, ArrayList<String>>) result.getBody()) + .get("TableNames") + .get(1)); assertTrue(expectedTables.equals(actualTables)); }) @@ -185,16 +201,15 @@ public void testListTables() { @Test public void testDescribeTable() { - final String body = "{\n" + - " \"TableName\": \"cities\"\n" + - "}\n"; + final String body = "{\n" + " \"TableName\": \"cities\"\n" + "}\n"; StepVerifier.create(execute("DescribeTable", body)) .assertNext(result -> { assertNotNull(result); assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - final Map<String, Object> table = ((Map<String, Map<String, Object>>) result.getBody()).get("Table"); + final Map<String, Object> table = + ((Map<String, Map<String, Object>>) result.getBody()).get("Table"); assertEquals("cities", table.get("TableName")); /* @@ -204,8 +219,8 @@ public void testDescribeTable() { * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, "DescribeTable", null, - null, null)); + expectedRequestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, "DescribeTable", null, null, null)); expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, body, null, null, null)); assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) @@ -214,14 +229,13 @@ public void testDescribeTable() { @Test public void testGetItem() { - final String body = "{\n" + - " \"TableName\": \"cities\",\n" + - " \"Key\": {\n" + - " \"Id\": {\n" + - " \"S\": \"1\"\n" + - " }\n" + - " }\n" + - "}\n"; + final String body = "{\n" + " \"TableName\": \"cities\",\n" + + " \"Key\": {\n" + + " \"Id\": {\n" + + " \"S\": \"1\"\n" + + " }\n" + + " }\n" + + "}\n"; StepVerifier.create(execute("GetItem", body)) .assertNext(result -> { @@ -237,14 +251,13 @@ public void testGetItem() { @Test public void testQuery() { - final String body = "{\n" + - " \"TableName\": \"cities\", \n" + - "\t\"KeyConditionExpression\": \"Id=:v1\",\n" + - "\t\"ExpressionAttributeValues\": {\n" + - " \":v1\": {\"S\": \"1\"}\n" + - " },\n" + - " \"ReturnConsumedCapacity\": \"TOTAL\"\n" + - "}"; + final String body = "{\n" + " \"TableName\": \"cities\", \n" + + "\t\"KeyConditionExpression\": \"Id=:v1\",\n" + + "\t\"ExpressionAttributeValues\": {\n" + + " \":v1\": {\"S\": \"1\"}\n" + + " },\n" + + " \"ReturnConsumedCapacity\": \"TOTAL\"\n" + + "}"; StepVerifier.create(execute("Query", body)) .assertNext(result -> { @@ -260,17 +273,16 @@ public void testQuery() { @Test public void testPutItem() { - final String body = "{\n" + - " \"TableName\": \"cities\",\n" + - " \"Item\": {\n" + - " \"Id\": {\n" + - " \"S\": \"9\"\n" + - " },\n" + - " \"City\": {\n" + - " \"S\": \"Mumbai\"\n" + - " }\n" + - " }\n" + - "}\n"; + final String body = "{\n" + " \"TableName\": \"cities\",\n" + + " \"Item\": {\n" + + " \"Id\": {\n" + + " \"S\": \"9\"\n" + + " },\n" + + " \"City\": {\n" + + " \"S\": \"Mumbai\"\n" + + " }\n" + + " }\n" + + "}\n"; StepVerifier.create(execute("PutItem", body)) .assertNext(result -> { @@ -284,21 +296,20 @@ public void testPutItem() { @Test public void testUpdateItem() { - final String body = "{\n" + - " \"TableName\": \"cities\",\n" + - " \"Key\": {\n" + - " \"Id\": {\n" + - " \"S\": \"2\"\n" + - " }\n" + - " },\n" + - " \"UpdateExpression\": \"set City = :new_city\",\n" + - " \"ExpressionAttributeValues\": {\n" + - " \":new_city\": {\n" + - " \"S\": \"Bengaluru\"\n" + - " }\n" + - " },\n" + - " \"ReturnValues\": \"ALL_NEW\"\n" + - "}\n"; + final String body = "{\n" + " \"TableName\": \"cities\",\n" + + " \"Key\": {\n" + + " \"Id\": {\n" + + " \"S\": \"2\"\n" + + " }\n" + + " },\n" + + " \"UpdateExpression\": \"set City = :new_city\",\n" + + " \"ExpressionAttributeValues\": {\n" + + " \":new_city\": {\n" + + " \"S\": \"Bengaluru\"\n" + + " }\n" + + " },\n" + + " \"ReturnValues\": \"ALL_NEW\"\n" + + "}\n"; StepVerifier.create(execute("UpdateItem", body)) .assertNext(result -> { @@ -314,9 +325,7 @@ public void testUpdateItem() { @Test public void testScan() { - final String body = "{\n" + - " \"TableName\": \"cities\"\n" + - "}\n"; + final String body = "{\n" + " \"TableName\": \"cities\"\n" + "}\n"; StepVerifier.create(execute("Scan", body)) .assertNext(result -> { @@ -333,40 +342,37 @@ public void testScan() { @Test public void testBatchGetItem() { - final String body = "{\n" + - " \"RequestItems\": {\n" + - " \"cities\": {\n" + - " \"Keys\": [\n" + - " {\n" + - " \"Id\": {\n" + - " \"S\": \"1\"\n" + - " }\n" + - " },\n" + - " {\n" + - " \"Id\": {\n" + - " \"S\": \"2\"\n" + - " }\n" + - " }\n" + - " ],\n" + - " \"ProjectionExpression\":\"City\"\n" + - " }\n" + - " },\n" + - " \"ReturnConsumedCapacity\": \"TOTAL\"\n" + - "}"; + final String body = "{\n" + " \"RequestItems\": {\n" + + " \"cities\": {\n" + + " \"Keys\": [\n" + + " {\n" + + " \"Id\": {\n" + + " \"S\": \"1\"\n" + + " }\n" + + " },\n" + + " {\n" + + " \"Id\": {\n" + + " \"S\": \"2\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"ProjectionExpression\":\"City\"\n" + + " }\n" + + " },\n" + + " \"ReturnConsumedCapacity\": \"TOTAL\"\n" + + "}"; StepVerifier.create(execute("BatchGetItem", body)) .assertNext(result -> { assertNotNull(result); assertTrue(result.getIsExecutionSuccess()); final Map<String, ?> response = (Map) result.getBody(); - assertEquals( - Collections.emptyMap(), - response.remove("UnprocessedKeys") - ); + assertEquals(Collections.emptyMap(), response.remove("UnprocessedKeys")); // Test transformed response Map<String, Object> transformedResponse = (Map<String, Object>) response.get("Responses"); - ArrayList<Map<String, Object>> transformedCitiesList = (ArrayList<Map<String, Object>>) transformedResponse.get("cities"); + ArrayList<Map<String, Object>> transformedCitiesList = + (ArrayList<Map<String, Object>>) transformedResponse.get("cities"); assertEquals("New Delhi", transformedCitiesList.get(0).get("City")); }) .verifyComplete(); @@ -374,22 +380,20 @@ public void testBatchGetItem() { @Test public void testTransactGetItems() { - final String body = - "{\n" + - " \"ReturnConsumedCapacity\": \"NONE\",\n" + - " \"TransactItems\": [\n" + - " {\n" + - " \"Get\": {\n" + - " \"Key\": {\n" + - " \"Id\": {\n" + - " \"S\": \"1\"\n" + - " }\n" + - " },\n" + - " \"TableName\": \"cities\"\n" + - " }\n" + - " }\n" + - " ]\n" + - "}"; + final String body = "{\n" + " \"ReturnConsumedCapacity\": \"NONE\",\n" + + " \"TransactItems\": [\n" + + " {\n" + + " \"Get\": {\n" + + " \"Key\": {\n" + + " \"Id\": {\n" + + " \"S\": \"1\"\n" + + " }\n" + + " },\n" + + " \"TableName\": \"cities\"\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; StepVerifier.create(execute("TransactGetItems", body)) .assertNext(result -> { @@ -399,19 +403,19 @@ public void testTransactGetItems() { final Map<String, ?> response = (Map) result.getBody(); // Test transformed response - ArrayList<Map<String, Object>> transformedResponse = (ArrayList<Map<String, Object>>) response.get("Responses"); - assertEquals("New Delhi", + ArrayList<Map<String, Object>> transformedResponse = + (ArrayList<Map<String, Object>>) response.get("Responses"); + assertEquals( + "New Delhi", ((Map<String, Object>) transformedResponse.get(0).get("Item")).get("City")); - }) .verifyComplete(); } @Test public void testStructure() { - final Mono<DatasourceStructure> structureMono = pluginExecutor - .datasourceCreate(dsConfig) - .flatMap(conn -> pluginExecutor.getStructure(conn, dsConfig)); + final Mono<DatasourceStructure> structureMono = + pluginExecutor.datasourceCreate(dsConfig).flatMap(conn -> pluginExecutor.getStructure(conn, dsConfig)); StepVerifier.create(structureMono) .assertNext(structure -> { @@ -437,9 +441,7 @@ public void testStructure() { */ @Test public void testParsingCapabilityForAllTypes() { - final String body = "{\n" + - " \"TableName\": \"allTypes\"\n" + - "}\n"; + final String body = "{\n" + " \"TableName\": \"allTypes\"\n" + "}\n"; StepVerifier.create(execute("Scan", body)) .assertNext(result -> { @@ -453,21 +455,28 @@ public void testParsingCapabilityForAllTypes() { /* * - Check if the transformed data is correct. */ - ArrayList<Map<String, Object>> transformedItems = (ArrayList<Map<String, Object>>) resultBody.get("Items"); + ArrayList<Map<String, Object>> transformedItems = + (ArrayList<Map<String, Object>>) resultBody.get("Items"); Map<String, Object> transformedItemMap = transformedItems.get(0); assertEquals("1", transformedItemMap.get("Id")); assertEquals("str", transformedItemMap.get("StringType")); assertEquals("true", transformedItemMap.get("BooleanType").toString()); assertEquals("payload1", transformedItemMap.get("BinaryType")); assertEquals("true", transformedItemMap.get("NullType").toString()); - assertArrayEquals(new String[]{"str1", "str2"}, + assertArrayEquals( + new String[] {"str1", "str2"}, ((ArrayList<String>) transformedItemMap.get("StringSetType")).toArray()); - assertArrayEquals(new String[]{"payload1", "payload2"}, + assertArrayEquals( + new String[] {"payload1", "payload2"}, ((ArrayList<String>) transformedItemMap.get("BinarySetType")).toArray()); - assertArrayEquals(new String[]{"1", "2"}, + assertArrayEquals( + new String[] {"1", "2"}, ((ArrayList<String>) transformedItemMap.get("NumberSetType")).toArray()); - assertEquals("mapValue", - ((Map<String, Object>) transformedItemMap.get("MapType")).get("mapKey").toString()); + assertEquals( + "mapValue", + ((Map<String, Object>) transformedItemMap.get("MapType")) + .get("mapKey") + .toString()); assertEquals("listValue1", ((ArrayList<String>) transformedItemMap.get("ListType")).get(0)); assertEquals("listValue2", ((ArrayList<String>) transformedItemMap.get("ListType")).get(1)); }) @@ -505,16 +514,21 @@ public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { assertTrue(datasourceTestResult.getInvalids().isEmpty()); }) .verifyComplete(); - } @Test public void verifyUniquenessOfDynamoDBPluginErrorCode() { - assert (Arrays.stream(DynamoPluginError.values()).map(DynamoPluginError::getAppErrorCode).distinct().count() == DynamoPluginError.values().length); - - assert (Arrays.stream(DynamoPluginError.values()).map(DynamoPluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-DYN")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(DynamoPluginError.values()) + .map(DynamoPluginError::getAppErrorCode) + .distinct() + .count() + == DynamoPluginError.values().length); + + assert (Arrays.stream(DynamoPluginError.values()) + .map(DynamoPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-DYN")) + .collect(Collectors.toList()) + .size() + == 0); } } diff --git a/app/server/appsmith-plugins/dynamoPlugin/src/test/java/com/external/plugins/PlainToSdkTests.java b/app/server/appsmith-plugins/dynamoPlugin/src/test/java/com/external/plugins/PlainToSdkTests.java index 5e77ed93ff85..1830054ccc89 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/src/test/java/com/external/plugins/PlainToSdkTests.java +++ b/app/server/appsmith-plugins/dynamoPlugin/src/test/java/com/external/plugins/PlainToSdkTests.java @@ -19,10 +19,7 @@ public class PlainToSdkTests { @Test public void testListTablesNull() throws Exception { - final ListTablesRequest request = plainToSdk( - null, - ListTablesRequest.class - ); + final ListTablesRequest request = plainToSdk(null, ListTablesRequest.class); assertNotNull(request); assertNull(request.exclusiveStartTableName()); @@ -31,13 +28,8 @@ public void testListTablesNull() throws Exception { @Test public void testListTables() throws Exception { - final ListTablesRequest request = plainToSdk( - Map.of( - "ExclusiveStartTableName", "table_name", - "Limit", 1 - ), - ListTablesRequest.class - ); + final ListTablesRequest request = + plainToSdk(Map.of("ExclusiveStartTableName", "table_name", "Limit", 1), ListTablesRequest.class); assertNotNull(request); assertEquals("table_name", request.exclusiveStartTableName()); @@ -48,37 +40,41 @@ public void testListTables() throws Exception { public void testPutItem() throws Exception { final PutItemRequest request = plainToSdk( Map.of( - "ConditionalOperator", "conditional operator value", - "ConditionExpression", "conditional expression value", - "ExpressionAttributeNames", Map.of( - "#P", "Percentile" - ), - "ExpressionAttributeValues", Map.of( + "ConditionalOperator", + "conditional operator value", + "ConditionExpression", + "conditional expression value", + "ExpressionAttributeNames", + Map.of("#P", "Percentile"), + "ExpressionAttributeValues", + Map.of( ":token1", Map.of("S", "value1"), - ":token2", Map.of("N", "42") - ), - "Item", Map.of( + ":token2", Map.of("N", "42")), + "Item", + Map.of( "one", Map.of("B", "binary blob as a string"), "two", Map.of("BOOL", true), "three", Map.of("BS", List.of("binary blob 1", "binary blob 2")), - "four", Map.of("L", List.of( - Map.of("S", "string in list 1"), - Map.of("S", "string in list 2"), - Map.of("S", "string in list 3") - )), - "five", Map.of("M", Map.of( - "key1", "val1", - "key2", "val2" - )), + "four", + Map.of( + "L", + List.of( + Map.of("S", "string in list 1"), + Map.of("S", "string in list 2"), + Map.of("S", "string in list 3"))), + "five", + Map.of( + "M", + Map.of( + "key1", "val1", + "key2", "val2")), "six", Map.of("N", "1234"), "seven", Map.of("NS", List.of("12", "34", "56")), "eight", Map.of("NULL", true), - "nine", Map.of("S", "string value") - ), - "TableName", "table_name" - ), - PutItemRequest.class - ); + "nine", Map.of("S", "string value")), + "TableName", + "table_name"), + PutItemRequest.class); assertNotNull(request); assertEquals("conditional operator value", request.conditionalOperatorAsString()); @@ -93,37 +89,37 @@ public void testGetItem() throws Exception { Map.of( "AttributesToGet", List.of("one", "two", "three"), "ConsistentRead", true, - "ExpressionAttributeNames", Map.of( - "#P", "Percentile" - ), - "Key", Map.of( - "one", Map.of("B", "binary blob as a string"), - "two", Map.of("BOOL", true), - "three", Map.of("BS", List.of("binary blob 1", "binary blob 2")), - "four", Map.of("L", List.of( - Map.of("S", "string in list 1"), - Map.of("S", "string in list 2"), - Map.of("S", "string in list 3") - )), - "five", Map.of("M", Map.of( - "key1", "val1", - "key2", "val2" - )), - "six", Map.of("N", "1234"), - "seven", Map.of("NS", List.of("12", "34", "56")), - "eight", Map.of("NULL", true), - "nine", Map.of("S", "string value") - ), - "TableName", "table_name" - ), - GetItemRequest.class - ); + "ExpressionAttributeNames", Map.of("#P", "Percentile"), + "Key", + Map.of( + "one", Map.of("B", "binary blob as a string"), + "two", Map.of("BOOL", true), + "three", Map.of("BS", List.of("binary blob 1", "binary blob 2")), + "four", + Map.of( + "L", + List.of( + Map.of("S", "string in list 1"), + Map.of("S", "string in list 2"), + Map.of("S", "string in list 3"))), + "five", + Map.of( + "M", + Map.of( + "key1", "val1", + "key2", "val2")), + "six", Map.of("N", "1234"), + "seven", Map.of("NS", List.of("12", "34", "56")), + "eight", Map.of("NULL", true), + "nine", Map.of("S", "string value")), + "TableName", "table_name"), + GetItemRequest.class); assertNotNull(request); - assertArrayEquals(new String[]{"one", "two", "three"}, request.attributesToGet().toArray()); + assertArrayEquals( + new String[] {"one", "two", "three"}, request.attributesToGet().toArray()); assertTrue(request.consistentRead()); assertEquals(9, request.key().size()); assertEquals("table_name", request.tableName()); } - } diff --git a/app/server/appsmith-plugins/elasticSearchPlugin/pom.xml b/app/server/appsmith-plugins/elasticSearchPlugin/pom.xml index ad3481f3f06a..b3a787632587 100644 --- a/app/server/appsmith-plugins/elasticSearchPlugin/pom.xml +++ b/app/server/appsmith-plugins/elasticSearchPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>elasticSearchPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -54,10 +53,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java index 0976e7865eac..c9f9dcabba64 100644 --- a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java +++ b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java @@ -66,20 +66,17 @@ public static class ElasticSearchPluginExecutor implements PluginExecutor<RestCl private final Scheduler scheduler = Schedulers.boundedElastic(); - private static final Pattern patternForUnauthorized = Pattern.compile( - ".*unauthorized.*", - Pattern.CASE_INSENSITIVE - ); + private static final Pattern patternForUnauthorized = + Pattern.compile(".*unauthorized.*", Pattern.CASE_INSENSITIVE); - private static final Pattern patternForNotFound = Pattern.compile( - ".*not.?found|refused|not.?known|timed?\\s?out.*", - Pattern.CASE_INSENSITIVE - ); + private static final Pattern patternForNotFound = + Pattern.compile(".*not.?found|refused|not.?known|timed?\\s?out.*", Pattern.CASE_INSENSITIVE); @Override - public Mono<ActionExecutionResult> execute(RestClient client, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + RestClient client, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final Map<String, Object> requestData = new HashMap<>(); @@ -96,8 +93,8 @@ public Mono<ActionExecutionResult> execute(RestClient client, HttpMethod httpMethod = actionConfiguration.getHttpMethod(); requestData.put("method", httpMethod.name()); - requestParams.add(new RequestParamDTO("actionConfiguration.httpMethod", httpMethod.name(), null, - null, null)); + requestParams.add(new RequestParamDTO( + "actionConfiguration.httpMethod", httpMethod.name(), null, null, null)); requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null)); @@ -113,12 +110,17 @@ public Mono<ActionExecutionResult> execute(RestClient client, try { List<Object> commands = objectMapper.readValue(body, ArrayList.class); for (Object object : commands) { - ndJsonBuilder.append(objectMapper.writeValueAsString(object)).append("\n"); + ndJsonBuilder + .append(objectMapper.writeValueAsString(object)) + .append("\n"); } } catch (IOException e) { final String message = "Error converting array to ND-JSON: " + e.getMessage(); log.warn(message, e); - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ElasticSearchErrorMessages.ARRAY_TO_ND_JSON_ARRAY_CONVERSION_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ElasticSearchErrorMessages.ARRAY_TO_ND_JSON_ARRAY_CONVERSION_ERROR_MSG, + e.getMessage())); } body = ndJsonBuilder.toString(); } @@ -129,13 +131,18 @@ public Mono<ActionExecutionResult> execute(RestClient client, } try { - final String responseBody = new String( - client.performRequest(request).getEntity().getContent().readAllBytes()); + final String responseBody = new String(client.performRequest(request) + .getEntity() + .getContent() + .readAllBytes()); result.setBody(objectMapper.readValue(responseBody, HashMap.class)); } catch (IOException e) { final String message = "Error performing request: " + e.getMessage(); log.warn(message, e); - return Mono.error(new AppsmithPluginException(ElasticSearchPluginError.QUERY_EXECUTION_FAILED, ElasticSearchErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + ElasticSearchPluginError.QUERY_EXECUTION_FAILED, + ElasticSearchErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage())); } result.setIsExecutionSuccess(true); @@ -147,8 +154,11 @@ public Mono<ActionExecutionResult> execute(RestClient client, .onErrorResume(error -> { ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(ElasticSearchPluginError.QUERY_EXECUTION_FAILED, ElasticSearchErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error); + if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + ElasticSearchPluginError.QUERY_EXECUTION_FAILED, + ElasticSearchErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error); } result.setErrorInfo(error); return Mono.just(result); @@ -188,7 +198,8 @@ public Mono<RestClient> datasourceCreate(DatasourceConfiguration datasourceConfi try { url = new URL(endpoint.getHost()); } catch (MalformedURLException e) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, ElasticSearchErrorMessages.DS_INVALID_HOST_ERROR_MSG)); } String scheme = "http"; @@ -199,7 +210,7 @@ public Mono<RestClient> datasourceCreate(DatasourceConfiguration datasourceConfi hosts.add(new HttpHost(url.getHost(), getPort(endpoint).intValue(), scheme)); } - final RestClientBuilder clientBuilder = RestClient.builder(hosts.toArray(new HttpHost[]{})); + final RestClientBuilder clientBuilder = RestClient.builder(hosts.toArray(new HttpHost[] {})); final DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); if (authentication != null @@ -208,27 +219,19 @@ public Mono<RestClient> datasourceCreate(DatasourceConfiguration datasourceConfi final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( AuthScope.ANY, - new UsernamePasswordCredentials(authentication.getUsername(), authentication.getPassword()) - ); - - clientBuilder - .setHttpClientConfigCallback( - httpClientBuilder -> httpClientBuilder - .setDefaultCredentialsProvider(credentialsProvider) - ); + new UsernamePasswordCredentials(authentication.getUsername(), authentication.getPassword())); + + clientBuilder.setHttpClientConfigCallback( + httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)); } if (!CollectionUtils.isEmpty(datasourceConfiguration.getHeaders())) { - clientBuilder.setDefaultHeaders( - (Header[]) datasourceConfiguration.getHeaders() - .stream() - .map(h -> new BasicHeader(h.getKey(), (String) h.getValue())) - .toArray() - ); + clientBuilder.setDefaultHeaders((Header[]) datasourceConfiguration.getHeaders().stream() + .map(h -> new BasicHeader(h.getKey(), (String) h.getValue())) + .toArray()); } - return Mono.fromCallable(clientBuilder::build) - .subscribeOn(scheduler); + return Mono.fromCallable(clientBuilder::build).subscribeOn(scheduler); } @Override @@ -258,9 +261,7 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur invalids.add(ElasticSearchErrorMessages.DS_INVALID_HOST_ERROR_MSG); } } - } - } return invalids; @@ -272,7 +273,8 @@ public Mono<DatasourceTestResult> testDatasource(RestClient connection) { if (connection == null) { return new DatasourceTestResult("Null client object to ElasticSearch."); } - // This HEAD request is to check if the base of datasource exists. It responds with 200 if the index exists, + // This HEAD request is to check if the base of datasource exists. It responds with 200 if the index + // exists, // 404 if it doesn't. We just check for either of these two. // Ref: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-exists.html Request request = new Request("HEAD", "/"); @@ -307,8 +309,7 @@ public Mono<DatasourceTestResult> testDatasource(RestClient connection) { } if (statusLine.getStatusCode() != 200) { - return new DatasourceTestResult( - "Unexpected response from ElasticSearch: " + statusLine); + return new DatasourceTestResult("Unexpected response from ElasticSearch: " + statusLine); } return new DatasourceTestResult(); diff --git a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/exceptions/ElasticSearchErrorMessages.java b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/exceptions/ElasticSearchErrorMessages.java index a15923a69aed..e9e3c6ffc28b 100644 --- a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/exceptions/ElasticSearchErrorMessages.java +++ b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/exceptions/ElasticSearchErrorMessages.java @@ -6,23 +6,27 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) // To prevent instantiation public class ElasticSearchErrorMessages extends BasePluginErrorMessages { - public static final String ARRAY_TO_ND_JSON_ARRAY_CONVERSION_ERROR_MSG = "Error occurred while converting array to ND-JSON"; + public static final String ARRAY_TO_ND_JSON_ARRAY_CONVERSION_ERROR_MSG = + "Error occurred while converting array to ND-JSON"; public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Error occurred while executing Elasticsearch query."; - public static final String NOT_FOUND_ERROR_MSG = "Either your host URL is invalid or the page you are trying to access does not exist"; + public static final String NOT_FOUND_ERROR_MSG = + "Either your host URL is invalid or the page you are trying to access does not exist"; public static final String UNAUTHORIZED_ERROR_MSG = "Your username or password is not correct"; - /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ + /* + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ - public static final String DS_INVALID_HOST_ERROR_MSG = "Invalid host provided. It should be of the form http(s)://your-es-url.com"; + public static final String DS_INVALID_HOST_ERROR_MSG = + "Invalid host provided. It should be of the form http(s)://your-es-url.com"; - public static final String DS_NO_ENDPOINT_ERROR_MSG = "No endpoint provided. Please provide a host:port where ElasticSearch is reachable."; + public static final String DS_NO_ENDPOINT_ERROR_MSG = + "No endpoint provided. Please provide a host:port where ElasticSearch is reachable."; public static final String DS_MISSING_HOST_ERROR_MSG = "Missing host for endpoint"; } diff --git a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/exceptions/ElasticSearchPluginError.java b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/exceptions/ElasticSearchPluginError.java index a6c189c9b993..187dbc77787a 100644 --- a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/exceptions/ElasticSearchPluginError.java +++ b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/exceptions/ElasticSearchPluginError.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum ElasticSearchPluginError implements BasePluginError { QUERY_EXECUTION_FAILED( @@ -16,9 +15,7 @@ public enum ElasticSearchPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ) - ; + "{2}"); private final Integer httpErrorCode; private final String appErrorCode; @@ -31,8 +28,15 @@ public enum ElasticSearchPluginError implements BasePluginError { private final String downstreamErrorCode; - ElasticSearchPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + ElasticSearchPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -59,5 +63,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.java b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.java index 6a0121ccb180..13c8a348fe37 100644 --- a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.java +++ b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.java @@ -222,8 +222,7 @@ public final HttpAsyncClientBuilder setPublicSuffixMatcher(final PublicSuffixMat /** * Assigns {@link NHttpClientConnectionManager} instance. */ - public final HttpAsyncClientBuilder setConnectionManager( - final NHttpClientConnectionManager connManager) { + public final HttpAsyncClientBuilder setConnectionManager(final NHttpClientConnectionManager connManager) { this.connManager = connManager; return this; } @@ -241,8 +240,7 @@ public final HttpAsyncClientBuilder setConnectionManager( * * @since 4.1 */ - public final HttpAsyncClientBuilder setConnectionManagerShared( - final boolean shared) { + public final HttpAsyncClientBuilder setConnectionManagerShared(final boolean shared) { this.connManagerShared = shared; return this; } @@ -250,8 +248,7 @@ public final HttpAsyncClientBuilder setConnectionManagerShared( /** * Assigns {@link SchemePortResolver} instance. */ - public final HttpAsyncClientBuilder setSchemePortResolver( - final SchemePortResolver schemePortResolver) { + public final HttpAsyncClientBuilder setSchemePortResolver(final SchemePortResolver schemePortResolver) { this.schemePortResolver = schemePortResolver; return this; } @@ -286,7 +283,8 @@ public final HttpAsyncClientBuilder setMaxConnPerRoute(final int maxConnPerRoute * * @since 4.1 */ - public final HttpAsyncClientBuilder setConnectionTimeToLive(final long connTimeToLive, final TimeUnit connTimeToLiveTimeUnit) { + public final HttpAsyncClientBuilder setConnectionTimeToLive( + final long connTimeToLive, final TimeUnit connTimeToLiveTimeUnit) { this.connTimeToLive = connTimeToLive; this.connTimeToLiveTimeUnit = connTimeToLiveTimeUnit; return this; @@ -295,8 +293,7 @@ public final HttpAsyncClientBuilder setConnectionTimeToLive(final long connTimeT /** * Assigns {@link ConnectionReuseStrategy} instance. */ - public final HttpAsyncClientBuilder setConnectionReuseStrategy( - final ConnectionReuseStrategy reuseStrategy) { + public final HttpAsyncClientBuilder setConnectionReuseStrategy(final ConnectionReuseStrategy reuseStrategy) { this.reuseStrategy = reuseStrategy; return this; } @@ -304,8 +301,7 @@ public final HttpAsyncClientBuilder setConnectionReuseStrategy( /** * Assigns {@link ConnectionKeepAliveStrategy} instance. */ - public final HttpAsyncClientBuilder setKeepAliveStrategy( - final ConnectionKeepAliveStrategy keepAliveStrategy) { + public final HttpAsyncClientBuilder setKeepAliveStrategy(final ConnectionKeepAliveStrategy keepAliveStrategy) { this.keepAliveStrategy = keepAliveStrategy; return this; } @@ -335,8 +331,7 @@ public final HttpAsyncClientBuilder setTargetAuthenticationStrategy( * Assigns {@link AuthenticationStrategy} instance for target * host authentication. */ - public final HttpAsyncClientBuilder setProxyAuthenticationStrategy( - final AuthenticationStrategy proxyAuthStrategy) { + public final HttpAsyncClientBuilder setProxyAuthenticationStrategy(final AuthenticationStrategy proxyAuthStrategy) { this.proxyAuthStrategy = proxyAuthStrategy; return this; } @@ -447,13 +442,11 @@ public final HttpAsyncClientBuilder setDefaultCookieStore(final CookieStore cook * for request execution if not explicitly set in the client execution * context. */ - public final HttpAsyncClientBuilder setDefaultCredentialsProvider( - final CredentialsProvider credentialsProvider) { + public final HttpAsyncClientBuilder setDefaultCredentialsProvider(final CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } - /** * Assigns default {@link org.apache.http.auth.AuthScheme} registry which will * be used for request execution if not explicitly set in the client execution @@ -690,10 +683,10 @@ public CloseableHttpAsyncClient build() { sslcontext = SSLContexts.createDefault(); } } - final String[] supportedProtocols = systemProperties ? split( - System.getProperty("https.protocols")) : null; - final String[] supportedCipherSuites = systemProperties ? split( - System.getProperty("https.cipherSuites")) : null; + final String[] supportedProtocols = + systemProperties ? split(System.getProperty("https.protocols")) : null; + final String[] supportedCipherSuites = + systemProperties ? split(System.getProperty("https.cipherSuites")) : null; HostnameVerifier hostnameVerifier = this.hostnameVerifier; if (hostnameVerifier == null) { hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher); @@ -783,19 +776,18 @@ public CloseableHttpAsyncClient build() { } if (userAgent == null) { userAgent = VersionInfo.getUserAgent( - "Apache-HttpAsyncClient", - "org.apache.http.nio.client", getClass()); + "Apache-HttpAsyncClient", "org.apache.http.nio.client", getClass()); } } final HttpProcessorBuilder b = HttpProcessorBuilder.create(); if (requestFirst != null) { - for (final HttpRequestInterceptor i: requestFirst) { + for (final HttpRequestInterceptor i : requestFirst) { b.addFirst(i); } } if (responseFirst != null) { - for (final HttpResponseInterceptor i: responseFirst) { + for (final HttpResponseInterceptor i : responseFirst) { b.addFirst(i); } } @@ -816,12 +808,12 @@ public CloseableHttpAsyncClient build() { b.add(new ResponseProcessCookies()); } if (requestLast != null) { - for (final HttpRequestInterceptor i: requestLast) { + for (final HttpRequestInterceptor i : requestLast) { b.addLast(i); } } if (responseLast != null) { - for (final HttpResponseInterceptor i: responseLast) { + for (final HttpResponseInterceptor i : responseLast) { b.addLast(i); } } @@ -833,8 +825,7 @@ public CloseableHttpAsyncClient build() { if (proxy != null) { routePlanner = new DefaultProxyRoutePlanner(proxy, schemePortResolver); } else if (systemProperties) { - routePlanner = new SystemDefaultRoutePlanner( - schemePortResolver, ProxySelector.getDefault()); + routePlanner = new SystemDefaultRoutePlanner(schemePortResolver, ProxySelector.getDefault()); } else { routePlanner = new DefaultRoutePlanner(schemePortResolver); } @@ -891,12 +882,7 @@ public CloseableHttpAsyncClient build() { } final MainClientExec exec = new MainClientExec( - httpprocessor, - routePlanner, - redirectStrategy, - targetAuthStrategy, - proxyAuthStrategy, - userTokenHandler); + httpprocessor, routePlanner, redirectStrategy, targetAuthStrategy, proxyAuthStrategy, userTokenHandler); ThreadFactory threadFactory = null; NHttpClientEventHandler eventHandler = null; @@ -923,5 +909,4 @@ public CloseableHttpAsyncClient build() { defaultCredentialsProvider, defaultRequestConfig); } - } diff --git a/app/server/appsmith-plugins/elasticSearchPlugin/src/test/java/com/external/plugins/ElasticSearchPluginTest.java b/app/server/appsmith-plugins/elasticSearchPlugin/src/test/java/com/external/plugins/ElasticSearchPluginTest.java index bc5e2b74bc57..d0cbba2e574e 100755 --- a/app/server/appsmith-plugins/elasticSearchPlugin/src/test/java/com/external/plugins/ElasticSearchPluginTest.java +++ b/app/server/appsmith-plugins/elasticSearchPlugin/src/test/java/com/external/plugins/ElasticSearchPluginTest.java @@ -43,40 +43,39 @@ @Slf4j @Testcontainers public class ElasticSearchPluginTest { - ElasticSearchPlugin.ElasticSearchPluginExecutor pluginExecutor = new ElasticSearchPlugin.ElasticSearchPluginExecutor(); + ElasticSearchPlugin.ElasticSearchPluginExecutor pluginExecutor = + new ElasticSearchPlugin.ElasticSearchPluginExecutor(); @Container - public static final ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:7.12.1") + public static final ElasticsearchContainer container = new ElasticsearchContainer( + "docker.elastic.co/elasticsearch/elasticsearch:7.12.1") .withEnv("discovery.type", "single-node") .withPassword("esPassword"); + private static String username = "elastic"; private static String password = "esPassword"; private static final DatasourceConfiguration dsConfig = new DatasourceConfiguration(); - private static DBAuth elasticInstanceCredentials = new DBAuth(DBAuth.Type.USERNAME_PASSWORD, username, password, null); + private static DBAuth elasticInstanceCredentials = + new DBAuth(DBAuth.Type.USERNAME_PASSWORD, username, password, null); private static String host; private static Integer port; - @BeforeAll public static void setUp() throws IOException { port = container.getMappedPort(9200); host = "http://" + container.getContainerIpAddress(); - final CredentialsProvider credentialsProvider = - new BasicCredentialsProvider(); - credentialsProvider.setCredentials(AuthScope.ANY, - new UsernamePasswordCredentials(username, password)); + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); - RestClient client = RestClient.builder( - new HttpHost(container.getContainerIpAddress(), port, "http")) + RestClient client = RestClient.builder(new HttpHost(container.getContainerIpAddress(), port, "http")) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override - public HttpAsyncClientBuilder customizeHttpClient( - HttpAsyncClientBuilder httpClientBuilder) { - return httpClientBuilder - .setDefaultCredentialsProvider(credentialsProvider); + public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { + return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } - }).build(); + }) + .build(); Request request; @@ -119,7 +118,7 @@ public void testDefaultPort() { Long defaultPort = pluginExecutor.getPort(endpoint); - assertEquals(9200L,defaultPort); + assertEquals(9200L, defaultPort); } @Test @@ -137,18 +136,17 @@ public void testGet() { @Test public void testMultiGet() { - final String contentJson = "{\n" + - " \"docs\": [\n" + - " {\n" + - " \"_index\": \"planets\",\n" + - " \"_id\": \"id1\"\n" + - " },\n" + - " {\n" + - " \"_index\": \"planets\",\n" + - " \"_id\": \"id2\"\n" + - " }\n" + - " ]\n" + - "}"; + final String contentJson = "{\n" + " \"docs\": [\n" + + " {\n" + + " \"_index\": \"planets\",\n" + + " \"_id\": \"id1\"\n" + + " },\n" + + " {\n" + + " \"_index\": \"planets\",\n" + + " \"_id\": \"id2\"\n" + + " }\n" + + " ]\n" + + "}"; StepVerifier.create(execute(HttpMethod.GET, "/planets/_mget", contentJson)) .assertNext(result -> { assertNotNull(result); @@ -165,10 +163,12 @@ public void testMultiGet() { * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO("actionConfiguration.httpMethod", HttpMethod.GET.toString(), - null, null, null)); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, "/planets/_mget", null, null, null)); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, contentJson, null, null, null)); + expectedRequestParams.add(new RequestParamDTO( + "actionConfiguration.httpMethod", HttpMethod.GET.toString(), null, null, null)); + expectedRequestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_PATH, "/planets/_mget", null, null, null)); + expectedRequestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_BODY, contentJson, null, null, null)); assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -220,15 +220,15 @@ public void testDelete() { @Test public void testBulkWithArrayBody() { - final String contentJson = "[\n" + - " { \"index\" : { \"_index\" : \"test1\", \"_type\": \"doc\", \"_id\" : \"1\" } },\n" + - " { \"field1\" : \"value1\" },\n" + - " { \"delete\" : { \"_index\" : \"test1\", \"_type\": \"doc\", \"_id\" : \"2\" } },\n" + - " { \"create\" : { \"_index\" : \"test1\", \"_type\": \"doc\", \"_id\" : \"3\" } },\n" + - " { \"field1\" : \"value3\" },\n" + - " { \"update\" : {\"_id\" : \"1\", \"_type\": \"doc\", \"_index\" : \"test1\"} },\n" + - " { \"doc\" : {\"field2\" : \"value2\"} }\n" + - "]"; + final String contentJson = + "[\n" + " { \"index\" : { \"_index\" : \"test1\", \"_type\": \"doc\", \"_id\" : \"1\" } },\n" + + " { \"field1\" : \"value1\" },\n" + + " { \"delete\" : { \"_index\" : \"test1\", \"_type\": \"doc\", \"_id\" : \"2\" } },\n" + + " { \"create\" : { \"_index\" : \"test1\", \"_type\": \"doc\", \"_id\" : \"3\" } },\n" + + " { \"field1\" : \"value3\" },\n" + + " { \"update\" : {\"_id\" : \"1\", \"_type\": \"doc\", \"_index\" : \"test1\"} },\n" + + " { \"doc\" : {\"field2\" : \"value2\"} }\n" + + "]"; StepVerifier.create(execute(HttpMethod.POST, "/_bulk", contentJson)) .assertNext(result -> { @@ -244,14 +244,13 @@ public void testBulkWithArrayBody() { @Test public void testBulkWithDirectBody() { - final String contentJson = - "{ \"index\" : { \"_index\" : \"test2\", \"_type\": \"doc\", \"_id\" : \"1\" } }\n" + - "{ \"field1\" : \"value1\" }\n" + - "{ \"delete\" : { \"_index\" : \"test2\", \"_type\": \"doc\", \"_id\" : \"2\" } }\n" + - "{ \"create\" : { \"_index\" : \"test2\", \"_type\": \"doc\", \"_id\" : \"3\" } }\n" + - "{ \"field1\" : \"value3\" }\n" + - "{ \"update\" : {\"_id\" : \"1\", \"_type\": \"doc\", \"_index\" : \"test2\"} }\n" + - "{ \"doc\" : {\"field2\" : \"value2\"} }\n"; + final String contentJson = "{ \"index\" : { \"_index\" : \"test2\", \"_type\": \"doc\", \"_id\" : \"1\" } }\n" + + "{ \"field1\" : \"value1\" }\n" + + "{ \"delete\" : { \"_index\" : \"test2\", \"_type\": \"doc\", \"_id\" : \"2\" } }\n" + + "{ \"create\" : { \"_index\" : \"test2\", \"_type\": \"doc\", \"_id\" : \"3\" } }\n" + + "{ \"field1\" : \"value3\" }\n" + + "{ \"update\" : {\"_id\" : \"1\", \"_type\": \"doc\", \"_index\" : \"test2\"} }\n" + + "{ \"doc\" : {\"field2\" : \"value2\"} }\n"; StepVerifier.create(execute(HttpMethod.POST, "/_bulk", contentJson)) .assertNext(result -> { @@ -270,7 +269,8 @@ public void itShouldValidateDatasourceWithNoEndpoints() { DatasourceConfiguration invalidDatasourceConfiguration = new DatasourceConfiguration(); invalidDatasourceConfiguration.setAuthentication(elasticInstanceCredentials); - assertEquals(Set.of("No endpoint provided. Please provide a host:port where ElasticSearch is reachable."), + assertEquals( + Set.of("No endpoint provided. Please provide a host:port where ElasticSearch is reachable."), pluginExecutor.validateDatasource(invalidDatasourceConfiguration)); } @@ -282,8 +282,7 @@ public void itShouldValidateDatasourceWithEmptyPort() { endpoint.setHost(host); datasourceConfiguration.setEndpoints(Collections.singletonList(endpoint)); - assertEquals(Set.of(), - pluginExecutor.validateDatasource(datasourceConfiguration)); + assertEquals(Set.of(), pluginExecutor.validateDatasource(datasourceConfiguration)); } @Test @@ -294,8 +293,7 @@ public void itShouldValidateDatasourceWithEmptyHost() { endpoint.setPort(Long.valueOf(port)); datasourceConfiguration.setEndpoints(Collections.singletonList(endpoint)); - assertEquals(Set.of("Missing host for endpoint"), - pluginExecutor.validateDatasource(datasourceConfiguration)); + assertEquals(Set.of("Missing host for endpoint"), pluginExecutor.validateDatasource(datasourceConfiguration)); } @Test @@ -305,8 +303,7 @@ public void itShouldValidateDatasourceWithMissingEndpoint() { Endpoint endpoint = new Endpoint(); datasourceConfiguration.setEndpoints(Collections.singletonList(endpoint)); - assertEquals(Set.of("Missing host for endpoint"), - pluginExecutor.validateDatasource(datasourceConfiguration)); + assertEquals(Set.of("Missing host for endpoint"), pluginExecutor.validateDatasource(datasourceConfiguration)); } @Test @@ -318,9 +315,9 @@ public void itShouldValidateDatasourceWithEndpointNoProtocol() { endpoint.setPort(Long.valueOf(port)); datasourceConfiguration.setEndpoints(Collections.singletonList(endpoint)); - assertEquals(Set.of("Invalid host provided. It should be of the form http(s)://your-es-url.com"), - pluginExecutor.validateDatasource(datasourceConfiguration) - ); + assertEquals( + Set.of("Invalid host provided. It should be of the form http(s)://your-es-url.com"), + pluginExecutor.validateDatasource(datasourceConfiguration)); } @Test @@ -356,17 +353,14 @@ public void shouldVerifyUnauthorized() { Endpoint endpoint = new Endpoint(secureHostEndpoint, Long.valueOf(secureHostPort)); datasourceConfiguration.setEndpoints(Collections.singletonList(endpoint)); - - StepVerifier.create(pluginExecutor.testDatasource(datasourceConfiguration) - .map(result -> { + StepVerifier.create( + pluginExecutor.testDatasource(datasourceConfiguration).map(result -> { return (Set<String>) result.getInvalids(); })) .expectNext(Set.of("Your username or password is not correct")) .verifyComplete(); - } - @Test public void shouldVerifyNotFound() { final Integer secureHostPort = container.getMappedPort(9200); @@ -375,13 +369,13 @@ public void shouldVerifyNotFound() { Endpoint endpoint = new Endpoint(secureHostEndpoint, Long.valueOf(secureHostPort)); datasourceConfiguration.setEndpoints(Collections.singletonList(endpoint)); - StepVerifier.create(pluginExecutor.testDatasource(datasourceConfiguration) - .map(result -> { + StepVerifier.create( + pluginExecutor.testDatasource(datasourceConfiguration).map(result -> { return (Set<String>) result.getInvalids(); })) - .expectNext(Set.of("Either your host URL is invalid or the page you are trying to access does not exist")) + .expectNext( + Set.of("Either your host URL is invalid or the page you are trying to access does not exist")) .verifyComplete(); - } @Test @@ -396,7 +390,8 @@ public void itShouldDenyTestDatasourceWithInstanceMetadataAws() { StepVerifier.create(pluginExecutor.testDatasource(datasourceConfiguration)) .assertNext(result -> { assertFalse(result.getInvalids().isEmpty()); - assertTrue(result.getInvalids().contains("Error running HEAD request: Host 169.254.169.254 is not allowed")); + assertTrue(result.getInvalids() + .contains("Error running HEAD request: Host 169.254.169.254 is not allowed")); }) .verifyComplete(); } @@ -413,7 +408,8 @@ public void itShouldDenyTestDatasourceWithInstanceMetadataAwsWithDnsResolution() StepVerifier.create(pluginExecutor.testDatasource(datasourceConfiguration)) .assertNext(result -> { assertFalse(result.getInvalids().isEmpty()); - assertTrue(result.getInvalids().contains("Error running HEAD request: Host 169.254.169.254.nip.io is not allowed")); + assertTrue(result.getInvalids() + .contains("Error running HEAD request: Host 169.254.169.254.nip.io is not allowed")); }) .verifyComplete(); } @@ -430,7 +426,8 @@ public void itShouldDenyTestDatasourceWithInstanceMetadataGcp() { StepVerifier.create(pluginExecutor.testDatasource(datasourceConfiguration)) .assertNext(result -> { assertFalse(result.getInvalids().isEmpty()); - assertTrue(result.getInvalids().contains("Error running HEAD request: Host metadata.google.internal is not allowed")); + assertTrue(result.getInvalids() + .contains("Error running HEAD request: Host metadata.google.internal is not allowed")); }) .verifyComplete(); } @@ -455,7 +452,9 @@ public void itShouldRejectGetToMetadataAws() { StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); - assertEquals("Host 169.254.169.254 is not allowed", result.getPluginErrorDetails().getDownstreamErrorMessage()); + assertEquals( + "Host 169.254.169.254 is not allowed", + result.getPluginErrorDetails().getDownstreamErrorMessage()); }) .verifyComplete(); } @@ -480,7 +479,9 @@ public void itShouldRejectGetToMetadataAwsWithDnsResolution() { StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); - assertEquals("Host 169.254.169.254.nip.io is not allowed", result.getPluginErrorDetails().getDownstreamErrorMessage()); + assertEquals( + "Host 169.254.169.254.nip.io is not allowed", + result.getPluginErrorDetails().getDownstreamErrorMessage()); }) .verifyComplete(); } @@ -512,7 +513,9 @@ public void itShouldRejectGetToMetadataAwsWithDnsResolutionAndRedirect() throws StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); - assertEquals("Host 169.254.169.254.nip.io is not allowed", result.getPluginErrorDetails().getDownstreamErrorMessage()); + assertEquals( + "Host 169.254.169.254.nip.io is not allowed", + result.getPluginErrorDetails().getDownstreamErrorMessage()); }) .verifyComplete(); } @@ -537,7 +540,9 @@ public void itShouldRejectGetToMetadataGcp() { StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); - assertEquals("Host metadata.google.internal is not allowed", result.getPluginErrorDetails().getDownstreamErrorMessage()); + assertEquals( + "Host metadata.google.internal is not allowed", + result.getPluginErrorDetails().getDownstreamErrorMessage()); }) .verifyComplete(); } @@ -545,9 +550,8 @@ public void itShouldRejectGetToMetadataGcp() { @Test public void itShouldRejectGetToMetadataGcpAndRedirect() throws IOException { MockWebServer mockWebServer = new MockWebServer(); - MockResponse mockRedirectResponse = new MockResponse() - .setResponseCode(301) - .addHeader("Location", "http://metadata.google.internal"); + MockResponse mockRedirectResponse = + new MockResponse().setResponseCode(301).addHeader("Location", "http://metadata.google.internal"); mockWebServer.enqueue(mockRedirectResponse); mockWebServer.start(); @@ -569,19 +573,26 @@ public void itShouldRejectGetToMetadataGcpAndRedirect() throws IOException { StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); - assertEquals("Host metadata.google.internal is not allowed", result.getPluginErrorDetails().getDownstreamErrorMessage()); + assertEquals( + "Host metadata.google.internal is not allowed", + result.getPluginErrorDetails().getDownstreamErrorMessage()); }) .verifyComplete(); } @Test public void verifyUniquenessOfElasticSearchPluginErrorCode() { - assert (Arrays.stream(ElasticSearchPluginError.values()).map(ElasticSearchPluginError::getAppErrorCode).distinct().count() == ElasticSearchPluginError.values().length); - - assert (Arrays.stream(ElasticSearchPluginError.values()).map(ElasticSearchPluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-ELS")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(ElasticSearchPluginError.values()) + .map(ElasticSearchPluginError::getAppErrorCode) + .distinct() + .count() + == ElasticSearchPluginError.values().length); + + assert (Arrays.stream(ElasticSearchPluginError.values()) + .map(ElasticSearchPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-ELS")) + .collect(Collectors.toList()) + .size() + == 0); } - } diff --git a/app/server/appsmith-plugins/firestorePlugin/pom.xml b/app/server/appsmith-plugins/firestorePlugin/pom.xml index 5f84deca3e4c..264b97b8ea7f 100644 --- a/app/server/appsmith-plugins/firestorePlugin/pom.xml +++ b/app/server/appsmith-plugins/firestorePlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>firestorePlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -33,7 +32,6 @@ </exclusions> </dependency> - <!-- Test Dependencies --> <dependency> <groupId>org.testcontainers</groupId> @@ -60,10 +58,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/constants/FieldName.java b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/constants/FieldName.java index 07b92c61d6e0..e8b3c6a21e00 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/constants/FieldName.java +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/constants/FieldName.java @@ -20,4 +20,3 @@ public class FieldName { public static final String WHERE_CHILDREN = WHERE + "." + CHILDREN; } - diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java index 8a262573a05a..808903ed8ba7 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java @@ -12,11 +12,11 @@ import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.DatasourceTestResult; import com.appsmith.external.models.MustacheBindingToken; import com.appsmith.external.models.PaginationField; import com.appsmith.external.models.Param; import com.appsmith.external.models.RequestParamDTO; -import com.appsmith.external.models.DatasourceTestResult; import com.appsmith.external.plugins.BasePlugin; import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.external.plugins.SmartSubstitutionInterface; @@ -25,12 +25,12 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.google.api.core.ApiFuture; import com.google.auth.oauth2.GoogleCredentials; -import com.google.cloud.firestore.FirestoreException; import com.google.cloud.firestore.CollectionReference; import com.google.cloud.firestore.DocumentReference; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.FieldValue; import com.google.cloud.firestore.Firestore; +import com.google.cloud.firestore.FirestoreException; import com.google.cloud.firestore.Query; import com.google.cloud.firestore.QuerySnapshot; import com.google.cloud.firestore.WriteResult; @@ -109,23 +109,26 @@ public static class FirestorePluginExecutor implements PluginExecutor<Firestore> @Override @Deprecated - public Mono<ActionExecutionResult> execute(Firestore connection, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { - return Mono.error(new AppsmithPluginException(FirestorePluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); + public Mono<ActionExecutionResult> execute( + Firestore connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { + return Mono.error( + new AppsmithPluginException(FirestorePluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) { String jsonBody = (String) input; Param param = (Param) args[0]; - return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue(jsonBody, value, null, insertedParams, - null, param); + return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue( + jsonBody, value, null, insertedParams, null, param); } @Override @@ -148,7 +151,8 @@ public Mono<ActionExecutionResult> executeParameterized( // Smartly substitute in actionConfiguration.body and replace all the bindings with values. List<Map.Entry<String, String>> parameters = new ArrayList<>(); if (TRUE.equals(smartJsonSubstitution)) { - String query = PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), BODY, STRING_TYPE); + String query = PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), BODY, STRING_TYPE); if (query != null) { // First extract all the bindings in order @@ -157,10 +161,8 @@ public Mono<ActionExecutionResult> executeParameterized( String updatedQuery = MustacheHelper.replaceMustacheWithPlaceholder(query, mustacheKeysInOrder); try { - updatedQuery = (String) smartSubstitutionOfBindings(updatedQuery, - mustacheKeysInOrder, - executeActionDTO.getParams(), - parameters); + updatedQuery = (String) smartSubstitutionOfBindings( + updatedQuery, mustacheKeysInOrder, executeActionDTO.getParams(), parameters); } catch (AppsmithPluginException e) { ActionExecutionResult errorResult = new ActionExecutionResult(); errorResult.setIsExecutionSuccess(false); @@ -187,12 +189,9 @@ public Mono<ActionExecutionResult> executeParameterized( String command = PluginUtils.getDataValueSafelyFromFormData(formData, COMMAND, STRING_TYPE); if (isBlank(command)) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.MANDATORY_PARAM_COMMAND_MISSING_ERROR_MSG - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + FirestoreErrorMessages.MANDATORY_PARAM_COMMAND_MISSING_ERROR_MSG)); } requestData.put("command", command); @@ -202,33 +201,29 @@ public Mono<ActionExecutionResult> executeParameterized( requestParams.add(new RequestParamDTO(COMMAND, command, null, null, null)); requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null)); - final PaginationField paginationField = executeActionDTO == null ? null : executeActionDTO.getPaginationField(); + final PaginationField paginationField = + executeActionDTO == null ? null : executeActionDTO.getPaginationField(); Set<String> hintMessages = new HashSet<>(); - return Mono - .justOrEmpty(query) + return Mono.justOrEmpty(query) .flatMap(strBody -> { - if (method == null) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.MISSING_FIRESTORE_METHOD_ERROR_MSG - )); + FirestoreErrorMessages.MISSING_FIRESTORE_METHOD_ERROR_MSG)); } if (isBlank(path)) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.EMPTY_DOC_OR_COLLECTION_PATH_ERROR_MSG - )); + FirestoreErrorMessages.EMPTY_DOC_OR_COLLECTION_PATH_ERROR_MSG)); } if (path.startsWith("/") || path.endsWith("/")) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.FIRESTORE_PATH_INVALID_STARTING_CHAR_ERROR_MSG - )); + FirestoreErrorMessages.FIRESTORE_PATH_INVALID_STARTING_CHAR_ERROR_MSG)); } if (isBlank(strBody)) { @@ -254,27 +249,27 @@ public Mono<ActionExecutionResult> executeParameterized( return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, FirestoreErrorMessages.QUERY_CONVERSION_TO_HASHMAP_FAILED_ERROR_MSG, - e.getMessage() - )); + e.getMessage())); } }) .flatMap(mapBody -> { - if (mapBody.isEmpty()) { if (method.isBodyNeeded()) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - String.format(FirestoreErrorMessages.NON_EMPTY_BODY_REQUIRED_FOR_METHOD_ERROR_MSG, method) - )); + String.format( + FirestoreErrorMessages.NON_EMPTY_BODY_REQUIRED_FOR_METHOD_ERROR_MSG, + method))); } if (isSetOrUpdateOrCreateOrAddMethod(method) && isTimestampAndDeleteFieldValuePathEmpty(formData)) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - String.format(FirestoreErrorMessages.NON_EMPTY_FIELD_REQUIRED_FOR_METHOD_ERROR_MSG, method) - )); + String.format( + FirestoreErrorMessages.NON_EMPTY_FIELD_REQUIRED_FOR_METHOD_ERROR_MSG, + method))); } } @@ -293,15 +288,27 @@ && isTimestampAndDeleteFieldValuePathEmpty(formData)) { if (method.isDocumentLevel()) { return handleDocumentLevelMethod(connection, path, method, mapBody, query, requestParams); } else { - return handleCollectionLevelMethod(connection, path, method, formData, mapBody, - paginationField, query, requestParams, hintMessages, actionConfiguration); + return handleCollectionLevelMethod( + connection, + path, + method, + formData, + mapBody, + paginationField, + query, + requestParams, + hintMessages, + actionConfiguration); } }) .onErrorResume(error -> { ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(FirestorePluginError.QUERY_EXECUTION_FAILED, FirestoreErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error); + if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + FirestorePluginError.QUERY_EXECUTION_FAILED, + FirestoreErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error); } result.setErrorInfo(error); return Mono.just(result); @@ -329,17 +336,21 @@ && isBlank(PluginUtils.getDataValueSafelyFromFormData(formData, DELETE_KEY_PATH, } private boolean isSetOrUpdateOrCreateOrAddMethod(Method method) { - return Method.SET_DOCUMENT.equals(method) || Method.UPDATE_DOCUMENT.equals(method) - || Method.CREATE_DOCUMENT.equals(method) || Method.ADD_TO_COLLECTION.equals(method); + return Method.SET_DOCUMENT.equals(method) + || Method.UPDATE_DOCUMENT.equals(method) + || Method.CREATE_DOCUMENT.equals(method) + || Method.ADD_TO_COLLECTION.equals(method); } /* * - Update mapBody with FieldValue.xyz() values if the FieldValue paths are provided. */ - private void insertFieldValues(Map<String, Object> mapBody, - Map<String, Object> formData, - Method method, - List<RequestParamDTO> requestParams) throws AppsmithPluginException { + private void insertFieldValues( + Map<String, Object> mapBody, + Map<String, Object> formData, + Method method, + List<RequestParamDTO> requestParams) + throws AppsmithPluginException { /* * - Check that FieldValue.delete() option is only available for UPDATE operation. @@ -348,8 +359,7 @@ private void insertFieldValues(Map<String, Object> mapBody, && !isBlank(PluginUtils.getDataValueSafelyFromFormData(formData, DELETE_KEY_PATH, STRING_TYPE))) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.UNEXPECTED_PROPERTY_DELETE_KEY_PATH_ERROR_MSG - ); + FirestoreErrorMessages.UNEXPECTED_PROPERTY_DELETE_KEY_PATH_ERROR_MSG); } /* @@ -360,14 +370,12 @@ private void insertFieldValues(Map<String, Object> mapBody, requestParams.add(new RequestParamDTO(DELETE_KEY_PATH, deletePaths, null, null, null)); List<String> deletePathsList; try { - deletePathsList = objectMapper.readValue(deletePaths, new TypeReference<List<String>>() { - }); + deletePathsList = objectMapper.readValue(deletePaths, new TypeReference<List<String>>() {}); } catch (IOException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, FirestoreErrorMessages.FAILED_TO_PARSE_DELETE_KEY_PATH_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } /* @@ -379,38 +387,36 @@ private void insertFieldValues(Map<String, Object> mapBody, * - dot notation is safe to use with delete FieldValue because this FieldValue only works with update * operation. */ - deletePathsList.stream() - .forEach(path -> mapBody.put(path, FieldValue.delete())); + deletePathsList.stream().forEach(path -> mapBody.put(path, FieldValue.delete())); } /* * - Check that FieldValue.serverTimestamp() option is not available for any GET or DELETE operations. */ if (isGetOrDeleteMethod(method) - && !isBlank(PluginUtils.getDataValueSafelyFromFormData(formData, TIMESTAMP_VALUE_PATH, STRING_TYPE))) { + && !isBlank( + PluginUtils.getDataValueSafelyFromFormData(formData, TIMESTAMP_VALUE_PATH, STRING_TYPE))) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.UNEXPECTED_PROPERTY_TIMESTAMP_ERROR_MSG - ); + FirestoreErrorMessages.UNEXPECTED_PROPERTY_TIMESTAMP_ERROR_MSG); } /* * - Parse severTimestamp FieldValue path. */ if (!isBlank(PluginUtils.getDataValueSafelyFromFormData(formData, TIMESTAMP_VALUE_PATH, STRING_TYPE))) { - String timestampValuePaths = PluginUtils.getDataValueSafelyFromFormData(formData, TIMESTAMP_VALUE_PATH, STRING_TYPE); + String timestampValuePaths = + PluginUtils.getDataValueSafelyFromFormData(formData, TIMESTAMP_VALUE_PATH, STRING_TYPE); requestParams.add(new RequestParamDTO(TIMESTAMP_VALUE_PATH, timestampValuePaths, null, null, null)); List<String> timestampPathsStringList; // ["key1.key2", "key3.key4"] try { - timestampPathsStringList = objectMapper.readValue(timestampValuePaths, - new TypeReference<List<String>>() { - }); + timestampPathsStringList = + objectMapper.readValue(timestampValuePaths, new TypeReference<List<String>>() {}); } catch (IOException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, FirestoreErrorMessages.FAILED_TO_PARSE_TIMESTAMP_VALUE_PATH_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } /* @@ -429,7 +435,8 @@ private void insertFieldValues(Map<String, Object> mapBody, } private boolean isGetOrDeleteMethod(Method method) { - return Method.GET_DOCUMENT.equals(method) || Method.GET_COLLECTION.equals(method) + return Method.GET_DOCUMENT.equals(method) + || Method.GET_COLLECTION.equals(method) || Method.DELETE_DOCUMENT.equals(method); } @@ -438,9 +445,8 @@ private boolean isGetOrDeleteMethod(Method method) { * - It iterates over the map body and replaces the value of keys defined by pathsList with a FieldValue * entity defined by fieldValueName. */ - private void insertFieldValueByMethodName(Map<String, Object> mapBody, - List<List<String>> pathsList, - String fieldValueName) { + private void insertFieldValueByMethodName( + Map<String, Object> mapBody, List<List<String>> pathsList, String fieldValueName) { pathsList.stream() .filter(singlePathList -> !CollectionUtils.isEmpty(singlePathList)) @@ -459,9 +465,11 @@ private void insertFieldValueByMethodName(Map<String, Object> mapBody, */ if (targetKeyValuePair.get(key) == null) { String nextKey = singlePathList.get(i + 1); - targetKeyValuePair.put(key, new HashMap<>() {{ - put(nextKey, null); - }}); + targetKeyValuePair.put(key, new HashMap<>() { + { + put(nextKey, null); + } + }); } /* @@ -478,8 +486,7 @@ private void insertFieldValueByMethodName(Map<String, Object> mapBody, * specified obj argument is ignored. It may be null. * - Ref: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Object...- */ - FieldValue.class.getMethod(fieldValueName).invoke(null) - ); + FieldValue.class.getMethod(fieldValueName).invoke(null)); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { /* * - Please offer suggestions if this exception can be handled in a better way. @@ -495,14 +502,12 @@ public Mono<ActionExecutionResult> handleDocumentLevelMethod( com.external.plugins.Method method, Map<String, Object> mapBody, String query, - List<RequestParamDTO> requestParams - ) { + List<RequestParamDTO> requestParams) { return Mono.just(method) // Get the actual Java method to be called. .flatMap(method1 -> { - - - final String methodName = method1.toString().split("_")[0].toLowerCase(); + final String methodName = + method1.toString().split("_")[0].toLowerCase(); try { switch (method1) { case GET_DOCUMENT: @@ -511,23 +516,22 @@ public Mono<ActionExecutionResult> handleDocumentLevelMethod( case SET_DOCUMENT: case CREATE_DOCUMENT: case UPDATE_DOCUMENT: - requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, - null, null)); + requestParams.add( + new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null)); return Mono.justOrEmpty(DocumentReference.class.getMethod(methodName, Map.class)); default: return Mono.error(new AppsmithPluginException( FirestorePluginError.QUERY_EXECUTION_FAILED, - String.format(FirestoreErrorMessages.INVALID_DOCUMENT_LEVEL_METHOD_ERROR_MSG, method1) - )); + String.format( + FirestoreErrorMessages.INVALID_DOCUMENT_LEVEL_METHOD_ERROR_MSG, + method1))); } } catch (NoSuchMethodException e) { return Mono.error(new AppsmithPluginException( FirestorePluginError.QUERY_EXECUTION_FAILED, String.format(FirestoreErrorMessages.ACTUAL_METHOD_GETTING_ERROR_MSG, method1), - e.getMessage() - )); - + e.getMessage())); } }) // Call that method and get a Future of the result. @@ -547,8 +551,10 @@ public Mono<ActionExecutionResult> handleDocumentLevelMethod( * - Printing the stack because e.getMessage() returns null for FieldValue errors. */ e.printStackTrace(); - return Mono.error(new AppsmithPluginException(FirestorePluginError.QUERY_EXECUTION_FAILED, FirestoreErrorMessages.METHOD_INVOCATION_FAILED_ERROR_MSG, e.getMessage())); - + return Mono.error(new AppsmithPluginException( + FirestorePluginError.QUERY_EXECUTION_FAILED, + FirestoreErrorMessages.METHOD_INVOCATION_FAILED_ERROR_MSG, + e.getMessage())); } return Mono.just((ApiFuture<Object>) objFuture); @@ -559,7 +565,10 @@ public Mono<ActionExecutionResult> handleDocumentLevelMethod( return Mono.just(resultFuture.get()); } catch (InterruptedException | ExecutionException e) { - return Mono.error(new AppsmithPluginException(FirestorePluginError.QUERY_EXECUTION_FAILED, FirestoreErrorMessages.FAILURE_IN_GETTING_RESULT_FROM_FUTURE_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + FirestorePluginError.QUERY_EXECUTION_FAILED, + FirestoreErrorMessages.FAILURE_IN_GETTING_RESULT_FROM_FUTURE_ERROR_MSG, + e.getMessage())); } }) // Build a response object with the result. @@ -591,35 +600,42 @@ public Mono<ActionExecutionResult> handleCollectionLevelMethod( final CollectionReference collection = connection.collection(path); if (method == Method.GET_COLLECTION) { - return methodGetCollection(collection, formData, paginationField, requestParams, hintMessages, actionConfiguration); + return methodGetCollection( + collection, formData, paginationField, requestParams, hintMessages, actionConfiguration); } else if (method == Method.ADD_TO_COLLECTION) { requestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null)); return methodAddToCollection(collection, mapBody); - } return Mono.error(new AppsmithPluginException( FirestorePluginError.QUERY_EXECUTION_FAILED, - String.format(FirestoreErrorMessages.UNSUPPORTED_COLLECTION_METHOD_ERROR_MSG, method) - )); + String.format(FirestoreErrorMessages.UNSUPPORTED_COLLECTION_METHOD_ERROR_MSG, method))); } - private Mono<ActionExecutionResult> methodGetCollection(CollectionReference query, Map<String, Object> formData, - PaginationField paginationField, - List<RequestParamDTO> requestParams, - Set<String> hintMessages, ActionConfiguration actionConfiguration) { - final String limitString = PluginUtils.getDataValueSafelyFromFormData(formData, LIMIT_DOCUMENTS, STRING_TYPE); + private Mono<ActionExecutionResult> methodGetCollection( + CollectionReference query, + Map<String, Object> formData, + PaginationField paginationField, + List<RequestParamDTO> requestParams, + Set<String> hintMessages, + ActionConfiguration actionConfiguration) { + final String limitString = + PluginUtils.getDataValueSafelyFromFormData(formData, LIMIT_DOCUMENTS, STRING_TYPE); final int limit = StringUtils.isEmpty(limitString) ? 10 : Integer.parseInt(limitString); - final String orderByString = PluginUtils.getDataValueSafelyFromFormData(formData, ORDER_BY, STRING_TYPE, ""); + final String orderByString = + PluginUtils.getDataValueSafelyFromFormData(formData, ORDER_BY, STRING_TYPE, ""); requestParams.add(new RequestParamDTO(ORDER_BY, orderByString, null, null, null)); final List<String> orderings; try { - orderings = StringUtils.isEmpty(orderByString) ? Collections.emptyList() : objectMapper.readValue(orderByString, List.class); + orderings = StringUtils.isEmpty(orderByString) + ? Collections.emptyList() + : objectMapper.readValue(orderByString, List.class); } catch (IOException e) { // TODO: Investigate how many actions are using this today on prod. - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, orderByString, e)); + return Mono.error( + new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, orderByString, e)); } Map<String, Object> startAfterTemp = null; @@ -630,9 +646,12 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer requestParams.add(new RequestParamDTO(START_AFTER, startAfterJson, null, null, null)); if (PaginationField.NEXT.equals(paginationField)) { try { - startAfterTemp = StringUtils.isEmpty(startAfterJson) ? Collections.emptyMap() : objectMapper.readValue(startAfterJson, Map.class); + startAfterTemp = StringUtils.isEmpty(startAfterJson) + ? Collections.emptyMap() + : objectMapper.readValue(startAfterJson, Map.class); } catch (IOException e) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, startAfterJson, e)); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, startAfterJson, e)); } } @@ -644,14 +663,17 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer requestParams.add(new RequestParamDTO(END_BEFORE, endBeforeJson, null, null, null)); if (PaginationField.PREV.equals(paginationField)) { try { - endBeforeTemp = StringUtils.isEmpty(endBeforeJson) ? Collections.emptyMap() : objectMapper.readValue(endBeforeJson, Map.class); + endBeforeTemp = StringUtils.isEmpty(endBeforeJson) + ? Collections.emptyMap() + : objectMapper.readValue(endBeforeJson, Map.class); } catch (IOException e) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, endBeforeJson, e)); + return Mono.error( + new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, endBeforeJson, e)); } } - requestParams.add(new RequestParamDTO(LIMIT_DOCUMENTS, limitString == null ? "" : limitString, null, null - , null)); + requestParams.add( + new RequestParamDTO(LIMIT_DOCUMENTS, limitString == null ? "" : limitString, null, null, null)); final Map<String, Object> startAfter = startAfterTemp; final Map<String, Object> endBefore = endBeforeTemp; @@ -659,8 +681,7 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer if (paginationField != null && CollectionUtils.isEmpty(orderings)) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.PAGINATION_WITHOUT_SPECIFYING_ORDERING_ERROR_MSG - )); + FirestoreErrorMessages.PAGINATION_WITHOUT_SPECIFYING_ORDERING_ERROR_MSG)); } return Mono.just(query) @@ -672,8 +693,7 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer for (final String field : orderings) { q = q.orderBy( field.replaceAll("^-", ""), - field.startsWith("-") ? Query.Direction.DESCENDING : Query.Direction.ASCENDING - ); + field.startsWith("-") ? Query.Direction.DESCENDING : Query.Direction.ASCENDING); if (startAfter != null) { startAfterValues.add(startAfter.get(field)); } @@ -683,7 +703,8 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer } if (PaginationField.NEXT.equals(paginationField) && !CollectionUtils.isEmpty(startAfter)) { q = q.startAfter(startAfterValues.toArray()); - } else if (PaginationField.PREV.equals(paginationField) && !CollectionUtils.isEmpty(endBefore)) { + } else if (PaginationField.PREV.equals(paginationField) + && !CollectionUtils.isEmpty(endBefore)) { q = q.endBefore(endBeforeValues.toArray()); } return q; @@ -694,8 +715,8 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer return Mono.just(query1); } - Map<String, List<Map<String, String>>> childrenMap = PluginUtils.getDataValueSafelyFromFormData(formData, WHERE, new TypeReference<>() { - }); + Map<String, List<Map<String, String>>> childrenMap = + PluginUtils.getDataValueSafelyFromFormData(formData, WHERE, new TypeReference<>() {}); final List<Map<String, String>> conditionList = childrenMap.get("children"); requestParams.add(new RequestParamDTO(WHERE, conditionList, null, null, null)); @@ -704,10 +725,12 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer String operatorString = condition.get("condition"); String value = condition.get("value"); - if (StringUtils.isEmpty(path) || StringUtils.isEmpty(operatorString) || StringUtils.isEmpty(value)) { - String emptyConditionMessage = "At least one of the conditions in the 'where' clause " + - "has missing operator or operand(s). These conditions were ignored during the" + - " execution of the query."; + if (StringUtils.isEmpty(path) + || StringUtils.isEmpty(operatorString) + || StringUtils.isEmpty(value)) { + String emptyConditionMessage = "At least one of the conditions in the 'where' clause " + + "has missing operator or operand(s). These conditions were ignored during the" + + " execution of the query."; hintMessages.add(emptyConditionMessage); continue; } @@ -721,7 +744,8 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer return Mono.just(query1); }) - // Apply limit, always provided, since without it, we can inadvertently end up processing too much data. + // Apply limit, always provided, since without it, we can inadvertently end up processing too much + // data. .map(query1 -> { if (PaginationField.PREV.equals(paginationField) && !CollectionUtils.isEmpty(endBefore)) { return query1.limitToLast(limit); @@ -735,7 +759,10 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer try { return Mono.just(resultFuture.get()); } catch (InterruptedException | ExecutionException e) { - return Mono.error(new AppsmithPluginException(FirestorePluginError.QUERY_EXECUTION_FAILED, FirestoreErrorMessages.FAILURE_IN_GETTING_RESULT_FROM_FUTURE_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + FirestorePluginError.QUERY_EXECUTION_FAILED, + FirestoreErrorMessages.FAILURE_IN_GETTING_RESULT_FROM_FUTURE_ERROR_MSG, + e.getMessage())); } }) // Build response object with the results from the Future. @@ -753,9 +780,8 @@ private Mono<ActionExecutionResult> methodGetCollection(CollectionReference quer } private boolean isWhereMethodUsed(Map<String, Object> formData) { - final Map<String, List<Object>> childrenMap = getDataValueSafelyFromFormData(formData, WHERE, new TypeReference<>() { - } - ); + final Map<String, List<Object>> childrenMap = + getDataValueSafelyFromFormData(formData, WHERE, new TypeReference<>() {}); if (childrenMap == null || childrenMap.isEmpty()) { return false; @@ -768,8 +794,8 @@ private boolean isWhereMethodUsed(Map<String, Object> formData) { } // Check if all keys in the where clause are null. - boolean allValuesNull = conditionList.stream() - .allMatch(condition -> isBlank((String) ((Map) condition).get("key"))); + boolean allValuesNull = + conditionList.stream().allMatch(condition -> isBlank((String) ((Map) condition).get("key"))); if (allValuesNull) { return false; @@ -778,7 +804,8 @@ private boolean isWhereMethodUsed(Map<String, Object> formData) { return true; } - private Mono<ActionExecutionResult> methodAddToCollection(CollectionReference collection, Map<String, Object> mapBody) { + private Mono<ActionExecutionResult> methodAddToCollection( + CollectionReference collection, Map<String, Object> mapBody) { return Mono.justOrEmpty(collection.add(mapBody)) .flatMap(future -> { try { @@ -787,8 +814,7 @@ private Mono<ActionExecutionResult> methodAddToCollection(CollectionReference co return Mono.error(new AppsmithPluginException( FirestorePluginError.QUERY_EXECUTION_FAILED, FirestoreErrorMessages.FAILURE_IN_GETTING_RESULT_FROM_FUTURE_ERROR_MSG, - e.getMessage() - )); + e.getMessage())); } }) .flatMap(opResult -> { @@ -821,7 +847,8 @@ private Object resultToMap(Object objResult, boolean isRoot) throws AppsmithPlug Map<String, Object> resultMap = new HashMap<>(); resultMap.put("_ref", resultToMap(documentSnapshot.getReference())); if (documentSnapshot.getData() != null) { - for (final Map.Entry<String, Object> entry : documentSnapshot.getData().entrySet()) { + for (final Map.Entry<String, Object> entry : + documentSnapshot.getData().entrySet()) { resultMap.put(entry.getKey(), resultToMap(entry.getValue(), false)); } } @@ -836,8 +863,7 @@ private Object resultToMap(Object objResult, boolean isRoot) throws AppsmithPlug DocumentReference documentReference = (DocumentReference) objResult; return Map.of( "id", documentReference.getId(), - "path", documentReference.getPath() - ); + "path", documentReference.getPath()); } else if (objResult instanceof Map) { Map<String, Object> resultMap = (Map) objResult; @@ -857,9 +883,9 @@ private Object resultToMap(Object objResult, boolean isRoot) throws AppsmithPlug } else if (isRoot) { throw new AppsmithPluginException( FirestorePluginError.QUERY_EXECUTION_FAILED, - String.format(FirestoreErrorMessages.OBJECT_SERIALIZATION_FAILED_ERROR_MSG, objResult.getClass().getName()) - ); - + String.format( + FirestoreErrorMessages.OBJECT_SERIALIZATION_FAILED_ERROR_MSG, + objResult.getClass().getName())); } return objResult; @@ -871,7 +897,8 @@ public Mono<Firestore> datasourceCreate(DatasourceConfiguration datasourceConfig final Set<String> errors = validateDatasource(datasourceConfiguration); if (!CollectionUtils.isEmpty(errors)) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, errors.iterator().next())); } @@ -880,8 +907,7 @@ public Mono<Firestore> datasourceCreate(DatasourceConfiguration datasourceConfig InputStream serviceAccount = new ByteArrayInputStream(clientJson.getBytes()); - return Mono - .fromSupplier(() -> { + return Mono.fromSupplier(() -> { GoogleCredentials credentials; try { credentials = GoogleCredentials.fromStream(serviceAccount); @@ -889,8 +915,7 @@ public Mono<Firestore> datasourceCreate(DatasourceConfiguration datasourceConfig throw Exceptions.propagate(new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, FirestoreErrorMessages.DS_VALIDATION_FAILED_FOR_SERVICE_ACC_CREDENTIALS_ERROR_MSG, - e.getMessage() - )); + e.getMessage())); } return FirebaseOptions.builder() @@ -912,25 +937,24 @@ public Mono<Firestore> datasourceCreate(DatasourceConfiguration datasourceConfig } @Override - public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration){ + public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) { - return datasourceCreate(datasourceConfiguration) - .flatMap(connection -> { - try { - connection.listCollections(); - } catch (FirestoreException e){ - log.debug("Invalid datasource configuration : {}", e.getMessage()); - if(e.getMessage().contains("Metadata operations require admin authentication")){ - DatasourceTestResult datasourceTestResult = new DatasourceTestResult(); - datasourceTestResult.setMessages(new HashSet<>(Collections.singletonList( - FirestoreErrorMessages.META_DATA_ACCESS_MISSING_MESSAGE))); - return Mono.just(datasourceTestResult); - } - return Mono.just(new DatasourceTestResult(FirestoreErrorMessages. - DS_CONNECTION_FAILED_FOR_PROJECT_ID)); - } - return Mono.just(new DatasourceTestResult()); - }); + return datasourceCreate(datasourceConfiguration).flatMap(connection -> { + try { + connection.listCollections(); + } catch (FirestoreException e) { + log.debug("Invalid datasource configuration : {}", e.getMessage()); + if (e.getMessage().contains("Metadata operations require admin authentication")) { + DatasourceTestResult datasourceTestResult = new DatasourceTestResult(); + datasourceTestResult.setMessages(new HashSet<>( + Collections.singletonList(FirestoreErrorMessages.META_DATA_ACCESS_MISSING_MESSAGE))); + return Mono.just(datasourceTestResult); + } + return Mono.just( + new DatasourceTestResult(FirestoreErrorMessages.DS_CONNECTION_FAILED_FOR_PROJECT_ID)); + } + return Mono.just(new DatasourceTestResult()); + }); } @Override @@ -956,7 +980,6 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur if (StringUtils.isEmpty(authentication.getPassword())) { invalids.add(FirestoreErrorMessages.DS_MISSING_CLIENTJSON_ERROR_MSG); } - } if (isBlank(datasourceConfiguration.getUrl())) { @@ -967,12 +990,13 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur } @Override - public Mono<DatasourceStructure> getStructure(Firestore connection, DatasourceConfiguration datasourceConfiguration) { - return Mono - .fromSupplier(() -> { + public Mono<DatasourceStructure> getStructure( + Firestore connection, DatasourceConfiguration datasourceConfiguration) { + return Mono.fromSupplier(() -> { Iterable<CollectionReference> collectionReferences = connection.listCollections(); - List<DatasourceStructure.Table> tables = StreamSupport.stream(collectionReferences.spliterator(), false) + List<DatasourceStructure.Table> tables = StreamSupport.stream( + collectionReferences.spliterator(), false) .map(collectionReference -> { String id = collectionReference.getId(); final ArrayList<DatasourceStructure.Template> templates = new ArrayList<>(); @@ -982,8 +1006,7 @@ public Mono<DatasourceStructure> getStructure(Firestore connection, DatasourceCo id, new ArrayList<>(), new ArrayList<>(), - templates - ); + templates); }) .collect(Collectors.toList()); @@ -997,7 +1020,8 @@ public Mono<DatasourceStructure> getStructure(Firestore connection, DatasourceCo @Override public Set<String> getSelfReferencingDataPaths() { - return Set.of("formData.prev.data", "formData.next.data", "formData.startAfter.data", "formData.endBefore.data"); + return Set.of( + "formData.prev.data", "formData.next.data", "formData.startAfter.data", "formData.endBefore.data"); } } } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/exceptions/FirestoreErrorMessages.java b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/exceptions/FirestoreErrorMessages.java index 9ebdae482439..df16216fdbd2 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/exceptions/FirestoreErrorMessages.java +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/exceptions/FirestoreErrorMessages.java @@ -6,36 +6,46 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) // To prevent instantiation public class FirestoreErrorMessages extends BasePluginErrorMessages { - public static final String MANDATORY_PARAM_COMMAND_MISSING_ERROR_MSG = "Mandatory parameter 'Command' is missing. Did you forget to select one of the commands" + - " from the Command dropdown ?"; + public static final String MANDATORY_PARAM_COMMAND_MISSING_ERROR_MSG = + "Mandatory parameter 'Command' is missing. Did you forget to select one of the commands" + + " from the Command dropdown ?"; public static final String MISSING_FIRESTORE_METHOD_ERROR_MSG = "Missing Firestore method."; public static final String EMPTY_DOC_OR_COLLECTION_PATH_ERROR_MSG = "Document/Collection path cannot be empty"; - public static final String FIRESTORE_PATH_INVALID_STARTING_CHAR_ERROR_MSG = "Firestore paths should not begin or end with `/` character."; + public static final String FIRESTORE_PATH_INVALID_STARTING_CHAR_ERROR_MSG = + "Firestore paths should not begin or end with `/` character."; - public static final String QUERY_CONVERSION_TO_HASHMAP_FAILED_ERROR_MSG = "Error occurred while preparing your query to run. Please check the error details for more information."; + public static final String QUERY_CONVERSION_TO_HASHMAP_FAILED_ERROR_MSG = + "Error occurred while preparing your query to run. Please check the error details for more information."; - public static final String NON_EMPTY_BODY_REQUIRED_FOR_METHOD_ERROR_MSG = "The method %s needs a non-empty body to work."; + public static final String NON_EMPTY_BODY_REQUIRED_FOR_METHOD_ERROR_MSG = + "The method %s needs a non-empty body to work."; - public static final String NON_EMPTY_FIELD_REQUIRED_FOR_METHOD_ERROR_MSG = "The method %s needs at least one of the following " + - "fields to be non-empty: 'Timestamp Value Path', 'Delete Key Value " + - "Pair Path', 'Body'"; + public static final String NON_EMPTY_FIELD_REQUIRED_FOR_METHOD_ERROR_MSG = + "The method %s needs at least one of the following " + + "fields to be non-empty: 'Timestamp Value Path', 'Delete Key Value " + + "Pair Path', 'Body'"; - public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Firestore query has failed to execute. To know more please check the error details."; + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = + "Firestore query has failed to execute. To know more please check the error details."; - public static final String UNEXPECTED_PROPERTY_DELETE_KEY_PATH_ERROR_MSG = "Appsmith has found an unexpected query form property - 'Delete Key Value Pair Path'. Please " + - "reach out to Appsmith customer support to resolve this."; + public static final String UNEXPECTED_PROPERTY_DELETE_KEY_PATH_ERROR_MSG = + "Appsmith has found an unexpected query form property - 'Delete Key Value Pair Path'. Please " + + "reach out to Appsmith customer support to resolve this."; - public static final String UNEXPECTED_PROPERTY_TIMESTAMP_ERROR_MSG ="Appsmith has found an unexpected query form property - 'Timestamp Value Path'. Please reach " + - "out to Appsmith customer support to resolve this."; + public static final String UNEXPECTED_PROPERTY_TIMESTAMP_ERROR_MSG = + "Appsmith has found an unexpected query form property - 'Timestamp Value Path'. Please reach " + + "out to Appsmith customer support to resolve this."; - public static final String FAILED_TO_PARSE_DELETE_KEY_PATH_ERROR_MSG = "Appsmith failed to parse the query editor form field 'Delete Key Value Pair Path'. " + - "Please check out Appsmith's documentation to find the correct syntax."; + public static final String FAILED_TO_PARSE_DELETE_KEY_PATH_ERROR_MSG = + "Appsmith failed to parse the query editor form field 'Delete Key Value Pair Path'. " + + "Please check out Appsmith's documentation to find the correct syntax."; - public static final String FAILED_TO_PARSE_TIMESTAMP_VALUE_PATH_ERROR_MSG = "Appsmith failed to parse the query editor form field 'Timestamp Value Path'. " + - "Please check out Appsmith's documentation to find the correct syntax."; + public static final String FAILED_TO_PARSE_TIMESTAMP_VALUE_PATH_ERROR_MSG = + "Appsmith failed to parse the query editor form field 'Timestamp Value Path'. " + + "Please check out Appsmith's documentation to find the correct syntax."; public static final String INVALID_DOCUMENT_LEVEL_METHOD_ERROR_MSG = "Invalid document-level method %s"; @@ -43,33 +53,42 @@ public class FirestoreErrorMessages extends BasePluginErrorMessages { public static final String UNSUPPORTED_COLLECTION_METHOD_ERROR_MSG = "Unsupported collection-level command: %s"; - public static final String METHOD_INVOCATION_FAILED_ERROR_MSG = "Method invocation failed. Please check the error details for more information."; + public static final String METHOD_INVOCATION_FAILED_ERROR_MSG = + "Method invocation failed. Please check the error details for more information."; - public static final String FAILURE_IN_GETTING_RESULT_FROM_FUTURE_ERROR_MSG = "Error occurred while getting the response. To know more please check the error details."; + public static final String FAILURE_IN_GETTING_RESULT_FROM_FUTURE_ERROR_MSG = + "Error occurred while getting the response. To know more please check the error details."; - public static final String PAGINATION_WITHOUT_SPECIFYING_ORDERING_ERROR_MSG = "Cannot do pagination without specifying an ordering."; + public static final String PAGINATION_WITHOUT_SPECIFYING_ORDERING_ERROR_MSG = + "Cannot do pagination without specifying an ordering."; public static final String OBJECT_SERIALIZATION_FAILED_ERROR_MSG = "Unable to serialize object of type %s."; - public static final String WHERE_CONDITIONAL_NULL_QUERY_ERROR_MSG = "Appsmith server has found null query object when applying where conditional on Firestore " + - "query. Please contact Appsmith's customer support to resolve this."; + public static final String WHERE_CONDITIONAL_NULL_QUERY_ERROR_MSG = + "Appsmith server has found null query object when applying where conditional on Firestore " + + "query. Please contact Appsmith's customer support to resolve this."; - public static final String WHERE_CONDITION_INVALID_OPERATOR_ERROR_MSG = "Appsmith server has encountered an invalid operator for Firestore query's where conditional." + - " Please contact Appsmith's customer support to resolve this."; + public static final String WHERE_CONDITION_INVALID_OPERATOR_ERROR_MSG = + "Appsmith server has encountered an invalid operator for Firestore query's where conditional." + + " Please contact Appsmith's customer support to resolve this."; - public static final String WHERE_CONDITION_UNPARSABLE_AS_JSON_LIST_ERROR_MSG = "Unable to parse condition value as a JSON list."; + public static final String WHERE_CONDITION_UNPARSABLE_AS_JSON_LIST_ERROR_MSG = + "Unable to parse condition value as a JSON list."; - public static final String DS_CONNECTION_FAILED_FOR_PROJECT_ID = "Unable to connect to the Firestore project. No project found for the given ProjectID."; + public static final String DS_CONNECTION_FAILED_FOR_PROJECT_ID = + "Unable to connect to the Firestore project. No project found for the given ProjectID."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ - public static final String DS_VALIDATION_FAILED_FOR_SERVICE_ACC_CREDENTIALS_ERROR_MSG = "Validation failed for field 'Service account credentials'. Please check the " + - "value provided in the 'Service account credentials' field."; - public static final String DS_MISSING_PROJECT_ID_AND_CLIENTJSON_ERROR_MSG = "Missing ProjectID and ClientJSON in datasource."; + public static final String DS_VALIDATION_FAILED_FOR_SERVICE_ACC_CREDENTIALS_ERROR_MSG = + "Validation failed for field 'Service account credentials'. Please check the " + + "value provided in the 'Service account credentials' field."; + public static final String DS_MISSING_PROJECT_ID_AND_CLIENTJSON_ERROR_MSG = + "Missing ProjectID and ClientJSON in datasource."; public static final String DS_MISSING_PROJECT_ID_ERROR_MSG = "Missing ProjectID in datasource."; @@ -78,11 +97,11 @@ public class FirestoreErrorMessages extends BasePluginErrorMessages { public static final String DS_MISSING_FIRESTORE_URL_ERROR_MSG = "Missing Firestore URL."; /* - ************************************************************************************************************************************************ - Warning messages related to datasource. - ************************************************************************************************************************************************ - */ - public static final String META_DATA_ACCESS_MISSING_MESSAGE = "Hi, it seems that the credentials provided here " + - "don't have the permission to gather metadata information. Please reach out to your database admin " + - "to understand more. "; + ************************************************************************************************************************************************ + Warning messages related to datasource. + ************************************************************************************************************************************************ + */ + public static final String META_DATA_ACCESS_MISSING_MESSAGE = "Hi, it seems that the credentials provided here " + + "don't have the permission to gather metadata information. Please reach out to your database admin " + + "to understand more. "; } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/exceptions/FirestorePluginError.java b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/exceptions/FirestorePluginError.java index 6e34f933a070..53dc84d22060 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/exceptions/FirestorePluginError.java +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/exceptions/FirestorePluginError.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum FirestorePluginError implements BasePluginError { QUERY_EXECUTION_FAILED( @@ -16,8 +15,7 @@ public enum FirestorePluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; @@ -31,8 +29,15 @@ public enum FirestorePluginError implements BasePluginError { private final String downstreamErrorCode; - FirestorePluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + FirestorePluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -59,5 +64,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/utils/WhereConditionUtils.java b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/utils/WhereConditionUtils.java index 6e6f692cc079..00accaa3f1ef 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/utils/WhereConditionUtils.java +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/utils/WhereConditionUtils.java @@ -21,15 +21,15 @@ public class WhereConditionUtils { protected static final ObjectMapper objectMapper = new ObjectMapper(); - public static Query applyWhereConditional(Query query, String strPath, String operatorString, String strValue) throws AppsmithPluginException { + public static Query applyWhereConditional(Query query, String strPath, String operatorString, String strValue) + throws AppsmithPluginException { String path = strPath.trim(); if (query == null) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.WHERE_CONDITIONAL_NULL_QUERY_ERROR_MSG - ); + FirestoreErrorMessages.WHERE_CONDITIONAL_NULL_QUERY_ERROR_MSG); } ConditionalOperator operator; @@ -39,8 +39,7 @@ public static Query applyWhereConditional(Query query, String strPath, String op throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, FirestoreErrorMessages.WHERE_CONDITION_INVALID_OPERATOR_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } DataType dataType = DataTypeStringUtils.stringToKnownDataTypeConverter(strValue); @@ -66,7 +65,7 @@ public static Query applyWhereConditional(Query query, String strPath, String op try { date = sdf.parse(strValue); } catch (ParseException e) { - //Input may not be of above pattern + // Input may not be of above pattern } value = date; break; @@ -77,7 +76,7 @@ public static Query applyWhereConditional(Query query, String strPath, String op try { timeStamp = sdfTs.parse(strValue); } catch (ParseException e) { - //Input may not be of above pattern + // Input may not be of above pattern } value = timeStamp; break; @@ -91,9 +90,9 @@ public static Query applyWhereConditional(Query query, String strPath, String op return query.whereLessThanOrEqualTo(fieldPath, value); case EQ: return query.whereEqualTo(fieldPath, value); - // TODO: NOT_EQ operator support is awaited in the next version of Firestore driver. - // case NOT_EQ: - // return Mono.just(query.whereNotEqualTo(path, value)); + // TODO: NOT_EQ operator support is awaited in the next version of Firestore driver. + // case NOT_EQ: + // return Mono.just(query.whereNotEqualTo(path, value)); case GT: return query.whereGreaterThan(fieldPath, value); case GTE: @@ -107,8 +106,7 @@ public static Query applyWhereConditional(Query query, String strPath, String op throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, FirestoreErrorMessages.WHERE_CONDITION_UNPARSABLE_AS_JSON_LIST_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } case IN: try { @@ -117,8 +115,7 @@ public static Query applyWhereConditional(Query query, String strPath, String op throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, FirestoreErrorMessages.WHERE_CONDITION_UNPARSABLE_AS_JSON_LIST_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } // TODO: NOT_IN operator support is awaited in the next version of Firestore driver. // case NOT_IN: @@ -126,8 +123,7 @@ public static Query applyWhereConditional(Query query, String strPath, String op default: throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - FirestoreErrorMessages.WHERE_CONDITION_INVALID_OPERATOR_ERROR_MSG - ); + FirestoreErrorMessages.WHERE_CONDITION_INVALID_OPERATOR_ERROR_MSG); } } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/test/java/com/external/plugins/FirestorePluginTest.java b/app/server/appsmith-plugins/firestorePlugin/src/test/java/com/external/plugins/FirestorePluginTest.java index 894434af9bcf..e53c1f27b4e9 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/test/java/com/external/plugins/FirestorePluginTest.java +++ b/app/server/appsmith-plugins/firestorePlugin/src/test/java/com/external/plugins/FirestorePluginTest.java @@ -88,8 +88,7 @@ public class FirestorePluginTest { @Container public static final FirestoreEmulatorContainer emulator = new FirestoreEmulatorContainer( - DockerImageName.parse("gcr.io/google.com/cloudsdktool/cloud-sdk:316.0.0-emulators") - ); + DockerImageName.parse("gcr.io/google.com/cloudsdktool/cloud-sdk:316.0.0-emulators")); static Firestore firestoreConnection; @@ -105,69 +104,118 @@ public static void setUp() throws ExecutionException, InterruptedException, Pars .build() .getService(); - firestoreConnection.document("initial/one").set(Map.of("value", 1, "name", "one", "isPlural", false, - "category", "test")).get(); + firestoreConnection + .document("initial/one") + .set(Map.of("value", 1, "name", "one", "isPlural", false, "category", "test")) + .get(); final Map<String, Object> twoData = new HashMap<>(Map.of( - "value", 2, - "name", "two", - "isPlural", true, - "geo", new GeoPoint(-90, 90), - "dt", FieldValue.serverTimestamp(), - "ref", firestoreConnection.document("initial/one"), - "bytes", Blob.fromBytes("abc def".getBytes(StandardCharsets.UTF_8)), - "category", "test" - )); + "value", + 2, + "name", + "two", + "isPlural", + true, + "geo", + new GeoPoint(-90, 90), + "dt", + FieldValue.serverTimestamp(), + "ref", + firestoreConnection.document("initial/one"), + "bytes", + Blob.fromBytes("abc def".getBytes(StandardCharsets.UTF_8)), + "category", + "test")); twoData.put("null-ref", null); firestoreConnection.document("initial/two").set(twoData).get(); - firestoreConnection.document("initial/inner-ref").set(Map.of( - "name", "third", - "data", Map.of( - "ref", firestoreConnection.document("initial/one"), - "isAwesome", false, - "anotherRef", firestoreConnection.document("initial/two") - ), - "ref-list", List.of( - firestoreConnection.document("initial/one"), - firestoreConnection.document("initial/two") - ) - )).get(); + firestoreConnection + .document("initial/inner-ref") + .set(Map.of( + "name", "third", + "data", + Map.of( + "ref", firestoreConnection.document("initial/one"), + "isAwesome", false, + "anotherRef", firestoreConnection.document("initial/two")), + "ref-list", + List.of( + firestoreConnection.document("initial/one"), + firestoreConnection.document("initial/two")))) + .get(); final Map<String, Object> numData = new HashMap<>(Map.of( "score", Integer.valueOf("99"), "isPlural", Boolean.TRUE, "dob", new SimpleDateFormat("yyyy-MM-dd").parse("2000-03-24"), - "start", Timestamp.valueOf("2018-09-01 09:01:15") - )); + "start", Timestamp.valueOf("2018-09-01 09:01:15"))); firestoreConnection.document("numeric/two").set(numData).get(); - firestoreConnection.document("info/family") + firestoreConnection + .document("info/family") .set(Map.of( "kids", Arrays.asList("Ally", "Dolly", "Shelly", "Kelly"), "cars", Arrays.asList("Odyssey", "Dodge"), "wife", "Billy", - "phone_numbers", Arrays.asList(Integer.valueOf("555"), Integer.valueOf("99"), Integer.valueOf("333"), Integer.valueOf("888")) - )) + "phone_numbers", + Arrays.asList( + Integer.valueOf("555"), + Integer.valueOf("99"), + Integer.valueOf("333"), + Integer.valueOf("888")))) .get(); - firestoreConnection.document("changing/to-update").set(Map.of("value", 1)).get(); - firestoreConnection.document("changing/to-delete").set(Map.of("value", 1)).get(); + firestoreConnection + .document("changing/to-update") + .set(Map.of("value", 1)) + .get(); + firestoreConnection + .document("changing/to-delete") + .set(Map.of("value", 1)) + .get(); final CollectionReference paginationCol = firestoreConnection.collection("pagination"); - paginationCol.add(Map.of("n", 1, "name", "Michele Cole", "firm", "Appsmith")).get(); - paginationCol.add(Map.of("n", 2, "name", "Meghan Steele", "firm", "Google")).get(); - paginationCol.add(Map.of("n", 3, "name", "Della Moore", "firm", "Facebook")).get(); - paginationCol.add(Map.of("n", 4, "name", "Eunice Hines", "firm", "Microsoft")).get(); - paginationCol.add(Map.of("n", 5, "name", "Harriet Myers", "firm", "Netflix")).get(); - paginationCol.add(Map.of("n", 6, "name", "Lowell Reese", "firm", "Apple")).get(); - paginationCol.add(Map.of("n", 7, "name", "Gerard Neal", "firm", "Oracle")).get(); + paginationCol + .add(Map.of("n", 1, "name", "Michele Cole", "firm", "Appsmith")) + .get(); + paginationCol + .add(Map.of("n", 2, "name", "Meghan Steele", "firm", "Google")) + .get(); + paginationCol + .add(Map.of("n", 3, "name", "Della Moore", "firm", "Facebook")) + .get(); + paginationCol + .add(Map.of("n", 4, "name", "Eunice Hines", "firm", "Microsoft")) + .get(); + paginationCol + .add(Map.of("n", 5, "name", "Harriet Myers", "firm", "Netflix")) + .get(); + paginationCol + .add(Map.of("n", 6, "name", "Lowell Reese", "firm", "Apple")) + .get(); + paginationCol + .add(Map.of("n", 7, "name", "Gerard Neal", "firm", "Oracle")) + .get(); paginationCol.add(Map.of("n", 8, "name", "Allen Arnold", "firm", "IBM")).get(); - paginationCol.add(Map.of("n", 9, "name", "Josefina Perkins", "firm", "Google")).get(); - paginationCol.add(Map.of("n", 10, "name", "Alvin Zimmerman", "firm", "Facebook")).get(); - paginationCol.add(Map.of("n", 11, "name", "Israel Broc", "firm", "Microsoft")).get(); - paginationCol.add(Map.of("n", 12, "name", "Larry Frazie", "firm", "Netflix")).get(); - paginationCol.add(Map.of("n", 13, "name", "Rufus Green", "firm", "Apple")).get(); - paginationCol.add(Map.of("n", 14, "name", "Marco Murray", "firm", "Oracle")).get(); - paginationCol.add(Map.of("n", 15, "name", "Jeremy Mille", "firm", "IBM")).get(); + paginationCol + .add(Map.of("n", 9, "name", "Josefina Perkins", "firm", "Google")) + .get(); + paginationCol + .add(Map.of("n", 10, "name", "Alvin Zimmerman", "firm", "Facebook")) + .get(); + paginationCol + .add(Map.of("n", 11, "name", "Israel Broc", "firm", "Microsoft")) + .get(); + paginationCol + .add(Map.of("n", 12, "name", "Larry Frazie", "firm", "Netflix")) + .get(); + paginationCol + .add(Map.of("n", 13, "name", "Rufus Green", "firm", "Apple")) + .get(); + paginationCol + .add(Map.of("n", 14, "name", "Marco Murray", "firm", "Oracle")) + .get(); + paginationCol + .add(Map.of("n", 15, "name", "Jeremy Mille", "firm", "IBM")) + .get(); dsConfig.setUrl(emulator.getEmulatorEndpoint()); DBAuth auth = new DBAuth(); @@ -185,8 +233,8 @@ public void testGetSingleDocument() { setDataValueSafelyInFormData(configMap, PATH, "initial/one"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -205,8 +253,13 @@ public void testGetSingleDocument() { */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); expectedRequestParams.add(new RequestParamDTO(COMMAND, "GET_DOCUMENT", null, null, null)); // Method - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), PATH, STRING_TYPE), - null, null, null)); // Path + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_PATH, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), PATH, STRING_TYPE), + null, + null, + null)); // Path assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -221,8 +274,8 @@ public void testGetSingleDocument2() { setDataValueSafelyInFormData(configMap, PATH, "initial/two"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -234,7 +287,9 @@ public void testGetSingleDocument2() { assertEquals(Map.of("path", "initial/one", "id", "one"), doc.remove("ref")); assertEquals(new GeoPoint(-90, 90), doc.remove("geo")); assertNotNull(doc.remove("dt")); - assertEquals("abc def", ((Blob) doc.remove("bytes")).toByteString().toStringUtf8()); + assertEquals( + "abc def", + ((Blob) doc.remove("bytes")).toByteString().toStringUtf8()); assertNull(doc.remove("null-ref")); assertEquals(Map.of("id", "two", "path", "initial/two"), doc.remove("_ref")); assertEquals("test", doc.remove("category")); @@ -252,23 +307,25 @@ public void testGetSingleDocument3() { setDataValueSafelyInFormData(configMap, PATH, "initial/inner-ref"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); final Map<String, Object> doc = (Map) result.getBody(); assertEquals("third", doc.remove("name")); - assertEquals(Map.of( - "ref", Map.of("path", "initial/one", "id", "one"), - "isAwesome", false, - "anotherRef", Map.of("path", "initial/two", "id", "two") - ), doc.remove("data")); - assertEquals(List.of( - Map.of("path", "initial/one", "id", "one"), - Map.of("path", "initial/two", "id", "two") - ), doc.remove("ref-list")); + assertEquals( + Map.of( + "ref", Map.of("path", "initial/one", "id", "one"), + "isAwesome", false, + "anotherRef", Map.of("path", "initial/two", "id", "two")), + doc.remove("data")); + assertEquals( + List.of( + Map.of("path", "initial/one", "id", "one"), + Map.of("path", "initial/two", "id", "two")), + doc.remove("ref-list")); assertEquals(Map.of("id", "inner-ref", "path", "initial/inner-ref"), doc.remove("_ref")); assertEquals(Collections.emptyMap(), doc); }) @@ -284,8 +341,8 @@ public void testGetDocumentsInCollection() { setDataValueSafelyInFormData(configMap, PATH, "initial"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -294,7 +351,10 @@ public void testGetDocumentsInCollection() { List<Map<String, Object>> results = (List) result.getBody(); assertEquals(3, results.size()); - final Map<String, Object> first = results.stream().filter(d -> "one".equals(d.get("name"))).findFirst().orElse(null); + final Map<String, Object> first = results.stream() + .filter(d -> "one".equals(d.get("name"))) + .findFirst() + .orElse(null); assertNotNull(first); assertEquals("one", first.remove("name")); assertFalse((Boolean) first.remove("isPlural")); @@ -303,7 +363,10 @@ public void testGetDocumentsInCollection() { assertEquals("test", first.remove("category")); assertEquals(Collections.emptyMap(), first); - final Map<String, Object> second = results.stream().filter(d -> "two".equals(d.get("name"))).findFirst().orElse(null); + final Map<String, Object> second = results.stream() + .filter(d -> "two".equals(d.get("name"))) + .findFirst() + .orElse(null); assertNotNull(second); assertEquals("two", second.remove("name")); assertTrue((Boolean) second.remove("isPlural")); @@ -311,24 +374,31 @@ public void testGetDocumentsInCollection() { assertEquals(Map.of("path", "initial/one", "id", "one"), second.remove("ref")); assertEquals(new GeoPoint(-90, 90), second.remove("geo")); assertNotNull(second.remove("dt")); - assertEquals("abc def", ((Blob) second.remove("bytes")).toByteString().toStringUtf8()); + assertEquals( + "abc def", + ((Blob) second.remove("bytes")).toByteString().toStringUtf8()); assertNull(second.remove("null-ref")); assertEquals(Map.of("id", "two", "path", "initial/two"), second.remove("_ref")); assertEquals("test", second.remove("category")); assertEquals(Collections.emptyMap(), second); - final Map<String, Object> third = results.stream().filter(d -> "third".equals(d.get("name"))).findFirst().orElse(null); + final Map<String, Object> third = results.stream() + .filter(d -> "third".equals(d.get("name"))) + .findFirst() + .orElse(null); assertNotNull(third); assertEquals("third", third.remove("name")); - assertEquals(Map.of( - "ref", Map.of("path", "initial/one", "id", "one"), - "isAwesome", false, - "anotherRef", Map.of("path", "initial/two", "id", "two") - ), third.remove("data")); - assertEquals(List.of( - Map.of("path", "initial/one", "id", "one"), - Map.of("path", "initial/two", "id", "two") - ), third.remove("ref-list")); + assertEquals( + Map.of( + "ref", Map.of("path", "initial/one", "id", "one"), + "isAwesome", false, + "anotherRef", Map.of("path", "initial/two", "id", "two")), + third.remove("data")); + assertEquals( + List.of( + Map.of("path", "initial/one", "id", "one"), + Map.of("path", "initial/two", "id", "two")), + third.remove("ref-list")); assertEquals(Map.of("id", "inner-ref", "path", "initial/inner-ref"), third.remove("_ref")); assertEquals(Collections.emptyMap(), third); }) @@ -342,14 +412,12 @@ public void testSetNewDocument() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, COMMAND, "SET_DOCUMENT"); setDataValueSafelyInFormData(configMap, PATH, "test/new_with_set"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"firstName\": \"test\",\n" + - " \"lastName\":\"lastTest\"\n" + - "}"); + setDataValueSafelyInFormData( + configMap, BODY, "{\n" + " \"firstName\": \"test\",\n" + " \"lastName\":\"lastTest\"\n" + "}"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -361,10 +429,20 @@ public void testSetNewDocument() { */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); expectedRequestParams.add(new RequestParamDTO(COMMAND, "SET_DOCUMENT", null, null, null)); // Method - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), PATH, STRING_TYPE), - null, null, null)); // Path - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), BODY, STRING_TYPE), null, null, null)); // Body + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_PATH, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), PATH, STRING_TYPE), + null, + null, + null)); // Path + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), BODY, STRING_TYPE), + null, + null, + null)); // Body assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -377,14 +455,12 @@ public void testCreateDocument() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, COMMAND, "CREATE_DOCUMENT"); setDataValueSafelyInFormData(configMap, PATH, "test/new_with_create"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"firstName\": \"test\",\n" + - " \"lastName\":\"lastTest\"\n" + - "}"); + setDataValueSafelyInFormData( + configMap, BODY, "{\n" + " \"firstName\": \"test\",\n" + " \"lastName\":\"lastTest\"\n" + "}"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -396,10 +472,20 @@ public void testCreateDocument() { */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); expectedRequestParams.add(new RequestParamDTO(COMMAND, "CREATE_DOCUMENT", null, null, null)); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), PATH, STRING_TYPE), - null, null, null)); // Path - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), BODY, STRING_TYPE), null, null, null)); // Body + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_PATH, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), PATH, STRING_TYPE), + null, + null, + null)); // Path + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), BODY, STRING_TYPE), + null, + null, + null)); // Body assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -412,19 +498,20 @@ public void testUpdateDocument() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE_DOCUMENT"); setDataValueSafelyInFormData(configMap, PATH, "changing/to-update"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"value\": 2\n" + - "}"); + setDataValueSafelyInFormData(configMap, BODY, "{\n" + " \"value\": 2\n" + "}"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); try { - final DocumentSnapshot documentSnapshot = firestoreConnection.document("changing/to-update").get().get(); + final DocumentSnapshot documentSnapshot = firestoreConnection + .document("changing/to-update") + .get() + .get(); assertTrue(documentSnapshot.exists()); assertEquals(2L, documentSnapshot.getLong("value").longValue()); } catch (NullPointerException | InterruptedException | ExecutionException e) { @@ -443,14 +530,17 @@ public void testDeleteDocument() { setDataValueSafelyInFormData(configMap, PATH, "changing/to-delete"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); try { - final DocumentSnapshot documentSnapshot = firestoreConnection.document("changing/to-delete").get().get(); + final DocumentSnapshot documentSnapshot = firestoreConnection + .document("changing/to-delete") + .get() + .get(); assertFalse(documentSnapshot.exists()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); @@ -462,8 +552,13 @@ public void testDeleteDocument() { */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); expectedRequestParams.add(new RequestParamDTO(COMMAND, "DELETE_DOCUMENT", null, null, null)); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), PATH, STRING_TYPE), - null, null, null)); // Path + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_PATH, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), PATH, STRING_TYPE), + null, + null, + null)); // Path assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -476,15 +571,17 @@ public void testAddToCollection() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, COMMAND, "ADD_TO_COLLECTION"); setDataValueSafelyInFormData(configMap, PATH, "changing"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"question\": \"What is the answer to life, universe and everything else?\",\n" + - " \"answer\": 42\n" + - "}"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " \"question\": \"What is the answer to life, universe and everything else?\",\n" + + " \"answer\": 42\n" + + "}"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -497,10 +594,20 @@ public void testAddToCollection() { */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); expectedRequestParams.add(new RequestParamDTO(COMMAND, "ADD_TO_COLLECTION", null, null, null)); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), PATH, STRING_TYPE), - null, null, null)); // Path - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), BODY, STRING_TYPE), null, null, null)); // Body + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_PATH, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), PATH, STRING_TYPE), + null, + null, + null)); // Path + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), BODY, STRING_TYPE), + null, + null, + null)); // Body assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -529,7 +636,8 @@ private ActionConfiguration constructActionConfiguration(Map<String, Object> fir return actionConfiguration; } - private Mono<ActionExecutionResult> getNextOrPrevPage(ActionExecutionResult currentPage, PaginationField paginationField) { + private Mono<ActionExecutionResult> getNextOrPrevPage( + ActionExecutionResult currentPage, PaginationField paginationField) { List<Map<String, Object>> results = (List) currentPage.getBody(); final Map<String, Object> first = results.get(0); final Map<String, Object> last = results.get(results.size() - 1); @@ -579,30 +687,37 @@ public void testPagination() { assertEquals(5, firstResults.size()); assertEquals( "[1, 2, 3, 4, 5]", - firstResults.stream().map(m -> m.get("n").toString()).collect(Collectors.toList()).toString() - ); + firstResults.stream() + .map(m -> m.get("n").toString()) + .collect(Collectors.toList()) + .toString()); List<Map<String, Object>> secondResults = (List) secondPageResult.getBody(); assertEquals(5, secondResults.size()); assertEquals( "[6, 7, 8, 9, 10]", - secondResults.stream().map(m -> m.get("n").toString()).collect(Collectors.toList()).toString() - ); + secondResults.stream() + .map(m -> m.get("n").toString()) + .collect(Collectors.toList()) + .toString()); List<Map<String, Object>> firstResultsAgain = (List) thirdPageResult.getBody(); assertEquals(5, firstResultsAgain.size()); assertEquals( "[11, 12, 13, 14, 15]", - firstResultsAgain.stream().map(m -> m.get("n").toString()).collect(Collectors.toList()).toString() - ); + firstResultsAgain.stream() + .map(m -> m.get("n").toString()) + .collect(Collectors.toList()) + .toString()); List<Map<String, Object>> secondResultsAgain = (List) secondPageResultAgain.getBody(); assertEquals(5, secondResultsAgain.size()); assertEquals( "[6, 7, 8, 9, 10]", - secondResultsAgain.stream().map(m -> m.get("n").toString()).collect(Collectors.toList()).toString() - ); - + secondResultsAgain.stream() + .map(m -> m.get("n").toString()) + .collect(Collectors.toList()) + .toString()); }) .verifyComplete(); } @@ -627,7 +742,9 @@ public void testDatasourceCreateErrorOnBadServiceAccountCredentials() { error.getMessage()); // Check that the error does not get logged externally. - assertNotEquals(AppsmithErrorAction.LOG_EXTERNALLY, ((AppsmithPluginException) error).getError().getErrorAction()); + assertNotEquals( + AppsmithErrorAction.LOG_EXTERNALLY, + ((AppsmithPluginException) error).getError().getErrorAction()); }) .verify(); } @@ -652,7 +769,7 @@ public void testDatasource_withCorrectCredentials_returnsWithoutInvalids() { @Test public void testDatasource_withValidProjectId_WithoutMetaDataAccess() { - //This test validates the Firestore connection, not the ProjectId given by the user + // This test validates the Firestore connection, not the ProjectId given by the user FirestorePlugin.FirestorePluginExecutor spyExecutor = Mockito.spy(pluginExecutor); Mockito.when(spyExecutor.datasourceCreate(dsConfig)).thenReturn(Mono.just(firestoreConnection)); final Mono<DatasourceTestResult> testDatasourceMono = spyExecutor.testDatasource(dsConfig); @@ -663,8 +780,8 @@ public void testDatasource_withValidProjectId_WithoutMetaDataAccess() { assertTrue(datasourceTestResult.isSuccess()); assertTrue(datasourceTestResult.getInvalids().isEmpty()); assertFalse(datasourceTestResult.getMessages().isEmpty()); - assertTrue(datasourceTestResult.getMessages().stream().anyMatch(s -> s.equals(FirestoreErrorMessages - .META_DATA_ACCESS_MISSING_MESSAGE))); + assertTrue(datasourceTestResult.getMessages().stream() + .anyMatch(s -> s.equals(FirestoreErrorMessages.META_DATA_ACCESS_MISSING_MESSAGE))); }) .verifyComplete(); } @@ -672,10 +789,10 @@ public void testDatasource_withValidProjectId_WithoutMetaDataAccess() { @Test public void testDatasource_withInvalidProjectId_WithMetaDataAccess() { - //This validates firestore connection and the ProjectId given by the user + // This validates firestore connection and the ProjectId given by the user FirestorePlugin.FirestorePluginExecutor spyExecutor = Mockito.spy(pluginExecutor); - //We cannot use the datasource create flow here as the client authentication json is unknown. Hence, using the - //default emulator credentials + // We cannot use the datasource create flow here as the client authentication json is unknown. Hence, using the + // default emulator credentials FirebaseOptions firebaseOptions = FirebaseOptions.builder() .setProjectId("test-project-invalid") .setDatabaseUrl(emulator.getEmulatorEndpoint()) @@ -691,8 +808,8 @@ public void testDatasource_withInvalidProjectId_WithMetaDataAccess() { assertNotNull(datasourceTestResult); assertFalse(datasourceTestResult.isSuccess()); assertFalse(datasourceTestResult.getInvalids().isEmpty()); - assertTrue(datasourceTestResult.getInvalids().stream().anyMatch(s -> s.equals( - FirestoreErrorMessages.DS_CONNECTION_FAILED_FOR_PROJECT_ID))); + assertTrue(datasourceTestResult.getInvalids().stream() + .anyMatch(s -> s.equals(FirestoreErrorMessages.DS_CONNECTION_FAILED_FOR_PROJECT_ID))); }) .verifyComplete(); } @@ -708,8 +825,8 @@ public void testGetDocumentsInCollectionOrdering() { setDataValueSafelyInFormData(configMap, PATH, "pagination"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -718,7 +835,8 @@ public void testGetDocumentsInCollectionOrdering() { List<Map<String, Object>> results = (List) result.getBody(); assertEquals(15, results.size()); - final List<Object> names = results.stream().map(d -> d.get("name")).collect(Collectors.toList()); + final List<Object> names = + results.stream().map(d -> d.get("name")).collect(Collectors.toList()); assertEquals( List.of( "Lowell Reese", @@ -735,10 +853,8 @@ public void testGetDocumentsInCollectionOrdering() { "Harriet Myers", "Larry Frazie", "Gerard Neal", - "Marco Murray" - ), - names - ); + "Marco Murray"), + names); /* * - RequestParamDTO object only have attributes configProperty and value at this point. @@ -746,9 +862,15 @@ public void testGetDocumentsInCollectionOrdering() { */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); expectedRequestParams.add(new RequestParamDTO(COMMAND, "GET_COLLECTION", null, null, null)); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), PATH, STRING_TYPE), - null, null, null)); // Path - expectedRequestParams.add(new RequestParamDTO(ORDER_BY, "[\"firm\", \"name\"]", null, null, null)); // Order by + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_PATH, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), PATH, STRING_TYPE), + null, + null, + null)); // Path + expectedRequestParams.add( + new RequestParamDTO(ORDER_BY, "[\"firm\", \"name\"]", null, null, null)); // Order by expectedRequestParams.add(new RequestParamDTO(START_AFTER, "{}", null, null, null)); // Start after expectedRequestParams.add(new RequestParamDTO(END_BEFORE, "{}", null, null, null)); // End before expectedRequestParams.add(new RequestParamDTO(LIMIT_DOCUMENTS, "15", null, null, null)); // Limit @@ -768,8 +890,8 @@ public void testGetDocumentsInCollectionOrdering2() { setDataValueSafelyInFormData(configMap, PATH, "pagination"); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -778,7 +900,8 @@ public void testGetDocumentsInCollectionOrdering2() { List<Map<String, Object>> results = (List) result.getBody(); assertEquals(15, results.size()); - final List<Object> names = results.stream().map(d -> d.get("name")).collect(Collectors.toList()); + final List<Object> names = + results.stream().map(d -> d.get("name")).collect(Collectors.toList()); assertEquals( List.of( "Rufus Green", @@ -795,11 +918,8 @@ public void testGetDocumentsInCollectionOrdering2() { "Larry Frazie", "Harriet Myers", "Marco Murray", - "Gerard Neal" - ), - names - ); - + "Gerard Neal"), + names); }) .verifyComplete(); } @@ -815,21 +935,25 @@ public void testWhereConditional() { * - get all documents where category == test. * - this returns 2 documents. */ - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "EQ"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "EQ"); + put("value", "{{Input2.text}}"); + } + }); /* * - get all documents where name == two. * - Of the two documents returned by above condition, this will narrow it down to one. */ - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input3.text}}"); - put("condition", "EQ"); - put("value", "{{Input4.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input3.text}}"); + put("condition", "EQ"); + put("value", "{{Input4.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -859,8 +983,8 @@ public void testWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -869,7 +993,8 @@ public void testWhereConditional() { List<Map<String, Object>> results = (List) result.getBody(); assertEquals(1, results.size()); - final Map<String, Object> second = results.stream().findFirst().orElse(null); + final Map<String, Object> second = + results.stream().findFirst().orElse(null); assertNotNull(second); assertEquals("two", second.remove("name")); assertTrue((Boolean) second.remove("isPlural")); @@ -877,7 +1002,9 @@ public void testWhereConditional() { assertEquals(Map.of("path", "initial/one", "id", "one"), second.remove("ref")); assertEquals(new GeoPoint(-90, 90), second.remove("geo")); assertNotNull(second.remove("dt")); - assertEquals("abc def", ((Blob) second.remove("bytes")).toByteString().toStringUtf8()); + assertEquals( + "abc def", + ((Blob) second.remove("bytes")).toByteString().toStringUtf8()); assertNull(second.remove("null-ref")); assertEquals(Map.of("id", "two", "path", "initial/two"), second.remove("_ref")); assertEquals("test", second.remove("category")); @@ -892,11 +1019,13 @@ public void testNumberWhereConditional() { setDataValueSafelyInFormData(configMap, COMMAND, "GET_COLLECTION"); List<Object> children = new ArrayList<>(); - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "EQ"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "EQ"); + put("value", "{{Input2.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -918,8 +1047,8 @@ public void testNumberWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -936,11 +1065,13 @@ public void testBooleanWhereConditional() { setDataValueSafelyInFormData(configMap, COMMAND, "GET_COLLECTION"); List<Object> children = new ArrayList<>(); - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "EQ"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "EQ"); + put("value", "{{Input2.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -962,8 +1093,8 @@ public void testBooleanWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -980,11 +1111,13 @@ public void testDateWhereConditional() { setDataValueSafelyInFormData(configMap, COMMAND, "GET_COLLECTION"); List<Object> children = new ArrayList<>(); - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "EQ"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "EQ"); + put("value", "{{Input2.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -1006,8 +1139,8 @@ public void testDateWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1024,11 +1157,13 @@ public void testTimeStampWhereConditional() { setDataValueSafelyInFormData(configMap, COMMAND, "GET_COLLECTION"); List<Object> children = new ArrayList<>(); - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "EQ"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "EQ"); + put("value", "{{Input2.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -1049,8 +1184,8 @@ public void testTimeStampWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1067,11 +1202,13 @@ public void testArrayContainsWhereConditional() { setDataValueSafelyInFormData(configMap, COMMAND, "GET_COLLECTION"); List<Object> children = new ArrayList<>(); - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "ARRAY_CONTAINS"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "ARRAY_CONTAINS"); + put("value", "{{Input2.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -1092,8 +1229,8 @@ public void testArrayContainsWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1102,7 +1239,6 @@ public void testArrayContainsWhereConditional() { assertEquals(1, results.size()); }) .verifyComplete(); - } @Test @@ -1111,11 +1247,13 @@ public void testArrayContainsNumberWhereConditional() { setDataValueSafelyInFormData(configMap, COMMAND, "GET_COLLECTION"); List<Object> children = new ArrayList<>(); - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "ARRAY_CONTAINS"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "ARRAY_CONTAINS"); + put("value", "{{Input2.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -1136,8 +1274,8 @@ public void testArrayContainsNumberWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1148,18 +1286,19 @@ public void testArrayContainsNumberWhereConditional() { .verifyComplete(); } - @Test public void testArrayContainsAnyWhereConditional() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, COMMAND, "GET_COLLECTION"); List<Object> children = new ArrayList<>(); - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "ARRAY_CONTAINS_ANY"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "ARRAY_CONTAINS_ANY"); + put("value", "{{Input2.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -1180,8 +1319,8 @@ public void testArrayContainsAnyWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1198,11 +1337,13 @@ public void testArrayInWhereConditional() { setDataValueSafelyInFormData(configMap, COMMAND, "GET_COLLECTION"); List<Object> children = new ArrayList<>(); - children.add(new HashMap<String, Object>() {{ - put("key", "{{Input1.text}}"); - put("condition", "IN"); - put("value", "{{Input2.text}}"); - }}); + children.add(new HashMap<String, Object>() { + { + put("key", "{{Input1.text}}"); + put("condition", "IN"); + put("value", "{{Input2.text}}"); + } + }); Map<String, Object> whereMap = new HashMap<>(); whereMap.put(CHILDREN, children); @@ -1223,8 +1364,8 @@ public void testArrayInWhereConditional() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1235,7 +1376,6 @@ public void testArrayInWhereConditional() { .verifyComplete(); } - @Test public void testUpdateDocumentWithFieldValueTimestamp() { @@ -1243,21 +1383,22 @@ public void testUpdateDocumentWithFieldValueTimestamp() { setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE_DOCUMENT"); setDataValueSafelyInFormData(configMap, TIMESTAMP_VALUE_PATH, "[\"value\"]"); setDataValueSafelyInFormData(configMap, PATH, "changing/to-update"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"value\": 2\n" + - "}"); + setDataValueSafelyInFormData(configMap, BODY, "{\n" + " \"value\": 2\n" + "}"); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); try { - final DocumentSnapshot documentSnapshot = firestoreConnection.document("changing/to-update").get().get(); + final DocumentSnapshot documentSnapshot = firestoreConnection + .document("changing/to-update") + .get() + .get(); assertTrue(documentSnapshot.exists()); try { @@ -1287,15 +1428,13 @@ public void testUpdateDocumentWithFieldValueDelete() { setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE_DOCUMENT"); setDataValueSafelyInFormData(configMap, DELETE_KEY_PATH, "[\"value\"]"); setDataValueSafelyInFormData(configMap, PATH, "changing/to-update"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"value\": 2\n" + - "}"); + setDataValueSafelyInFormData(configMap, BODY, "{\n" + " \"value\": 2\n" + "}"); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); /* * - Delete key. @@ -1310,11 +1449,22 @@ public void testUpdateDocumentWithFieldValueDelete() { */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); expectedRequestParams.add(new RequestParamDTO(COMMAND, "UPDATE_DOCUMENT", null, null, null)); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_PATH, PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), PATH, STRING_TYPE), - null, null, null)); // Path - expectedRequestParams.add(new RequestParamDTO(DELETE_KEY_PATH, "[\"value\"]", null, null, null)); // Method - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), BODY, STRING_TYPE), null, null, null)); // Body + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_PATH, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), PATH, STRING_TYPE), + null, + null, + null)); // Path + expectedRequestParams.add( + new RequestParamDTO(DELETE_KEY_PATH, "[\"value\"]", null, null, null)); // Method + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), BODY, STRING_TYPE), + null, + null, + null)); // Body assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -1323,8 +1473,8 @@ public void testUpdateDocumentWithFieldValueDelete() { setDataValueSafelyInFormData(configMap, PATH, "changing/to-update"); setDataValueSafelyInFormData(configMap, BODY, ""); setDataValueSafelyInFormData(configMap, COMMAND, "GET_DOCUMENT"); - resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); /* * - Verify that the key does not exist in the list of keys returned by reading the document. @@ -1344,25 +1494,23 @@ public void testFieldValueDeleteWithUnsupportedAction() { setDataValueSafelyInFormData(configMap, COMMAND, "CREATE_DOCUMENT"); setDataValueSafelyInFormData(configMap, DELETE_KEY_PATH, "[\"value\"]"); setDataValueSafelyInFormData(configMap, PATH, "changing/to-update"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"value\": 2\n" + - "}"); + setDataValueSafelyInFormData(configMap, BODY, "{\n" + " \"value\": 2\n" + "}"); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String expectedErrorMessage = FirestoreErrorMessages.UNEXPECTED_PROPERTY_DELETE_KEY_PATH_ERROR_MSG; - assertTrue(expectedErrorMessage.equals(result.getPluginErrorDetails().getAppsmithErrorMessage())); + assertTrue(expectedErrorMessage.equals( + result.getPluginErrorDetails().getAppsmithErrorMessage())); assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); - } @Test @@ -1371,21 +1519,20 @@ public void testFieldValueTimestampWithUnsupportedAction() { setDataValueSafelyInFormData(configMap, COMMAND, "GET_DOCUMENT"); setDataValueSafelyInFormData(configMap, TIMESTAMP_VALUE_PATH, "[\"value\"]"); setDataValueSafelyInFormData(configMap, PATH, "changing/to-update"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"value\": 2\n" + - "}"); + setDataValueSafelyInFormData(configMap, BODY, "{\n" + " \"value\": 2\n" + "}"); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String expectedErrorMessage = FirestoreErrorMessages.UNEXPECTED_PROPERTY_TIMESTAMP_ERROR_MSG; - assertTrue(expectedErrorMessage.equals(result.getPluginErrorDetails().getAppsmithErrorMessage())); + assertTrue(expectedErrorMessage.equals( + result.getPluginErrorDetails().getAppsmithErrorMessage())); assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); @@ -1397,21 +1544,20 @@ public void testFieldValueDeleteWithBadArgument() { setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE_DOCUMENT"); setDataValueSafelyInFormData(configMap, DELETE_KEY_PATH, "value"); setDataValueSafelyInFormData(configMap, PATH, "changing/to-update"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"value\": 2\n" + - "}"); + setDataValueSafelyInFormData(configMap, BODY, "{\n" + " \"value\": 2\n" + "}"); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); String expectedErrorMessage = FirestoreErrorMessages.FAILED_TO_PARSE_DELETE_KEY_PATH_ERROR_MSG; - assertTrue(expectedErrorMessage.equals(result.getPluginErrorDetails().getAppsmithErrorMessage())); + assertTrue(expectedErrorMessage.equals( + result.getPluginErrorDetails().getAppsmithErrorMessage())); assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); @@ -1423,22 +1569,20 @@ public void testFieldValueTimestampWithBadArgument() { setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE_DOCUMENT"); setDataValueSafelyInFormData(configMap, TIMESTAMP_VALUE_PATH, "value"); setDataValueSafelyInFormData(configMap, PATH, "changing/to-update"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " \"value\": 2\n" + - "}"); + setDataValueSafelyInFormData(configMap, BODY, "{\n" + " \"value\": 2\n" + "}"); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setFormData(configMap); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration); StepVerifier.create(resultMono) .assertNext(result -> { - assertFalse(result.getIsExecutionSuccess()); String expectedErrorMessage = FirestoreErrorMessages.FAILED_TO_PARSE_TIMESTAMP_VALUE_PATH_ERROR_MSG; - assertTrue(expectedErrorMessage.equals(result.getPluginErrorDetails().getAppsmithErrorMessage())); + assertTrue(expectedErrorMessage.equals( + result.getPluginErrorDetails().getAppsmithErrorMessage())); assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); }) .verifyComplete(); @@ -1460,11 +1604,13 @@ public void testDynamicBindingSubstitutionInActionConfiguration() { * - get all documents where category == test. * - this returns 2 documents. */ - ((List) whereProperty.getValue()).add(new HashMap<String, Object>() {{ - put("path", "{{Input2.text}}"); - put("operator", "EQ"); - put("value", "{{Input3.text}}"); - }}); + ((List) whereProperty.getValue()).add(new HashMap<String, Object>() { + { + put("path", "{{Input2.text}}"); + put("operator", "EQ"); + put("value", "{{Input3.text}}"); + } + }); pluginSpecifiedTemplates.add(whereProperty); actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates); @@ -1486,17 +1632,26 @@ public void testDynamicBindingSubstitutionInActionConfiguration() { executeActionDTO.setParams(params); // Substitute dynamic binding values - pluginExecutor - .prepareConfigurationsForExecution(executeActionDTO, actionConfiguration, null); + pluginExecutor.prepareConfigurationsForExecution(executeActionDTO, actionConfiguration, null); // check if dynamic binding values have been substituted correctly assertEquals("initial", actionConfiguration.getPath()); - assertEquals("category", - ((Map) ((List) actionConfiguration.getPluginSpecifiedTemplates().get(3).getValue()).get(0)).get( - "path")); - assertEquals("test", - ((Map) ((List) actionConfiguration.getPluginSpecifiedTemplates().get(3).getValue()).get(0)).get( - "value")); + assertEquals( + "category", + ((Map) ((List) actionConfiguration + .getPluginSpecifiedTemplates() + .get(3) + .getValue()) + .get(0)) + .get("path")); + assertEquals( + "test", + ((Map) ((List) actionConfiguration + .getPluginSpecifiedTemplates() + .get(3) + .getValue()) + .get(0)) + .get("value")); } @Test @@ -1509,12 +1664,14 @@ public void testJsonSmartSubstitution() { Map<String, Object> configMap1 = new HashMap<>(); setDataValueSafelyInFormData(configMap1, COMMAND, "CREATE_DOCUMENT"); setDataValueSafelyInFormData(configMap1, PATH, "test/json_smart_substitution_test"); - setDataValueSafelyInFormData(configMap1, BODY, "{\n" + - " \"firstName\":{{Input1.text}},\n" + - " \"lastName\":{{Input2.text}},\n" + - " \"locationPreferences\":{{Input3.text}},\n" + - " \"testScores\":{{Input4.text}}\n" + - "}"); + setDataValueSafelyInFormData( + configMap1, + BODY, + "{\n" + " \"firstName\":{{Input1.text}},\n" + + " \"lastName\":{{Input2.text}},\n" + + " \"locationPreferences\":{{Input3.text}},\n" + + " \"testScores\":{{Input4.text}}\n" + + "}"); ActionConfiguration actionConfiguration1 = new ActionConfiguration(); actionConfiguration1.setFormData(configMap1); @@ -1544,8 +1701,8 @@ public void testJsonSmartSubstitution() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor - .executeParameterized(firestoreConnection, executeActionDTO, dsConfig, actionConfiguration1); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + firestoreConnection, executeActionDTO, dsConfig, actionConfiguration1); StepVerifier.create(resultMono) .assertNext(result -> assertTrue(result.getIsExecutionSuccess())) @@ -1559,8 +1716,8 @@ public void testJsonSmartSubstitution() { ActionConfiguration actionConfiguration2 = new ActionConfiguration(); actionConfiguration2.setFormData(configMap2); - Mono<ActionExecutionResult> resultMono2 = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration2); + Mono<ActionExecutionResult> resultMono2 = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration2); StepVerifier.create(resultMono2) .assertNext(result -> { @@ -1570,8 +1727,13 @@ public void testJsonSmartSubstitution() { assertEquals("Von Neumann", first.get("lastName")); assertEquals("Zuric", ((List) first.get("locationPreferences")).get(0)); assertEquals("Gottingen", ((List) first.get("locationPreferences")).get(1)); - assertEquals("100", ((Map) first.get("testScores")).get("computational complexity").toString()); - assertEquals("100", ((Map) first.get("testScores")).get("math").toString()); + assertEquals( + "100", + ((Map) first.get("testScores")) + .get("computational complexity") + .toString()); + assertEquals( + "100", ((Map) first.get("testScores")).get("math").toString()); }) .verifyComplete(); @@ -1583,15 +1745,17 @@ public void testJsonSmartSubstitution() { ActionConfiguration actionConfiguration3 = new ActionConfiguration(); actionConfiguration3.setFormData(configMap3); - Mono<ActionExecutionResult> resultMono3 = pluginExecutor - .executeParameterized(firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration3); + Mono<ActionExecutionResult> resultMono3 = pluginExecutor.executeParameterized( + firestoreConnection, new ExecuteActionDTO(), dsConfig, actionConfiguration3); StepVerifier.create(resultMono3) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); try { - final DocumentSnapshot documentSnapshot = firestoreConnection.document("test" + - "/json_smart_substitution_test").get().get(); + final DocumentSnapshot documentSnapshot = firestoreConnection + .document("test" + "/json_smart_substitution_test") + .get() + .get(); assertFalse(documentSnapshot.exists()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); @@ -1602,11 +1766,17 @@ public void testJsonSmartSubstitution() { @Test public void verifyUniquenessOfFirestorePluginErrorCode() { - assert (Arrays.stream(FirestorePluginError.values()).map(FirestorePluginError::getAppErrorCode).distinct().count() == FirestorePluginError.values().length); - - assert (Arrays.stream(FirestorePluginError.values()).map(FirestorePluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-FST")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(FirestorePluginError.values()) + .map(FirestorePluginError::getAppErrorCode) + .distinct() + .count() + == FirestorePluginError.values().length); + + assert (Arrays.stream(FirestorePluginError.values()) + .map(FirestorePluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-FST")) + .collect(Collectors.toList()) + .size() + == 0); } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/pom.xml b/app/server/appsmith-plugins/googleSheetsPlugin/pom.xml index 6d00b48c05ee..a966367df516 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/pom.xml +++ b/app/server/appsmith-plugins/googleSheetsPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>googleSheetsPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -68,7 +67,8 @@ </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> - <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --> + <artifactId>jjwt-jackson</artifactId> + <!-- or jjwt-gson if Gson is preferred --> <version>${jjwt.version}</version> </dependency> @@ -116,10 +116,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy</goal> </goals> + <phase>package</phase> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <artifactItems> diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/ClearMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/ClearMethod.java index 0e1266f9a793..1e4158792b27 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/ClearMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/ClearMethod.java @@ -25,31 +25,34 @@ public ClearMethod(ObjectMapper objectMapper) { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } - if (methodConfig.getSpreadsheetRange() == null || methodConfig.getSpreadsheetRange().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_CELL_RANGE_ERROR_MSG); + if (methodConfig.getSpreadsheetRange() == null + || methodConfig.getSpreadsheetRange().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_CELL_RANGE_ERROR_MSG); } return true; - } @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + "/values/" - + URLEncoder.encode(methodConfig.getSpreadsheetRange(), StandardCharsets.UTF_8) /* spreadsheet Range */ + + URLEncoder.encode( + methodConfig.getSpreadsheetRange(), StandardCharsets.UTF_8) /* spreadsheet Range */ + ":clear", - true - ); + true); - return webClient.method(HttpMethod.POST) + return webClient + .method(HttpMethod.POST) .uri(uriBuilder.build(true).toUri()) .body(BodyInserters.empty()); } - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/CopyMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/CopyMethod.java index df2acddba048..72eb8c2043df 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/CopyMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/CopyMethod.java @@ -22,11 +22,14 @@ public CopyMethod(ObjectMapper objectMapper) { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } if (methodConfig.getSheetId() == null || methodConfig.getSheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SHEET_ID_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SHEET_ID_ERROR_MSG); } return true; } @@ -34,17 +37,17 @@ public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + "/sheets/" + methodConfig.getSheetId() /* sheet Id*/ + ":copyTo", - true - ); + true); - return webClient.method(HttpMethod.POST) + return webClient + .method(HttpMethod.POST) .uri(uriBuilder.build(true).toUri()) .body(BodyInserters.fromObject(methodConfig.getRowObjects())); } - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/ExecutionMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/ExecutionMethod.java index 0f9b3d438a97..ae6bef0a7c94 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/ExecutionMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/ExecutionMethod.java @@ -29,8 +29,7 @@ public interface ExecutionMethod { String BASE_DRIVE_API_URL = "https://www.googleapis.com/drive/v3/files/"; - ExchangeStrategies EXCHANGE_STRATEGIES = ExchangeStrategies - .builder() + ExchangeStrategies EXCHANGE_STRATEGIES = ExchangeStrategies.builder() .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(/* 10MB */ 10 * 1024 * 1024)) .build(); @@ -43,18 +42,31 @@ default UriComponentsBuilder getBaseUriBuilder(String baseUri, String path, bool try { String decodedURL = URLDecoder.decode(baseUri + path, StandardCharsets.UTF_8); URL url = new URL(decodedURL); - URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); + URI uri = new URI( + url.getProtocol(), + url.getUserInfo(), + url.getHost(), + url.getPort(), + url.getPath(), + url.getQuery(), + url.getRef()); UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance(); return uriBuilder.uri(uri); } catch (URISyntaxException | MalformedURLException e) { - throw Exceptions.propagate(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.UNABLE_TO_CREATE_URI_ERROR_MSG, e.getMessage())); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.UNABLE_TO_CREATE_URI_ERROR_MSG, + e.getMessage())); } } else { try { UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance(); return uriBuilder.uri(new URI(baseUri + path)); } catch (URISyntaxException e) { - throw Exceptions.propagate(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.UNABLE_TO_CREATE_URI_ERROR_MSG, e.getMessage())); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.UNABLE_TO_CREATE_URI_ERROR_MSG, + e.getMessage())); } } } @@ -67,11 +79,11 @@ default Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oaut WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig); - default JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + default JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG)); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG)); } // By default, no transformation takes place return response; diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileCreateMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileCreateMethod.java index 552d4012fe80..76f3f1aa308d 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileCreateMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileCreateMethod.java @@ -46,7 +46,8 @@ public FileCreateMethod(ObjectMapper objectMapper) { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetName() == null || methodConfig.getSpreadsheetName().isBlank()) { + if (methodConfig.getSpreadsheetName() == null + || methodConfig.getSpreadsheetName().isBlank()) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); @@ -82,12 +83,11 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M sheet.setData(List.of(gridData)); final Map<Integer, RowObject> collectedRows = StreamSupport.stream(bodyNode.spliterator(), false) - .map(rowJson -> - { - RowObject rowObject = new RowObject( - this.objectMapper.convertValue(rowJson, TypeFactory - .defaultInstance() - .constructMapType(LinkedHashMap.class, String.class, String.class))) + .map(rowJson -> { + RowObject rowObject = new RowObject(this.objectMapper.convertValue( + rowJson, + TypeFactory.defaultInstance() + .constructMapType(LinkedHashMap.class, String.class, String.class))) .initialize(); if (ref.startingRow == null || rowObject.getCurrentRowIndex() < ref.startingRow) { ref.startingRow = rowObject.getCurrentRowIndex(); @@ -100,26 +100,25 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M if (ref.headers.isEmpty()) { ref.headers.addAll(rowObject.getValueMap().keySet()); } else { - ref.unknownHeaders.addAll(rowObject.getValueMap().keySet()); + ref.unknownHeaders.addAll( + rowObject.getValueMap().keySet()); } return rowObject; }) .collect(Collectors.toUnmodifiableMap( - RowObject::getCurrentRowIndex, - rowObject -> rowObject, - (a, b) -> b)); + RowObject::getCurrentRowIndex, rowObject -> rowObject, (a, b) -> b)); ref.headers.addAll(ref.unknownHeaders); -// if (!ref.unknownHeaders.isEmpty()) { -// throw new AppsmithPluginException( -// AppsmithPluginError.PLUGIN_ERROR, -// "Unable to parse request body. " + -// "Expected all row objects to have same headers. " + -// "Found extra headers:" -// + ref.unknownHeaders); -// } + // if (!ref.unknownHeaders.isEmpty()) { + // throw new AppsmithPluginException( + // AppsmithPluginError.PLUGIN_ERROR, + // "Unable to parse request body. " + + // "Expected all row objects to have same headers. " + + // "Found extra headers:" + // + ref.unknownHeaders); + // } ref.startingRow = ref.startingRow > 0 ? ref.startingRow : 0; gridData.setStartRow(0); @@ -128,14 +127,18 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M final String[] headerArray = ref.headers.toArray(new String[ref.headers.size()]); List<RowData> collect = IntStream.range(0, ref.endingRow + 1) - .mapToObj(rowIndex -> collectedRows.getOrDefault(rowIndex, new RowObject(new LinkedHashMap<>()))) + .mapToObj( + rowIndex -> collectedRows.getOrDefault(rowIndex, new RowObject(new LinkedHashMap<>()))) .map(row -> row.getAsSheetRowData(headerArray)) .collect(Collectors.toCollection(ArrayList::new)); - collect.add(0, new RowData() - .setValues(Arrays.stream(headerArray) - .map(header -> new CellData().setUserEnteredValue(new ExtendedValue().setStringValue(header))) - .collect(Collectors.toList()))); + collect.add( + 0, + new RowData() + .setValues(Arrays.stream(headerArray) + .map(header -> new CellData() + .setUserEnteredValue(new ExtendedValue().setStringValue(header))) + .collect(Collectors.toList()))); gridData.setRowData(collect); @@ -149,7 +152,8 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, "", true); - return webClient.method(HttpMethod.POST) + return webClient + .method(HttpMethod.POST) .uri(uriBuilder.build(true).toUri()) .body(BodyInserters.fromValue(spreadsheet)); } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileDeleteMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileDeleteMethod.java index 7771b4296050..c7b5e7cfcbac 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileDeleteMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileDeleteMethod.java @@ -28,8 +28,10 @@ public FileDeleteMethod(ObjectMapper objectMapper) { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } return true; } @@ -42,27 +44,22 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_DRIVE_API_URL, - methodConfig.getSpreadsheetId(), /* spreadsheet Id */ - true - ); - - return webClient.method(HttpMethod.DELETE) - .uri(uriBuilder.build(true).toUri()); + UriComponentsBuilder uriBuilder = + getBaseUriBuilder(this.BASE_DRIVE_API_URL, methodConfig.getSpreadsheetId(), /* spreadsheet Id */ true); + return webClient.method(HttpMethod.DELETE).uri(uriBuilder.build(true).toUri()); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } String errorMessage = "Deleted spreadsheet successfully!"; return this.objectMapper.valueToTree(Map.of("message", errorMessage)); } - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileInfoMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileInfoMethod.java index e94fd0ac5b7a..e43d2e2ceab7 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileInfoMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileInfoMethod.java @@ -37,57 +37,58 @@ public FileInfoMethod(ObjectMapper objectMapper) { @Override public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth2) { - WebClient client = WebClientUtils.builder() - .exchangeStrategies(EXCHANGE_STRATEGIES) - .build(); - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, - methodConfig.getSpreadsheetId()); + WebClient client = + WebClientUtils.builder().exchangeStrategies(EXCHANGE_STRATEGIES).build(); + UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId()); uriBuilder.queryParam("fields", "sheets/properties"); return client.method(HttpMethod.GET) - .uri(uriBuilder.build(false).toUri()) - .body(BodyInserters.empty()) - .headers(headers -> headers.set( - "Authorization", - "Bearer " + oauth2.getAuthenticationResponse().getToken())) - .exchange() - .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) - .map(response -> {// Choose body depending on response status - byte[] responseBody = response.getBody(); - - if (responseBody == null || !response.getStatusCode().is2xxSuccessful()) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); - } - String jsonBody = new String(responseBody); - JsonNode sheets = null; - try { - sheets = objectMapper.readTree(jsonBody).get("sheets"); - } catch (IOException e) { - throw Exceptions.propagate(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(responseBody), - e.getMessage() - )); - } - - assert sheets != null; - List<JsonNode> sheetMetadata = new ArrayList<>(); - for (JsonNode sheet : sheets) { - final JsonNode properties = sheet.get("properties"); - if (!properties.get("title").asText().isEmpty()) { - sheetMetadata.add(properties); - } - } - methodConfig.setBody(sheetMetadata); - return methodConfig; - }); + .uri(uriBuilder.build(false).toUri()) + .body(BodyInserters.empty()) + .headers(headers -> headers.set( + "Authorization", + "Bearer " + oauth2.getAuthenticationResponse().getToken())) + .exchange() + .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) + .map( + response -> { // Choose body depending on response status + byte[] responseBody = response.getBody(); + + if (responseBody == null + || !response.getStatusCode().is2xxSuccessful()) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); + } + String jsonBody = new String(responseBody); + JsonNode sheets = null; + try { + sheets = objectMapper.readTree(jsonBody).get("sheets"); + } catch (IOException e) { + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, + new String(responseBody), + e.getMessage())); + } + + assert sheets != null; + List<JsonNode> sheetMetadata = new ArrayList<>(); + for (JsonNode sheet : sheets) { + final JsonNode properties = sheet.get("properties"); + if (!properties.get("title").asText().isEmpty()) { + sheetMetadata.add(properties); + } + } + methodConfig.setBody(sheetMetadata); + return methodConfig; + }); } @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } return true; @@ -96,21 +97,23 @@ public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_DRIVE_API_URL, - methodConfig.getSpreadsheetId() + - "?fields=id,name,permissions/role,permissions/emailAddress,createdTime,modifiedTime"); + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_DRIVE_API_URL, + methodConfig.getSpreadsheetId() + + "?fields=id,name,permissions/role,permissions/emailAddress,createdTime,modifiedTime"); - return webClient.method(HttpMethod.GET) + return webClient + .method(HttpMethod.GET) .uri(uriBuilder.build(false).toUri()) .body(BodyInserters.empty()); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } Map<String, Object> responseObj = new HashMap<>(); @@ -132,20 +135,20 @@ public boolean validateTriggerMethodRequest(MethodConfig methodConfig) { @Override public WebClient.RequestHeadersSpec<?> getTriggerClient(WebClient webClient, MethodConfig methodConfig) { - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, - methodConfig.getSpreadsheetId()); + UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId()); uriBuilder.queryParam("fields", "sheets/properties"); - return webClient.method(HttpMethod.GET) + return webClient + .method(HttpMethod.GET) .uri(uriBuilder.build(false).toUri()) .body(BodyInserters.empty()); } @Override - public JsonNode transformTriggerResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformTriggerResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } final JsonNode sheets = response.get("sheets"); @@ -155,8 +158,7 @@ public JsonNode transformTriggerResponse(JsonNode response, MethodConfig methodC if (!properties.get("title").asText().isEmpty()) { sheetsList.add(Map.of( "label", properties.get("title").asText(), - "value", properties.get("title").asText() - )); + "value", properties.get("title").asText())); } } return this.objectMapper.valueToTree(sheetsList); diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileListMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileListMethod.java index 4922b450bb3b..9dcd65994649 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileListMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/FileListMethod.java @@ -1,11 +1,9 @@ package com.external.config; -import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.external.constants.ErrorMessages; import com.external.enums.GoogleSheetMethodEnum; import com.external.plugins.exceptions.GSheetsPluginError; -import static com.external.utils.SheetsUtil.getSpreadsheetData; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.HttpMethod; @@ -20,6 +18,8 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; +import static com.external.utils.SheetsUtil.getSpreadsheetData; + /** * API reference: https://developers.google.com/sheets/api/guides/migration#list_spreadsheets_for_the_authenticated_user */ @@ -38,26 +38,29 @@ public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_DRIVE_API_URL, - "?q=mimeType%3D'application%2Fvnd.google-apps.spreadsheet'%20and%20trashed%3Dfalse", true); + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_DRIVE_API_URL, + "?q=mimeType%3D'application%2Fvnd.google-apps.spreadsheet'%20and%20trashed%3Dfalse", + true); - return webClient.method(HttpMethod.GET) + return webClient + .method(HttpMethod.GET) .uri(uriBuilder.build(true).toUri()) .body(BodyInserters.empty()); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } if (response.get("files") == null) { return this.objectMapper.createArrayNode(); } - List<Map<String, String>> filesList = StreamSupport - .stream(response.get("files").spliterator(), false) + List<Map<String, String>> filesList = StreamSupport.stream( + response.get("files").spliterator(), false) .map(file -> getSpreadsheetData((JsonNode) file, userAuthorizedSheetIds, GoogleSheetMethodEnum.EXECUTE)) .filter(Objects::nonNull) .collect(Collectors.toList()); @@ -70,29 +73,27 @@ public boolean validateTriggerMethodRequest(MethodConfig methodConfig) { return this.validateExecutionMethodRequest(methodConfig); } - @Override public WebClient.RequestHeadersSpec<?> getTriggerClient(WebClient webClient, MethodConfig methodConfig) { return this.getExecutionClient(webClient, methodConfig); } @Override - public JsonNode transformTriggerResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformTriggerResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } if (response.get("files") == null) { return this.objectMapper.createArrayNode(); } - List<Map<String, String>> filesList = StreamSupport - .stream(response.get("files").spliterator(), false) + List<Map<String, String>> filesList = StreamSupport.stream( + response.get("files").spliterator(), false) .map(file -> getSpreadsheetData((JsonNode) file, userAuthorizedSheetIds, GoogleSheetMethodEnum.TRIGGER)) .filter(Objects::nonNull) .collect(Collectors.toList()); return this.objectMapper.valueToTree(filesList); } - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GetDatasourceMetadataMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GetDatasourceMetadataMethod.java index f474c2b24e4d..36b1df5c897f 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GetDatasourceMetadataMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GetDatasourceMetadataMethod.java @@ -47,12 +47,11 @@ public static Mono<DatasourceConfiguration> getDatasourceMetadata(DatasourceConf return Mono.just(datasourceConfiguration); } - return fetchEmailAddressFromGoogleAPI(accessToken) - .map(emailAddress -> { - List<Property> properties = datasourceConfiguration.getProperties(); - datasourceConfiguration.setProperties(setPropertiesWithEmailAddress(properties, emailAddress)); - return datasourceConfiguration; - }); + return fetchEmailAddressFromGoogleAPI(accessToken).map(emailAddress -> { + List<Property> properties = datasourceConfiguration.getProperties(); + datasourceConfiguration.setProperties(setPropertiesWithEmailAddress(properties, emailAddress)); + return datasourceConfiguration; + }); } public static List<Property> setPropertiesWithEmailAddress(List<Property> properties, String emailAddress) { @@ -74,7 +73,8 @@ public static Mono<String> fetchEmailAddressFromGoogleAPI(String accessToken) { WebClient client = WebClientUtils.builder().build(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance(); try { - uriBuilder.uri(new URI(FieldName.GOOGLE_API_BASE_URL +"/drive/v3/about")) + uriBuilder + .uri(new URI(FieldName.GOOGLE_API_BASE_URL + "/drive/v3/about")) .queryParam("fields", "user"); } catch (URISyntaxException e) { // since the datasource authorisation doesn't get affected if this flow fails, @@ -103,11 +103,7 @@ public static Mono<String> fetchEmailAddressFromGoogleAPI(String accessToken) { userNode = objectMapper.readTree(jsonBody).get("user"); } catch (IOException e) { throw Exceptions.propagate(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(responseBody), - e.getMessage() - )); - + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, new String(responseBody), e.getMessage())); } return userNode.get(FieldName.EMAIL_ADDRESS).asText(); diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GetStructureMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GetStructureMethod.java index fa11d2f2b730..ca6925c9b59f 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GetStructureMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GetStructureMethod.java @@ -44,19 +44,21 @@ public GetStructureMethod(ObjectMapper objectMapper) { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { if (Integer.parseInt(methodConfig.getTableHeaderIndex()) <= 0) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } return true; } @@ -66,14 +68,13 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M final List<String> ranges = validateInputs(methodConfig); - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, - methodConfig.getSpreadsheetId() /* spreadsheet Id */ - + "/values:batchGet" - ); + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + "/values:batchGet"); uriBuilder.queryParam("majorDimension", "ROWS"); uriBuilder.queryParam("ranges", ranges); - return webClient.method(HttpMethod.GET) + return webClient + .method(HttpMethod.GET) .uri(uriBuilder.build(false).toUri()) .body(BodyInserters.empty()); } @@ -81,10 +82,11 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M private List<String> validateInputs(MethodConfig methodConfig) { // Setting default values int rowOffset = 0; - int rowLimit = 1; //Get header and next row for types + int rowLimit = 1; // Get header and next row for types int tableHeaderIndex = 1; - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { tableHeaderIndex = Integer.parseInt(methodConfig.getTableHeaderIndex()); if (tableHeaderIndex <= 0) { @@ -97,18 +99,22 @@ private List<String> validateInputs(MethodConfig methodConfig) { return List.of( "'" + methodConfig.getSheetName() + "'!" + tableHeaderIndex + ":" + tableHeaderIndex, - "'" + methodConfig.getSheetName() + "'!" + (tableHeaderIndex + rowOffset + 1) + ":" + (tableHeaderIndex + rowOffset + rowLimit)); + "'" + methodConfig.getSheetName() + "'!" + (tableHeaderIndex + rowOffset + 1) + ":" + + (tableHeaderIndex + rowOffset + rowLimit)); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { - throw new AppsmithPluginException(GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + throw new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } ArrayNode valueRanges = (ArrayNode) response.get("valueRanges"); ArrayNode headers = (ArrayNode) valueRanges.get(0).get("values"); - ArrayNode values = valueRanges.get(1) != null ? (ArrayNode) valueRanges.get(1).get("values") : null; + ArrayNode values = + valueRanges.get(1) != null ? (ArrayNode) valueRanges.get(1).get("values") : null; int valueSize = 0; if (headers == null || headers.isEmpty()) { @@ -135,7 +141,8 @@ public JsonNode transformExecutionResponse(JsonNode response, MethodConfig metho for (int i = 0; i < values.size(); i++) { ArrayNode row = (ArrayNode) values.get(i); - RowObject rowObject = new RowObject( headerArray, + RowObject rowObject = new RowObject( + headerArray, objectMapper.convertValue(row, String[].class), rowOffset - tableHeaderIndex + i - 1); collectedCells.add(rowObject.getValueMap()); @@ -143,7 +150,6 @@ public JsonNode transformExecutionResponse(JsonNode response, MethodConfig metho } else { RowObject rowObject = new RowObject(headerArray, new String[0], 0); collectedCells.add(rowObject.getValueMap()); - } preFilteringResponse = this.objectMapper.valueToTree(collectedCells); @@ -191,14 +197,17 @@ public WebClient.RequestHeadersSpec<?> getTriggerClient(WebClient webClient, Met } @Override - public JsonNode transformTriggerResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformTriggerResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { - throw new AppsmithPluginException(GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + throw new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } ArrayNode valueRanges = (ArrayNode) response.get("valueRanges"); ArrayNode headers = (ArrayNode) valueRanges.get(0).get("values"); - ArrayNode values = valueRanges.get(1) != null ? (ArrayNode) valueRanges.get(1).get("values") : null; + ArrayNode values = + valueRanges.get(1) != null ? (ArrayNode) valueRanges.get(1).get("values") : null; int valueSize = 0; if (headers == null || headers.isEmpty()) { @@ -214,15 +223,11 @@ public JsonNode transformTriggerResponse(JsonNode response, MethodConfig methodC Set<String> columnsSet = sanitizeHeaders(headers, valueSize); List<Map<String, String>> columnsList = new ArrayList<>(); - columnsSet - .stream() - .forEach(columnName -> { - columnsList.add(Map.of( - "label", columnName, - "value", columnName - )); - }); - + columnsSet.stream().forEach(columnName -> { + columnsList.add(Map.of( + "label", columnName, + "value", columnName)); + }); return this.objectMapper.valueToTree(columnsList); } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GoogleSheetsMethodStrategy.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GoogleSheetsMethodStrategy.java index a5a3905fee44..6908f4d0069c 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GoogleSheetsMethodStrategy.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/GoogleSheetsMethodStrategy.java @@ -51,7 +51,9 @@ public static ExecutionMethod getExecutionMethod(Map<String, Object> formData, O case MethodIdentifiers.ROWS_DELETE_ONE: return new RowsDeleteMethod(objectMapper); default: - throw Exceptions.propagate(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(ErrorMessages.UNKNOWN_EXECUTION_METHOD_ERROR_MSG, type))); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format(ErrorMessages.UNKNOWN_EXECUTION_METHOD_ERROR_MSG, type))); } } @@ -64,9 +66,11 @@ public static TriggerMethod getTriggerMethod(TriggerRequestDTO triggerRequestDTO case MethodIdentifiers.TRIGGER_COLUMNS_SELECTOR: return new GetStructureMethod(objectMapper); default: - throw Exceptions.propagate(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(ErrorMessages.UNKNOWN_TRIGGER_METHOD_ERROR_MSG, triggerRequestDTO.getRequestType()))); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format( + ErrorMessages.UNKNOWN_TRIGGER_METHOD_ERROR_MSG, triggerRequestDTO.getRequestType()))); } - } public static TemplateMethod getTemplateMethod(Map<String, Object> formData) { @@ -84,7 +88,9 @@ public static TemplateMethod getTemplateMethod(Map<String, Object> formData) { case MethodIdentifiers.ROWS_DELETE_ONE: return new RowsDeleteMethod(); default: - throw Exceptions.propagate(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(ErrorMessages.UNKNOWN_EXECUTION_METHOD_ERROR_MSG, type))); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format(ErrorMessages.UNKNOWN_EXECUTION_METHOD_ERROR_MSG, type))); } } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/MethodConfig.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/MethodConfig.java index 400fa0b2f551..e3edd66e785f 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/MethodConfig.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/MethodConfig.java @@ -6,14 +6,12 @@ import com.appsmith.external.models.TriggerRequestDTO; import com.external.constants.ErrorMessages; import com.external.constants.FieldName; -import com.external.plugins.exceptions.GSheetsPluginError; import com.fasterxml.jackson.core.type.TypeReference; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import org.springframework.util.StringUtils; import java.util.HashMap; import java.util.List; @@ -72,28 +70,20 @@ public MethodConfig(Map<String, Object> formData) { this.sheetName = getTrimmedStringDataValueSafelyFromFormData(formData, SHEET_NAME); this.rowObjects = getTrimmedStringDataValueSafelyFromFormData(formData, FieldName.ROW_OBJECTS); - if (validDataConfigurationPresentInFormData(formData, FieldName.WHERE, - new TypeReference<Map<String, Object>>() { - })) { + if (validDataConfigurationPresentInFormData( + formData, FieldName.WHERE, new TypeReference<Map<String, Object>>() {})) { Map<String, Object> whereForm = getDataValueSafelyFromFormData( - formData, - FieldName.WHERE, - new TypeReference<Map<String, Object>>() { - }, - new HashMap<>()); + formData, FieldName.WHERE, new TypeReference<Map<String, Object>>() {}, new HashMap<>()); this.whereConditions = parseWhereClause(whereForm); } - this.projection = getDataValueSafelyFromFormData(formData, FieldName.PROJECTION, new TypeReference<>() { - }); + this.projection = getDataValueSafelyFromFormData(formData, FieldName.PROJECTION, new TypeReference<>() {}); // Always add rowIndex to a valid projection if (this.projection != null && !this.projection.isEmpty()) { this.projection.add("rowIndex"); } - this.sortBy = getDataValueSafelyFromFormData(formData, FieldName.SORT_BY, new TypeReference<>() { - }); - this.paginateBy = getDataValueSafelyFromFormData(formData, FieldName.PAGINATION, new TypeReference<>() { - }); + this.sortBy = getDataValueSafelyFromFormData(formData, FieldName.SORT_BY, new TypeReference<>() {}); + this.paginateBy = getDataValueSafelyFromFormData(formData, FieldName.PAGINATION, new TypeReference<>() {}); } private void setSpreadsheetUrlFromSpreadsheetId() { @@ -101,7 +91,9 @@ private void setSpreadsheetUrlFromSpreadsheetId() { if (matcher.find()) { this.spreadsheetId = matcher.group(1); } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.SPREADSHEET_ID_NOT_FOUND_IN_URL_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.SPREADSHEET_ID_NOT_FOUND_IN_URL_ERROR_MSG); } } @@ -117,5 +109,4 @@ public MethodConfig(TriggerRequestDTO triggerRequestDTO) { setSpreadsheetUrlFromSpreadsheetId(); } } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/MethodIdentifiers.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/MethodIdentifiers.java index f4e33028eb68..81bfd607b6ca 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/MethodIdentifiers.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/MethodIdentifiers.java @@ -20,5 +20,4 @@ public class MethodIdentifiers { public static final String TRIGGER_SPREADSHEET_SELECTOR = "SPREADSHEET_SELECTOR"; public static final String TRIGGER_SHEET_SELECTOR = "SHEET_SELECTOR"; public static final String TRIGGER_COLUMNS_SELECTOR = "COLUMNS_SELECTOR"; - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsAppendMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsAppendMethod.java index 68f63cc2e12d..f9ed085ef341 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsAppendMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsAppendMethod.java @@ -44,60 +44,64 @@ public RowsAppendMethod(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } - public RowsAppendMethod() { - } + public RowsAppendMethod() {} @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } if (methodConfig.getSheetName() == null || methodConfig.getSheetName().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); } - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { if (Integer.parseInt(methodConfig.getTableHeaderIndex()) <= 0) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } JsonNode bodyNode; try { bodyNode = this.objectMapper.readTree(methodConfig.getRowObjects()); } catch (IllegalArgumentException e) { if (!StringUtils.hasLength(methodConfig.getRowObjects())) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.EMPTY_ROW_OBJECT_MESSAGE); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EMPTY_ROW_OBJECT_MESSAGE); } throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, e.getMessage()); } catch (JsonProcessingException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, methodConfig.getRowObjects(), - ErrorMessages.PARSING_FAILED_EXPECTED_A_ROW_OBJECT_ERROR_MSG + " Error: " + e.getMessage() - ); + ErrorMessages.PARSING_FAILED_EXPECTED_A_ROW_OBJECT_ERROR_MSG + " Error: " + e.getMessage()); } if (bodyNode.isArray()) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EXPECTED_ROW_OBJECT_BUT_FOUND_ARRAY_ERROR_MSG); + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.EXPECTED_ROW_OBJECT_BUT_FOUND_ARRAY_ERROR_MSG); } return true; } @Override public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth2) { - WebClient client = WebClientUtils.builder() - .exchangeStrategies(EXCHANGE_STRATEGIES) - .build(); + WebClient client = + WebClientUtils.builder().exchangeStrategies(EXCHANGE_STRATEGIES).build(); final RowsGetMethod rowsGetMethod = new RowsGetMethod(this.objectMapper); RowObject rowObjectFromBody = null; @@ -109,8 +113,7 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth assert rowObjectFromBody != null; final int rowStart = Integer.parseInt(methodConfig.getTableHeaderIndex()); final int rowEnd = rowStart + 1; - final MethodConfig newMethodConfig = methodConfig - .toBuilder() + final MethodConfig newMethodConfig = methodConfig.toBuilder() .queryFormat("RANGE") .spreadsheetRange(rowStart + ":" + rowEnd) .projection(new ArrayList<>()) @@ -132,8 +135,7 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth if (responseBody == null) { throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.NULL_RESPONSE_BODY_ERROR_MSG)); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.NULL_RESPONSE_BODY_ERROR_MSG)); } String jsonBody = new String(responseBody); JsonNode jsonNodeBody; @@ -141,10 +143,7 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth jsonNodeBody = objectMapper.readTree(jsonBody); } catch (IOException e) { throw Exceptions.propagate(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(responseBody), - e.getMessage() - )); + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, new String(responseBody), e.getMessage())); } if (jsonNodeBody == null) { throw Exceptions.propagate(new AppsmithPluginException( @@ -152,10 +151,13 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth ErrorMessages.EXPECTED_EXISTING_HEADERS_IN_RESPONSE_ERROR_MSG)); } - if (response.getStatusCode() != null && !response.getStatusCode().is2xxSuccessful()) { - if (jsonNodeBody.get("error") != null && jsonNodeBody.get("error").get("message") != null) { + if (response.getStatusCode() != null + && !response.getStatusCode().is2xxSuccessful()) { + if (jsonNodeBody.get("error") != null + && jsonNodeBody.get("error").get("message") != null) { throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, jsonNodeBody.get("error").get("message").toString())); + GSheetsPluginError.QUERY_EXECUTION_FAILED, + jsonNodeBody.get("error").get("message").toString())); } throw Exceptions.propagate(new AppsmithPluginException( @@ -193,26 +195,28 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth } } - final LinkedHashMap<String, String> headerMap = new LinkedHashMap<>(finalRowObjectFromBody.getValueMap()); + final LinkedHashMap<String, String> headerMap = + new LinkedHashMap<>(finalRowObjectFromBody.getValueMap()); headerMap.replaceAll((k, v) -> k); methodConfig.setBody(List.of(new RowObject(headerMap), finalRowObjectFromBody)); return methodConfig; - }); } @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - final String range = "'" + methodConfig.getSheetName() + "'!" + - methodConfig.getTableHeaderIndex() + ":" + methodConfig.getTableHeaderIndex(); + final String range = "'" + methodConfig.getSheetName() + "'!" + methodConfig.getTableHeaderIndex() + ":" + + methodConfig.getTableHeaderIndex(); - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + "/values/" + URLEncoder.encode(range, StandardCharsets.UTF_8) - + ":append", true); + + ":append", + true); uriBuilder.queryParam("valueInputOption", "USER_ENTERED"); uriBuilder.queryParam("includeValuesInResponse", Boolean.FALSE); @@ -220,28 +224,31 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M List<List<Object>> collect; if (methodConfig.getBody() instanceof RowObject) { final RowObject body1 = (RowObject) methodConfig.getBody(); - collect = List.of(body1.getAsSheetValues(body1.getValueMap().keySet().toArray(new String[0]))); + collect = + List.of(body1.getAsSheetValues(body1.getValueMap().keySet().toArray(new String[0]))); } else { final List<RowObject> body1 = (List<RowObject>) methodConfig.getBody(); collect = body1.stream() - .map(row -> row.getAsSheetValues(body1.get(0).getValueMap().keySet().toArray(new String[0]))) + .map(row -> row.getAsSheetValues( + body1.get(0).getValueMap().keySet().toArray(new String[0]))) .collect(Collectors.toList()); } final ValueRange valueRange = new ValueRange(); valueRange.setMajorDimension("ROWS"); valueRange.setRange(range); valueRange.setValues(collect); - return webClient.method(HttpMethod.POST) + return webClient + .method(HttpMethod.POST) .uri(uriBuilder.build(true).toUri()) .body(BodyInserters.fromValue(valueRange)); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } return this.objectMapper.valueToTree(Map.of("message", "Inserted row successfully!")); @@ -250,18 +257,17 @@ public JsonNode transformExecutionResponse(JsonNode response, MethodConfig metho private RowObject getRowObjectFromBody(JsonNode body) { if (body.isArray()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.EXPECTED_ROW_OBJECT_MESSAGE); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EXPECTED_ROW_OBJECT_MESSAGE); } if (body.isEmpty()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.EMPTY_ROW_OBJECT_MESSAGE); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EMPTY_ROW_OBJECT_MESSAGE); } - return new RowObject(this.objectMapper.convertValue(body, TypeFactory - .defaultInstance() - .constructMapType(LinkedHashMap.class, String.class, String.class))); + return new RowObject(this.objectMapper.convertValue( + body, TypeFactory.defaultInstance().constructMapType(LinkedHashMap.class, String.class, String.class))); } @Override diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsBulkAppendMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsBulkAppendMethod.java index 09148bfc0724..d39d8363b91f 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsBulkAppendMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsBulkAppendMethod.java @@ -45,42 +45,49 @@ public RowsBulkAppendMethod(ObjectMapper objectMapper) { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } if (methodConfig.getSheetName() == null || methodConfig.getSheetName().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); } - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { if (Integer.parseInt(methodConfig.getTableHeaderIndex()) <= 0) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX, e.getMessage()); } } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } JsonNode bodyNode; try { bodyNode = this.objectMapper.readTree(methodConfig.getRowObjects()); } catch (IllegalArgumentException e) { if (!StringUtils.hasLength(methodConfig.getRowObjects())) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EMPTY_ROW_ARRAY_OBJECT_MESSAGE); } - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR,e.getMessage()); + throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, e.getMessage()); } catch (JsonProcessingException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, methodConfig.getRowObjects(), - ErrorMessages.EXPECTED_LIST_OF_ROW_OBJECTS_ERROR_MSG + " Error: " + e.getMessage() - ); + ErrorMessages.EXPECTED_LIST_OF_ROW_OBJECTS_ERROR_MSG + " Error: " + e.getMessage()); } if (!bodyNode.isArray()) { @@ -96,16 +103,15 @@ public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { */ @Override public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth2) { - WebClient client = WebClientUtils.builder() - .exchangeStrategies(EXCHANGE_STRATEGIES) - .build(); + WebClient client = + WebClientUtils.builder().exchangeStrategies(EXCHANGE_STRATEGIES).build(); final RowsGetMethod rowsGetMethod = new RowsGetMethod(this.objectMapper); List<RowObject> rowObjectListFromBody = null; try { JsonNode body = this.objectMapper.readTree(methodConfig.getRowObjects()); - if ( body.isEmpty()) { + if (body.isEmpty()) { return Mono.empty(); } @@ -119,8 +125,7 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth assert rowObjectFromBody != null; final int rowStart = Integer.parseInt(methodConfig.getTableHeaderIndex()); final int rowEnd = rowStart + 1; - final MethodConfig newMethodConfig = methodConfig - .toBuilder() + final MethodConfig newMethodConfig = methodConfig.toBuilder() .queryFormat("RANGE") .spreadsheetRange(rowStart + ":" + rowEnd) .projection(new ArrayList<>()) @@ -136,95 +141,100 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth "Bearer " + oauth2.getAuthenticationResponse().getToken())) .exchange() .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) - .map(response -> {// Choose body depending on response status - byte[] responseBody = response.getBody(); - - if (responseBody == null) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.NULL_RESPONSE_BODY_ERROR_MSG)); - } - String jsonBody = new String(responseBody); - JsonNode jsonNodeBody; - try { - jsonNodeBody = objectMapper.readTree(jsonBody); - } catch (IOException e) { - throw Exceptions.propagate(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(responseBody), - e.getMessage() - )); - } - - if (response.getStatusCode() != null && !response.getStatusCode().is2xxSuccessful()) { - if (jsonNodeBody.get("error") != null && jsonNodeBody.get("error").get("message") !=null) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, jsonNodeBody.get("error").get("message").toString())); - } - - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); - } - - if (jsonNodeBody == null) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.EXPECTED_EXISTING_HEADERS_IN_RESPONSE_ERROR_MSG)); - } - - ArrayNode valueRanges = (ArrayNode) jsonNodeBody.get("valueRanges"); - ArrayNode values = (ArrayNode) valueRanges.get(0).get("values"); - - // We replace these original values with new ones - if (values != null && !values.isEmpty()) { - ArrayNode headers = (ArrayNode) values.get(0); - if (headers != null && !headers.isEmpty()) { - for (RowObject rowObject : finalRowObjectListFromBody) { - final Map<String, String> valueMap = new LinkedHashMap<>(); - boolean validValues = false; - final Map<String, String> inputValueMap = rowObject.getValueMap(); - for (JsonNode header : headers) { - final String value = inputValueMap.getOrDefault(header.asText(), null); - if (value != null) { - validValues = true; - } - valueMap.put(header.asText(), value); - } - if (Boolean.TRUE.equals(validValues)) { - rowObject.setValueMap(valueMap); - } else { + .map( + response -> { // Choose body depending on response status + byte[] responseBody = response.getBody(); + + if (responseBody == null) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.NULL_RESPONSE_BODY_ERROR_MSG)); + } + String jsonBody = new String(responseBody); + JsonNode jsonNodeBody; + try { + jsonNodeBody = objectMapper.readTree(jsonBody); + } catch (IOException e) { + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, + new String(responseBody), + e.getMessage())); + } + + if (response.getStatusCode() != null + && !response.getStatusCode().is2xxSuccessful()) { + if (jsonNodeBody.get("error") != null + && jsonNodeBody.get("error").get("message") != null) { throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.RESPONSE_PROCESSING_ERROR, - ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); + GSheetsPluginError.QUERY_EXECUTION_FAILED, + jsonNodeBody + .get("error") + .get("message") + .toString())); } + + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); } - methodConfig.setBody(finalRowObjectListFromBody); - return methodConfig; - } - } + if (jsonNodeBody == null) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.EXPECTED_EXISTING_HEADERS_IN_RESPONSE_ERROR_MSG)); + } + + ArrayNode valueRanges = (ArrayNode) jsonNodeBody.get("valueRanges"); + ArrayNode values = (ArrayNode) valueRanges.get(0).get("values"); + + // We replace these original values with new ones + if (values != null && !values.isEmpty()) { + ArrayNode headers = (ArrayNode) values.get(0); + if (headers != null && !headers.isEmpty()) { + for (RowObject rowObject : finalRowObjectListFromBody) { + final Map<String, String> valueMap = new LinkedHashMap<>(); + boolean validValues = false; + final Map<String, String> inputValueMap = rowObject.getValueMap(); + for (JsonNode header : headers) { + final String value = inputValueMap.getOrDefault(header.asText(), null); + if (value != null) { + validValues = true; + } + valueMap.put(header.asText(), value); + } + if (Boolean.TRUE.equals(validValues)) { + rowObject.setValueMap(valueMap); + } else { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.RESPONSE_PROCESSING_ERROR, + ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); + } + } + + methodConfig.setBody(finalRowObjectListFromBody); + return methodConfig; + } + } - final LinkedHashMap<String, String> headerMap = - finalRowObjectListFromBody - .stream() + final LinkedHashMap<String, String> headerMap = finalRowObjectListFromBody.stream() .map(RowObject::getValueMap) .flatMap(x -> x.keySet().stream()) .collect(Collectors.toMap(x -> x, x -> x, (a, b) -> a, LinkedHashMap::new)); - finalRowObjectListFromBody.add(0, new RowObject(headerMap)); + finalRowObjectListFromBody.add(0, new RowObject(headerMap)); - methodConfig.setBody(finalRowObjectListFromBody); - return methodConfig; - }); + methodConfig.setBody(finalRowObjectListFromBody); + return methodConfig; + }); } @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - final String range = "'" + methodConfig.getSheetName() + "'!" + - methodConfig.getTableHeaderIndex() + ":" + methodConfig.getTableHeaderIndex(); + final String range = "'" + methodConfig.getSheetName() + "'!" + methodConfig.getTableHeaderIndex() + ":" + + methodConfig.getTableHeaderIndex(); - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + "/values/" + URLEncoder.encode(range, StandardCharsets.UTF_8) @@ -237,24 +247,26 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M final List<RowObject> body1 = (List<RowObject>) methodConfig.getBody(); List<List<Object>> collect = body1.stream() - .map(row -> row.getAsSheetValues(body1.get(0).getValueMap().keySet().toArray(new String[0]))) + .map(row -> + row.getAsSheetValues(body1.get(0).getValueMap().keySet().toArray(new String[0]))) .collect(Collectors.toList()); final ValueRange valueRange = new ValueRange(); valueRange.setMajorDimension("ROWS"); valueRange.setRange(range); valueRange.setValues(collect); - return webClient.method(HttpMethod.POST) + return webClient + .method(HttpMethod.POST) .uri(uriBuilder.build(true).toUri()) .body(BodyInserters.fromValue(valueRange)); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } return this.objectMapper.valueToTree(Map.of("message", "Inserted rows successfully!")); @@ -263,24 +275,21 @@ public JsonNode transformExecutionResponse(JsonNode response, MethodConfig metho private List<RowObject> getRowObjectListFromBody(JsonNode body) { if (!body.isArray()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EXPECTED_ARRAY_OF_ROW_OBJECT_MESSAGE); } if (body.isEmpty()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.EMPTY_ROW_ARRAY_OBJECT_MESSAGE); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EMPTY_ROW_ARRAY_OBJECT_MESSAGE); } - return StreamSupport - .stream(body.spliterator(), false) - .map(rowJson -> new RowObject( - this.objectMapper.convertValue( - rowJson, - TypeFactory - .defaultInstance() - .constructMapType(LinkedHashMap.class, String.class, String.class)))) + return StreamSupport.stream(body.spliterator(), false) + .map(rowJson -> new RowObject(this.objectMapper.convertValue( + rowJson, + TypeFactory.defaultInstance() + .constructMapType(LinkedHashMap.class, String.class, String.class)))) .collect(Collectors.toList()); - } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsBulkUpdateMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsBulkUpdateMethod.java index d568daf892ef..8110636ff405 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsBulkUpdateMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsBulkUpdateMethod.java @@ -26,8 +26,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.TreeMap; import java.util.Set; +import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @@ -44,26 +44,33 @@ public RowsBulkUpdateMethod(ObjectMapper objectMapper) { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } if (methodConfig.getSheetName() == null || methodConfig.getSheetName().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); } - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { if (Integer.parseInt(methodConfig.getTableHeaderIndex()) <= 0) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX, e.getMessage()); } } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } JsonNode bodyNode; try { @@ -73,16 +80,14 @@ public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EMPTY_UPDATE_ROW_OBJECTS_MESSAGE, - e.getMessage() - ); + e.getMessage()); } - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR,e.getMessage()); + throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, e.getMessage()); } catch (JsonProcessingException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, methodConfig.getRowObjects(), - ErrorMessages.EXPECTED_LIST_OF_ROW_OBJECTS_ERROR_MSG + " Error: " + e.getMessage() - ); + ErrorMessages.EXPECTED_LIST_OF_ROW_OBJECTS_ERROR_MSG + " Error: " + e.getMessage()); } if (!bodyNode.isArray()) { @@ -94,23 +99,26 @@ public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { @Override public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth2) { - WebClient client = WebClientUtils.builder() - .exchangeStrategies(EXCHANGE_STRATEGIES) - .build(); + WebClient client = + WebClientUtils.builder().exchangeStrategies(EXCHANGE_STRATEGIES).build(); final RowsGetMethod rowsGetMethod = new RowsGetMethod(this.objectMapper); Map<Integer, RowObject> rowObjectMapFromBody = null; try { - rowObjectMapFromBody = this.getRowObjectMapFromBody(this.objectMapper.readTree(methodConfig.getRowObjects())); + rowObjectMapFromBody = + this.getRowObjectMapFromBody(this.objectMapper.readTree(methodConfig.getRowObjects())); } catch (JsonProcessingException e) { // Should never enter here } assert rowObjectMapFromBody != null; - final Integer rowStart = Integer.parseInt(methodConfig.getTableHeaderIndex()) + ((TreeMap<Integer, RowObject>) rowObjectMapFromBody).firstKey() + 1; - final Integer rowEnd = Integer.parseInt(methodConfig.getTableHeaderIndex()) + ((TreeMap<Integer, RowObject>) rowObjectMapFromBody).lastKey() + 1; - final MethodConfig newMethodConfig = methodConfig - .toBuilder() + final Integer rowStart = Integer.parseInt(methodConfig.getTableHeaderIndex()) + + ((TreeMap<Integer, RowObject>) rowObjectMapFromBody).firstKey() + + 1; + final Integer rowEnd = Integer.parseInt(methodConfig.getTableHeaderIndex()) + + ((TreeMap<Integer, RowObject>) rowObjectMapFromBody).lastKey() + + 1; + final MethodConfig newMethodConfig = methodConfig.toBuilder() .queryFormat("RANGE") .spreadsheetRange(rowStart + ":" + rowEnd) .projection(new ArrayList<>()) @@ -132,8 +140,7 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth if (responseBody == null) { throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.NULL_RESPONSE_BODY_ERROR_MSG)); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.NULL_RESPONSE_BODY_ERROR_MSG)); } String jsonBody = new String(responseBody); JsonNode jsonNodeBody; @@ -141,22 +148,18 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth jsonNodeBody = objectMapper.readTree(jsonBody); } catch (IOException e) { throw Exceptions.propagate(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(responseBody), - e.getMessage() - )); + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, new String(responseBody), e.getMessage())); } - - if (response.getStatusCode() != null && !response.getStatusCode().is2xxSuccessful()) { - if (jsonNodeBody.get("error") != null && jsonNodeBody.get("error").get("message") !=null) { + if (response.getStatusCode() != null + && !response.getStatusCode().is2xxSuccessful()) { + if (jsonNodeBody.get("error") != null + && jsonNodeBody.get("error").get("message") != null) { throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.UNSUCCESSFUL_RESPONSE_ERROR_MSG, - jsonNodeBody.get("error").get("message").toString(), - "HTTP " + response.getStatusCode() - ) - ); + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.UNSUCCESSFUL_RESPONSE_ERROR_MSG, + jsonNodeBody.get("error").get("message").toString(), + "HTTP " + response.getStatusCode())); } throw Exceptions.propagate(new AppsmithPluginException( @@ -165,29 +168,27 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth } // This is the object with the original values in the referred row - final JsonNode jsonNode = rowsGetMethod - .transformExecutionResponse(jsonNodeBody, methodConfig, null); + final JsonNode jsonNode = + rowsGetMethod.transformExecutionResponse(jsonNodeBody, methodConfig, null); if (jsonNode == null || jsonNode.isEmpty()) { throw Exceptions.propagate(new AppsmithPluginException( GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.NO_DATA_FOUND_CURRENT_ROW_INDEX_ERROR_MSG - )); + ErrorMessages.NO_DATA_FOUND_CURRENT_ROW_INDEX_ERROR_MSG)); } // This is the rowObject for original values - final List<RowObject> returnedRowObjects = - new ArrayList<>(this.getRowObjectMapFromBody(jsonNode).values()); + final List<RowObject> returnedRowObjects = new ArrayList<>( + this.getRowObjectMapFromBody(jsonNode).values()); boolean updatable = false; // We replace these original values with new ones for (RowObject rowObject : returnedRowObjects) { if (finalRowObjectMapFromBody.containsKey(rowObject.getCurrentRowIndex())) { - final Map<String, String> valueMap = - finalRowObjectMapFromBody - .get(rowObject.getCurrentRowIndex()) - .getValueMap(); + final Map<String, String> valueMap = finalRowObjectMapFromBody + .get(rowObject.getCurrentRowIndex()) + .getValueMap(); // We replace these original values with new ones final Map<String, String> returnedRowObjectValueMap = rowObject.getValueMap(); for (Map.Entry<String, String> entry : returnedRowObjectValueMap.entrySet()) { @@ -202,20 +203,13 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth if (Boolean.FALSE.equals(updatable)) { throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.NOTHING_TO_UPDATE_ERROR_MSG - )); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.NOTHING_TO_UPDATE_ERROR_MSG)); } methodConfig.setBody(returnedRowObjects); assert jsonNodeBody != null; methodConfig.setSpreadsheetRange( - jsonNodeBody - .get("valueRanges") - .get(1) - .get("range") - .asText() - ); + jsonNodeBody.get("valueRanges").get(1).get("range").asText()); return methodConfig; }); } @@ -223,36 +217,35 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + "/values/" + URLEncoder.encode(methodConfig.getSpreadsheetRange(), StandardCharsets.UTF_8), - true - ); + true); uriBuilder.queryParam("valueInputOption", "USER_ENTERED"); uriBuilder.queryParam("includeValuesInResponse", Boolean.TRUE); final List<RowObject> body1 = (List<RowObject>) methodConfig.getBody(); List<List<Object>> collect = body1.stream() - .map(row -> row.getAsSheetValues(body1.get(0).getValueMap().keySet().toArray(new String[0]))) + .map(row -> + row.getAsSheetValues(body1.get(0).getValueMap().keySet().toArray(new String[0]))) .collect(Collectors.toList()); - return webClient.method(HttpMethod.PUT) + return webClient + .method(HttpMethod.PUT) .uri(uriBuilder.build(true).toUri()) .body(BodyInserters.fromValue(Map.of( - "range", methodConfig.getSpreadsheetRange(), - "majorDimension", "ROWS", - "values", collect - ))); + "range", methodConfig.getSpreadsheetRange(), "majorDimension", "ROWS", "values", collect))); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } return this.objectMapper.valueToTree(Map.of("message", "Updated sheet successfully!")); @@ -261,29 +254,23 @@ public JsonNode transformExecutionResponse(JsonNode response, MethodConfig metho private Map<Integer, RowObject> getRowObjectMapFromBody(JsonNode body) { if (!body.isArray()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EXPECTED_ARRAY_OF_ROW_OBJECT_MESSAGE); } if (body.isEmpty()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.EMPTY_UPDATE_ROW_OBJECTS_MESSAGE); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EMPTY_UPDATE_ROW_OBJECTS_MESSAGE); } - return StreamSupport - .stream(body.spliterator(), false) - .map(rowJson -> new RowObject( - this.objectMapper.convertValue(rowJson, TypeFactory - .defaultInstance() - .constructMapType(LinkedHashMap.class, String.class, String.class))) + return StreamSupport.stream(body.spliterator(), false) + .map(rowJson -> new RowObject(this.objectMapper.convertValue( + rowJson, + TypeFactory.defaultInstance() + .constructMapType(LinkedHashMap.class, String.class, String.class))) .initialize()) .collect(Collectors.toMap( - RowObject::getCurrentRowIndex, - rowObject -> rowObject, - (r1, r2) -> r2, - TreeMap::new - )); - + RowObject::getCurrentRowIndex, rowObject -> rowObject, (r1, r2) -> r2, TreeMap::new)); } - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsDeleteMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsDeleteMethod.java index c9a407c9f59e..c348b8276778 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsDeleteMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsDeleteMethod.java @@ -31,57 +31,63 @@ public RowsDeleteMethod(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } - public RowsDeleteMethod() { - } + public RowsDeleteMethod() {} @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } if (methodConfig.getSheetName() == null || methodConfig.getSheetName().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); } if (methodConfig.getRowIndex() == null || methodConfig.getRowIndex().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_ROW_INDEX_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_ROW_INDEX_ERROR_MSG); } int rowIndex = 0; try { rowIndex = Integer.parseInt(methodConfig.getRowIndex()); if (rowIndex < 0) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_ROW_INDEX_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_ROW_INDEX_ERROR_MSG); } } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_ROW_INDEX_ERROR_MSG, e.getMessage()); } - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { if (Integer.parseInt(methodConfig.getTableHeaderIndex()) <= 0) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX, e.getMessage()); } } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } return true; } @Override public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth2) { - WebClient client = WebClientUtils.builder() - .exchangeStrategies(EXCHANGE_STRATEGIES) - .build(); - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, - methodConfig.getSpreadsheetId()); + WebClient client = + WebClientUtils.builder().exchangeStrategies(EXCHANGE_STRATEGIES).build(); + UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId()); uriBuilder.queryParam("fields", "sheets/properties"); return client.method(HttpMethod.GET) .uri(uriBuilder.build(false).toUri()) @@ -91,81 +97,86 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth "Bearer " + oauth2.getAuthenticationResponse().getToken())) .exchange() .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) - .map(response -> {// Choose body depending on response status - byte[] responseBody = response.getBody(); - - if (responseBody == null || !response.getStatusCode().is2xxSuccessful()) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); - } - String jsonBody = new String(responseBody); - JsonNode sheets = null; - try { - sheets = objectMapper.readTree(jsonBody).get("sheets"); - } catch (IOException e) { - Mono.error(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(responseBody), - e.getMessage() - )); - } - - assert sheets != null; - String sheetId = null; - for (JsonNode sheet : sheets) { - final JsonNode properties = sheet.get("properties"); - if (methodConfig.getSheetName().equals(properties.get("title").asText())) { - sheetId = properties.get("sheetId").asText(); - } - } - - if (sheetId == null) { - throw Exceptions.propagate(new AppsmithPluginException(GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.UNKNOWN_SHEET_NAME_ERROR_MSG)); - } else { - methodConfig.setSheetId(sheetId); - } - - return methodConfig; - }); + .map( + response -> { // Choose body depending on response status + byte[] responseBody = response.getBody(); + + if (responseBody == null + || !response.getStatusCode().is2xxSuccessful()) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); + } + String jsonBody = new String(responseBody); + JsonNode sheets = null; + try { + sheets = objectMapper.readTree(jsonBody).get("sheets"); + } catch (IOException e) { + Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, + new String(responseBody), + e.getMessage())); + } + + assert sheets != null; + String sheetId = null; + for (JsonNode sheet : sheets) { + final JsonNode properties = sheet.get("properties"); + if (methodConfig + .getSheetName() + .equals(properties.get("title").asText())) { + sheetId = properties.get("sheetId").asText(); + } + } + + if (sheetId == null) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.UNKNOWN_SHEET_NAME_ERROR_MSG)); + } else { + methodConfig.setSheetId(sheetId); + } + + return methodConfig; + }); } @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, - methodConfig.getSpreadsheetId() /* spreadsheet Id */ - + ":batchUpdate", - true); + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + ":batchUpdate", true); - final int rowIndex = Integer.parseInt(methodConfig.getTableHeaderIndex()) + - Integer.parseInt(methodConfig.getRowIndex()); - return webClient.method(HttpMethod.POST) + final int rowIndex = + Integer.parseInt(methodConfig.getTableHeaderIndex()) + Integer.parseInt(methodConfig.getRowIndex()); + return webClient + .method(HttpMethod.POST) .uri(uriBuilder.build(true).toUri()) - .body(BodyInserters.fromValue( - Map.of( - "requests", List.of( + .body(BodyInserters.fromValue(Map.of( + "requests", + List.of(Map.of( + "deleteDimension", + Map.of( + "range", Map.of( - "deleteDimension", Map.of( - "range", Map.of( - "sheetId", methodConfig.getSheetId(), - "dimension", "ROWS", - "startIndex", rowIndex, - "endIndex", rowIndex + 1 - ) - )))))); + "sheetId", + methodConfig.getSheetId(), + "dimension", + "ROWS", + "startIndex", + rowIndex, + "endIndex", + rowIndex + 1))))))); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } - return this.objectMapper.valueToTree(Map.of("message", - "Deleted row successfully!")); + return this.objectMapper.valueToTree(Map.of("message", "Deleted row successfully!")); } - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsGetMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsGetMethod.java index 33a6de8a2793..49fdc3e19b05 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsGetMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsGetMethod.java @@ -39,8 +39,7 @@ public RowsGetMethod(ObjectMapper objectMapper) { this.filterDataService = FilterDataService.getInstance(); } - public RowsGetMethod() { - } + public RowsGetMethod() {} // Used to capture the range of columns in this request. The handling for this regex makes sure that // all possible combinations of A1 notation for a range map to a common format @@ -55,30 +54,39 @@ public RowsGetMethod() { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } if (methodConfig.getSheetName() == null || methodConfig.getSheetName().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); } - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { if (Integer.parseInt(methodConfig.getTableHeaderIndex()) <= 0) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX, e.getMessage()); } } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } if ("RANGE".equalsIgnoreCase(methodConfig.getQueryFormat())) { - if (methodConfig.getSpreadsheetRange() == null || methodConfig.getSpreadsheetRange().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_CELL_RANGE_ERROR_MSG); + if (methodConfig.getSpreadsheetRange() == null + || methodConfig.getSpreadsheetRange().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_CELL_RANGE_ERROR_MSG); } } @@ -90,21 +98,21 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M final List<String> ranges = validateInputs(methodConfig); - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, - methodConfig.getSpreadsheetId() /* spreadsheet Id */ - + "/values:batchGet" - ); + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + "/values:batchGet"); uriBuilder.queryParam("majorDimension", "ROWS"); uriBuilder.queryParam("ranges", ranges); - return webClient.method(HttpMethod.GET) + return webClient + .method(HttpMethod.GET) .uri(uriBuilder.build(false).toUri()) .body(BodyInserters.empty()); } private List<String> validateInputs(MethodConfig methodConfig) { int tableHeaderIndex = 1; - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { tableHeaderIndex = Integer.parseInt(methodConfig.getTableHeaderIndex()); if (tableHeaderIndex <= 0) { @@ -122,18 +130,19 @@ private List<String> validateInputs(MethodConfig methodConfig) { Matcher matcher = findAllRowsPattern.matcher(methodConfig.getSpreadsheetRange()); matcher.find(); return List.of( - "'" + methodConfig.getSheetName() + "'!" + matcher.group(1) + tableHeaderIndex + ":" + matcher.group(2) + tableHeaderIndex, + "'" + methodConfig.getSheetName() + "'!" + matcher.group(1) + tableHeaderIndex + ":" + + matcher.group(2) + tableHeaderIndex, "'" + methodConfig.getSheetName() + "'!" + methodConfig.getSpreadsheetRange()); } return List.of(); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } ArrayNode valueRanges = (ArrayNode) response.get("valueRanges"); @@ -164,16 +173,15 @@ public JsonNode transformExecutionResponse(JsonNode response, MethodConfig metho for (int i = 0; i < values.size(); i++) { ArrayNode row = (ArrayNode) values.get(i); RowObject rowObject = new RowObject( - headerArray, - objectMapper.convertValue(row, String[].class), - rowOffset - tableHeaderIndex + i - 1); + headerArray, objectMapper.convertValue(row, String[].class), rowOffset - tableHeaderIndex + i - 1); collectedCells.add(rowObject.getValueMap()); } ArrayNode preFilteringResponse = this.objectMapper.valueToTree(collectedCells); if (isWhereConditionConfigured(methodConfig)) { - return filterDataService.filterDataNew(preFilteringResponse, + return filterDataService.filterDataNew( + preFilteringResponse, new UQIDataFilterParams( methodConfig.getWhereConditions(), methodConfig.getProjection(), @@ -219,6 +227,5 @@ private Boolean isWhereConditionConfigured(MethodConfig methodConfig) { // At least 1 condition exists return whereConditions != null; - } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsUpdateMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsUpdateMethod.java index 2b68737c0f0e..8b7acf5e552a 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsUpdateMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/RowsUpdateMethod.java @@ -41,55 +41,61 @@ public RowsUpdateMethod(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } - public RowsUpdateMethod() { - } + public RowsUpdateMethod() {} @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } if (methodConfig.getSheetName() == null || methodConfig.getSheetName().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); } - if (methodConfig.getTableHeaderIndex() != null && !methodConfig.getTableHeaderIndex().isBlank()) { + if (methodConfig.getTableHeaderIndex() != null + && !methodConfig.getTableHeaderIndex().isBlank()) { try { if (Integer.parseInt(methodConfig.getTableHeaderIndex()) <= 0) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX, e.getMessage()); } } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.INVALID_TABLE_HEADER_INDEX); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.INVALID_TABLE_HEADER_INDEX); } final String body = methodConfig.getRowObjects(); try { this.getRowObjectFromBody(this.objectMapper.readTree(body)); } catch (IllegalArgumentException e) { if (!StringUtils.hasLength(body)) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EMPTY_UPDATE_ROW_OBJECT_MESSAGE); } throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, e.getMessage()); } catch (JsonProcessingException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, methodConfig.getRowObjects(), - ErrorMessages.PARSING_FAILED_EXPECTED_A_ROW_OBJECT_ERROR_MSG + " Error: " + e.getMessage() - ); + ErrorMessages.PARSING_FAILED_EXPECTED_A_ROW_OBJECT_ERROR_MSG + " Error: " + e.getMessage()); } return true; } @Override public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth2) { - WebClient client = WebClientUtils.builder() - .exchangeStrategies(EXCHANGE_STRATEGIES) - .build(); + WebClient client = + WebClientUtils.builder().exchangeStrategies(EXCHANGE_STRATEGIES).build(); final RowsGetMethod rowsGetMethod = new RowsGetMethod(this.objectMapper); final String body = methodConfig.getRowObjects(); @@ -101,9 +107,9 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth } assert rowObjectFromBody != null; - final int row = Integer.parseInt(methodConfig.getTableHeaderIndex()) + rowObjectFromBody.getCurrentRowIndex() + 1; - final MethodConfig newMethodConfig = methodConfig - .toBuilder() + final int row = + Integer.parseInt(methodConfig.getTableHeaderIndex()) + rowObjectFromBody.getCurrentRowIndex() + 1; + final MethodConfig newMethodConfig = methodConfig.toBuilder() .queryFormat("RANGE") .spreadsheetRange(row + ":" + row) .projection(new ArrayList<>()) @@ -120,79 +126,85 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth "Bearer " + oauth2.getAuthenticationResponse().getToken())) .exchange() .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) - .map(response -> {// Choose body depending on response status - byte[] responseBody = response.getBody(); - - if (responseBody == null) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.NULL_RESPONSE_BODY_ERROR_MSG)); - } - String jsonBody = new String(responseBody); - JsonNode jsonNodeBody = null; - try { - jsonNodeBody = objectMapper.readTree(jsonBody); - } catch (IOException e) { - throw Exceptions.propagate(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(responseBody), - e.getMessage() - )); - } - if (response.getStatusCode() != null && !response.getStatusCode().is2xxSuccessful()) { - if (jsonNodeBody.get("error") != null && jsonNodeBody.get("error").get("message") != null) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.UNSUCCESSFUL_RESPONSE_ERROR_MSG, - jsonNodeBody.get("error").get("message").toString(), - "HTTP " + response.getStatusCode()) - ); - } - - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); - } - - // This is the object with the original values in the referred row - final JsonNode jsonNode = rowsGetMethod - .transformExecutionResponse(jsonNodeBody, methodConfig, null) - .get(0); - - if (jsonNode == null) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.NO_DATA_FOUND_CURRENT_ROW_INDEX_ERROR_MSG - )); - } - - // This is the rowObject for original values - final RowObject returnedRowObject = this.getRowObjectFromBody(jsonNode); - final Map<String, String> valueMap = finalRowObjectFromBody.getValueMap(); - // We replace these original values with new ones - final Map<String, String> returnedRowObjectValueMap = returnedRowObject.getValueMap(); - boolean updatable = false; - - for (Map.Entry<String, String> entry : returnedRowObjectValueMap.entrySet()) { - String k = entry.getKey(); - if (valueMap.containsKey(k)) { - returnedRowObjectValueMap.put(k, valueMap.get(k)); - updatable = true; - } - } - - if (Boolean.FALSE.equals(updatable)) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.NOTHING_TO_UPDATE_ERROR_MSG - )); - } - - methodConfig.setBody(returnedRowObject); - assert jsonNodeBody != null; - methodConfig.setSpreadsheetRange(jsonNodeBody.get("valueRanges").get(1).get("range").asText()); - return methodConfig; - }); + .map( + response -> { // Choose body depending on response status + byte[] responseBody = response.getBody(); + + if (responseBody == null) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.NULL_RESPONSE_BODY_ERROR_MSG)); + } + String jsonBody = new String(responseBody); + JsonNode jsonNodeBody = null; + try { + jsonNodeBody = objectMapper.readTree(jsonBody); + } catch (IOException e) { + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, + new String(responseBody), + e.getMessage())); + } + if (response.getStatusCode() != null + && !response.getStatusCode().is2xxSuccessful()) { + if (jsonNodeBody.get("error") != null + && jsonNodeBody.get("error").get("message") != null) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.UNSUCCESSFUL_RESPONSE_ERROR_MSG, + jsonNodeBody + .get("error") + .get("message") + .toString(), + "HTTP " + response.getStatusCode())); + } + + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); + } + + // This is the object with the original values in the referred row + final JsonNode jsonNode = rowsGetMethod + .transformExecutionResponse(jsonNodeBody, methodConfig, null) + .get(0); + + if (jsonNode == null) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.NO_DATA_FOUND_CURRENT_ROW_INDEX_ERROR_MSG)); + } + + // This is the rowObject for original values + final RowObject returnedRowObject = this.getRowObjectFromBody(jsonNode); + final Map<String, String> valueMap = finalRowObjectFromBody.getValueMap(); + // We replace these original values with new ones + final Map<String, String> returnedRowObjectValueMap = returnedRowObject.getValueMap(); + boolean updatable = false; + + for (Map.Entry<String, String> entry : returnedRowObjectValueMap.entrySet()) { + String k = entry.getKey(); + if (valueMap.containsKey(k)) { + returnedRowObjectValueMap.put(k, valueMap.get(k)); + updatable = true; + } + } + + if (Boolean.FALSE.equals(updatable)) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.NOTHING_TO_UPDATE_ERROR_MSG)); + } + + methodConfig.setBody(returnedRowObject); + assert jsonNodeBody != null; + methodConfig.setSpreadsheetRange(jsonNodeBody + .get("valueRanges") + .get(1) + .get("range") + .asText()); + return methodConfig; + }); } @Override @@ -200,33 +212,34 @@ public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, M RowObject rowObject = (RowObject) methodConfig.getBody(); - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + "/values/" - + URLEncoder.encode(methodConfig.getSpreadsheetRange(), StandardCharsets.UTF_8), /* spreadsheet Range */ - true - ); + + URLEncoder.encode( + methodConfig.getSpreadsheetRange(), StandardCharsets.UTF_8), /* spreadsheet Range */ + true); uriBuilder.queryParam("valueInputOption", "USER_ENTERED"); uriBuilder.queryParam("includeValuesInResponse", Boolean.TRUE); final List<String> objects = new ArrayList<>(rowObject.getValueMap().values()); - return webClient.method(HttpMethod.PUT) + return webClient + .method(HttpMethod.PUT) .uri(uriBuilder.build(true).toUri()) .body(BodyInserters.fromValue(Map.of( "range", methodConfig.getSpreadsheetRange(), "majorDimension", "ROWS", - "values", List.of(objects) - ))); + "values", List.of(objects)))); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } return this.objectMapper.valueToTree(Map.of("message", "Updated sheet successfully!")); @@ -235,19 +248,19 @@ public JsonNode transformExecutionResponse(JsonNode response, MethodConfig metho private RowObject getRowObjectFromBody(JsonNode body) { if (body.isArray()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.EXPECTED_ROW_OBJECT_MESSAGE); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EXPECTED_ROW_OBJECT_MESSAGE); } if (body.isEmpty()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.EMPTY_UPDATE_ROW_OBJECT_MESSAGE); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.EMPTY_UPDATE_ROW_OBJECT_MESSAGE); } - return new RowObject( - this.objectMapper.convertValue(body, TypeFactory - .defaultInstance() - .constructMapType(LinkedHashMap.class, String.class, String.class))) + return new RowObject(this.objectMapper.convertValue( + body, + TypeFactory.defaultInstance() + .constructMapType(LinkedHashMap.class, String.class, String.class))) .initialize(); } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/SheetDeleteMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/SheetDeleteMethod.java index 0e0ddf32f76e..707e1c076864 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/SheetDeleteMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/SheetDeleteMethod.java @@ -34,11 +34,15 @@ public SheetDeleteMethod(ObjectMapper objectMapper) { @Override public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { - if (methodConfig.getSpreadsheetId() == null || methodConfig.getSpreadsheetId().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); + if (methodConfig.getSpreadsheetId() == null + || methodConfig.getSpreadsheetId().isBlank()) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_URL_ERROR_MSG); } if (methodConfig.getSheetName() == null || methodConfig.getSheetName().isBlank()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.MISSING_SPREADSHEET_NAME_ERROR_MSG); } return true; @@ -46,11 +50,9 @@ public boolean validateExecutionMethodRequest(MethodConfig methodConfig) { @Override public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth2) { - WebClient client = WebClientUtils.builder() - .exchangeStrategies(EXCHANGE_STRATEGIES) - .build(); - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, - methodConfig.getSpreadsheetId()) + WebClient client = + WebClientUtils.builder().exchangeStrategies(EXCHANGE_STRATEGIES).build(); + UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId()) .queryParam("includeGridData", false); return client.method(HttpMethod.GET) @@ -61,76 +63,78 @@ public Mono<Object> executePrerequisites(MethodConfig methodConfig, OAuth2 oauth "Bearer " + oauth2.getAuthenticationResponse().getToken())) .exchange() .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) - .map(response -> {// Choose body depending on response status - byte[] responseBody = response.getBody(); - - if (responseBody == null || !response.getStatusCode().is2xxSuccessful()) { - throw Exceptions.propagate(new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); - } - String jsonBody = new String(responseBody); - JsonNode jsonNodeBody; - try { - jsonNodeBody = objectMapper.readTree(jsonBody); - } catch (IOException e) { - throw Exceptions.propagate(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(responseBody), - e.getMessage() - )); - } - - final ArrayNode sheets = (ArrayNode) jsonNodeBody.get("sheets"); - - String sheetId = null; - for (JsonNode sheet : sheets) { - final JsonNode properties = sheet.get("properties"); - if (methodConfig.getSheetName().equalsIgnoreCase(properties.get("title").asText())) { - sheetId = properties.get("sheetId").asText(); - } - } - - if (sheetId == null) { - throw Exceptions.propagate(new AppsmithPluginException(GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.UNKNOWN_SHEET_NAME_ERROR_MSG)); - } else { - methodConfig.setSheetId(sheetId); - } - - return methodConfig; - }); + .map( + response -> { // Choose body depending on response status + byte[] responseBody = response.getBody(); + + if (responseBody == null + || !response.getStatusCode().is2xxSuccessful()) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG)); + } + String jsonBody = new String(responseBody); + JsonNode jsonNodeBody; + try { + jsonNodeBody = objectMapper.readTree(jsonBody); + } catch (IOException e) { + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, + new String(responseBody), + e.getMessage())); + } + + final ArrayNode sheets = (ArrayNode) jsonNodeBody.get("sheets"); + + String sheetId = null; + for (JsonNode sheet : sheets) { + final JsonNode properties = sheet.get("properties"); + if (methodConfig + .getSheetName() + .equalsIgnoreCase( + properties.get("title").asText())) { + sheetId = properties.get("sheetId").asText(); + } + } + + if (sheetId == null) { + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.UNKNOWN_SHEET_NAME_ERROR_MSG)); + } else { + methodConfig.setSheetId(sheetId); + } + + return methodConfig; + }); } @Override public WebClient.RequestHeadersSpec<?> getExecutionClient(WebClient webClient, MethodConfig methodConfig) { - UriComponentsBuilder uriBuilder = getBaseUriBuilder(this.BASE_SHEETS_API_URL, - methodConfig.getSpreadsheetId() /* spreadsheet Id */ - + ":batchUpdate", true); + UriComponentsBuilder uriBuilder = getBaseUriBuilder( + this.BASE_SHEETS_API_URL, methodConfig.getSpreadsheetId() /* spreadsheet Id */ + ":batchUpdate", true); - return webClient.method(HttpMethod.POST) + return webClient + .method(HttpMethod.POST) .uri(uriBuilder.build(true).toUri()) - .body(BodyInserters.fromValue( - Map.of( - "requests", List.of( - Map.of( - "deleteSheet", Map.of( - "sheetId", methodConfig.getSheetId()))), - "includeSpreadsheetInResponse", false))); - + .body(BodyInserters.fromValue(Map.of( + "requests", + List.of(Map.of("deleteSheet", Map.of("sheetId", methodConfig.getSheetId()))), + "includeSpreadsheetInResponse", + false))); } @Override - public JsonNode transformExecutionResponse(JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { + public JsonNode transformExecutionResponse( + JsonNode response, MethodConfig methodConfig, Set<String> userAuthorizedSheetIds) { if (response == null) { throw new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); + GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG); } String errorMessage = "Deleted sheet " + methodConfig.getSheetName() + " successfully!"; return this.objectMapper.valueToTree(Map.of("message", errorMessage)); } - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/TemplateMethod.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/TemplateMethod.java index ee694874270b..6a7e45b47bc9 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/TemplateMethod.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/config/TemplateMethod.java @@ -4,6 +4,5 @@ public interface TemplateMethod { - default void replaceMethodConfigTemplate(Map<String, Object> formData, Map<String, String> mappedColumns) { - } + default void replaceMethodConfigTemplate(Map<String, Object> formData, Map<String, String> mappedColumns) {} } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/ErrorMessages.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/ErrorMessages.java index db991bcf783a..466b205d2e07 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/ErrorMessages.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/ErrorMessages.java @@ -17,13 +17,15 @@ public class ErrorMessages extends BasePluginErrorMessages { public static final String EXPECTED_ROW_OBJECT_MESSAGE = "Expected a row object, but did not find it."; - public static final String EXPECTED_ARRAY_OF_ROW_OBJECT_MESSAGE = "Expected an array of row object, but did not find it."; + public static final String EXPECTED_ARRAY_OF_ROW_OBJECT_MESSAGE = + "Expected an array of row object, but did not find it."; public static final String REQUEST_BODY_NOT_ARRAY = "Request body was not an array."; public static final String MISSING_GSHEETS_METHOD_ERROR_MSG = "Missing Google Sheets method."; - public static final String UNSUCCESSFUL_RESPONSE_ERROR_MSG = "Appsmith server has received unsuccessful response from GoogleSheets."; + public static final String UNSUCCESSFUL_RESPONSE_ERROR_MSG = + "Appsmith server has received unsuccessful response from GoogleSheets."; public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Your GoogleSheets query failed to execute"; @@ -41,17 +43,22 @@ public class ErrorMessages extends BasePluginErrorMessages { public static final String MISSING_VALID_RESPONSE_ERROR_MSG = "Missing a valid response object."; - public static final String EXPECTED_LIST_OF_ROW_OBJECTS_ERROR_MSG = "Unable to parse request body. Expected a list of row objects."; + public static final String EXPECTED_LIST_OF_ROW_OBJECTS_ERROR_MSG = + "Unable to parse request body. Expected a list of row objects."; - public static final String INVALID_ROW_INDEX_ERROR_MSG = "Unexpected value for row index. Please use a number starting from 0"; + public static final String INVALID_ROW_INDEX_ERROR_MSG = + "Unexpected value for row index. Please use a number starting from 0"; - public static final String INVALID_TABLE_HEADER_INDEX = "Unexpected value for table header index. Please use a number starting from 1"; + public static final String INVALID_TABLE_HEADER_INDEX = + "Unexpected value for table header index. Please use a number starting from 1"; - public static final String RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG = "Could not map response to existing data. Appsmith server has either received an empty response or an unexpected response."; + public static final String RESPONSE_DATA_MAPPING_FAILED_ERROR_MSG = + "Could not map response to existing data. Appsmith server has either received an empty response or an unexpected response."; public static final String UNKNOWN_SHEET_NAME_ERROR_MSG = "Invalid sheet name"; - public static final String PARSING_FAILED_EXPECTED_A_ROW_OBJECT_ERROR_MSG = "Unable to parse request body. Expected a row object."; + public static final String PARSING_FAILED_EXPECTED_A_ROW_OBJECT_ERROR_MSG = + "Unable to parse request body. Expected a row object."; public static final String NULL_RESPONSE_BODY_ERROR_MSG = "Expected to receive a response body."; @@ -63,10 +70,12 @@ public class ErrorMessages extends BasePluginErrorMessages { public static final String UNKNOWN_EXECUTION_METHOD_ERROR_MSG = "Unknown execution method type: %s"; - public static final String EXPECTED_ROW_OBJECT_BUT_FOUND_ARRAY_ERROR_MSG = "Request body was an array. Expected a row object."; + public static final String EXPECTED_ROW_OBJECT_BUT_FOUND_ARRAY_ERROR_MSG = + "Request body was an array. Expected a row object."; - public static final String EXPECTED_EXISTING_HEADERS_IN_RESPONSE_ERROR_MSG = "Expected to receive a response of existing headers."; - - public static final String SPREADSHEET_ID_NOT_FOUND_IN_URL_ERROR_MSG = "Cannot read spreadsheet URL. Please verify that the provided the Spreadsheet URL matches this pattern https://docs.google.com/spreadsheets/d/spreadsheetId_should_be_here/."; + public static final String EXPECTED_EXISTING_HEADERS_IN_RESPONSE_ERROR_MSG = + "Expected to receive a response of existing headers."; + public static final String SPREADSHEET_ID_NOT_FOUND_IN_URL_ERROR_MSG = + "Cannot read spreadsheet URL. Please verify that the provided the Spreadsheet URL matches this pattern https://docs.google.com/spreadsheets/d/spreadsheetId_should_be_here/."; } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/FieldName.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/FieldName.java index 29352d1716fa..3a352dd27c12 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/FieldName.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/FieldName.java @@ -27,5 +27,4 @@ public class FieldName { public static final String SORT_BY = "sortBy"; public static final String EMAIL_ADDRESS = "emailAddress"; public static final String GOOGLE_API_BASE_URL = "https://www.googleapis.com"; - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/domains/RowObject.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/domains/RowObject.java index 153036131a7a..a2d1639fdb25 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/domains/RowObject.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/domains/RowObject.java @@ -63,12 +63,14 @@ public RowObject(String[] headerValues, String[] rowValues, int rowIndex) { public RowObject initialize() { if (this.rowIndex == null) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Missing required field row index."); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Missing required field row index."); } try { this.currentRowIndex = Integer.parseInt(this.rowIndex); } catch (NumberFormatException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Unable to parse row index: " + this.rowIndex); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Unable to parse row index: " + this.rowIndex); } return this; } @@ -76,8 +78,7 @@ public RowObject initialize() { public RowData getAsSheetRowData(String[] referenceKeys) { RowData rowData = new RowData(); if (referenceKeys == null) { - rowData.setValues(this.valueMap.values() - .stream() + rowData.setValues(this.valueMap.values().stream() .map(value -> new CellData().setFormattedValue(value)) .collect(Collectors.toList())); return rowData; @@ -86,10 +87,9 @@ public RowData getAsSheetRowData(String[] referenceKeys) { List<CellData> cellDataList = new ArrayList<>(); for (String referenceKey : referenceKeys) { - cellDataList - .add(new CellData() - .setUserEnteredValue(new ExtendedValue() - .setStringValue(this.valueMap.getOrDefault(referenceKey, null)))); + cellDataList.add(new CellData() + .setUserEnteredValue( + new ExtendedValue().setStringValue(this.valueMap.getOrDefault(referenceKey, null)))); } return rowData.setValues(cellDataList); diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java index 0bf4cdee4988..5f6cd38dec88 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java @@ -11,7 +11,6 @@ import com.appsmith.external.models.MustacheBindingToken; import com.appsmith.external.models.OAuth2; import com.appsmith.external.models.Param; -import com.appsmith.external.models.Property; import com.appsmith.external.models.TriggerRequestDTO; import com.appsmith.external.models.TriggerResultDTO; import com.appsmith.external.plugins.BasePlugin; @@ -60,8 +59,7 @@ public class GoogleSheetsPlugin extends BasePlugin { // Setting max content length. This would've been coming from `spring.codec.max-in-memory-size` property if the // `WebClient` instance was loaded as an auto-wired bean. - public static final ExchangeStrategies EXCHANGE_STRATEGIES = ExchangeStrategies - .builder() + public static final ExchangeStrategies EXCHANGE_STRATEGIES = ExchangeStrategies.builder() .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(/* 10MB */ 10 * 1024 * 1024)) .build(); @@ -74,16 +72,15 @@ public static class GoogleSheetsPluginExecutor implements PluginExecutor<Void>, private static final int SMART_JSON_SUBSTITUTION_INDEX = 13; - private static final Set<String> jsonFields = new HashSet<>(Arrays.asList( - FieldName.ROW_OBJECT, - FieldName.ROW_OBJECTS - )); + private static final Set<String> jsonFields = + new HashSet<>(Arrays.asList(FieldName.ROW_OBJECT, FieldName.ROW_OBJECTS)); @Override - public Mono<ActionExecutionResult> executeParameterized(Void connection, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> executeParameterized( + Void connection, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { boolean smartJsonSubstitution; final Map<String, Object> formData = actionConfiguration.getFormData(); @@ -93,7 +90,8 @@ public Mono<ActionExecutionResult> executeParameterized(Void connection, if (!validConfigurationPresentInFormData(formData, FieldName.SMART_SUBSTITUTION)) { smartJsonSubstitution = true; } else { - Object ssubValue = getDataValueSafelyFromFormData(formData, FieldName.SMART_SUBSTITUTION, OBJECT_TYPE, true); + Object ssubValue = + getDataValueSafelyFromFormData(formData, FieldName.SMART_SUBSTITUTION, OBJECT_TYPE, true); if (ssubValue instanceof Boolean) { smartJsonSubstitution = (Boolean) ssubValue; } else if (ssubValue instanceof String) { @@ -111,14 +109,14 @@ public Mono<ActionExecutionResult> executeParameterized(Void connection, if (property != null) { // First extract all the bindings in order - List<MustacheBindingToken> mustacheKeysInOrder = MustacheHelper.extractMustacheKeysInOrder(property); + List<MustacheBindingToken> mustacheKeysInOrder = + MustacheHelper.extractMustacheKeysInOrder(property); // Replace all the bindings with a placeholder - String updatedValue = MustacheHelper.replaceMustacheWithPlaceholder(property, mustacheKeysInOrder); + String updatedValue = + MustacheHelper.replaceMustacheWithPlaceholder(property, mustacheKeysInOrder); - updatedValue = (String) smartSubstitutionOfBindings(updatedValue, - mustacheKeysInOrder, - executeActionDTO.getParams(), - parameters); + updatedValue = (String) smartSubstitutionOfBindings( + updatedValue, mustacheKeysInOrder, executeActionDTO.getParams(), parameters); setDataValueSafelyInFormData(formData, jsonField, updatedValue); } @@ -137,9 +135,10 @@ public Mono<ActionExecutionResult> executeParameterized(Void connection, return this.executeCommon(connection, datasourceConfiguration, actionConfiguration); } - public Mono<ActionExecutionResult> executeCommon(Void connection, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> executeCommon( + Void connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Initializing object for error condition ActionExecutionResult errorResult = new ActionExecutionResult(); @@ -155,8 +154,7 @@ public Mono<ActionExecutionResult> executeCommon(Void connection, if (executionMethod == null) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - ErrorMessages.MISSING_GSHEETS_METHOD_ERROR_MSG - )); + ErrorMessages.MISSING_GSHEETS_METHOD_ERROR_MSG)); } // Convert unreadable map to a DTO @@ -173,17 +171,23 @@ public Mono<ActionExecutionResult> executeCommon(Void connection, final OAuth2 oauth2 = (OAuth2) datasourceConfiguration.getAuthentication(); assert (oauth2.getAuthenticationResponse() != null); - // This will get list of authorised sheet ids from datasource config, and transform execution response to contain only authorised files + // This will get list of authorised sheet ids from datasource config, and transform execution response to + // contain only authorised files final Set<String> userAuthorizedSheetIds = getUserAuthorizedSheetIds(datasourceConfiguration); // Triggering the actual REST API call - return executionMethod.executePrerequisites(methodConfig, oauth2) - // This method call will populate the request with all the configurations it needs for a particular method + return executionMethod + .executePrerequisites(methodConfig, oauth2) + // This method call will populate the request with all the configurations it needs for a particular + // method .flatMap(res -> { - return executionMethod.getExecutionClient(client, methodConfig) + return executionMethod + .getExecutionClient(client, methodConfig) .headers(headers -> headers.set( "Authorization", - "Bearer " + oauth2.getAuthenticationResponse().getToken())) + "Bearer " + + oauth2.getAuthenticationResponse() + .getToken())) .exchange() .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) .map(response -> { @@ -191,8 +195,10 @@ public Mono<ActionExecutionResult> executeCommon(Void connection, ActionExecutionResult result = new ActionExecutionResult(); // Set response status - result.setStatusCode(response.getStatusCode().toString()); - result.setIsExecutionSuccess(response.getStatusCode().is2xxSuccessful()); + result.setStatusCode( + response.getStatusCode().toString()); + result.setIsExecutionSuccess( + response.getStatusCode().is2xxSuccessful()); HttpHeaders headers = response.getHeaders(); // Convert the headers into json tree to store in the results @@ -200,21 +206,18 @@ public Mono<ActionExecutionResult> executeCommon(Void connection, try { headerInJsonString = objectMapper.writeValueAsString(headers); } catch (JsonProcessingException e) { - throw Exceptions.propagate( - new AppsmithPluginException(GSheetsPluginError.RESPONSE_PROCESSING_ERROR, e)); + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.RESPONSE_PROCESSING_ERROR, e)); } // Set headers in the result now try { result.setHeaders(objectMapper.readTree(headerInJsonString)); } catch (IOException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - headerInJsonString, - e.getMessage() - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, + headerInJsonString, + e.getMessage())); } // Choose body depending on response status @@ -227,7 +230,8 @@ public Mono<ActionExecutionResult> executeCommon(Void connection, JsonNode jsonNodeBody = objectMapper.readTree(jsonBody); if (response.getStatusCode().is2xxSuccessful()) { - result.setBody(executionMethod.transformExecutionResponse(jsonNodeBody, methodConfig, userAuthorizedSheetIds)); + result.setBody(executionMethod.transformExecutionResponse( + jsonNodeBody, methodConfig, userAuthorizedSheetIds)); } else { result.setBody(jsonNodeBody .get("error") @@ -235,13 +239,10 @@ public Mono<ActionExecutionResult> executeCommon(Void connection, .asText()); } } catch (IOException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - new String(body), - e.getMessage() - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, + new String(body), + e.getMessage())); } return result; @@ -249,8 +250,11 @@ public Mono<ActionExecutionResult> executeCommon(Void connection, .onErrorResume(e -> { errorResult.setBody(Exceptions.unwrap(e).getMessage()); log.debug("Received error on Google Sheets action execution", e); - if (! (e instanceof AppsmithPluginException)) { - e = new AppsmithPluginException(GSheetsPluginError.QUERY_EXECUTION_FAILED, ErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e); + if (!(e instanceof AppsmithPluginException)) { + e = new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e); } errorResult.setErrorInfo(e); return Mono.just(errorResult); @@ -272,9 +276,13 @@ private Mono<ActionExecutionResult> handleEmptyMono() { } @Override - public Mono<ActionExecutionResult> execute(Void connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + Void connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Unused function - return Mono.error(new AppsmithPluginException(GSheetsPluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); + return Mono.error( + new AppsmithPluginException(GSheetsPluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); } @Override @@ -293,19 +301,22 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) { String jsonBody = (String) input; Param param = (Param) args[0]; - return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue(jsonBody, value, null, insertedParams, null, param); + return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue( + jsonBody, value, null, insertedParams, null, param); } @Override - public Mono<TriggerResultDTO> trigger(Void connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) { + public Mono<TriggerResultDTO> trigger( + Void connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) { final TriggerMethod triggerMethod = GoogleSheetsMethodStrategy.getTriggerMethod(request, objectMapper); MethodConfig methodConfig = new MethodConfig(request); @@ -314,18 +325,19 @@ public Mono<TriggerResultDTO> trigger(Void connection, DatasourceConfiguration d triggerMethod.validateTriggerMethodRequest(methodConfig); - WebClient client = webClientBuilder - .exchangeStrategies(EXCHANGE_STRATEGIES) - .build(); + WebClient client = + webClientBuilder.exchangeStrategies(EXCHANGE_STRATEGIES).build(); // Authentication will already be valid at this point final OAuth2 oauth2 = (OAuth2) datasourceConfiguration.getAuthentication(); assert (oauth2.getAuthenticationResponse() != null); - // This will get list of authorised sheet ids from datasource config, and transform trigger response to contain only authorised files + // This will get list of authorised sheet ids from datasource config, and transform trigger response to + // contain only authorised files Set<String> userAuthorizedSheetIds = getUserAuthorizedSheetIds(datasourceConfiguration); - return triggerMethod.getTriggerClient(client, methodConfig) + return triggerMethod + .getTriggerClient(client, methodConfig) .headers(headers -> headers.set( "Authorization", "Bearer " + oauth2.getAuthenticationResponse().getToken())) @@ -343,30 +355,22 @@ public Mono<TriggerResultDTO> trigger(Void connection, DatasourceConfiguration d try { jsonNodeBody = objectMapper.readTree(jsonBody); } catch (JsonProcessingException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - jsonBody, - e.getMessage() - )); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, jsonBody, e.getMessage())); } if (response.getStatusCode().is2xxSuccessful()) { - final JsonNode triggerResponse = triggerMethod.transformTriggerResponse(jsonNodeBody, methodConfig, userAuthorizedSheetIds); + final JsonNode triggerResponse = triggerMethod.transformTriggerResponse( + jsonNodeBody, methodConfig, userAuthorizedSheetIds); final TriggerResultDTO triggerResultDTO = new TriggerResultDTO(); triggerResultDTO.setTrigger(triggerResponse); return triggerResultDTO; } else { - throw Exceptions.propagate( - new AppsmithPluginException( - GSheetsPluginError.QUERY_EXECUTION_FAILED, - ErrorMessages.UNSUCCESSFUL_RESPONSE_ERROR_MSG, - jsonNodeBody - .get("error") - .get("message") - .asText(), - "HTTP " + response.getStatusCode()) - ); + throw Exceptions.propagate(new AppsmithPluginException( + GSheetsPluginError.QUERY_EXECUTION_FAILED, + ErrorMessages.UNSUCCESSFUL_RESPONSE_ERROR_MSG, + jsonNodeBody.get("error").get("message").asText(), + "HTTP " + response.getStatusCode())); } }); } @@ -379,7 +383,10 @@ public Mono<TriggerResultDTO> trigger(Void connection, DatasourceConfiguration d * @param pluginSpecificTemplateParams plugin specified fields like S3 bucket name etc */ @Override - public void updateCrudTemplateFormData(Map<String, Object> formData, Map<String, String> mappedColumns, Map<String, String> pluginSpecificTemplateParams) { + public void updateCrudTemplateFormData( + Map<String, Object> formData, + Map<String, String> mappedColumns, + Map<String, String> pluginSpecificTemplateParams) { pluginSpecificTemplateParams.forEach((k, v) -> { if (formData.containsKey(k)) { setDataValueSafelyInFormData(formData, k, v); @@ -395,6 +402,5 @@ public void updateCrudTemplateFormData(Map<String, Object> formData, Map<String, public Mono<DatasourceConfiguration> getDatasourceMetadata(DatasourceConfiguration datasourceConfiguration) { return GetDatasourceMetadataMethod.getDatasourceMetadata(datasourceConfiguration); } - } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/exceptions/GSheetsPluginError.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/exceptions/GSheetsPluginError.java index e7e448015270..4d3d60dffa53 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/exceptions/GSheetsPluginError.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/exceptions/GSheetsPluginError.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum GSheetsPluginError implements BasePluginError { QUERY_EXECUTION_FAILED( @@ -16,8 +15,7 @@ public enum GSheetsPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), RESPONSE_PROCESSING_ERROR( 500, "PE-GSH-5001", @@ -26,9 +24,7 @@ public enum GSheetsPluginError implements BasePluginError { "Response processing error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ) - ; + "{2}"); private final Integer httpErrorCode; private final String appErrorCode; @@ -41,8 +37,15 @@ public enum GSheetsPluginError implements BasePluginError { private final String downstreamErrorCode; - GSheetsPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + GSheetsPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -69,5 +72,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/utils/SheetsUtil.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/utils/SheetsUtil.java index 91ebd3bfc0e9..08185de3dcf7 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/utils/SheetsUtil.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/utils/SheetsUtil.java @@ -1,5 +1,6 @@ package com.external.utils; +import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.OAuth2; import com.external.enums.GoogleSheetMethodEnum; import com.fasterxml.jackson.databind.JsonNode; @@ -9,8 +10,8 @@ import java.util.Map; import java.util.Set; import java.util.regex.Pattern; + import static org.apache.commons.collections.CollectionUtils.isEmpty; -import com.appsmith.external.models.DatasourceConfiguration; public class SheetsUtil { @@ -24,7 +25,7 @@ public static int getColumnNumber(String columnName) { for (int i = 0; i < columnName.length(); i++) { String character = String.valueOf(columnName.charAt(i)); character = character.toUpperCase(); - column = column * 26 + ((int)character.charAt(0)) - 64; + column = column * 26 + ((int) character.charAt(0)) - 64; } return column; } @@ -36,16 +37,24 @@ public static Set<String> getUserAuthorizedSheetIds(DatasourceConfiguration data if (!isEmpty(datasourceConfiguration.getProperties()) && datasourceConfiguration.getProperties().size() > 1 && datasourceConfiguration.getProperties().get(USER_AUTHORIZED_SHEET_IDS_INDEX) != null - && datasourceConfiguration.getProperties().get(USER_AUTHORIZED_SHEET_IDS_INDEX).getValue() != null + && datasourceConfiguration + .getProperties() + .get(USER_AUTHORIZED_SHEET_IDS_INDEX) + .getValue() + != null && oAuth2.getScope() != null && oAuth2.getScope().contains(FILE_SPECIFIC_DRIVE_SCOPE)) { - ArrayList<String> temp = (ArrayList) datasourceConfiguration.getProperties().get(USER_AUTHORIZED_SHEET_IDS_INDEX).getValue(); + ArrayList<String> temp = (ArrayList) datasourceConfiguration + .getProperties() + .get(USER_AUTHORIZED_SHEET_IDS_INDEX) + .getValue(); return new HashSet<String>(temp); } return null; } - public static Map<String, String> getSpreadsheetData(JsonNode file, Set<String> userAuthorizedSheetIds, GoogleSheetMethodEnum methodType) { + public static Map<String, String> getSpreadsheetData( + JsonNode file, Set<String> userAuthorizedSheetIds, GoogleSheetMethodEnum methodType) { // This if block will be executed for all sheets modality if (userAuthorizedSheetIds == null) { return extractSheetData((JsonNode) file, methodType); @@ -62,15 +71,14 @@ public static Map<String, String> getSpreadsheetData(JsonNode file, Set<String> } private static Map<String, String> extractSheetData(JsonNode file, GoogleSheetMethodEnum methodType) { - final String spreadSheetUrl = "https://docs.google.com/spreadsheets/d/" + file.get("id").asText() + "/edit"; + final String spreadSheetUrl = + "https://docs.google.com/spreadsheets/d/" + file.get("id").asText() + "/edit"; switch (methodType) { case TRIGGER: - return Map.of("label", file.get("name").asText(), - "value", spreadSheetUrl); + return Map.of("label", file.get("name").asText(), "value", spreadSheetUrl); default: - return Map.of("id", file.get("id").asText(), - "name", file.get("name").asText(), - "url", spreadSheetUrl); + return Map.of( + "id", file.get("id").asText(), "name", file.get("name").asText(), "url", spreadSheetUrl); } } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/FileInfoMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/FileInfoMethodTest.java index 539db8f6dbe2..ee3d3dd467d6 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/FileInfoMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/FileInfoMethodTest.java @@ -11,7 +11,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -79,7 +78,8 @@ public void testTransformExecutionResponse_emptySheets_returnsEmpty() throws Jso public void testTransformExecutionResponse_validSheets_toListOfSheets() throws JsonProcessingException { final String jsonString = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; - final String sheetMetadataString = "{\"sheetId\":\"1\", \"title\":\"test\", \"sheetType\":\"GRID\", \"index\":0}"; + final String sheetMetadataString = + "{\"sheetId\":\"1\", \"title\":\"test\", \"sheetType\":\"GRID\", \"index\":0}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); @@ -94,7 +94,8 @@ public void testTransformExecutionResponse_validSheets_toListOfSheets() throws J assertNotNull(result); assertTrue(result.isObject()); assertEquals(1, result.get("sheets").size()); - assertTrue("test".equalsIgnoreCase(result.get("sheets").get(0).get("title").asText())); + assertTrue( + "test".equalsIgnoreCase(result.get("sheets").get(0).get("title").asText())); } @Test diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/FileListMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/FileListMethodTest.java index 1d87965346a6..4fd54eafe4b5 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/FileListMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/FileListMethodTest.java @@ -127,7 +127,8 @@ public void testTransformTriggerResponse_withSheets_returnsDropdownOptions() thr public void testTransformTriggerResponse_withAllSheetsAccess_returnsAllSheets() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"files\":[{\"id\":\"id1\",\"name\":\"test1\"},{\"id\":\"id2\",\"name\":\"test2\"}]}"; + final String jsonString = + "{\"files\":[{\"id\":\"id1\",\"name\":\"test1\"},{\"id\":\"id2\",\"name\":\"test2\"}]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); @@ -157,7 +158,8 @@ public void testTransformTriggerResponse_withAllSheetsAccess_returnsAllSheets() public void testTransformTriggerResponse_withSpecificSheets_returnsSpecificSheets() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"files\":[{\"id\":\"id1\",\"name\":\"test1\"},{\"id\":\"id2\",\"name\":\"test2\"}]}"; + final String jsonString = + "{\"files\":[{\"id\":\"id1\",\"name\":\"test1\"},{\"id\":\"id2\",\"name\":\"test2\"}]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); Set<String> userAuthorizedSheetIds = new HashSet<String>(); @@ -183,7 +185,8 @@ public void testTransformTriggerResponse_withSpecificSheets_returnsSpecificSheet public void testTransformExecutionResponse_withAllSheetsAccess_returnsAllSheets() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"files\":[{\"id\":\"id1\",\"name\":\"test1\"},{\"id\":\"id2\",\"name\":\"test2\"}]}"; + final String jsonString = + "{\"files\":[{\"id\":\"id1\",\"name\":\"test1\"},{\"id\":\"id2\",\"name\":\"test2\"}]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); @@ -212,10 +215,12 @@ public void testTransformExecutionResponse_withAllSheetsAccess_returnsAllSheets( } @Test - public void testTransformExecutionResponse_withSpecificSheets_returnsSpecificSheets() throws JsonProcessingException { + public void testTransformExecutionResponse_withSpecificSheets_returnsSpecificSheets() + throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"files\":[{\"id\":\"id1\",\"name\":\"test1\"},{\"id\":\"id2\",\"name\":\"test2\"}]}"; + final String jsonString = + "{\"files\":[{\"id\":\"id1\",\"name\":\"test1\"},{\"id\":\"id2\",\"name\":\"test2\"}]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); Set<String> userAuthorizedSheetIds = new HashSet<String>(); diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/GetDatasourceMetadataMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/GetDatasourceMetadataMethodTest.java index 57984b65da3a..d1c712e9eeaa 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/GetDatasourceMetadataMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/GetDatasourceMetadataMethodTest.java @@ -13,10 +13,11 @@ public class GetDatasourceMetadataMethodTest { public void verifyEmailStorageInPropertiesInDatasourceConfiguration() { List<Property> properties = new ArrayList<>(); String emailAddress = "mockEmailAddress"; - List<Property> returnedProperties= GetDatasourceMetadataMethod.setPropertiesWithEmailAddress(properties, emailAddress); - assert(!returnedProperties.isEmpty()); - assert(returnedProperties.get(0).getKey().equals(FieldName.EMAIL_ADDRESS)); - assert(returnedProperties.get(0).getValue().equals(emailAddress)); + List<Property> returnedProperties = + GetDatasourceMetadataMethod.setPropertiesWithEmailAddress(properties, emailAddress); + assert (!returnedProperties.isEmpty()); + assert (returnedProperties.get(0).getKey().equals(FieldName.EMAIL_ADDRESS)); + assert (returnedProperties.get(0).getValue().equals(emailAddress)); } @Test @@ -27,12 +28,13 @@ public void verifyNewerEmailReplacesOldEmailInSamePropertyObject() { properties.add(oldEmailProperty); String emailAddress = "mockEmailAddress"; - List<Property> returnedProperties= GetDatasourceMetadataMethod.setPropertiesWithEmailAddress(properties, emailAddress); - assert(!returnedProperties.isEmpty()); - assert(returnedProperties.size() == 1); - assert(returnedProperties.get(0).getKey().equals(FieldName.EMAIL_ADDRESS)); - assert(returnedProperties.get(0).getValue().equals(emailAddress)); - assert(returnedProperties.get(0).equals(oldEmailProperty)); + List<Property> returnedProperties = + GetDatasourceMetadataMethod.setPropertiesWithEmailAddress(properties, emailAddress); + assert (!returnedProperties.isEmpty()); + assert (returnedProperties.size() == 1); + assert (returnedProperties.get(0).getKey().equals(FieldName.EMAIL_ADDRESS)); + assert (returnedProperties.get(0).getValue().equals(emailAddress)); + assert (returnedProperties.get(0).equals(oldEmailProperty)); } @Test @@ -42,10 +44,11 @@ public void verifyEmailPropertyReplacesOtherPropertyObjectAtZeroIndexInPropertie properties.add(otherProperty); String emailAddress = "mockEmailAddress"; - List<Property> returnedProperties= GetDatasourceMetadataMethod.setPropertiesWithEmailAddress(properties, emailAddress); - assert(!returnedProperties.isEmpty()); - assert(returnedProperties.size() == 1); - assert(returnedProperties.get(0).getKey().equals(FieldName.EMAIL_ADDRESS)); - assert(returnedProperties.get(0).getValue().equals(emailAddress)); + List<Property> returnedProperties = + GetDatasourceMetadataMethod.setPropertiesWithEmailAddress(properties, emailAddress); + assert (!returnedProperties.isEmpty()); + assert (returnedProperties.size() == 1); + assert (returnedProperties.get(0).getKey().equals(FieldName.EMAIL_ADDRESS)); + assert (returnedProperties.get(0).getValue().equals(emailAddress)); } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/GetStructureMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/GetStructureMethodTest.java index f3a7415bd664..8de401af4b30 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/GetStructureMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/GetStructureMethodTest.java @@ -24,7 +24,10 @@ public void testTransformExecutionResponse_missingJSON_throwsException() { GetStructureMethod getStructureMethod = new GetStructureMethod(objectMapper); try { - JsonNode result = getStructureMethod.transformExecutionResponse(null, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = getStructureMethod.transformExecutionResponse( + null, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertFalse(result == null); } catch (AppsmithPluginException e) { assertTrue(ErrorMessages.MISSING_VALID_RESPONSE_ERROR_MSG.equalsIgnoreCase(e.getMessage())); @@ -53,18 +56,20 @@ public void testTransformExecutionResponse_missingValues_returnsEmpty() throws J public void testTransformExecutionResponse_HeadersOnly_returnsValue() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"range\":\"Sheet1!A1:D1\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"range\":\"Sheet1!A1:D1\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}" + + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); GetStructureMethod getStructureMethod = new GetStructureMethod(objectMapper); - JsonNode result = getStructureMethod.transformExecutionResponse(jsonNode, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = getStructureMethod.transformExecutionResponse( + jsonNode, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertNotNull(result); assertTrue(result.isArray()); @@ -75,21 +80,23 @@ public void testTransformExecutionResponse_HeadersOnly_returnsValue() throws Jso public void testTransformExecutionResponse_emptyStartingRows_toListOfObjects() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"range\":\"Sheet1!A1:D1\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + - "{\"range\":\"Sheet1!A2:D2\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[]]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"range\":\"Sheet1!A1:D1\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + + "{\"range\":\"Sheet1!A2:D2\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[]]}" + + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); GetStructureMethod getStructureMethod = new GetStructureMethod(objectMapper); - JsonNode result = getStructureMethod.transformExecutionResponse(jsonNode, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = getStructureMethod.transformExecutionResponse( + jsonNode, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertNotNull(result); assertTrue(result.isArray() && result.size() == 1); @@ -102,21 +109,23 @@ public void testTransformExecutionResponse_emptyStartingRows_toListOfObjects() t public void testTransformExecutionResponse_emptyRows_returnsIndices() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"range\":\"Sheet1!A1:D1\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + - "{\"range\":\"Sheet1!A2:D2\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[]]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"range\":\"Sheet1!A1:D1\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + + "{\"range\":\"Sheet1!A2:D2\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[]]}" + + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); GetStructureMethod getStructureMethod = new GetStructureMethod(objectMapper); - JsonNode result = getStructureMethod.transformExecutionResponse(jsonNode, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = getStructureMethod.transformExecutionResponse( + jsonNode, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertNotNull(result); assertTrue(result.isArray()); @@ -128,65 +137,68 @@ public void testTransformExecutionResponse_emptyRows_returnsIndices() throws Jso public void testTransformExecutionResponse_fetchNonEmptyRows() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"range\":\"Sheet1!A1:D2\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"\",\"\",\"\",\"\"],[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + - "{\"range\":\"Sheet1!A3:D3\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Bean\",\"Sean\",\"Dean\",\"Mean\"]]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"range\":\"Sheet1!A1:D2\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"\",\"\",\"\",\"\"],[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + + "{\"range\":\"Sheet1!A3:D3\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Bean\",\"Sean\",\"Dean\",\"Mean\"]]}" + + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); GetStructureMethod getStructureMethod = new GetStructureMethod(objectMapper); - JsonNode result = getStructureMethod.transformExecutionResponse(jsonNode, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = getStructureMethod.transformExecutionResponse( + jsonNode, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertNotNull(result); assertTrue(result.isArray()); assertEquals(1, result.size()); } - @Test public void testTransformExecutionResponse_VerifyEndResult() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"range\":\"Sheet1!A1:D1\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + - "{\"range\":\"Sheet1!A2:D2\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Luke\",\"Make\",\"Duke\",\"Cake\"]]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"range\":\"Sheet1!A1:D1\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + + "{\"range\":\"Sheet1!A2:D2\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Luke\",\"Make\",\"Duke\",\"Cake\"]]}" + + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); GetStructureMethod getStructureMethod = new GetStructureMethod(objectMapper); - JsonNode result = getStructureMethod.transformExecutionResponse(jsonNode, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = getStructureMethod.transformExecutionResponse( + jsonNode, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertNotNull(result); - assertEquals(result.toString(), "[{\"Name\":\"Luke\",\"Actor\":\"Make\",\"Music\":\"Duke\",\"Director\":\"Cake\",\"rowIndex\":\"0\"}]"); - + assertEquals( + result.toString(), + "[{\"Name\":\"Luke\",\"Actor\":\"Make\",\"Music\":\"Duke\",\"Director\":\"Cake\",\"rowIndex\":\"0\"}]"); } @Test public void testTransformTriggerResponse_withValidHeaders_returnsDropdownOptions() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"range\":\"Sheet1!A1:D1\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + - "{\"range\":\"Sheet1!A2:D2\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Luke\",\"Make\",\"Duke\",\"Cake\"]]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"range\":\"Sheet1!A1:D1\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Name\",\"Actor\",\"Music\",\"Director\"]]}," + + "{\"range\":\"Sheet1!A2:D2\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Luke\",\"Make\",\"Duke\",\"Cake\"]]}" + + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); @@ -202,8 +214,5 @@ public void testTransformTriggerResponse_withValidHeaders_returnsDropdownOptions Map.of("label", "Music", "value", "Music"), Map.of("label", "Director", "value", "Director")); assertEquals(objectMapper.valueToTree(expectedColumnsList), result); - } - - } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/MethodConfigTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/MethodConfigTest.java index 5e90481d2ebd..79dc8734e30d 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/MethodConfigTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/MethodConfigTest.java @@ -1,6 +1,5 @@ package com.external.config; - import com.appsmith.external.helpers.PluginUtils; import org.junit.jupiter.api.Test; @@ -16,7 +15,7 @@ public void testWhiteSpaceRemovalForIntegerParsingErrors() throws Exception { MethodConfig methodConfig; final String[] testPropKeys = {"range", "tableHeaderIndex", "rowIndex"}; - //Test data Expected output vs inputs + // Test data Expected output vs inputs Map<String, String> testDataMap = new HashMap<String, String>(); testDataMap.put("2", "2 "); testDataMap.put("22", " 22 "); @@ -49,46 +48,44 @@ public void testWhiteSpaceRemovalForIntegerParsingErrors() throws Exception { assertEquals(e.getKey(), methodConfig.getRowIndex()); break; } - } } } -// @Test -// public void testInitialEmptyWhereCondition() { -// Map condition = new LinkedHashMap(); -// condition.put(PATH_KEY, ""); -// condition.put(VALUE_KEY, ""); -// -// List<Map> listOfConditions = new ArrayList<>(); -// listOfConditions.add(condition); -// -// Property property = new Property("where", listOfConditions); -// List<Property> propertyList = new ArrayList(); -// propertyList.add(property); -// -// MethodConfig methodConfig = new MethodConfig(propertyList); -// List<Condition> parsedWhereConditions = methodConfig.getWhereConditions(); -// assertEquals(0, parsedWhereConditions.size()); -// } -// -// @Test(expected = AppsmithPluginException.class) -// public void testNonEmptyOperatorWithEmptyColumnWhereCondition() { -// Map condition = new LinkedHashMap(); -// condition.put(PATH_KEY, ""); -// condition.put(OPERATOR_KEY, "EQ"); -// condition.put(VALUE_KEY, ""); -// -// List<Map> listOfConditions = new ArrayList<>(); -// listOfConditions.add(condition); -// -// Property property = new Property("where", listOfConditions); -// List<Property> propertyList = new ArrayList(); -// propertyList.add(property); -// -// MethodConfig methodConfig = new MethodConfig(propertyList); -// List<Condition> parsedWhereConditions = methodConfig.getWhereConditions(); -// assertEquals(0, parsedWhereConditions.size()); -// } + // @Test + // public void testInitialEmptyWhereCondition() { + // Map condition = new LinkedHashMap(); + // condition.put(PATH_KEY, ""); + // condition.put(VALUE_KEY, ""); + // + // List<Map> listOfConditions = new ArrayList<>(); + // listOfConditions.add(condition); + // + // Property property = new Property("where", listOfConditions); + // List<Property> propertyList = new ArrayList(); + // propertyList.add(property); + // + // MethodConfig methodConfig = new MethodConfig(propertyList); + // List<Condition> parsedWhereConditions = methodConfig.getWhereConditions(); + // assertEquals(0, parsedWhereConditions.size()); + // } + // + // @Test(expected = AppsmithPluginException.class) + // public void testNonEmptyOperatorWithEmptyColumnWhereCondition() { + // Map condition = new LinkedHashMap(); + // condition.put(PATH_KEY, ""); + // condition.put(OPERATOR_KEY, "EQ"); + // condition.put(VALUE_KEY, ""); + // + // List<Map> listOfConditions = new ArrayList<>(); + // listOfConditions.add(condition); + // + // Property property = new Property("where", listOfConditions); + // List<Property> propertyList = new ArrayList(); + // propertyList.add(property); + // + // MethodConfig methodConfig = new MethodConfig(propertyList); + // List<Condition> parsedWhereConditions = methodConfig.getWhereConditions(); + // assertEquals(0, parsedWhereConditions.size()); + // } } - diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsAppendMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsAppendMethodTest.java index fa045ae7d151..01a5dec6a3ee 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsAppendMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsAppendMethodTest.java @@ -11,14 +11,14 @@ import com.external.plugins.GoogleSheetsPlugin; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class RowsAppendMethodTest { GoogleSheetsPlugin.GoogleSheetsPluginExecutor pluginExecutor = new GoogleSheetsPlugin.GoogleSheetsPluginExecutor(); @@ -29,19 +29,30 @@ public void testRowAppendMethodWithEmptyBody() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setAuthentication(getOAuthObject()); - Map<String,Object> formData = new HashMap<>(); - formData.put("command", Collections.singletonMap("data","INSERT_ONE")); - formData.put("entityType", Collections.singletonMap("data","ROWS")); - formData.put("tableHeaderIndex", Collections.singletonMap("data","1")); - formData.put("projection", Collections.singletonMap("data",Collections.emptyList())); - formData.put("queryFormat", Collections.singletonMap("data","ROWS")); - formData.put("range", Collections.singletonMap("data","")); - formData.put("where", Collections.singletonMap("data",Map.of("condition","AND","children",Collections.singletonList(Collections.singletonMap("condition","LT"))))); - formData.put("pagination",Collections.singletonMap("data",Map.of("limit",20,"offset",0))); - formData.put("smartSubstitution",Collections.singletonMap("data",true)); - formData.put("sheetUrl",Collections.singletonMap("data","https://docs.google.com/spreadsheets/d/123/edit")); - formData.put("sheetName",Collections.singletonMap("data","portSheet")); - formData.put("sortBy",Collections.singletonMap("data",Collections.singletonList(Map.of("column","","order","Ascending")))); + Map<String, Object> formData = new HashMap<>(); + formData.put("command", Collections.singletonMap("data", "INSERT_ONE")); + formData.put("entityType", Collections.singletonMap("data", "ROWS")); + formData.put("tableHeaderIndex", Collections.singletonMap("data", "1")); + formData.put("projection", Collections.singletonMap("data", Collections.emptyList())); + formData.put("queryFormat", Collections.singletonMap("data", "ROWS")); + formData.put("range", Collections.singletonMap("data", "")); + formData.put( + "where", + Collections.singletonMap( + "data", + Map.of( + "condition", + "AND", + "children", + Collections.singletonList(Collections.singletonMap("condition", "LT"))))); + formData.put("pagination", Collections.singletonMap("data", Map.of("limit", 20, "offset", 0))); + formData.put("smartSubstitution", Collections.singletonMap("data", true)); + formData.put("sheetUrl", Collections.singletonMap("data", "https://docs.google.com/spreadsheets/d/123/edit")); + formData.put("sheetName", Collections.singletonMap("data", "portSheet")); + formData.put( + "sortBy", + Collections.singletonMap( + "data", Collections.singletonList(Map.of("column", "", "order", "Ascending")))); ActionConfiguration actionConfiguration = new ActionConfiguration(); @@ -50,19 +61,20 @@ public void testRowAppendMethodWithEmptyBody() { actionConfiguration.setEncodeParamsToggle(true); actionConfiguration.setFormData(formData); - String[] testDataArray = {null,"","{}"}; + String[] testDataArray = {null, "", "{}"}; - for(int i=0; i<testDataArray.length; i++) { + for (int i = 0; i < testDataArray.length; i++) { - formData.put("rowObjects",new HashMap<>(Collections.singletonMap("data",testDataArray[i]))); + formData.put("rowObjects", new HashMap<>(Collections.singletonMap("data", testDataArray[i]))); AppsmithPluginException appsmithPluginException = assertThrows(AppsmithPluginException.class, () -> { - pluginExecutor.executeParameterized(null,new ExecuteActionDTO(),datasourceConfiguration,actionConfiguration); + pluginExecutor.executeParameterized( + null, new ExecuteActionDTO(), datasourceConfiguration, actionConfiguration); }); String actualMessage = appsmithPluginException.getMessage(); - assertEquals(actualMessage,ErrorMessages.EMPTY_ROW_OBJECT_MESSAGE); + assertEquals(actualMessage, ErrorMessages.EMPTY_ROW_OBJECT_MESSAGE); } } @@ -70,13 +82,16 @@ public void testRowAppendMethodWithEmptyBody() { * Simulated oAuth2 object, just to bypass few case. * @return */ - private OAuth2 getOAuthObject(){ + private OAuth2 getOAuthObject() { OAuth2 oAuth2 = new OAuth2(); - oAuth2.setAuthenticationResponse(new AuthenticationResponse() ); + oAuth2.setAuthenticationResponse(new AuthenticationResponse()); oAuth2.getAuthenticationResponse().setToken("welcome123"); oAuth2.setGrantType(OAuth2.Type.AUTHORIZATION_CODE); - oAuth2.setScopeString("https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly"); - oAuth2.setScope(Set.of("https://www.googleapis.com/auth/spreadsheets.readonly","https://www.googleapis.com/auth/drive.readonly")); + oAuth2.setScopeString( + "https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly"); + oAuth2.setScope(Set.of( + "https://www.googleapis.com/auth/spreadsheets.readonly", + "https://www.googleapis.com/auth/drive.readonly")); return oAuth2; } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsBulkAppendMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsBulkAppendMethodTest.java index d8adee2dde92..f1b2e7ea1cd1 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsBulkAppendMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsBulkAppendMethodTest.java @@ -35,13 +35,12 @@ public class RowsBulkAppendMethodTest { public void testBulkAppendHandleEmptyMonoExecutePrerequisites() { String[] testDataArray = {"[]", ""}; - for(int i=0; i<testDataArray.length; i++) { + for (int i = 0; i < testDataArray.length; i++) { RowsBulkAppendMethod bulkAppend = new RowsBulkAppendMethod(objectMapper); - Mono<Object> monoTest = bulkAppend.executePrerequisites(getMethodConfigObject(testDataArray[i]), getOAuthObject()); + Mono<Object> monoTest = + bulkAppend.executePrerequisites(getMethodConfigObject(testDataArray[i]), getOAuthObject()); - StepVerifier.create(monoTest) - .expectComplete() - .verify(); + StepVerifier.create(monoTest).expectComplete().verify(); } } @@ -51,19 +50,30 @@ public void testRowBulkAppendMethodWithEmptyBody() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setAuthentication(getOAuthObject()); - Map<String,Object> formData = new HashMap<>(); - formData.put("command", Collections.singletonMap("data","INSERT_MANY")); - formData.put("entityType", Collections.singletonMap("data","ROWS")); - formData.put("tableHeaderIndex", Collections.singletonMap("data","1")); - formData.put("projection", Collections.singletonMap("data",Collections.emptyList())); - formData.put("queryFormat", Collections.singletonMap("data","ROWS")); - formData.put("range", Collections.singletonMap("data","")); - formData.put("where", Collections.singletonMap("data",Map.of("condition","AND","children",Collections.singletonList(Collections.singletonMap("condition","LT"))))); - formData.put("pagination",Collections.singletonMap("data",Map.of("limit",20,"offset",0))); - formData.put("smartSubstitution",Collections.singletonMap("data",true)); - formData.put("sheetUrl",Collections.singletonMap("data","https://docs.google.com/spreadsheets/d/123/edit")); - formData.put("sheetName",Collections.singletonMap("data","portSheet")); - formData.put("sortBy",Collections.singletonMap("data",Collections.singletonList(Map.of("column","","order","Ascending")))); + Map<String, Object> formData = new HashMap<>(); + formData.put("command", Collections.singletonMap("data", "INSERT_MANY")); + formData.put("entityType", Collections.singletonMap("data", "ROWS")); + formData.put("tableHeaderIndex", Collections.singletonMap("data", "1")); + formData.put("projection", Collections.singletonMap("data", Collections.emptyList())); + formData.put("queryFormat", Collections.singletonMap("data", "ROWS")); + formData.put("range", Collections.singletonMap("data", "")); + formData.put( + "where", + Collections.singletonMap( + "data", + Map.of( + "condition", + "AND", + "children", + Collections.singletonList(Collections.singletonMap("condition", "LT"))))); + formData.put("pagination", Collections.singletonMap("data", Map.of("limit", 20, "offset", 0))); + formData.put("smartSubstitution", Collections.singletonMap("data", true)); + formData.put("sheetUrl", Collections.singletonMap("data", "https://docs.google.com/spreadsheets/d/123/edit")); + formData.put("sheetName", Collections.singletonMap("data", "portSheet")); + formData.put( + "sortBy", + Collections.singletonMap( + "data", Collections.singletonList(Map.of("column", "", "order", "Ascending")))); ActionConfiguration actionConfiguration = new ActionConfiguration(); @@ -72,35 +82,43 @@ public void testRowBulkAppendMethodWithEmptyBody() { actionConfiguration.setEncodeParamsToggle(true); actionConfiguration.setFormData(formData); - String[] testDataArray = {null,"","{}"}; + String[] testDataArray = {null, "", "{}"}; - String[] expectedErrorMessageArray = {ErrorMessages.EMPTY_ROW_ARRAY_OBJECT_MESSAGE,ErrorMessages.REQUEST_BODY_NOT_ARRAY,ErrorMessages.REQUEST_BODY_NOT_ARRAY}; + String[] expectedErrorMessageArray = { + ErrorMessages.EMPTY_ROW_ARRAY_OBJECT_MESSAGE, + ErrorMessages.REQUEST_BODY_NOT_ARRAY, + ErrorMessages.REQUEST_BODY_NOT_ARRAY + }; - for(int i=0; i<testDataArray.length; i++) { + for (int i = 0; i < testDataArray.length; i++) { - formData.put("rowObjects",new HashMap<>(Collections.singletonMap("data",testDataArray[i]))); + formData.put("rowObjects", new HashMap<>(Collections.singletonMap("data", testDataArray[i]))); AppsmithPluginException appsmithPluginException = assertThrows(AppsmithPluginException.class, () -> { - pluginExecutor.executeParameterized(null,new ExecuteActionDTO(),datasourceConfiguration,actionConfiguration); + pluginExecutor.executeParameterized( + null, new ExecuteActionDTO(), datasourceConfiguration, actionConfiguration); }); String actualMessage = appsmithPluginException.getMessage(); - assertEquals(actualMessage,expectedErrorMessageArray[i]); + assertEquals(actualMessage, expectedErrorMessageArray[i]); } } - /** + /** * Simulated oAuth2 object, just to bypass few case. * @return */ - private OAuth2 getOAuthObject(){ + private OAuth2 getOAuthObject() { OAuth2 oAuth2 = new OAuth2(); - oAuth2.setAuthenticationResponse(new AuthenticationResponse() ); + oAuth2.setAuthenticationResponse(new AuthenticationResponse()); oAuth2.getAuthenticationResponse().setToken("welcome123"); oAuth2.setGrantType(OAuth2.Type.AUTHORIZATION_CODE); - oAuth2.setScopeString("https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly"); - oAuth2.setScope(Set.of("https://www.googleapis.com/auth/spreadsheets.readonly","https://www.googleapis.com/auth/drive.readonly")); + oAuth2.setScopeString( + "https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly"); + oAuth2.setScope(Set.of( + "https://www.googleapis.com/auth/spreadsheets.readonly", + "https://www.googleapis.com/auth/drive.readonly")); return oAuth2; } @@ -109,11 +127,11 @@ private OAuth2 getOAuthObject(){ * @param rowObject * @return */ - private MethodConfig getMethodConfigObject(String rowObject) { + private MethodConfig getMethodConfigObject(String rowObject) { MethodConfig methodConfig = new MethodConfig(Map.of()); methodConfig.setRowObjects(rowObject); return methodConfig; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsBulkUpdateMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsBulkUpdateMethodTest.java index 9bb5f9c7a5fb..05837496b56f 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsBulkUpdateMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsBulkUpdateMethodTest.java @@ -29,19 +29,30 @@ public void testRowBulkUpdateMethodWithEmptyBody() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setAuthentication(getOAuthObject()); - Map<String,Object> formData = new HashMap<>(); - formData.put("command", Collections.singletonMap("data","UPDATE_MANY")); - formData.put("entityType", Collections.singletonMap("data","ROWS")); - formData.put("tableHeaderIndex", Collections.singletonMap("data","1")); - formData.put("projection", Collections.singletonMap("data",Collections.emptyList())); - formData.put("queryFormat", Collections.singletonMap("data","ROWS")); - formData.put("range", Collections.singletonMap("data","")); - formData.put("where", Collections.singletonMap("data",Map.of("condition","AND","children",Collections.singletonList(Collections.singletonMap("condition","LT"))))); - formData.put("pagination",Collections.singletonMap("data",Map.of("limit",20,"offset",0))); - formData.put("smartSubstitution",Collections.singletonMap("data",true)); - formData.put("sheetUrl",Collections.singletonMap("data","https://docs.google.com/spreadsheets/d/123/edit")); - formData.put("sheetName",Collections.singletonMap("data","portSheet")); - formData.put("sortBy",Collections.singletonMap("data",Collections.singletonList(Map.of("column","","order","Ascending")))); + Map<String, Object> formData = new HashMap<>(); + formData.put("command", Collections.singletonMap("data", "UPDATE_MANY")); + formData.put("entityType", Collections.singletonMap("data", "ROWS")); + formData.put("tableHeaderIndex", Collections.singletonMap("data", "1")); + formData.put("projection", Collections.singletonMap("data", Collections.emptyList())); + formData.put("queryFormat", Collections.singletonMap("data", "ROWS")); + formData.put("range", Collections.singletonMap("data", "")); + formData.put( + "where", + Collections.singletonMap( + "data", + Map.of( + "condition", + "AND", + "children", + Collections.singletonList(Collections.singletonMap("condition", "LT"))))); + formData.put("pagination", Collections.singletonMap("data", Map.of("limit", 20, "offset", 0))); + formData.put("smartSubstitution", Collections.singletonMap("data", true)); + formData.put("sheetUrl", Collections.singletonMap("data", "https://docs.google.com/spreadsheets/d/123/edit")); + formData.put("sheetName", Collections.singletonMap("data", "portSheet")); + formData.put( + "sortBy", + Collections.singletonMap( + "data", Collections.singletonList(Map.of("column", "", "order", "Ascending")))); ActionConfiguration actionConfiguration = new ActionConfiguration(); @@ -50,21 +61,26 @@ public void testRowBulkUpdateMethodWithEmptyBody() { actionConfiguration.setEncodeParamsToggle(true); actionConfiguration.setFormData(formData); - String[] testDataArray = {null,"","{}"}; + String[] testDataArray = {null, "", "{}"}; - String[] expectedErrorMessageArray = {ErrorMessages.EMPTY_UPDATE_ROW_OBJECTS_MESSAGE,ErrorMessages.REQUEST_BODY_NOT_ARRAY,ErrorMessages.REQUEST_BODY_NOT_ARRAY}; + String[] expectedErrorMessageArray = { + ErrorMessages.EMPTY_UPDATE_ROW_OBJECTS_MESSAGE, + ErrorMessages.REQUEST_BODY_NOT_ARRAY, + ErrorMessages.REQUEST_BODY_NOT_ARRAY + }; - for(int i=0; i<testDataArray.length; i++) { + for (int i = 0; i < testDataArray.length; i++) { - formData.put("rowObjects",new HashMap<>(Collections.singletonMap("data",testDataArray[i]))); + formData.put("rowObjects", new HashMap<>(Collections.singletonMap("data", testDataArray[i]))); AppsmithPluginException appsmithPluginException = assertThrows(AppsmithPluginException.class, () -> { - pluginExecutor.executeParameterized(null,new ExecuteActionDTO(),datasourceConfiguration,actionConfiguration); + pluginExecutor.executeParameterized( + null, new ExecuteActionDTO(), datasourceConfiguration, actionConfiguration); }); String actualMessage = appsmithPluginException.getMessage(); - assertEquals(actualMessage,expectedErrorMessageArray[i]); + assertEquals(actualMessage, expectedErrorMessageArray[i]); } } @@ -72,13 +88,16 @@ public void testRowBulkUpdateMethodWithEmptyBody() { * Simulated oAuth2 object, just to bypass few case. * @return */ - private OAuth2 getOAuthObject(){ + private OAuth2 getOAuthObject() { OAuth2 oAuth2 = new OAuth2(); - oAuth2.setAuthenticationResponse(new AuthenticationResponse() ); + oAuth2.setAuthenticationResponse(new AuthenticationResponse()); oAuth2.getAuthenticationResponse().setToken("welcome123"); oAuth2.setGrantType(OAuth2.Type.AUTHORIZATION_CODE); - oAuth2.setScopeString("https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly"); - oAuth2.setScope(Set.of("https://www.googleapis.com/auth/spreadsheets.readonly","https://www.googleapis.com/auth/drive.readonly")); + oAuth2.setScopeString( + "https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly"); + oAuth2.setScope(Set.of( + "https://www.googleapis.com/auth/spreadsheets.readonly", + "https://www.googleapis.com/auth/drive.readonly")); return oAuth2; } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsGetMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsGetMethodTest.java index bbadf0f859a2..716afcd65a0c 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsGetMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsGetMethodTest.java @@ -50,9 +50,7 @@ public void testTransformResponse_missingValues_returnsEmpty() throws JsonProces public void testTransformResponse_singleRowJSON_returnsEmpty() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"values\":[\"abc\"]},{}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"values\":[\"abc\"]},{}" + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); @@ -70,9 +68,7 @@ public void testTransformResponse_singleRowJSON_returnsEmpty() throws JsonProces public void testTransformResponse_emptyJSON_returnsEmpty() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"values\":[]},{\"values\":[]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"values\":[]},{\"values\":[]}" + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); @@ -90,21 +86,23 @@ public void testTransformResponse_emptyJSON_returnsEmpty() throws JsonProcessing public void testTransformResponse_emptyStartingRows_toListOfObjects() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"range\":\"Sheet1!A1:D1\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Some\",\"123\",\"values\",\"to\"]]}," + - "{\"range\":\"Sheet1!A2:D6\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[],[],[],[\"Some\",\"123\",\"values\",\"to\"],[\"work\",\"with\",\"and\",\"manipulate\"],[\"q\",\"w\",\"e\",\"r\"],[\"a\",\"s\",\"d\",\"f\"],[\"z\",\"x\",\"c\",\"v\"]]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"range\":\"Sheet1!A1:D1\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Some\",\"123\",\"values\",\"to\"]]}," + + "{\"range\":\"Sheet1!A2:D6\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[],[],[],[\"Some\",\"123\",\"values\",\"to\"],[\"work\",\"with\",\"and\",\"manipulate\"],[\"q\",\"w\",\"e\",\"r\"],[\"a\",\"s\",\"d\",\"f\"],[\"z\",\"x\",\"c\",\"v\"]]}" + + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); RowsGetMethod rowsGetMethod = new RowsGetMethod(objectMapper); - JsonNode result = rowsGetMethod.transformExecutionResponse(jsonNode, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = rowsGetMethod.transformExecutionResponse( + jsonNode, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertNotNull(result); assertTrue(result.isArray() && result.size() == 8); @@ -117,21 +115,23 @@ public void testTransformResponse_emptyStartingRows_toListOfObjects() throws Jso public void testTransformResponse_emptyRows_returnsIndices() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":[" + - "{\"range\":\"Sheet1!A1:D1\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[\"Some\",\"123\",\"values\",\"to\"]]}," + - "{\"range\":\"Sheet1!A2:D6\"," + - "\"majorDimension\":\"ROWS\"," + - "\"values\":[[],[],[]]}" + - "]}"; + final String jsonString = "{\"valueRanges\":[" + "{\"range\":\"Sheet1!A1:D1\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[\"Some\",\"123\",\"values\",\"to\"]]}," + + "{\"range\":\"Sheet1!A2:D6\"," + + "\"majorDimension\":\"ROWS\"," + + "\"values\":[[],[],[]]}" + + "]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); RowsGetMethod rowsGetMethod = new RowsGetMethod(objectMapper); - JsonNode result = rowsGetMethod.transformExecutionResponse(jsonNode, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = rowsGetMethod.transformExecutionResponse( + jsonNode, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertNotNull(result); assertTrue(result.isArray()); @@ -143,23 +143,25 @@ public void testTransformResponse_emptyRows_returnsIndices() throws JsonProcessi public void transformResponse() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); - final String jsonString = "{\"valueRanges\":\n" + - "[ {\n" + - " \"range\" : \"Sheet1!A1:Z1\",\n" + - " \"majorDimension\" : \"ROWS\",\n" + - " \"values\" : [ [ \"The timeline includes other auxillary functions each team will need to perform such as supporting the community with feature requests, fixing bugs, clearing tech debt, improving performance, re-architecting parts of the codebase, writing documentation, etc.\" ] ]\n" + - "}, {\n" + - " \"range\" : \"Sheet1!A2:Z4\",\n" + - " \"majorDimension\" : \"ROWS\",\n" + - " \"values\" : [ [ \"Quarter\", \"Projects\", \"Teams\", \"Frontend\", \"Backend\", \"QA\" ], [ \"\", \"Add 15 Widgets\", \"Widget Team\", \"0\", \"0\" ], [ \"\", \"Add 20 SAAS Integrations\", \"Integrations\", \"1\", \"1\", \"\", \"1\" ] ]\n" + - "} ]}"; + final String jsonString = "{\"valueRanges\":\n" + "[ {\n" + + " \"range\" : \"Sheet1!A1:Z1\",\n" + + " \"majorDimension\" : \"ROWS\",\n" + + " \"values\" : [ [ \"The timeline includes other auxillary functions each team will need to perform such as supporting the community with feature requests, fixing bugs, clearing tech debt, improving performance, re-architecting parts of the codebase, writing documentation, etc.\" ] ]\n" + + "}, {\n" + + " \"range\" : \"Sheet1!A2:Z4\",\n" + + " \"majorDimension\" : \"ROWS\",\n" + + " \"values\" : [ [ \"Quarter\", \"Projects\", \"Teams\", \"Frontend\", \"Backend\", \"QA\" ], [ \"\", \"Add 15 Widgets\", \"Widget Team\", \"0\", \"0\" ], [ \"\", \"Add 20 SAAS Integrations\", \"Integrations\", \"1\", \"1\", \"\", \"1\" ] ]\n" + + "} ]}"; JsonNode jsonNode = objectMapper.readTree(jsonString); assertNotNull(jsonNode); RowsGetMethod rowsGetMethod = new RowsGetMethod(objectMapper); - JsonNode result = rowsGetMethod.transformExecutionResponse(jsonNode, new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), null); + JsonNode result = rowsGetMethod.transformExecutionResponse( + jsonNode, + new MethodConfig(Map.of()).toBuilder().tableHeaderIndex("1").build(), + null); assertNotNull(result); assertTrue(result.isArray()); diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsUpdateMethodTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsUpdateMethodTest.java index ff75e68a0b73..d0f8e57c2a5d 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsUpdateMethodTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/RowsUpdateMethodTest.java @@ -29,19 +29,30 @@ public void testRowUpdateMethodWithEmptyBody() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setAuthentication(getOAuthObject()); - Map<String,Object> formData = new HashMap<>(); - formData.put("command", Collections.singletonMap("data","UPDATE_ONE")); - formData.put("entityType", Collections.singletonMap("data","ROWS")); - formData.put("tableHeaderIndex", Collections.singletonMap("data","1")); - formData.put("projection", Collections.singletonMap("data",Collections.emptyList())); - formData.put("queryFormat", Collections.singletonMap("data","ROWS")); - formData.put("range", Collections.singletonMap("data","")); - formData.put("where", Collections.singletonMap("data",Map.of("condition","AND","children",Collections.singletonList(Collections.singletonMap("condition","LT"))))); - formData.put("pagination",Collections.singletonMap("data",Map.of("limit",20,"offset",0))); - formData.put("smartSubstitution",Collections.singletonMap("data",true)); - formData.put("sheetUrl",Collections.singletonMap("data","https://docs.google.com/spreadsheets/d/123/edit")); - formData.put("sheetName",Collections.singletonMap("data","portSheet")); - formData.put("sortBy",Collections.singletonMap("data",Collections.singletonList(Map.of("column","","order","Ascending")))); + Map<String, Object> formData = new HashMap<>(); + formData.put("command", Collections.singletonMap("data", "UPDATE_ONE")); + formData.put("entityType", Collections.singletonMap("data", "ROWS")); + formData.put("tableHeaderIndex", Collections.singletonMap("data", "1")); + formData.put("projection", Collections.singletonMap("data", Collections.emptyList())); + formData.put("queryFormat", Collections.singletonMap("data", "ROWS")); + formData.put("range", Collections.singletonMap("data", "")); + formData.put( + "where", + Collections.singletonMap( + "data", + Map.of( + "condition", + "AND", + "children", + Collections.singletonList(Collections.singletonMap("condition", "LT"))))); + formData.put("pagination", Collections.singletonMap("data", Map.of("limit", 20, "offset", 0))); + formData.put("smartSubstitution", Collections.singletonMap("data", true)); + formData.put("sheetUrl", Collections.singletonMap("data", "https://docs.google.com/spreadsheets/d/123/edit")); + formData.put("sheetName", Collections.singletonMap("data", "portSheet")); + formData.put( + "sortBy", + Collections.singletonMap( + "data", Collections.singletonList(Map.of("column", "", "order", "Ascending")))); ActionConfiguration actionConfiguration = new ActionConfiguration(); @@ -50,19 +61,20 @@ public void testRowUpdateMethodWithEmptyBody() { actionConfiguration.setEncodeParamsToggle(true); actionConfiguration.setFormData(formData); - String[] testDataArray = {null,"","{}"}; + String[] testDataArray = {null, "", "{}"}; - for(int i=0; i<testDataArray.length; i++) { + for (int i = 0; i < testDataArray.length; i++) { - formData.put("rowObjects",new HashMap<>(Collections.singletonMap("data",testDataArray[i]))); + formData.put("rowObjects", new HashMap<>(Collections.singletonMap("data", testDataArray[i]))); AppsmithPluginException appsmithPluginException = assertThrows(AppsmithPluginException.class, () -> { - pluginExecutor.executeParameterized(null,new ExecuteActionDTO(),datasourceConfiguration,actionConfiguration); + pluginExecutor.executeParameterized( + null, new ExecuteActionDTO(), datasourceConfiguration, actionConfiguration); }); String actualMessage = appsmithPluginException.getMessage(); - assertEquals(actualMessage,ErrorMessages.EMPTY_UPDATE_ROW_OBJECT_MESSAGE); + assertEquals(actualMessage, ErrorMessages.EMPTY_UPDATE_ROW_OBJECT_MESSAGE); } } @@ -70,13 +82,16 @@ public void testRowUpdateMethodWithEmptyBody() { * Simulated oAuth2 object, just to bypass few case. * @return */ - private OAuth2 getOAuthObject(){ + private OAuth2 getOAuthObject() { OAuth2 oAuth2 = new OAuth2(); - oAuth2.setAuthenticationResponse(new AuthenticationResponse() ); + oAuth2.setAuthenticationResponse(new AuthenticationResponse()); oAuth2.getAuthenticationResponse().setToken("welcome123"); oAuth2.setGrantType(OAuth2.Type.AUTHORIZATION_CODE); - oAuth2.setScopeString("https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly"); - oAuth2.setScope(Set.of("https://www.googleapis.com/auth/spreadsheets.readonly","https://www.googleapis.com/auth/drive.readonly")); + oAuth2.setScopeString( + "https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly"); + oAuth2.setScope(Set.of( + "https://www.googleapis.com/auth/spreadsheets.readonly", + "https://www.googleapis.com/auth/drive.readonly")); return oAuth2; } } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/SheetsUtilTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/SheetsUtilTest.java index e29d4b1bd543..1b5d7856880a 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/SheetsUtilTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/SheetsUtilTest.java @@ -5,14 +5,13 @@ import com.appsmith.external.models.Property; import com.external.utils.SheetsUtil; import com.fasterxml.jackson.core.JsonProcessingException; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Set; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SheetsUtilTest { @@ -51,4 +50,4 @@ public void testGetUserAuthorizedSheetIds_specificSheets_returnsSetOfFileIds() t Set<String> result = SheetsUtil.getUserAuthorizedSheetIds(dsConfig); assertEquals(result.size(), 1); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/graphqlPlugin/pom.xml b/app/server/appsmith-plugins/graphqlPlugin/pom.xml index 4a469ef6e599..06bbe4b95c28 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/pom.xml +++ b/app/server/appsmith-plugins/graphqlPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>graphqlPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -79,7 +78,8 @@ </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> - <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --> + <artifactId>jjwt-jackson</artifactId> + <!-- or jjwt-gson if Gson is preferred --> <version>${jjwt.version}</version> </dependency> @@ -100,20 +100,20 @@ <artifactId>slf4j-api</artifactId> </exclusion> <exclusion> - <artifactId>reactor-core</artifactId> <groupId>io.projectreactor</groupId> + <artifactId>reactor-core</artifactId> </exclusion> <exclusion> - <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> + <artifactId>spring-core</artifactId> </exclusion> <exclusion> - <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> + <artifactId>spring-web</artifactId> </exclusion> <exclusion> - <artifactId>reactive-streams</artifactId> <groupId>org.reactivestreams</groupId> + <artifactId>reactive-streams</artifactId> </exclusion> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> @@ -159,10 +159,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy</goal> </goals> + <phase>package</phase> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <artifactItems> diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java index 45ece119f17d..1d9e737f3cd0 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java @@ -79,10 +79,11 @@ public GraphQLPluginExecutor(SharedConfig sharedConfig) { * @return */ @Override - public Mono<ActionExecutionResult> executeParameterized(APIConnection connection, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> executeParameterized( + APIConnection connection, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final List<Property> properties = actionConfiguration.getPluginSpecifiedTemplates(); List<Map.Entry<String, String>> parameters = new ArrayList<>(); @@ -92,16 +93,15 @@ public Mono<ActionExecutionResult> executeParameterized(APIConnection connection if (TRUE.equals(smartSubstitution)) { /* Apply smart JSON substitution logic to mustache binding values in query variables */ if (!isBlank(variables)) { - List<MustacheBindingToken> mustacheKeysInOrder = MustacheHelper.extractMustacheKeysInOrder(variables); + List<MustacheBindingToken> mustacheKeysInOrder = + MustacheHelper.extractMustacheKeysInOrder(variables); // Replace all the bindings with a ? as expected in a prepared statement. - String updatedVariables = MustacheHelper.replaceMustacheWithPlaceholder(variables, mustacheKeysInOrder); + String updatedVariables = + MustacheHelper.replaceMustacheWithPlaceholder(variables, mustacheKeysInOrder); try { - updatedVariables = (String) smartSubstitutionOfBindings(updatedVariables, - mustacheKeysInOrder, - executeActionDTO.getParams(), - parameters, - false); + updatedVariables = (String) smartSubstitutionOfBindings( + updatedVariables, mustacheKeysInOrder, executeActionDTO.getParams(), parameters, false); setValueSafelyInPropertyList(properties, QUERY_VARIABLES_INDEX, updatedVariables); } catch (AppsmithPluginException e) { ActionExecutionResult errorResult = new ActionExecutionResult(); @@ -119,11 +119,8 @@ public Mono<ActionExecutionResult> executeParameterized(APIConnection connection String updatedQuery = MustacheHelper.replaceMustacheWithPlaceholder(query, mustacheKeysInOrder); try { - updatedQuery = (String) smartSubstitutionOfBindings(updatedQuery, - mustacheKeysInOrder, - executeActionDTO.getParams(), - parameters, - true); + updatedQuery = (String) smartSubstitutionOfBindings( + updatedQuery, mustacheKeysInOrder, executeActionDTO.getParams(), parameters, true); actionConfiguration.setBody(updatedQuery); } catch (AppsmithPluginException e) { ActionExecutionResult errorResult = new ActionExecutionResult(); @@ -147,7 +144,8 @@ public Mono<ActionExecutionResult> executeParameterized(APIConnection connection return Mono.error(e); } - if (actionConfiguration.getPaginationType() != null && !PaginationType.NONE.equals(actionConfiguration.getPaginationType())) { + if (actionConfiguration.getPaginationType() != null + && !PaginationType.NONE.equals(actionConfiguration.getPaginationType())) { updateVariablesWithPaginationValues(actionConfiguration, executeActionDTO); } @@ -157,10 +155,11 @@ public Mono<ActionExecutionResult> executeParameterized(APIConnection connection return this.executeCommon(connection, datasourceConfiguration, actionConfiguration, parameters); } - public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration, - List<Map.Entry<String, String>> insertedParams) { + public Mono<ActionExecutionResult> executeCommon( + APIConnection apiConnection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration, + List<Map.Entry<String, String>> insertedParams) { // Initializing object for error condition ActionExecutionResult errorResult = new ActionExecutionResult(); @@ -173,16 +172,16 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, URI uri; try { - uri = uriUtils.createUriWithQueryParams(actionConfiguration, datasourceConfiguration, url, - encodeParamsToggle); + uri = uriUtils.createUriWithQueryParams( + actionConfiguration, datasourceConfiguration, url, encodeParamsToggle); } catch (URISyntaxException e) { - ActionExecutionRequest actionExecutionRequest = - RequestCaptureFilter.populateRequestFields(actionConfiguration, null, insertedParams, objectMapper); + ActionExecutionRequest actionExecutionRequest = RequestCaptureFilter.populateRequestFields( + actionConfiguration, null, insertedParams, objectMapper); actionExecutionRequest.setUrl(url); - errorResult.setErrorInfo( - new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, GraphQLErrorMessages.URI_SYNTAX_WRONG_ERROR_MSG, e.getMessage() - ) - ); + errorResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + GraphQLErrorMessages.URI_SYNTAX_WRONG_ERROR_MSG, + e.getMessage())); errorResult.setRequest(actionExecutionRequest); return Mono.just(errorResult); } @@ -190,28 +189,26 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, ActionExecutionRequest actionExecutionRequest = RequestCaptureFilter.populateRequestFields(actionConfiguration, uri, insertedParams, objectMapper); - WebClient.Builder webClientBuilder = restAPIActivateUtils.getWebClientBuilder(actionConfiguration, - datasourceConfiguration); + WebClient.Builder webClientBuilder = + restAPIActivateUtils.getWebClientBuilder(actionConfiguration, datasourceConfiguration); String reqContentType = headerUtils.getRequestContentType(actionConfiguration, datasourceConfiguration); /* Check for content type */ final String contentTypeError = headerUtils.verifyContentType(actionConfiguration.getHeaders()); if (contentTypeError != null) { - errorResult.setErrorInfo( - new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, GraphQLErrorMessages.INVALID_CONTENT_TYPE_ERROR_MSG - ) - ); + errorResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + GraphQLErrorMessages.INVALID_CONTENT_TYPE_ERROR_MSG)); errorResult.setRequest(actionExecutionRequest); return Mono.just(errorResult); } HttpMethod httpMethod = actionConfiguration.getHttpMethod(); if (httpMethod == null) { - errorResult.setErrorInfo( - new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, GraphQLErrorMessages.NO_HTTP_METHOD_ERROR_MSG - ) - ); + errorResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + GraphQLErrorMessages.NO_HTTP_METHOD_ERROR_MSG)); errorResult.setRequest(actionExecutionRequest); return Mono.just(errorResult); } @@ -261,32 +258,40 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, * Only POST and GET HTTP methods are supported by GraphQL specifications. * Ref: https://graphql.org/learn/serving-over-http/ */ - return Mono.error( - new AppsmithPluginException( - GraphQLPluginError.QUERY_EXECUTION_FAILED, - String.format(GraphQLErrorMessages.UNEXPECTED_HTTP_METHOD_ERROR_MSG, httpMethod) - ) - ); + return Mono.error(new AppsmithPluginException( + GraphQLPluginError.QUERY_EXECUTION_FAILED, + String.format(GraphQLErrorMessages.UNEXPECTED_HTTP_METHOD_ERROR_MSG, httpMethod))); } final RequestCaptureFilter requestCaptureFilter = new RequestCaptureFilter(objectMapper); - Object requestBodyObj = dataUtils.getRequestBodyObject(actionConfiguration, reqContentType, - encodeParamsToggle, httpMethod); - WebClient client = restAPIActivateUtils.getWebClient(webClientBuilder, apiConnection, reqContentType, - EXCHANGE_STRATEGIES, requestCaptureFilter); + Object requestBodyObj = + dataUtils.getRequestBodyObject(actionConfiguration, reqContentType, encodeParamsToggle, httpMethod); + WebClient client = restAPIActivateUtils.getWebClient( + webClientBuilder, apiConnection, reqContentType, EXCHANGE_STRATEGIES, requestCaptureFilter); /* Triggering the actual REST API call */ Set<String> hintMessages = new HashSet<>(); - return restAPIActivateUtils.triggerApiCall( - client, httpMethod, uri, requestBodyObj, actionExecutionRequest, - objectMapper, hintMessages, errorResult, requestCaptureFilter - ) + return restAPIActivateUtils + .triggerApiCall( + client, + httpMethod, + uri, + requestBodyObj, + actionExecutionRequest, + objectMapper, + hintMessages, + errorResult, + requestCaptureFilter) .onErrorResume(error -> { boolean isBodySentWithApiRequest = requestBodyObj == null ? false : true; - errorResult.setRequest(requestCaptureFilter.populateRequestFields(actionExecutionRequest, isBodySentWithApiRequest)); + errorResult.setRequest(requestCaptureFilter.populateRequestFields( + actionExecutionRequest, isBodySentWithApiRequest)); errorResult.setIsExecutionSuccess(false); - if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(GraphQLPluginError.QUERY_EXECUTION_FAILED, GraphQLErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error); + if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + GraphQLPluginError.QUERY_EXECUTION_FAILED, + GraphQLErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error); } errorResult.setErrorInfo(error); return Mono.just(errorResult); @@ -294,17 +299,19 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) { boolean isInputQueryBody = (boolean) args[0]; Param param = (Param) args[1]; if (!isInputQueryBody) { String queryVariables = (String) input; - return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue(queryVariables, value, null, insertedParams, null, param); + return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue( + queryVariables, value, null, insertedParams, null, param); } else { String queryBody = (String) input; return smartlyReplaceGraphQLQueryBodyPlaceholderWithValue(queryBody, value, insertedParams); @@ -319,7 +326,8 @@ public Object substituteValueInInput(int index, */ @Override public Set<String> getSelfReferencingDataPaths() { - return Set.of("pluginSpecifiedTemplates[" + PAGINATION_DATA_INDEX + "].value.limitBased.limit.value", + return Set.of( + "pluginSpecifiedTemplates[" + PAGINATION_DATA_INDEX + "].value.limitBased.limit.value", "pluginSpecifiedTemplates[" + PAGINATION_DATA_INDEX + "].value.limitBased.offset.value", "pluginSpecifiedTemplates[" + PAGINATION_DATA_INDEX + "].value.cursorBased.next.limit.value", "pluginSpecifiedTemplates[" + PAGINATION_DATA_INDEX + "].value.cursorBased.next.cursor.value", diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/exceptions/GraphQLErrorMessages.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/exceptions/GraphQLErrorMessages.java index 61365a37d71b..4b3a9aa0005a 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/exceptions/GraphQLErrorMessages.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/exceptions/GraphQLErrorMessages.java @@ -9,7 +9,8 @@ public class GraphQLErrorMessages extends BasePluginErrorMessages { public static final String URI_SYNTAX_WRONG_ERROR_MSG = "URI is invalid. Please rectify the URI and try again."; public static final String INVALID_CONTENT_TYPE_ERROR_MSG = "Invalid value for Content-Type."; public static final String NO_HTTP_METHOD_ERROR_MSG = "HTTPMethod must be set."; - public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "An error occurred during the execution of your GraphQL query. Please check the error logs for more details."; - public static final String UNEXPECTED_HTTP_METHOD_ERROR_MSG = "Appsmith server has found an unexpected HTTP method configured with the GraphQL " + - "plugin query: %s"; + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = + "An error occurred during the execution of your GraphQL query. Please check the error logs for more details."; + public static final String UNEXPECTED_HTTP_METHOD_ERROR_MSG = + "Appsmith server has found an unexpected HTTP method configured with the GraphQL " + "plugin query: %s"; } diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/exceptions/GraphQLPluginError.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/exceptions/GraphQLPluginError.java index b35a9cfc86e2..bf6df0e01a26 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/exceptions/GraphQLPluginError.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/exceptions/GraphQLPluginError.java @@ -17,8 +17,7 @@ public enum GraphQLPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; private final String appErrorCode; @@ -31,8 +30,15 @@ public enum GraphQLPluginError implements BasePluginError { private final String downstreamErrorCode; - GraphQLPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + GraphQLPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -47,7 +53,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLBodyUtils.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLBodyUtils.java index 46f7432b93aa..48fb84c592e0 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLBodyUtils.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLBodyUtils.java @@ -6,8 +6,8 @@ import com.appsmith.external.models.Property; import graphql.parser.InvalidSyntaxException; import graphql.parser.Parser; -import org.json.JSONObject; import org.json.JSONException; +import org.json.JSONObject; import java.util.ArrayList; import java.util.List; @@ -23,7 +23,8 @@ public class GraphQLBodyUtils { public static final String QUERY_KEY = "query"; public static final String VARIABLES_KEY = "variables"; - public static String convertToGraphQLPOSTBodyFormat(ActionConfiguration actionConfiguration) throws AppsmithPluginException { + public static String convertToGraphQLPOSTBodyFormat(ActionConfiguration actionConfiguration) + throws AppsmithPluginException { JSONObject query = new JSONObject(); query.put(QUERY_KEY, actionConfiguration.getBody()); @@ -34,20 +35,22 @@ public static String convertToGraphQLPOSTBodyFormat(ActionConfiguration actionCo JSONObject json = parseStringIntoJSONObject(variables); query.put(VARIABLES_KEY, json); } catch (JSONException | ClassCastException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "GraphQL query " + - "variables are not in proper JSON format: " + e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "GraphQL query " + "variables are not in proper JSON format: " + e.getMessage()); } } return query.toString(); } - public static void validateBodyAndVariablesSyntax(ActionConfiguration actionConfiguration) throws AppsmithPluginException { + public static void validateBodyAndVariablesSyntax(ActionConfiguration actionConfiguration) + throws AppsmithPluginException { if (isBlank(actionConfiguration.getBody())) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "Your GraphQL query body is empty. Please edit the 'Body' tab of your GraphQL API to provide a " + - "query body."); + "Your GraphQL query body is empty. Please edit the 'Body' tab of your GraphQL API to provide a " + + "query body."); } Parser graphqlParser = new Parser(); @@ -55,8 +58,7 @@ public static void validateBodyAndVariablesSyntax(ActionConfiguration actionConf graphqlParser.parseDocument(actionConfiguration.getBody()); } catch (InvalidSyntaxException e) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "Invalid GraphQL body: " + e.getMessage()); + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Invalid GraphQL body: " + e.getMessage()); } final List<Property> properties = actionConfiguration.getPluginSpecifiedTemplates(); String variables = getValueSafelyFromPropertyList(properties, QUERY_VARIABLES_INDEX, String.class); @@ -66,8 +68,7 @@ public static void validateBodyAndVariablesSyntax(ActionConfiguration actionConf } catch (JSONException e) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "GraphQL query variables are not in proper JSON format: " + e.getMessage() - ); + "GraphQL query variables are not in proper JSON format: " + e.getMessage()); } } } diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLConstants.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLConstants.java index 12d6bce095f4..e552911a4837 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLConstants.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLConstants.java @@ -13,7 +13,7 @@ public class GraphQLConstants { public static final String LIMIT_VAL = "limitValue"; public static final String OFFSET_VARIABLE_NAME = "offsetVariableName"; public static final String OFFSET_VAL = "offsetValue"; - protected static String HINT_MESSAGE_FOR_DUPLICATE_VARIABLE_DEFINITION = "Your GraphQL query may not run as " + - "expected because it has duplicate definition for variable(s): {0}. Please remove one of the definitions " + - "- either in the query variables section or the pagination tab to resolve this issue."; + protected static String HINT_MESSAGE_FOR_DUPLICATE_VARIABLE_DEFINITION = "Your GraphQL query may not run as " + + "expected because it has duplicate definition for variable(s): {0}. Please remove one of the definitions " + + "- either in the query variables section or the pagination tab to resolve this issue."; } diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLDataTypeUtils.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLDataTypeUtils.java index a9c80a102029..f9179e991000 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLDataTypeUtils.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLDataTypeUtils.java @@ -21,8 +21,8 @@ public class GraphQLDataTypeUtils { public static final ObjectMapper objectMapper = new ObjectMapper(); - public static String smartlyReplaceGraphQLQueryBodyPlaceholderWithValue(String queryBody, String replacement, - List<Map.Entry<String, String>> insertedParams) { + public static String smartlyReplaceGraphQLQueryBodyPlaceholderWithValue( + String queryBody, String replacement, List<Map.Entry<String, String>> insertedParams) { final GraphQLBodyDataType dataType = stringToKnownGraphQLDataTypeConverter(queryBody, replacement); Map.Entry<String, String> parameter = new AbstractMap.SimpleEntry<>(replacement, dataType.toString()); insertedParams.add(parameter); @@ -34,13 +34,8 @@ public static String smartlyReplaceGraphQLQueryBodyPlaceholderWithValue(String q String valueAsString = objectMapper.writeValueAsString(replacement); updatedReplacement = Matcher.quoteReplacement(valueAsString); } catch (JsonProcessingException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - replacement, - e.getMessage() - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, replacement, e.getMessage())); } break; case GRAPHQL_BODY_FULL: @@ -65,7 +60,7 @@ public static GraphQLBodyDataType stringToKnownGraphQLDataTypeConverter(String q graphqlParser.parseDocument(replacement); return GraphQLBodyDataType.GRAPHQL_BODY_FULL; } catch (InvalidSyntaxException e) { - // do nothing + // do nothing } try { diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLHintMessageUtils.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLHintMessageUtils.java index bfd7520b6d36..d586350eb0c4 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLHintMessageUtils.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLHintMessageUtils.java @@ -1,6 +1,5 @@ package com.external.utils; -import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.helpers.restApiUtils.helpers.HintMessageUtils; import com.appsmith.external.models.ActionConfiguration; @@ -9,8 +8,8 @@ import com.appsmith.external.models.Property; import com.external.plugins.exceptions.GraphQLPluginError; import lombok.NoArgsConstructor; -import org.json.JSONObject; import org.json.JSONException; +import org.json.JSONObject; import java.text.MessageFormat; import java.util.ArrayList; @@ -39,7 +38,8 @@ public class GraphQLHintMessageUtils extends HintMessageUtils { * This method checks if the user has defined a query variable in both the places - pagination tab and the query * variables editor section. If so, then a warning message is returned informing user of the same. */ - public static Set<String> getHintMessagesForDuplicatesInQueryVariables(ActionConfiguration actionConfiguration) throws AppsmithPluginException { + public static Set<String> getHintMessagesForDuplicatesInQueryVariables(ActionConfiguration actionConfiguration) + throws AppsmithPluginException { if (actionConfiguration == null) { return new HashSet<>(); } @@ -52,10 +52,10 @@ public static Set<String> getHintMessagesForDuplicatesInQueryVariables(ActionCon queryVariablesJson = parseStringIntoJSONObject(variables); } catch (JSONException | ClassCastException e) { /* Not returning an exception here since the user is still editing the query variables and hence it is -- expected that the query variables would not be parseable till the final edit. */ + - expected that the query variables would not be parseable till the final edit. */ } - Map<String, Object> paginationDataMap = getPaginationData(actionConfiguration); + Map<String, Object> paginationDataMap = getPaginationData(actionConfiguration); if (!PaginationType.NONE.equals(actionConfiguration.getPaginationType()) && !isEmpty(paginationDataMap)) { List<String> duplicateVariables = new ArrayList<String>(); if (PaginationType.PAGE_NO.equals(actionConfiguration.getPaginationType())) { @@ -69,8 +69,7 @@ public static Set<String> getHintMessagesForDuplicatesInQueryVariables(ActionCon if (queryVariablesJson.has(offsetVarName)) { duplicateVariables.add(offsetVarName); } - } - else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) { + } else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) { String prevLimitVarName = (String) paginationDataMap.get(PREV_LIMIT_VARIABLE_NAME); String prevCursorVarName = (String) paginationDataMap.get(PREV_CURSOR_VARIABLE_NAME); String nextLimitVarName = (String) paginationDataMap.get(NEXT_LIMIT_VARIABLE_NAME); @@ -91,18 +90,17 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) if (queryVariablesJson.has(nextCursorVarName)) { duplicateVariables.add(nextCursorVarName); } - } - else { + } else { throw new AppsmithPluginException( GraphQLPluginError.QUERY_EXECUTION_FAILED, - "Appsmith server encountered an unexpected error: unrecognized pagination type: " + actionConfiguration.getPaginationType() + - ". Please reach out to our customer support to resolve this." - ); + "Appsmith server encountered an unexpected error: unrecognized pagination type: " + + actionConfiguration.getPaginationType() + + ". Please reach out to our customer support to resolve this."); } if (!isEmpty(duplicateVariables)) { - String message = MessageFormat.format(HINT_MESSAGE_FOR_DUPLICATE_VARIABLE_DEFINITION, - duplicateVariables.toString()); + String message = MessageFormat.format( + HINT_MESSAGE_FOR_DUPLICATE_VARIABLE_DEFINITION, duplicateVariables.toString()); hintMessages.add(message); } } @@ -111,8 +109,8 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) } @Override - public Set<String> getActionHintMessages(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration) { + public Set<String> getActionHintMessages( + ActionConfiguration actionConfiguration, DatasourceConfiguration datasourceConfiguration) { Set<String> actionHintMessages = super.getActionHintMessages(actionConfiguration, datasourceConfiguration); diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLPaginationUtils.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLPaginationUtils.java index f0e4547845a5..7e16b94fcd17 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLPaginationUtils.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/utils/GraphQLPaginationUtils.java @@ -8,8 +8,8 @@ import com.appsmith.external.models.PaginationType; import com.appsmith.external.models.Property; import com.external.plugins.exceptions.GraphQLPluginError; -import org.json.JSONObject; import org.json.JSONException; +import org.json.JSONObject; import java.util.HashMap; import java.util.List; @@ -20,6 +20,7 @@ import static com.appsmith.external.helpers.PluginUtils.parseStringIntoJSONObject; import static com.appsmith.external.helpers.PluginUtils.setValueSafelyInPropertyList; import static com.external.utils.GraphQLBodyUtils.PAGINATION_DATA_INDEX; +import static com.external.utils.GraphQLBodyUtils.QUERY_VARIABLES_INDEX; import static com.external.utils.GraphQLConstants.LIMIT_VAL; import static com.external.utils.GraphQLConstants.LIMIT_VARIABLE_NAME; import static com.external.utils.GraphQLConstants.NEXT_CURSOR_VAL; @@ -32,7 +33,6 @@ import static com.external.utils.GraphQLConstants.PREV_CURSOR_VARIABLE_NAME; import static com.external.utils.GraphQLConstants.PREV_LIMIT_VAL; import static com.external.utils.GraphQLConstants.PREV_LIMIT_VARIABLE_NAME; -import static com.external.utils.GraphQLBodyUtils.QUERY_VARIABLES_INDEX; import static org.apache.commons.lang3.ObjectUtils.isEmpty; import static org.apache.commons.lang3.StringUtils.isBlank; @@ -48,14 +48,11 @@ public static Map getPaginationData(ActionConfiguration actionConfiguration) thr Map<String, Object> paginationData = null; if (PaginationType.PAGE_NO.equals(actionConfiguration.getPaginationType())) { - paginationData = - getValueSafelyFromFormData((Map) properties.get(PAGINATION_DATA_INDEX).getValue(), - "limitBased", Map.class, null); - } - else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) { - paginationData = - getValueSafelyFromFormData((Map) properties.get(PAGINATION_DATA_INDEX).getValue(), - "cursorBased", Map.class, null); + paginationData = getValueSafelyFromFormData( + (Map) properties.get(PAGINATION_DATA_INDEX).getValue(), "limitBased", Map.class, null); + } else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) { + paginationData = getValueSafelyFromFormData( + (Map) properties.get(PAGINATION_DATA_INDEX).getValue(), "cursorBased", Map.class, null); } if (isEmpty(paginationData)) { @@ -74,24 +71,22 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) transformedPaginationData.put(LIMIT_VAL, limitValString); transformedPaginationData.put(OFFSET_VARIABLE_NAME, offsetVarName); transformedPaginationData.put(OFFSET_VAL, offsetValString); - } - else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) { - String prevLimitVarName = getValueSafelyFromFormData(paginationData, "previous.limit.name", String.class, - ""); - String prevLimitValString = getValueSafelyFromFormData(paginationData, "previous.limit.value", String.class, - ""); - String prevCursorVarName = getValueSafelyFromFormData(paginationData, "previous.cursor.name", String.class, - ""); - String prevCursorValString = getValueSafelyFromFormData(paginationData, "previous.cursor.value", - String.class, - ""); + } else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) { + String prevLimitVarName = + getValueSafelyFromFormData(paginationData, "previous.limit.name", String.class, ""); + String prevLimitValString = + getValueSafelyFromFormData(paginationData, "previous.limit.value", String.class, ""); + String prevCursorVarName = + getValueSafelyFromFormData(paginationData, "previous.cursor.name", String.class, ""); + String prevCursorValString = + getValueSafelyFromFormData(paginationData, "previous.cursor.value", String.class, ""); String nextLimitVarName = getValueSafelyFromFormData(paginationData, "next.limit.name", String.class, ""); - String nextLimitValString = getValueSafelyFromFormData(paginationData, "next.limit.value", String.class, - ""); + String nextLimitValString = + getValueSafelyFromFormData(paginationData, "next.limit.value", String.class, ""); String nextCursorVarName = getValueSafelyFromFormData(paginationData, "next.cursor.name", String.class, ""); - String nextCursorValString = getValueSafelyFromFormData(paginationData, "next.cursor.value", String.class, - ""); + String nextCursorValString = + getValueSafelyFromFormData(paginationData, "next.cursor.value", String.class, ""); transformedPaginationData.put(PREV_LIMIT_VARIABLE_NAME, prevLimitVarName); transformedPaginationData.put(PREV_LIMIT_VAL, prevLimitValString); @@ -106,23 +101,26 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) return transformedPaginationData; } - public static void updateVariablesWithPaginationValues(ActionConfiguration actionConfiguration, - ExecuteActionDTO executeActionDTO) throws AppsmithPluginException { + public static void updateVariablesWithPaginationValues( + ActionConfiguration actionConfiguration, ExecuteActionDTO executeActionDTO) throws AppsmithPluginException { final List<Property> properties = actionConfiguration.getPluginSpecifiedTemplates(); String variables = getValueSafelyFromPropertyList(properties, QUERY_VARIABLES_INDEX, String.class); JSONObject queryVariablesJson = new JSONObject(); try { queryVariablesJson = parseStringIntoJSONObject(variables); } catch (JSONException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "GraphQL query " + - "variables are not in proper JSON format: " + e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "GraphQL query " + "variables are not in proper JSON format: " + e.getMessage()); } Map<String, String> paginationDataMap = getPaginationData(actionConfiguration); if (isEmpty(paginationDataMap)) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Appsmith " + - "server could not find any GraphQL pagination data even though pagination is toggled on. Please " + - "provide pagination data by editing relevant fields in the pagination tab."); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "Appsmith " + + "server could not find any GraphQL pagination data even though pagination is toggled on. Please " + + "provide pagination data by editing relevant fields in the pagination tab."); } if (PaginationType.PAGE_NO.equals(actionConfiguration.getPaginationType())) { @@ -132,8 +130,11 @@ public static void updateVariablesWithPaginationValues(ActionConfiguration actio try { limitValue = Integer.parseInt(limitValueString); } catch (Exception e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Please provide " + - "a valid integer value for the limit variable in the pagination tab. Current value: " + limitValueString); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "Please provide " + + "a valid integer value for the limit variable in the pagination tab. Current value: " + + limitValueString); } String offsetVarName = paginationDataMap.get(OFFSET_VARIABLE_NAME); @@ -142,14 +143,16 @@ public static void updateVariablesWithPaginationValues(ActionConfiguration actio try { offsetValue = Integer.parseInt(offsetValueString); } catch (Exception e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Please provide " + - "a valid integer value for the offset variable in the pagination tab. Current value: " + offsetValueString); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "Please provide " + + "a valid integer value for the offset variable in the pagination tab. Current value: " + + offsetValueString); } queryVariablesJson.put(limitVarName, limitValue); queryVariablesJson.put(offsetVarName, offsetValue); - } - else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) { + } else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) { if (PaginationField.PREV.equals(executeActionDTO.getPaginationField())) { String prevLimitVarName = paginationDataMap.get(PREV_LIMIT_VARIABLE_NAME); String prevLimitValueString = paginationDataMap.get(PREV_LIMIT_VAL); @@ -157,9 +160,12 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) try { prevLimitValue = Integer.parseInt(prevLimitValueString); } catch (Exception e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Please provide " + - "a valid integer value for the previous page limit variable in the pagination tab. " + - "Current value: " + prevLimitValueString); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "Please provide " + + "a valid integer value for the previous page limit variable in the pagination tab. " + + "Current value: " + + prevLimitValueString); } queryVariablesJson.put(prevLimitVarName, prevLimitValue); @@ -168,9 +174,8 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) if (isBlank(prevCursorValue)) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "Please provide a non empty value for the previous page cursor variable in the pagination" + - " tab." - ); + "Please provide a non empty value for the previous page cursor variable in the pagination" + + " tab."); } /** @@ -185,17 +190,19 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) if (!NULL_STRING.equals(prevCursorValue)) { queryVariablesJson.put(prevCursorVarName, prevCursorValue); } - } - else { + } else { String nextLimitVarName = paginationDataMap.get(NEXT_LIMIT_VARIABLE_NAME); String nextLimitValueString = paginationDataMap.get(NEXT_LIMIT_VAL); int nextLimitValue = 0; try { nextLimitValue = Integer.parseInt(nextLimitValueString); } catch (Exception e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Please provide " + - "a valid integer value for the next page limit variable in the pagination tab. " + - "Current value: " + nextLimitValueString); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "Please provide " + + "a valid integer value for the next page limit variable in the pagination tab. " + + "Current value: " + + nextLimitValueString); } queryVariablesJson.put(nextLimitVarName, nextLimitValue); @@ -204,8 +211,7 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) if (isBlank(nextCursorValue)) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "Please provide a non empty value for the next page cursor variable in the pagination tab." - ); + "Please provide a non empty value for the next page cursor variable in the pagination tab."); } /** @@ -221,17 +227,17 @@ else if (PaginationType.CURSOR.equals(actionConfiguration.getPaginationType())) * the cursor value. This will make sure that the just clicking on the run button will not fetch * paginated results based on the cursor value. */ - if (!NULL_STRING.equals(nextCursorValue) && PaginationField.NEXT.equals(executeActionDTO.getPaginationField())) { + if (!NULL_STRING.equals(nextCursorValue) + && PaginationField.NEXT.equals(executeActionDTO.getPaginationField())) { queryVariablesJson.put(nextCursorVarName, nextCursorValue); } } - } - else { + } else { throw new AppsmithPluginException( GraphQLPluginError.QUERY_EXECUTION_FAILED, - "Appsmith server encountered an unexpected error: unrecognized pagination type: " + actionConfiguration.getPaginationType() + - ". Please reach out to our customer support to resolve this." - ); + "Appsmith server encountered an unexpected error: unrecognized pagination type: " + + actionConfiguration.getPaginationType() + + ". Please reach out to our customer support to resolve this."); } setValueSafelyInPropertyList(properties, QUERY_VARIABLES_INDEX, queryVariablesJson.toString()); diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/test/java/com/external/plugins/GraphQLPluginTest.java b/app/server/appsmith-plugins/graphqlPlugin/src/test/java/com/external/plugins/GraphQLPluginTest.java index ef534c1fb076..522c532c079b 100644 --- a/app/server/appsmith-plugins/graphqlPlugin/src/test/java/com/external/plugins/GraphQLPluginTest.java +++ b/app/server/appsmith-plugins/graphqlPlugin/src/test/java/com/external/plugins/GraphQLPluginTest.java @@ -96,12 +96,13 @@ public String getRemoteExecutionUrl() { } } - GraphQLPlugin.GraphQLPluginExecutor pluginExecutor = new GraphQLPlugin.GraphQLPluginExecutor(new MockSharedConfig()); + GraphQLPlugin.GraphQLPluginExecutor pluginExecutor = + new GraphQLPlugin.GraphQLPluginExecutor(new MockSharedConfig()); @SuppressWarnings("rawtypes") @Container - public static GenericContainer graphqlContainer = new GenericContainer(CompletableFuture.completedFuture("appsmith/test-event" + - "-driver")) + public static GenericContainer graphqlContainer = new GenericContainer( + CompletableFuture.completedFuture("appsmith/test-event" + "-driver")) .withExposedPorts(5000) .waitingFor(Wait.forHttp("/").forStatusCode(404)); @@ -129,7 +130,8 @@ private ActionConfiguration getDefaultActionConfiguration() { ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); actionConfig.setHttpMethod(HttpMethod.POST); - String requestBody = """ + String requestBody = + """ query { allPosts(first: 1) { nodes { @@ -149,7 +151,8 @@ private ActionConfiguration getDefaultActionConfiguration() { public void testValidGraphQLApiExecutionWithQueryVariablesWithHttpPost() { DatasourceConfiguration dsConfig = getDefaultDatasourceConfig(); ActionConfiguration actionConfig = getDefaultActionConfiguration(); - String queryBody = """ + String queryBody = + """ query($limit: Int) { allPosts(first: $limit) { nodes { @@ -165,7 +168,8 @@ public void testValidGraphQLApiExecutionWithQueryVariablesWithHttpPost() { "limit": 2 }""")); actionConfig.setPluginSpecifiedTemplates(properties); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -183,12 +187,13 @@ public void testValidGraphQLApiExecutionWithWhitespacesInUrl() { DatasourceConfiguration dsConfig = getDefaultDatasourceConfig(); ActionConfiguration actionConfig = getDefaultActionConfiguration(); - //changing the url to add whitespaces at the start and end of the url + // changing the url to add whitespaces at the start and end of the url String url = dsConfig.getUrl(); url = String.format("%-" + (url.length() + 4) + "s", url); url = String.format("%" + (url.length() + 4) + "s", url); dsConfig.setUrl(url); - String queryBody = """ + String queryBody = + """ query($limit: Int) { allPosts(first: $limit) { nodes { @@ -204,7 +209,8 @@ public void testValidGraphQLApiExecutionWithWhitespacesInUrl() { "limit": 2 }""")); actionConfig.setPluginSpecifiedTemplates(properties); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -220,7 +226,8 @@ public void testValidGraphQLApiExecutionWithQueryVariablesWithHttpGet() { dsConfig.setUrl("https://rickandmortyapi.com/graphql"); ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - actionConfig.setBody(""" + actionConfig.setBody( + """ query Query { character(id: 1) { created @@ -231,7 +238,8 @@ public void testValidGraphQLApiExecutionWithQueryVariablesWithHttpGet() { properties.add(new Property("smartSubstitution", "true")); properties.add(new Property("queryVariables", "")); actionConfig.setPluginSpecifiedTemplates(properties); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -250,7 +258,8 @@ public void testValidGraphQLApiExecutionWithoutQueryVariables() { ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); actionConfig.setHttpMethod(HttpMethod.POST); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -269,7 +278,8 @@ public void testValidGraphQLApiExecutionWithContentTypeGraphql() { ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/graphql"))); // content-type graphql actionConfig.setHttpMethod(HttpMethod.POST); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -285,7 +295,8 @@ public void testValidGraphQLApiExecutionWithContentTypeGraphql() { public void testInvalidQueryBodyError() { DatasourceConfiguration dsConfig = getDefaultDatasourceConfig(); ActionConfiguration actionConfig = getDefaultActionConfiguration(); - actionConfig.setBody(""" + actionConfig.setBody( + """ query Capsules { capsules(limit: 1, offset: 0) { dragon\s @@ -294,22 +305,23 @@ public void testInvalidQueryBodyError() { } } }"""); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); - - StepVerifier.create(resultMono) - .verifyErrorSatisfies(error -> { - assertTrue(error instanceof AppsmithPluginException); - String expectedMessage = "Invalid GraphQL body: Invalid syntax encountered. There are extra " + - "tokens in the text that have not been consumed. Offending token '}' at line 8 column 1"; - assertEquals(expectedMessage, error.getMessage()); - }); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + + StepVerifier.create(resultMono).verifyErrorSatisfies(error -> { + assertTrue(error instanceof AppsmithPluginException); + String expectedMessage = "Invalid GraphQL body: Invalid syntax encountered. There are extra " + + "tokens in the text that have not been consumed. Offending token '}' at line 8 column 1"; + assertEquals(expectedMessage, error.getMessage()); + }); } @Test public void testInvalidQueryVariablesError() { DatasourceConfiguration dsConfig = getDefaultDatasourceConfig(); ActionConfiguration actionConfig = getDefaultActionConfiguration(); - actionConfig.setBody(""" + actionConfig.setBody( + """ query Capsules($limit: Int, $offset: Int) { capsules(limit: $limit, offset: $offset) { dragon { @@ -318,19 +330,23 @@ query Capsules($limit: Int, $offset: Int) { } } }"""); - actionConfig.getPluginSpecifiedTemplates().get(QUERY_VARIABLES_INDEX).setValue(""" + actionConfig + .getPluginSpecifiedTemplates() + .get(QUERY_VARIABLES_INDEX) + .setValue( + """ { "limit": 1 "offset": 0 }"""); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); - StepVerifier.create(resultMono) - .verifyErrorSatisfies(error -> { - assertTrue(error instanceof AppsmithPluginException); - String expectedMessage = "GraphQL query variables are not in proper JSON format: Expected a ',' " + - "or '}' at 18 [character 3 line 3]"; - assertEquals(expectedMessage, error.getMessage()); - }); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + StepVerifier.create(resultMono).verifyErrorSatisfies(error -> { + assertTrue(error instanceof AppsmithPluginException); + String expectedMessage = "GraphQL query variables are not in proper JSON format: Expected a ',' " + + "or '}' at 18 [character 3 line 3]"; + assertEquals(expectedMessage, error.getMessage()); + }); } @Test @@ -339,21 +355,17 @@ public void testValidSignature() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); final String secretKey = "a-random-key-that-should-be-32-chars-long-at-least"; - dsConfig.setProperties(List.of( - new Property("isSendSessionEnabled", "Y"), - new Property("sessionSignatureKey", secretKey) - )); + dsConfig.setProperties( + List.of(new Property("isSendSessionEnabled", "Y"), new Property("sessionSignatureKey", secretKey))); ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -373,7 +385,8 @@ public void testValidSignature() { .getBody() .getIssuer(); assertEquals("Appsmith", issuer); - final Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) result.getRequest().getHeaders()).fields(); + final Iterator<Map.Entry<String, JsonNode>> fields = + ((ObjectNode) result.getRequest().getHeaders()).fields(); fields.forEachRemaining(field -> { if ("X-Appsmith-Signature".equalsIgnoreCase(field.getKey())) { assertEquals(token, field.getValue().get(0).asText()); @@ -382,7 +395,6 @@ public void testValidSignature() { } catch (InterruptedException e) { assert false : e.getMessage(); } - }) .verifyComplete(); } @@ -395,11 +407,12 @@ public void testValidateDatasource_invalidAuthentication() { datasourceConfiguration.setAuthentication(oAuth2); Mono<GraphQLPlugin.GraphQLPluginExecutor> pluginExecutorMono = Mono.just(pluginExecutor); - Mono<Set<String>> invalidsMono = pluginExecutorMono.map(executor -> executor.validateDatasource(datasourceConfiguration)); + Mono<Set<String>> invalidsMono = + pluginExecutorMono.map(executor -> executor.validateDatasource(datasourceConfiguration)); - StepVerifier - .create(invalidsMono) - .assertNext(invalids -> assertTrue(invalids.containsAll(Set.of("Missing Client ID", "Missing client secret", "Missing access token URL")))); + StepVerifier.create(invalidsMono) + .assertNext(invalids -> assertTrue(invalids.containsAll( + Set.of("Missing Client ID", "Missing client secret", "Missing access token URL")))); } /** @@ -416,13 +429,11 @@ public void testSmartSubstitutionInQueryBodyForNumberStringBooleanAndSchemaTypes String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = getDefaultActionConfiguration(); - actionConfig.setBody(""" + actionConfig.setBody( + """ query Capsules { capsules(myNum: {{Input1.text}}, myStr: {{Input2.text}}, myBool: {{Input3.text}}) { dragon { @@ -459,13 +470,15 @@ public void testSmartSubstitutionInQueryBodyForNumberStringBooleanAndSchemaTypes params.add(param4); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - String expectedQueryBody = """ + String expectedQueryBody = + """ query Capsules { capsules(myNum: 3, myStr: "this is a string! Yay :D", myBool: true) { dragon { @@ -494,8 +507,8 @@ public void testSmartSubstitutionInQueryBodyForNumberStringBooleanAndSchemaTypes // Assert the debug request parameters are getting set. ActionExecutionRequest request = result.getRequest(); - List<Map.Entry<String, String>> parameters = - (List<Map.Entry<String, String>>) request.getProperties().get("smart-substitution-parameters"); + List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) + request.getProperties().get("smart-substitution-parameters"); assertEquals(4, parameters.size()); Map.Entry<String, String> parameterEntry = parameters.get(0); @@ -527,10 +540,7 @@ public void testSmartSubstitutionInQueryBodyForFullBodySubstitution() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setBody("{{Input1.text}}"); @@ -539,7 +549,8 @@ public void testSmartSubstitutionInQueryBodyForFullBodySubstitution() { List<Param> params = new ArrayList<>(); Param param1 = new Param(); param1.setKey("Input1.text"); - param1.setValue(""" + param1.setValue( + """ query Capsules { capsules(limit: 1, offset: 0) { dragon { @@ -552,12 +563,14 @@ public void testSmartSubstitutionInQueryBodyForFullBodySubstitution() { params.add(param1); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - String expectedQueryBody = """ + String expectedQueryBody = + """ query Capsules { capsules(limit: 1, offset: 0) { dragon { @@ -585,12 +598,14 @@ public void testSmartSubstitutionInQueryBodyForFullBodySubstitution() { // Assert the debug request parameters are getting set. ActionExecutionRequest request = result.getRequest(); - List<Map.Entry<String, String>> parameters = - (List<Map.Entry<String, String>>) request.getProperties().get("smart-substitution-parameters"); + List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) + request.getProperties().get("smart-substitution-parameters"); assertEquals(1, parameters.size()); Map.Entry<String, String> parameterEntry = parameters.get(0); - assertEquals(parameterEntry.getKey(), """ + assertEquals( + parameterEntry.getKey(), + """ query Capsules { capsules(limit: 1, offset: 0) { dragon { @@ -611,13 +626,11 @@ public void testSmartSubstitutionQueryVariables() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = getDefaultActionConfiguration(); - String queryVariables = """ + String queryVariables = + """ { "name" : {{Input1.text}}, "email" : {{Input2.text}}, @@ -658,22 +671,26 @@ public void testSmartSubstitutionQueryVariables() { params.add(param6); Param param7 = new Param(); param7.setKey("Table1.selectedRow"); - param7.setValue("{ \"id\": 2381224, \"email\": \"[email protected]\", \"userName\": \"Michael Lawson\", \"productName\": \"Chicken Sandwich\", \"orderAmount\": 4.99}"); + param7.setValue( + "{ \"id\": 2381224, \"email\": \"[email protected]\", \"userName\": \"Michael Lawson\", \"productName\": \"Chicken Sandwich\", \"orderAmount\": 4.99}"); param7.setClientDataType(ClientDataType.OBJECT); params.add(param7); Param param8 = new Param(); param8.setKey("Table1.tableData"); - param8.setValue("[ { \"id\": 2381224, \"email\": \"[email protected]\", \"userName\": \"Michael Lawson\", \"productName\": \"Chicken Sandwich\", \"orderAmount\": 4.99 }, { \"id\": 2736212, \"email\": \"[email protected]\", \"userName\": \"Lindsay Ferguson\", \"productName\": \"Tuna Salad\", \"orderAmount\": 9.99 }, { \"id\": 6788734, \"email\": \"[email protected]\", \"userName\": \"Tobias Funke\", \"productName\": \"Beef steak\", \"orderAmount\": 19.99 }]"); + param8.setValue( + "[ { \"id\": 2381224, \"email\": \"[email protected]\", \"userName\": \"Michael Lawson\", \"productName\": \"Chicken Sandwich\", \"orderAmount\": 4.99 }, { \"id\": 2736212, \"email\": \"[email protected]\", \"userName\": \"Lindsay Ferguson\", \"productName\": \"Tuna Salad\", \"orderAmount\": 9.99 }, { \"id\": 6788734, \"email\": \"[email protected]\", \"userName\": \"Tobias Funke\", \"productName\": \"Beef steak\", \"orderAmount\": 19.99 }]"); param8.setClientDataType(ClientDataType.ARRAY); params.add(param8); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - String expectedResultData = "{\"password\":\"12\\/01\\/2018\",\"name\":\"this is a string! Yay :D\",\"newField\":null,\"tableRow\":{\"orderAmount\":4.99,\"id\":2381224,\"userName\":\"Michael Lawson\",\"email\":\"[email protected]\",\"productName\":\"Chicken Sandwich\"},\"email\":true,\"table\":[{\"orderAmount\":4.99,\"id\":2381224,\"userName\":\"Michael Lawson\",\"email\":\"[email protected]\",\"productName\":\"Chicken Sandwich\"},{\"orderAmount\":9.99,\"id\":2736212,\"userName\":\"Lindsay Ferguson\",\"email\":\"[email protected]\",\"productName\":\"Tuna Salad\"},{\"orderAmount\":19.99,\"id\":6788734,\"userName\":\"Tobias Funke\",\"email\":\"[email protected]\",\"productName\":\"Beef steak\"}],\"username\":0}"; + String expectedResultData = + "{\"password\":\"12\\/01\\/2018\",\"name\":\"this is a string! Yay :D\",\"newField\":null,\"tableRow\":{\"orderAmount\":4.99,\"id\":2381224,\"userName\":\"Michael Lawson\",\"email\":\"[email protected]\",\"productName\":\"Chicken Sandwich\"},\"email\":true,\"table\":[{\"orderAmount\":4.99,\"id\":2381224,\"userName\":\"Michael Lawson\",\"email\":\"[email protected]\",\"productName\":\"Chicken Sandwich\"},{\"orderAmount\":9.99,\"id\":2736212,\"userName\":\"Lindsay Ferguson\",\"email\":\"[email protected]\",\"productName\":\"Tuna Salad\"},{\"orderAmount\":19.99,\"id\":6788734,\"userName\":\"Tobias Funke\",\"email\":\"[email protected]\",\"productName\":\"Beef steak\"}],\"username\":0}"; JSONParser jsonParser = new JSONParser(JSONParser.MODE_PERMISSIVE); try { final RecordedRequest recordedRequest = mockEndpoint.takeRequest(30, TimeUnit.SECONDS); @@ -692,8 +709,8 @@ public void testSmartSubstitutionQueryVariables() { // Assert the debug request parameters are getting set. ActionExecutionRequest request = result.getRequest(); - List<Map.Entry<String, String>> parameters = - (List<Map.Entry<String, String>>) request.getProperties().get("smart-substitution-parameters"); + List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) + request.getProperties().get("smart-substitution-parameters"); assertEquals(7, parameters.size()); Map.Entry<String, String> parameterEntry = parameters.get(0); @@ -726,10 +743,7 @@ public void testRequestWithApiKeyHeader() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); AuthenticationDTO authenticationDTO = new ApiKeyAuth(ApiKeyAuth.Type.HEADER, "api_key", "Token", "test"); dsConfig.setAuthentication(authenticationDTO); @@ -737,19 +751,22 @@ public void testRequestWithApiKeyHeader() { ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHeaders(List.of( new Property("content-type", "application/json"), - new Property(HttpHeaders.AUTHORIZATION, "auth-value") - )); + new Property(HttpHeaders.AUTHORIZATION, "auth-value"))); - final APIConnection apiConnection = pluginExecutor.datasourceCreate(dsConfig).block(); + final APIConnection apiConnection = + pluginExecutor.datasourceCreate(dsConfig).block(); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(apiConnection, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(apiConnection, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getRequest().getBody()); - final Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) result.getRequest().getHeaders()).fields(); + final Iterator<Map.Entry<String, JsonNode>> fields = + ((ObjectNode) result.getRequest().getHeaders()).fields(); fields.forEachRemaining(field -> { - if ("api_key".equalsIgnoreCase(field.getKey()) || HttpHeaders.AUTHORIZATION.equalsIgnoreCase(field.getKey())) { + if ("api_key".equalsIgnoreCase(field.getKey()) + || HttpHeaders.AUTHORIZATION.equalsIgnoreCase(field.getKey())) { assertEquals("****", field.getValue().get(0).asText()); } }); @@ -788,7 +805,7 @@ public void testGetDuplicateHeadersAndParams() { actionHeaders.add(new Property("myHeader4", "myVal")); actionHeaders.add(new Property("myHeader4", "myVal")); // duplicate actionHeaders.add(new Property("myHeader5", "myVal")); - actionHeaders.add(new Property("apiKey", "myVal")); // duplicate - because also inherited from authentication + actionHeaders.add(new Property("apiKey", "myVal")); // duplicate - because also inherited from authentication actionConfig.setHeaders(actionHeaders); // Add params to API query editor page. @@ -811,8 +828,7 @@ public void testGetDuplicateHeadersAndParams() { /* Test duplicate query params in datasource configuration only */ Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateParamsWithDsConfigOnly = - hintMessageUtils.getAllDuplicateParams(null, - dsConfig); + hintMessageUtils.getAllDuplicateParams(null, dsConfig); // Query param duplicates Set<String> expectedDuplicateParams = new HashSet<>(); @@ -844,8 +860,7 @@ public void testGetDuplicateHeadersAndParams() { /* Test duplicate query params in action + datasource config */ Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> allDuplicateParams = - hintMessageUtils.getAllDuplicateParams(actionConfig, - dsConfig); + hintMessageUtils.getAllDuplicateParams(actionConfig, dsConfig); // Query param duplicates in datasource config only expectedDuplicateParams = new HashSet<>(); @@ -877,7 +892,7 @@ public void testGetDuplicateHeadersWithOAuth() { // Add headers to API query editor page. ArrayList<Property> actionHeaders = new ArrayList<>(); actionHeaders.add(new Property("myHeader1", "myVal")); - actionHeaders.add(new Property("Authorization", "myVal")); // duplicate - because also inherited from dsConfig + actionHeaders.add(new Property("Authorization", "myVal")); // duplicate - because also inherited from dsConfig ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHeaders(actionHeaders); @@ -917,8 +932,7 @@ public void testGetDuplicateParamsWithOAuth() { /* Test duplicate params in datasource + action configuration */ Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> allDuplicateParams = - hintMessageUtils.getAllDuplicateParams(actionConfig, - dsConfig); + hintMessageUtils.getAllDuplicateParams(actionConfig, dsConfig); // Param duplicates in ds config only assertTrue(allDuplicateParams.get(DATASOURCE_CONFIG_ONLY).isEmpty()); @@ -959,26 +973,26 @@ public void testHintMessageForDuplicateHeadersAndParamsWithDatasourceConfigOnly( .assertNext(tuple -> { Set<String> datasourceHintMessages = tuple.getT1(); Set<String> expectedDatasourceHintMessages = new HashSet<>(); - expectedDatasourceHintMessages.add("API queries linked to this datasource may not run as expected" + - " because this datasource has duplicate definition(s) for param(s): [myParam1]. Please " + - "remove the duplicate definition(s) to resolve this warning. Please note that some of the" + - " authentication mechanisms also implicitly define a param."); - - expectedDatasourceHintMessages.add("API queries linked to this datasource may not run as expected" + - " because this datasource has duplicate definition(s) for header(s): [myHeader1]. Please " + - "remove the duplicate definition(s) to resolve this warning. Please note that some of the" + - " authentication mechanisms also implicitly define a header."); + expectedDatasourceHintMessages.add("API queries linked to this datasource may not run as expected" + + " because this datasource has duplicate definition(s) for param(s): [myParam1]. Please " + + "remove the duplicate definition(s) to resolve this warning. Please note that some of the" + + " authentication mechanisms also implicitly define a param."); + + expectedDatasourceHintMessages.add("API queries linked to this datasource may not run as expected" + + " because this datasource has duplicate definition(s) for header(s): [myHeader1]. Please " + + "remove the duplicate definition(s) to resolve this warning. Please note that some of the" + + " authentication mechanisms also implicitly define a header."); assertEquals(expectedDatasourceHintMessages, datasourceHintMessages); Set<String> actionHintMessages = tuple.getT2(); Set<String> expectedActionHintMessages = new HashSet<>(); - expectedActionHintMessages.add("Your API query may not run as expected because its datasource has" + - " duplicate definition(s) for param(s): [myParam1]. Please remove the duplicate " + - "definition(s) from the datasource to resolve this warning."); + expectedActionHintMessages.add("Your API query may not run as expected because its datasource has" + + " duplicate definition(s) for param(s): [myParam1]. Please remove the duplicate " + + "definition(s) from the datasource to resolve this warning."); - expectedActionHintMessages.add("Your API query may not run as expected because its datasource has" + - " duplicate definition(s) for header(s): [myHeader1]. Please remove the duplicate " + - "definition(s) from the datasource to resolve this warning."); + expectedActionHintMessages.add("Your API query may not run as expected because its datasource has" + + " duplicate definition(s) for header(s): [myHeader1]. Please remove the duplicate " + + "definition(s) from the datasource to resolve this warning."); assertEquals(expectedActionHintMessages, actionHintMessages); }) .verifyComplete(); @@ -1008,7 +1022,8 @@ public void testHintMessageForDuplicateHeadersAndParamsWithActionConfigOnly() { DatasourceConfiguration dsConfig = new DatasourceConfiguration(); dsConfig.setUrl("some_non_loc@lhost_url"); - Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = pluginExecutor.getHintMessages(actionConfig, dsConfig); + Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = + pluginExecutor.getHintMessages(actionConfig, dsConfig); StepVerifier.create(hintMessagesMono) .assertNext(tuple -> { Set<String> datasourceHintMessages = tuple.getT1(); @@ -1016,13 +1031,13 @@ public void testHintMessageForDuplicateHeadersAndParamsWithActionConfigOnly() { Set<String> actionHintMessages = tuple.getT2(); Set<String> expectedActionHintMessages = new HashSet<>(); - expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + - "definition(s) for header(s): [myHeader1]. Please remove the duplicate definition(s) from" + - " the 'Headers' tab to resolve this warning."); + expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + + "definition(s) for header(s): [myHeader1]. Please remove the duplicate definition(s) from" + + " the 'Headers' tab to resolve this warning."); - expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + - "definition(s) for param(s): [myParam1]. Please remove the duplicate definition(s) from " + - "the 'Params' tab to resolve this warning."); + expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + + "definition(s) for param(s): [myParam1]. Please remove the duplicate definition(s) from " + + "the 'Params' tab to resolve this warning."); assertEquals(expectedActionHintMessages, actionHintMessages); }) .verifyComplete(); @@ -1048,7 +1063,8 @@ public void testHintMessageForDuplicateHeaderWithOneInstanceEachInActionAndDsCon dsConfig.setAuthentication(authenticationDTO); dsConfig.setUrl("some_non_loc@lhost_url"); - Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = pluginExecutor.getHintMessages(actionConfig, dsConfig); + Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = + pluginExecutor.getHintMessages(actionConfig, dsConfig); StepVerifier.create(hintMessagesMono) .assertNext(tuple -> { Set<String> datasourceHintMessages = tuple.getT1(); @@ -1056,10 +1072,10 @@ public void testHintMessageForDuplicateHeaderWithOneInstanceEachInActionAndDsCon Set<String> actionHintMessages = tuple.getT2(); Set<String> expectedActionHintMessages = new HashSet<>(); - expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + - "definition(s) for header(s): [myHeader1]. Please remove the duplicate definition(s) from" + - " the 'Headers' section of either the API query or the datasource. Please note that some " + - "of the authentication mechanisms also implicitly define a header."); + expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + + "definition(s) for header(s): [myHeader1]. Please remove the duplicate definition(s) from" + + " the 'Headers' section of either the API query or the datasource. Please note that some " + + "of the authentication mechanisms also implicitly define a header."); assertEquals(expectedActionHintMessages, actionHintMessages); }) @@ -1079,7 +1095,6 @@ public void testHintMessageForDuplicateParamWithOneInstanceEachInActionAndDsConf params.add(new Property("myParam1", "myVal")); actionConfig.setQueryParameters(params); - // This authentication mechanism will add `myHeader1` as query param implicitly. AuthenticationDTO authenticationDTO = new ApiKeyAuth(ApiKeyAuth.Type.QUERY_PARAMS, "myParam1", "Token", "test"); authenticationDTO.setAuthenticationType(API_KEY); @@ -1087,7 +1102,8 @@ public void testHintMessageForDuplicateParamWithOneInstanceEachInActionAndDsConf dsConfig.setAuthentication(authenticationDTO); dsConfig.setUrl("some_non_loc@lhost_url"); - Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = pluginExecutor.getHintMessages(actionConfig, dsConfig); + Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = + pluginExecutor.getHintMessages(actionConfig, dsConfig); StepVerifier.create(hintMessagesMono) .assertNext(tuple -> { Set<String> datasourceHintMessages = tuple.getT1(); @@ -1095,10 +1111,10 @@ public void testHintMessageForDuplicateParamWithOneInstanceEachInActionAndDsConf Set<String> actionHintMessages = tuple.getT2(); Set<String> expectedActionHintMessages = new HashSet<>(); - expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + - "definition(s) for param(s): [myParam1]. Please remove the duplicate definition(s) from" + - " the 'Params' section of either the API query or the datasource. Please note that some " + - "of the authentication mechanisms also implicitly define a param."); + expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + + "definition(s) for param(s): [myParam1]. Please remove the duplicate definition(s) from" + + " the 'Params' section of either the API query or the datasource. Please note that some " + + "of the authentication mechanisms also implicitly define a param."); assertEquals(expectedActionHintMessages, actionHintMessages); }) @@ -1112,10 +1128,7 @@ public void testQueryParamsInDatasource() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setEncodeParamsToggle(true); @@ -1124,7 +1137,8 @@ public void testQueryParamsInDatasource() { queryParams.add(new Property("query_key", "query val")); /* encoding changes 'query val' to 'query+val' */ dsConfig.setQueryParameters(queryParams); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1142,7 +1156,6 @@ public void testQueryParamsInDatasource() { } catch (InterruptedException e) { assert false : e.getMessage(); } - }) .verifyComplete(); } @@ -1155,7 +1168,8 @@ public void testDenyInstanceMetadataAws() { ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> assertFalse(result.getIsExecutionSuccess())) .verifyComplete(); @@ -1169,7 +1183,8 @@ public void testDenyInstanceMetadataAwsViaCname() { ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> assertFalse(result.getIsExecutionSuccess())) .verifyComplete(); @@ -1183,7 +1198,8 @@ public void testDenyInstanceMetadataGcp() { ActionConfiguration actionConfig = getDefaultActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> assertFalse(result.getIsExecutionSuccess())) .verifyComplete(); @@ -1215,8 +1231,12 @@ public void testNextCursorKeyIsSkippedWhenCursorValueIsNull() { updateVariablesWithPaginationValues(actionConfig, executeActionDTO); String expectedVariableString = "{\"first\":3}"; - assertEquals(expectedVariableString, - actionConfig.getPluginSpecifiedTemplates().get(QUERY_VARIABLES_INDEX).getValue()); + assertEquals( + expectedVariableString, + actionConfig + .getPluginSpecifiedTemplates() + .get(QUERY_VARIABLES_INDEX) + .getValue()); } /** @@ -1245,8 +1265,12 @@ public void testPrevCursorKeyIsSkippedWhenCursorValueIsNull() { updateVariablesWithPaginationValues(actionConfig, executeActionDTO); String expectedVariableString = "{\"last\":3}"; - assertEquals(expectedVariableString, - actionConfig.getPluginSpecifiedTemplates().get(QUERY_VARIABLES_INDEX).getValue()); + assertEquals( + expectedVariableString, + actionConfig + .getPluginSpecifiedTemplates() + .get(QUERY_VARIABLES_INDEX) + .getValue()); } /** @@ -1277,21 +1301,29 @@ public void testNextCursorKeyIsSkippedWhenPaginationValueIsNull() { updateVariablesWithPaginationValues(actionConfig, executeActionDTO); String expectedVariableString = "{\"first\":3}"; - assertEquals(expectedVariableString, - actionConfig.getPluginSpecifiedTemplates().get(QUERY_VARIABLES_INDEX).getValue()); + assertEquals( + expectedVariableString, + actionConfig + .getPluginSpecifiedTemplates() + .get(QUERY_VARIABLES_INDEX) + .getValue()); } @Test public void verifyUniquenessOfGraphQLPluginErrorCode() { - assertEquals(GraphQLPluginError.values().length, Arrays.stream(GraphQLPluginError.values()).map(GraphQLPluginError::getAppErrorCode).distinct().count()); + assertEquals( + GraphQLPluginError.values().length, + Arrays.stream(GraphQLPluginError.values()) + .map(GraphQLPluginError::getAppErrorCode) + .distinct() + .count()); - assertEquals(0, + assertEquals( + 0, Arrays.stream(GraphQLPluginError.values()) .map(GraphQLPluginError::getAppErrorCode) .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-GQL")) .toList() .size()); - } - } diff --git a/app/server/appsmith-plugins/jsPlugin/pom.xml b/app/server/appsmith-plugins/jsPlugin/pom.xml index 9a0baa035e3f..67a3f13f7501 100644 --- a/app/server/appsmith-plugins/jsPlugin/pom.xml +++ b/app/server/appsmith-plugins/jsPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>jsPlugin</artifactId> <version>1.0-SNAPSHOT</version> diff --git a/app/server/appsmith-plugins/jsPlugin/src/main/java/com/external/plugins/JSPlugin.java b/app/server/appsmith-plugins/jsPlugin/src/main/java/com/external/plugins/JSPlugin.java index ef4ec39b14b3..22374f081758 100644 --- a/app/server/appsmith-plugins/jsPlugin/src/main/java/com/external/plugins/JSPlugin.java +++ b/app/server/appsmith-plugins/jsPlugin/src/main/java/com/external/plugins/JSPlugin.java @@ -21,7 +21,10 @@ public JSPlugin(PluginWrapper wrapper) { @Extension public static class JSPluginExecutor implements PluginExecutor<Void>, SmartSubstitutionInterface { @Override - public Mono<ActionExecutionResult> execute(Void connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + Void connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { return Mono.empty(); } @@ -31,13 +34,11 @@ public Mono<Void> datasourceCreate(DatasourceConfiguration datasourceConfigurati } @Override - public void datasourceDestroy(Void connection) { - } + public void datasourceDestroy(Void connection) {} @Override public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) { return Set.of(); } } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mongoPlugin/pom.xml b/app/server/appsmith-plugins/mongoPlugin/pom.xml index 01c272c883a4..6e5c8345ba5c 100644 --- a/app/server/appsmith-plugins/mongoPlugin/pom.xml +++ b/app/server/appsmith-plugins/mongoPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>mongoPlugin</artifactId> <version>1.0-SNAPSHOT</version> diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java index 7fd7a127f929..ff24ad4e02ef 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java @@ -142,12 +142,11 @@ public class MongoPlugin extends BasePlugin { private static final Set<DBAuth.Type> VALID_AUTH_TYPES = Set.of( DBAuth.Type.SCRAM_SHA_1, DBAuth.Type.SCRAM_SHA_256, - DBAuth.Type.MONGODB_CR // NOTE: Deprecated in the driver. - ); + DBAuth.Type.MONGODB_CR // NOTE: Deprecated in the driver. + ); - private static final String VALID_AUTH_TYPES_STR = VALID_AUTH_TYPES.stream() - .map(String::valueOf) - .collect(Collectors.joining(", ")); + private static final String VALID_AUTH_TYPES_STR = + VALID_AUTH_TYPES.stream().map(String::valueOf).collect(Collectors.joining(", ")); public static final String N_MODIFIED = "nModified"; @@ -163,7 +162,8 @@ public class MongoPlugin extends BasePlugin { * capturing the value group for regex. * e.g {"code" : {$regex: 8777}}, this whole substring will be matched and 8777 is captured for further processing. */ - private static final String mongo$regexWithNumberIdentifier = ".*\\{[\\s\\n]*\\$regex[\\s\\n]*:([\\s\\n]*(?:(?:\\\"[/]*)|(?:/[\\\"]*)|)[-]?[\\d]*\\.?[\\d]*(?:(?:[/]*\\\")|(?:[\\\"]*/)|)[\\s\\n]*)(?:,|\\})"; + private static final String mongo$regexWithNumberIdentifier = + ".*\\{[\\s\\n]*\\$regex[\\s\\n]*:([\\s\\n]*(?:(?:\\\"[/]*)|(?:/[\\\"]*)|)[-]?[\\d]*\\.?[\\d]*(?:(?:[/]*\\\")|(?:[\\\"]*/)|)[\\s\\n]*)(?:,|\\})"; /** * We use this regex to find usage of special Mongo data types like ObjectId(...) wrapped inside double quotes @@ -179,7 +179,8 @@ public class MongoPlugin extends BasePlugin { * o group 3 will match 'xyz' * o group 4 will match xyz */ - private static final String MONGODB_SPECIAL_TYPE_INSIDE_QUOTES_REGEX_TEMPLATE = "(\\\"(E\\((.*?((\\w|-|:|\\.|,|\\s)+).*?)?\\))\\\")"; + private static final String MONGODB_SPECIAL_TYPE_INSIDE_QUOTES_REGEX_TEMPLATE = + "(\\\"(E\\((.*?((\\w|-|:|\\.|,|\\s)+).*?)?\\))\\\")"; private static final int DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX = 1; @@ -195,8 +196,7 @@ public class MongoPlugin extends BasePlugin { FIND_PROJECTION, INSERT_DOCUMENT, UPDATE_QUERY, - UPDATE_OPERATION - )); + UPDATE_OPERATION)); private static final MongoErrorUtils mongoErrorUtils = MongoErrorUtils.getInstance(); @@ -208,8 +208,7 @@ public class MongoPlugin extends BasePlugin { new MapCodecProvider(), new DBRefCodecProvider(), new GeoJsonCodecProvider(), - new GridFSFileCodecProvider() - )); + new GridFSFileCodecProvider())); private static final BsonTypeClassMap DEFAULT_BSON_TYPE_CLASS_MAP = new org.bson.codecs.BsonTypeClassMap(); @@ -235,18 +234,19 @@ public static class MongoPluginExecutor implements PluginExecutor<MongoClient>, * @param actionConfiguration : These are the configurations which have been used to create an Action from a Datasource. */ @Override - public Mono<ActionExecutionResult> executeParameterized(MongoClient mongoClient, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { - + public Mono<ActionExecutionResult> executeParameterized( + MongoClient mongoClient, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final Map<String, Object> formData = actionConfiguration.getFormData(); List<Map.Entry<String, String>> parameters = new ArrayList<>(); Boolean smartBsonSubstitution = TRUE; - Object smartSubstitutionObject = PluginUtils.getDataValueSafelyFromFormData(formData, SMART_SUBSTITUTION, OBJECT_TYPE, TRUE); + Object smartSubstitutionObject = + PluginUtils.getDataValueSafelyFromFormData(formData, SMART_SUBSTITUTION, OBJECT_TYPE, TRUE); if (smartSubstitutionObject instanceof Boolean) { smartBsonSubstitution = (Boolean) smartSubstitutionObject; } else if (smartSubstitutionObject instanceof String) { @@ -260,14 +260,13 @@ public Mono<ActionExecutionResult> executeParameterized(MongoClient mongoClient, // If not raw, then it must be form input. if (!isRawCommand(formData)) { - smartSubstituteFormCommand(formData, - executeActionDTO.getParams(), parameters); + smartSubstituteFormCommand(formData, executeActionDTO.getParams(), parameters); } else { // For raw queries do smart replacements in BSON body final Object body = PluginUtils.getDataValueSafelyFromFormData(formData, BODY, OBJECT_TYPE); if (body != null) { - String updatedRawQuery = smartSubstituteBSON((String) body, - executeActionDTO.getParams(), parameters); + String updatedRawQuery = + smartSubstituteBSON((String) body, executeActionDTO.getParams(), parameters); setDataValueSafelyInFormData(formData, BODY, updatedRawQuery); } } @@ -296,10 +295,11 @@ public Mono<ActionExecutionResult> executeParameterized(MongoClient mongoClient, * @param actionConfiguration : These are the configurations which have been used to create an Action from a Datasource. * @return Result data from executing the action's query. */ - public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration, - List<Map.Entry<String, String>> parameters) { + public Mono<ActionExecutionResult> executeCommon( + MongoClient mongoClient, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration, + List<Map.Entry<String, String>> parameters) { if (mongoClient == null) { log.info("Encountered null connection in MongoDB plugin. Reporting back."); @@ -318,43 +318,35 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, Bson command = Document.parse(query); mongoOutputMono = Mono.from(database.runCommand(command)); - requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null - , null, null)); + requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null)); } catch (Exception error) { - return Mono.error(new AppsmithPluginException(MongoPluginError.QUERY_EXECUTION_FAILED, MongoPluginErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error)); + return Mono.error(new AppsmithPluginException( + MongoPluginError.QUERY_EXECUTION_FAILED, + MongoPluginErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error)); } return mongoOutputMono .onErrorMap( MongoTimeoutException.class, error -> new AppsmithPluginException( - AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR, - error.getMessage() - ) - ) + AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR, error.getMessage())) .onErrorMap( MongoCommandException.class, error -> new AppsmithPluginException( error, AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - MongoPluginErrorMessages.QUERY_INVALID_ERROR_MSG - ) - ) + MongoPluginErrorMessages.QUERY_INVALID_ERROR_MSG)) /** * This is to catch the cases when Mongo connection pool closes for some reason and hence throws * IllegalStateException when query is run. * Ref: https://github.com/appsmithorg/appsmith/issues/15548 */ - .onErrorMap( - IllegalStateException.class, - error -> new StaleConnectionException(error.getMessage()) - ) + .onErrorMap(IllegalStateException.class, error -> new StaleConnectionException(error.getMessage())) // This is an experimental fix to handle the scenario where after a period of inactivity, the mongo // database drops the connection which makes the client throw the following exception. .onErrorMap( - MongoSocketWriteException.class, - error -> new StaleConnectionException(error.getMessage()) - ) + MongoSocketWriteException.class, error -> new StaleConnectionException(error.getMessage())) .flatMap(mongoOutput -> { try { /* @@ -362,14 +354,12 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, * processing of DbRef Object. * https://github.com/spring-projects/spring-data-mongodb/issues/3015 : Mark Paluch commented */ - DocumentCodec documentCodec = new DocumentCodec( - DEFAULT_REGISTRY, - DEFAULT_BSON_TYPE_CLASS_MAP - ); + DocumentCodec documentCodec = + new DocumentCodec(DEFAULT_REGISTRY, DEFAULT_BSON_TYPE_CLASS_MAP); JSONObject outputJson = new JSONObject(mongoOutput.toJson(documentCodec)); - //The output json contains the key "ok". This is the status of the command + // The output json contains the key "ok". This is the status of the command BigInteger status = outputJson.getBigInteger("ok"); JSONArray headerArray = new JSONArray(); @@ -377,24 +367,23 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, result.setIsExecutionSuccess(true); result.setDataTypes(List.of( new ParsedDataType(DisplayDataType.JSON), - new ParsedDataType(DisplayDataType.RAW) - )); + new ParsedDataType(DisplayDataType.RAW))); /* - For the `findAndModify` command, we don't get the count of modifications made. Instead, - we either get the modified new value or the pre-modified old value (depending on the - `new` field in the command. Let's return that value to the user. - */ + For the `findAndModify` command, we don't get the count of modifications made. Instead, + we either get the modified new value or the pre-modified old value (depending on the + `new` field in the command. Let's return that value to the user. + */ if (outputJson.has(VALUE)) { result.setBody(objectMapper.readTree( - cleanUp(new JSONObject().put(VALUE, outputJson.get(VALUE))).toString() - )); + cleanUp(new JSONObject().put(VALUE, outputJson.get(VALUE))) + .toString())); } /* - The json contains key "cursor" when find command was issued and there are 1 or more - results. In case there are no results for find, this key is not present in the result json. - */ + The json contains key "cursor" when find command was issued and there are 1 or more + results. In case there are no results for find, this key is not present in the result json. + */ if (outputJson.has("cursor")) { JSONArray outputResult = (JSONArray) cleanUp( outputJson.getJSONObject("cursor").getJSONArray("firstBatch")); @@ -402,10 +391,10 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, } /* - The json contains key "n" when insert/update command is issued. "n" for update - signifies the no of documents selected for update. "n" in case of insert signifies the - number of documents inserted. - */ + The json contains key "n" when insert/update command is issued. "n" for update + signifies the no of documents selected for update. "n" in case of insert signifies the + number of documents inserted. + */ if (outputJson.has("n")) { JSONObject body = new JSONObject().put("n", outputJson.getBigInteger("n")); result.setBody(objectMapper.readTree(body.toString())); @@ -413,29 +402,28 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, } /* - The json key contains key "nModified" in case of update command. This signifies the no of - documents updated. - */ + The json key contains key "nModified" in case of update command. This signifies the no of + documents updated. + */ if (outputJson.has(N_MODIFIED)) { - JSONObject body = new JSONObject().put(N_MODIFIED, outputJson.getBigInteger(N_MODIFIED)); + JSONObject body = + new JSONObject().put(N_MODIFIED, outputJson.getBigInteger(N_MODIFIED)); result.setBody(objectMapper.readTree(body.toString())); headerArray.put(body); } /* - The json contains key "values" when distinct command is used. - */ + The json contains key "values" when distinct command is used. + */ if (outputJson.has(VALUES)) { - JSONArray outputResult = (JSONArray) cleanUp( - outputJson.getJSONArray(VALUES)); + JSONArray outputResult = (JSONArray) cleanUp(outputJson.getJSONArray(VALUES)); ObjectNode resultNode = objectMapper.createObjectNode(); // Create a JSON structure with the results stored with a key to abide by the // Server-Client contract of only sending array of objects in result. - resultNode - .putArray(VALUES) - .addAll((ArrayNode) objectMapper.readTree(outputResult.toString())); + resultNode.putArray(VALUES).addAll((ArrayNode) + objectMapper.readTree(outputResult.toString())); result.setBody(objectMapper.readTree(resultNode.toString())); } @@ -450,7 +438,10 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, headerArray.put(statusJson); result.setHeaders(objectMapper.readTree(headerArray.toString())); } catch (JsonProcessingException e) { - return Mono.error(new AppsmithPluginException(MongoPluginError.QUERY_EXECUTION_FAILED, MongoPluginErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + MongoPluginError.QUERY_EXECUTION_FAILED, + MongoPluginErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage())); } return Mono.just(result); @@ -459,8 +450,11 @@ public Mono<ActionExecutionResult> executeCommon(MongoClient mongoClient, if (error instanceof StaleConnectionException) { log.debug("The mongo connection seems to have been invalidated or doesn't exist anymore"); return Mono.error(error); - } else if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(MongoPluginError.QUERY_EXECUTION_FAILED, MongoPluginErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error); + } else if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + MongoPluginError.QUERY_EXECUTION_FAILED, + MongoPluginErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error); } ActionExecutionResult actionExecutionResult = new ActionExecutionResult(); actionExecutionResult.setIsExecutionSuccess(false); @@ -497,13 +491,13 @@ public String sanitizeReplacement(String replacementValue, DataType dataType) { if (DataType.BSON_SPECIAL_DATA_TYPES.equals(dataType)) { /* - For all other data types the replacementValue is prepared for replacement (by using Matcher - .quoteReplacement(...)) during the common handling of data types in - `jsonSmartReplacementPlaceholderWithValue(...)` method before reaching this program point. For - BSON_SPECIAL_DATA_TYPES it is skipped in the common handling flow because we want to modify - (removeOrAddQuotesAroundMongoDBSpecialTypes(...)) the replacement value further before the final - replacement happens. - */ + For all other data types the replacementValue is prepared for replacement (by using Matcher + .quoteReplacement(...)) during the common handling of data types in + `jsonSmartReplacementPlaceholderWithValue(...)` method before reaching this program point. For + BSON_SPECIAL_DATA_TYPES it is skipped in the common handling flow because we want to modify + (removeOrAddQuotesAroundMongoDBSpecialTypes(...)) the replacement value further before the final + replacement happens. + */ replacementValue = Matcher.quoteReplacement(replacementValue); } @@ -531,13 +525,13 @@ private String removeOrAddQuotesAroundMongoDBSpecialTypes(String query) { Matcher matcher = pattern.matcher(query); while (matcher.find()) { /* - `If` branch will match when any special data type is found wrapped within double quotes e.g. - "ObjectId('someId')": - o Group 1 = "ObjectId('someId')" - o Group 2 = ObjectId(someId) - o Group 3 = 'someId' - o Group 4 = someId - */ + `If` branch will match when any special data type is found wrapped within double quotes e.g. + "ObjectId('someId')": + o Group 1 = "ObjectId('someId')" + o Group 2 = ObjectId(someId) + o Group 3 = 'someId' + o Group 4 = someId + */ if (matcher.group(1) != null) { String objectIdWithQuotes = matcher.group(1); String objectIdWithoutQuotes = matcher.group(2); @@ -550,10 +544,7 @@ private String removeOrAddQuotesAroundMongoDBSpecialTypes(String query) { } } catch (JsonProcessingException e) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - argWithoutQuotes, - e.getMessage() - ); + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, argWithoutQuotes, e.getMessage()); } objectIdMap.put(objectIdWithQuotes, objectIdWithoutQuotes); objectIdMap.put(argWithQuotes, argWithoutQuotes); @@ -569,34 +560,30 @@ private String removeOrAddQuotesAroundMongoDBSpecialTypes(String query) { return query; } - private String smartSubstituteBSON(String rawQuery, - List<Param> params, - List<Map.Entry<String, String>> parameters) throws AppsmithPluginException { + private String smartSubstituteBSON( + String rawQuery, List<Param> params, List<Map.Entry<String, String>> parameters) + throws AppsmithPluginException { // First extract all the bindings in order List<MustacheBindingToken> mustacheKeysInOrder = MustacheHelper.extractMustacheKeysInOrder(rawQuery); // Replace all the bindings with a ? as expected in a prepared statement. String updatedQuery = MustacheHelper.replaceMustacheWithPlaceholder(rawQuery, mustacheKeysInOrder); - updatedQuery = (String) smartSubstitutionOfBindings(updatedQuery, - mustacheKeysInOrder, - params, - parameters); + updatedQuery = (String) smartSubstitutionOfBindings(updatedQuery, mustacheKeysInOrder, params, parameters); - updatedQuery = makeMongoRegexSubstitutionValid (updatedQuery); + updatedQuery = makeMongoRegexSubstitutionValid(updatedQuery); return updatedQuery; } - private static StringBuilder makeValidForRegex(String value) { StringBuilder valueSB = new StringBuilder(value.trim()); char quote = '\"'; char forwardSlash = '/'; - if ( valueSB.charAt(0) != quote && valueSB.charAt(0) != forwardSlash) { - valueSB.insert(0, quote ); + if (valueSB.charAt(0) != quote && valueSB.charAt(0) != forwardSlash) { + valueSB.insert(0, quote); // adds quote at the end of the line valueSB.append(quote); } @@ -624,18 +611,19 @@ private static String makeMongoRegexSubstitutionValid(String inputQuery) { try { valueSB = makeValidForRegex(mongo$regexIdentifierMatcher.group(1)); - } catch(StringIndexOutOfBoundsException e) { + } catch (StringIndexOutOfBoundsException e) { // when the match group detected is of length zero this error is thrown; return inputQuery; } catch (Exception e) { return inputQuery; } - - //groups are discovered in greedy manner hence it's sorted by default - // a sub-group within a big group could be due to the regex arguments provide by user hence will not parse that + // groups are discovered in greedy manner hence it's sorted by default + // a sub-group within a big group could be due to the regex arguments provide by user hence will not + // parse that if (startIndex > mongo$regexIdentifierMatcher.start()) { - // the matcher walks greedily to find the pattern, if there is a group overlapping with other group means that it's a subquery, and it's not meant to be parsed. + // the matcher walks greedily to find the pattern, if there is a group overlapping with other group + // means that it's a subquery, and it's not meant to be parsed. continue; } inputQuerySB.append(inputQuery.substring(startIndex, mongo$regexIdentifierMatcher.start(1))); @@ -653,13 +641,14 @@ private static String makeMongoRegexSubstitutionValid(String inputQuery) { * This function replaces the mustache variables using smart substitution and updates the existing formData * with the values post substitution */ - private void smartSubstituteFormCommand(Map<String, Object> formData, - List<Param> params, - List<Map.Entry<String, String>> parameters) throws AppsmithPluginException { + private void smartSubstituteFormCommand( + Map<String, Object> formData, List<Param> params, List<Map.Entry<String, String>> parameters) + throws AppsmithPluginException { for (String bsonField : bsonFields) { if (validConfigurationPresentInFormData(formData, bsonField)) { - String preSmartSubValue = PluginUtils.getDataValueSafelyFromFormData(formData, bsonField, STRING_TYPE); + String preSmartSubValue = + PluginUtils.getDataValueSafelyFromFormData(formData, bsonField, STRING_TYPE); String postSmartSubValue = smartSubstituteBSON(preSmartSubValue, params, parameters); setDataValueSafelyInFormData(formData, bsonField, postSmartSubValue); } @@ -669,10 +658,10 @@ private void smartSubstituteFormCommand(Map<String, Object> formData, @Override public Mono<MongoClient> datasourceCreate(DatasourceConfiguration datasourceConfiguration) { /* - TODO: ReadOnly seems to be not supported at the driver level. The recommendation is to connect with - a user that doesn't have write permissions on the database. - Ref: https://api.mongodb.com/java/2.13/com/mongodb/DB.html#setReadOnly-java.lang.Boolean- - */ + TODO: ReadOnly seems to be not supported at the driver level. The recommendation is to connect with + a user that doesn't have write permissions on the database. + Ref: https://api.mongodb.com/java/2.13/com/mongodb/DB.html#setReadOnly-java.lang.Boolean- + */ return Mono.just(datasourceConfiguration) .flatMap(dsConfig -> { @@ -682,25 +671,23 @@ public Mono<MongoClient> datasourceCreate(DatasourceConfiguration datasourceConf return Mono.error(e); } }) - .map(uriString -> MongoClients.create( - MongoClientSettings - .builder() - .applyToConnectionPoolSettings(t -> t.applySettings(ConnectionPoolSettings.builder().minSize(0).build())) - .applyConnectionString(new ConnectionString(uriString)) - .build() - )) + .map(uriString -> MongoClients.create(MongoClientSettings.builder() + .applyToConnectionPoolSettings(t -> t.applySettings( + ConnectionPoolSettings.builder().minSize(0).build())) + .applyConnectionString(new ConnectionString(uriString)) + .build())) .onErrorMap( IllegalArgumentException.class, - error -> - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - MongoPluginErrorMessages.DS_CREATION_FAILED_ERROR_MSG, - error.getMessage() - ) - ) + error -> new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + MongoPluginErrorMessages.DS_CREATION_FAILED_ERROR_MSG, + error.getMessage())) .onErrorMap(e -> { - if (! (e instanceof AppsmithPluginException)) { - return new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, MongoPluginErrorMessages.DS_CREATION_FAILED_ERROR_MSG, e.getMessage()); + if (!(e instanceof AppsmithPluginException)) { + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + MongoPluginErrorMessages.DS_CREATION_FAILED_ERROR_MSG, + e.getMessage()); } return e; @@ -708,7 +695,6 @@ public Mono<MongoClient> datasourceCreate(DatasourceConfiguration datasourceConf .subscribeOn(scheduler); } - @Override public void datasourceDestroy(MongoClient mongoClient) { if (mongoClient != null) { @@ -716,7 +702,6 @@ public void datasourceDestroy(MongoClient mongoClient) { } } - @Override public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) { Set<String> invalids = new HashSet<>(); @@ -726,7 +711,9 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur if (!hasNonEmptyURI(datasourceConfiguration)) { invalids.add(MongoPluginErrorMessages.DS_EMPTY_CONNECTION_URI_ERROR_MSG); } else { - String mongoUri = (String) properties.get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX).getValue(); + String mongoUri = (String) properties + .get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX) + .getValue(); if (!mongoUri.matches(MONGO_URI_REGEX)) { invalids.add(MongoPluginErrorMessages.DS_INVALID_CONNECTION_STRING_URI_ERROR_MSG); } else { @@ -739,7 +726,9 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur } if (!isAuthenticated(authentication, mongoUri)) { String mongoUriWithHiddenPassword = buildURIFromExtractedInfo(extractedInfo, "****"); - properties.get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX).setValue(mongoUriWithHiddenPassword); + properties + .get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX) + .setValue(mongoUriWithHiddenPassword); authentication = (authentication == null) ? new DBAuth() : authentication; authentication.setUsername((String) extractedInfo.get(KEY_USERNAME)); authentication.setPassword((String) extractedInfo.get(KEY_PASSWORD)); @@ -759,17 +748,15 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur if (CollectionUtils.isEmpty(endpoints)) { invalids.add(MongoPluginErrorMessages.DS_MISSING_ENDPOINTS_ERROR_MSG); - } else if (Connection.Type.REPLICA_SET.equals(datasourceConfiguration.getConnection().getType())) { + } else if (Connection.Type.REPLICA_SET.equals( + datasourceConfiguration.getConnection().getType())) { if (endpoints.size() == 1 && endpoints.get(0).getPort() != null) { invalids.add(MongoPluginErrorMessages.DS_NO_PORT_EXPECTED_IN_REPLICA_SET_CONNECTION_ERROR_MSG); } - } if (!CollectionUtils.isEmpty(endpoints)) { - boolean usingUri = endpoints - .stream() - .anyMatch(endPoint -> isHostStringConnectionURI(endPoint)); + boolean usingUri = endpoints.stream().anyMatch(endPoint -> isHostStringConnectionURI(endPoint)); if (usingUri) { invalids.add(MongoPluginErrorMessages.DS_USING_URI_BUT_EXPECTED_FORM_FIELDS_ERROR_MSG); @@ -780,13 +767,13 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur DBAuth.Type authType = authentication.getAuthType(); if (authType == null || !VALID_AUTH_TYPES.contains(authType)) { - invalids.add(String.format(MongoPluginErrorMessages.DS_INVALID_AUTH_TYPE_ERROR_MSG, VALID_AUTH_TYPES_STR)); + invalids.add(String.format( + MongoPluginErrorMessages.DS_INVALID_AUTH_TYPE_ERROR_MSG, VALID_AUTH_TYPES_STR)); } if (!StringUtils.hasLength(authentication.getDatabaseName())) { invalids.add(MongoPluginErrorMessages.DS_INVALID_AUTH_DATABASE_NAME); } - } /* @@ -805,42 +792,45 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur @Override public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) { - Function<TimeoutException, Throwable> timeoutExceptionThrowableFunction = error -> new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_TIMEOUT_ERROR, - MongoPluginErrorMessages.DS_TIMEOUT_ERROR_MSG - ); + Function<TimeoutException, Throwable> timeoutExceptionThrowableFunction = + error -> new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_TIMEOUT_ERROR, + MongoPluginErrorMessages.DS_TIMEOUT_ERROR_MSG); return datasourceCreate(datasourceConfiguration) .flatMap(mongoClient -> { final Publisher<String> result = mongoClient.listDatabaseNames(); - final Mono<List<String>> documentMono = Flux.from(result).collectList().cache(); - return documentMono.doFinally(ignored -> mongoClient.close()).then(documentMono); + final Mono<List<String>> documentMono = + Flux.from(result).collectList().cache(); + return documentMono + .doFinally(ignored -> mongoClient.close()) + .then(documentMono); }) .flatMap(names -> { - final String defaultDatabaseName; if (datasourceConfiguration.getConnection() != null) { - defaultDatabaseName = datasourceConfiguration.getConnection().getDefaultDatabaseName(); + defaultDatabaseName = + datasourceConfiguration.getConnection().getDefaultDatabaseName(); } else { defaultDatabaseName = null; } final String authDatabaseName; - if (datasourceConfiguration.getAuthentication() != null && - !isBlank(((DBAuth)datasourceConfiguration.getAuthentication()).getDatabaseName())) { + if (datasourceConfiguration.getAuthentication() != null + && !isBlank(((DBAuth) datasourceConfiguration.getAuthentication()).getDatabaseName())) { authDatabaseName = ((DBAuth) datasourceConfiguration.getAuthentication()).getDatabaseName(); } else { - return Mono.just(new DatasourceTestResult( - MongoPluginErrorMessages.DS_INVALID_AUTH_DATABASE_NAME)); + return Mono.just( + new DatasourceTestResult(MongoPluginErrorMessages.DS_INVALID_AUTH_DATABASE_NAME)); } final Optional<String> authDB = names.stream() .filter(name -> name.equals(authDatabaseName)) .findFirst(); - if(authDB.isEmpty()) { - return Mono.just(new DatasourceTestResult( - MongoPluginErrorMessages.DS_INVALID_AUTH_DATABASE_NAME)); + if (authDB.isEmpty()) { + return Mono.just( + new DatasourceTestResult(MongoPluginErrorMessages.DS_INVALID_AUTH_DATABASE_NAME)); } if (defaultDatabaseName == null || defaultDatabaseName.isBlank()) { @@ -853,18 +843,21 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasou if (defaultDB.isEmpty()) { // value entered in default database name is invalid - return Mono.just(new DatasourceTestResult(MongoPluginErrorMessages.DS_DEFAULT_DATABASE_NAME_INVALID_ERROR_MSG)); + return Mono.just(new DatasourceTestResult( + MongoPluginErrorMessages.DS_DEFAULT_DATABASE_NAME_INVALID_ERROR_MSG)); } return Mono.just(new DatasourceTestResult()); }) .timeout(Duration.ofSeconds(TEST_DATASOURCE_TIMEOUT_SECONDS)) .onErrorMap(TimeoutException.class, timeoutExceptionThrowableFunction) - .onErrorResume(error -> Mono.just(new DatasourceTestResult(mongoErrorUtils.getReadableError(error)))) + .onErrorResume( + error -> Mono.just(new DatasourceTestResult(mongoErrorUtils.getReadableError(error)))) .subscribeOn(scheduler); } @Override - public Mono<DatasourceStructure> getStructure(MongoClient mongoClient, DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + MongoClient mongoClient, DatasourceConfiguration datasourceConfiguration) { final DatasourceStructure structure = new DatasourceStructure(); List<DatasourceStructure.Table> tables = new ArrayList<>(); structure.setTables(tables); @@ -881,15 +874,16 @@ public Mono<DatasourceStructure> getStructure(MongoClient mongoClient, Datasourc collectionName, columns, new ArrayList<>(), - templates - )); + templates)); return Mono.zip( Mono.just(columns), Mono.just(templates), Mono.just(collectionName), - Mono.from(database.getCollection(collectionName).find().limit(1).first()) - ); + Mono.from(database.getCollection(collectionName) + .find() + .limit(1) + .first())); }) .flatMap(tuple -> { final ArrayList<DatasourceStructure.Column> columns = tuple.getT1(); @@ -908,44 +902,36 @@ public Mono<DatasourceStructure> getStructure(MongoClient mongoClient, Datasourc * IllegalStateException when query is run. * Ref: https://github.com/appsmithorg/appsmith/issues/15548 */ - .onErrorMap( - IllegalStateException.class, - error -> new StaleConnectionException(error.getMessage()) - ) + .onErrorMap(IllegalStateException.class, error -> new StaleConnectionException(error.getMessage())) // This is an experimental fix to handle the scenario where after a period of inactivity, the mongo // database drops the connection which makes the client throw the following exception. .onErrorMap( - MongoSocketWriteException.class, - error -> new StaleConnectionException(error.getMessage()) - ) - .onErrorMap( - MongoCommandException.class, - error -> { - if (MONGO_COMMAND_EXCEPTION_UNAUTHORIZED_ERROR_CODE.equals(error.getErrorCode())) { - return new AppsmithPluginException( - AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, - MongoPluginErrorMessages.DS_GET_STRUCTURE_ERROR_MSG - - ); - } + MongoSocketWriteException.class, error -> new StaleConnectionException(error.getMessage())) + .onErrorMap(MongoCommandException.class, error -> { + if (MONGO_COMMAND_EXCEPTION_UNAUTHORIZED_ERROR_CODE.equals(error.getErrorCode())) { + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + MongoPluginErrorMessages.DS_GET_STRUCTURE_ERROR_MSG); + } - return error; - } - ) + return error; + }) .subscribeOn(scheduler); } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) { String jsonBody = (String) input; Param param = (Param) args[0]; DataType dataType = stringToKnownMongoDBDataTypeConverter(value, param.getClientDataType()); - return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue(jsonBody, value, dataType, insertedParams, this, param); + return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue( + jsonBody, value, dataType, insertedParams, this, param); } /** @@ -959,12 +945,13 @@ public Object substituteValueInInput(int index, * @return identified data type of replacement value */ private DataType stringToKnownMongoDBDataTypeConverter(String replacement, ClientDataType clientDataType) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(clientDataType, replacement, MongoSpecificDataTypes.pluginSpecificTypes); + AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType( + clientDataType, replacement, MongoSpecificDataTypes.pluginSpecificTypes); DataType dataType = appsmithType.type(); if (dataType == DataType.STRING) { for (MongoSpecialDataTypes specialType : MongoSpecialDataTypes.values()) { - final String regex = MONGODB_SPECIAL_TYPE_INSIDE_QUOTES_REGEX_TEMPLATE.replace("E", - specialType.name()); + final String regex = + MONGODB_SPECIAL_TYPE_INSIDE_QUOTES_REGEX_TEMPLATE.replace("E", specialType.name()); final Pattern pattern = Pattern.compile(regex); final Matcher matcher = pattern.matcher(replacement); if (matcher.find()) { @@ -977,13 +964,14 @@ private DataType stringToKnownMongoDBDataTypeConverter(String replacement, Clien return dataType; } - @Override - public Mono<ActionExecutionResult> execute(MongoClient mongoClient, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + MongoClient mongoClient, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Unused function - return Mono.error(new AppsmithPluginException(MongoPluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); + return Mono.error( + new AppsmithPluginException(MongoPluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); } /** @@ -1001,9 +989,9 @@ public void extractAndSetNativeQueryFromFormData(ActionConfiguration actionConfi if (!isRawCommand(formData)) { /* - This translation must happen only if the user has not edited the raw mode. Hence, check that - user has not provided any raw query. - */ + This translation must happen only if the user has not edited the raw mode. Hence, check that + user has not provided any raw query. + */ if (isBlank(getDataValueSafelyFromFormData(formData, BODY, STRING_TYPE))) { try { String rawQuery = getRawQuery(actionConfiguration); @@ -1013,9 +1001,7 @@ public void extractAndSetNativeQueryFromFormData(ActionConfiguration actionConfi } } catch (Exception e) { throw new AppsmithPluginException( - MongoPluginError.FORM_TO_NATIVE_TRANSLATION_ERROR, - e.getMessage() - ); + MongoPluginError.FORM_TO_NATIVE_TRANSLATION_ERROR, e.getMessage()); } } } @@ -1044,14 +1030,12 @@ private static Object cleanUp(Object object) { And for dates on or after Jan 1, 1970 the output json from MongoDB driver is readily available and looks like "$date": "2022-07-01T10:32:37.318Z" */ - if (dateJSON != null && dateJSON.keySet().size() == 1 && - "$numberLong".equals(dateJSON.keys().next())) { - return DateTimeFormatter.ISO_INSTANT.format( - Instant.ofEpochMilli(dateJSON.getLong("$numberLong"))); + if (dateJSON != null + && dateJSON.keySet().size() == 1 + && "$numberLong".equals(dateJSON.keys().next())) { + return DateTimeFormatter.ISO_INSTANT.format(Instant.ofEpochMilli(dateJSON.getLong("$numberLong"))); } - return DateTimeFormatter.ISO_INSTANT.format( - Instant.parse(jsonObject.getString("$date")) - ); + return DateTimeFormatter.ISO_INSTANT.format(Instant.parse(jsonObject.getString("$date"))); } else if (isSingleKey && "$numberDecimal".equals(jsonObject.keys().next())) { return new BigDecimal(jsonObject.getString("$numberDecimal")); @@ -1060,7 +1044,6 @@ private static Object cleanUp(Object object) { for (String key : new HashSet<>(jsonObject.keySet())) { jsonObject.put(key, cleanUp(jsonObject.get(key))); } - } } else if (object instanceof JSONArray) { @@ -1071,10 +1054,8 @@ private static Object cleanUp(Object object) { } return new JSONArray(cleaned); - } return object; } - } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Aggregate.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Aggregate.java index aab97de584aa..8aa93382351a 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Aggregate.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Aggregate.java @@ -85,7 +85,10 @@ public Document parseCommand() { commandDocument.put("pipeline", arrayListFromInput); } } catch (JsonParseException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, MongoPluginErrorMessages.PIPELINE_ARRAY_PARSING_FAILED_ERROR_MSG, e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + MongoPluginErrorMessages.PIPELINE_ARRAY_PARSING_FAILED_ERROR_MSG, + e.getMessage()); } } else { // The command expects the pipelines to be sent in an array. Parse and create a single element array @@ -93,7 +96,9 @@ public Document parseCommand() { // check for enclosing curly bracket to make json validation more strict final String jsonObject = this.pipeline.trim(); if (jsonObject.charAt(jsonObject.length() - 1) != '}') { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, MongoPluginErrorMessages.PIPELINE_STAGE_NOT_VALID_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + MongoPluginErrorMessages.PIPELINE_STAGE_NOT_VALID_ERROR_MSG); } Document document = parseSafely("Array of pipelines", this.pipeline); @@ -158,18 +163,15 @@ public List<DatasourceStructure.Template> generateTemplate(Map<String, Object> t setDataValueSafelyInFormData(configMap, AGGREGATE_PIPELINES, "[ {\"$sort\" : {\"_id\": 1} } ]"); setDataValueSafelyInFormData(configMap, AGGREGATE_LIMIT, "10"); - String rawQuery = "{\n" + - " \"aggregate\": \"" + collectionName + "\",\n" + - " \"pipeline\": " + "[ {\"$sort\" : {\"_id\": 1} } ],\n" + - " \"limit\": 10,\n" + - " \"explain\": \"true\"\n" + // Specifies to return the information on the processing of the pipeline. (This also avoids the use of the 'cursor' aggregate key according to Mongo doc) + String rawQuery = "{\n" + " \"aggregate\": \"" + + collectionName + "\",\n" + " \"pipeline\": " + + "[ {\"$sort\" : {\"_id\": 1} } ],\n" + " \"limit\": 10,\n" + + " \"explain\": \"true\"\n" + + // Specifies to return the information on the processing of the pipeline. (This also avoids the use of + // the 'cursor' aggregate key according to Mongo doc) "}\n"; setDataValueSafelyInFormData(configMap, BODY, rawQuery); - return Collections.singletonList(new DatasourceStructure.Template( - "Aggregate", - null, - configMap - )); + return Collections.singletonList(new DatasourceStructure.Template("Aggregate", null, configMap)); } } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Count.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Count.java index f82ff0e9b612..de88c57f367d 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Count.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Count.java @@ -100,16 +100,11 @@ public List<DatasourceStructure.Template> generateTemplate(Map<String, Object> t setDataValueSafelyInFormData(configMap, COUNT_QUERY, "{\"_id\": {\"$exists\": true}}"); setDataValueSafelyInFormData(configMap, COLLECTION, collectionName); - String rawQuery = "{\n" + - " \"count\": \"" + collectionName + "\",\n" + - " \"query\": " + "{\"_id\": {\"$exists\": true}} \n" + - "}\n"; + String rawQuery = "{\n" + " \"count\": \"" + + collectionName + "\",\n" + " \"query\": " + + "{\"_id\": {\"$exists\": true}} \n" + "}\n"; setDataValueSafelyInFormData(configMap, BODY, rawQuery); - return Collections.singletonList(new DatasourceStructure.Template( - "Count", - null, - configMap - )); + return Collections.singletonList(new DatasourceStructure.Template("Count", null, configMap)); } } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Delete.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Delete.java index 605dcf7444de..1455d85a7743 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Delete.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Delete.java @@ -96,24 +96,19 @@ public List<DatasourceStructure.Template> generateTemplate(Map<String, Object> t setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{ \"_id\": ObjectId(\"id_of_document_to_delete\") }"); setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "SINGLE"); - String rawQuery = "{\n" + - " \"delete\": \"" + collectionName + "\",\n" + - " \"deletes\": [\n" + - " {\n" + - " \"q\": {\n" + - " \"_id\": \"id_of_document_to_delete\"\n" + - " },\n" + - " \"limit\": 1\n" + - " }\n" + - " ]\n" + - "}\n"; + String rawQuery = "{\n" + " \"delete\": \"" + + collectionName + "\",\n" + " \"deletes\": [\n" + + " {\n" + + " \"q\": {\n" + + " \"_id\": \"id_of_document_to_delete\"\n" + + " },\n" + + " \"limit\": 1\n" + + " }\n" + + " ]\n" + + "}\n"; setDataValueSafelyInFormData(configMap, BODY, rawQuery); - return Collections.singletonList(new DatasourceStructure.Template( - "Delete", - null, - configMap - )); + return Collections.singletonList(new DatasourceStructure.Template("Delete", null, configMap)); } /** @@ -145,4 +140,4 @@ public String getRawQuery() { return sb.toString(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Distinct.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Distinct.java index 95d9f44d736f..471b7ce0ffd1 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Distinct.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Distinct.java @@ -118,21 +118,17 @@ public List<DatasourceStructure.Template> generateTemplate(Map<String, Object> t setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "DISTINCT"); - setDataValueSafelyInFormData(configMap, DISTINCT_QUERY, "{ \"_id\": ObjectId(\"id_of_document_to_distinct\") }"); + setDataValueSafelyInFormData( + configMap, DISTINCT_QUERY, "{ \"_id\": ObjectId(\"id_of_document_to_distinct\") }"); setDataValueSafelyInFormData(configMap, DISTINCT_KEY, "_id"); setDataValueSafelyInFormData(configMap, COLLECTION, collectionName); - String rawQuery = "{\n" + - " \"distinct\": \"" + collectionName + "\",\n" + - " \"query\": { \"_id\": ObjectId(\"id_of_document_to_distinct\") }," + - " \"key\": \"_id\"," + - "}\n"; + String rawQuery = "{\n" + " \"distinct\": \"" + + collectionName + "\",\n" + " \"query\": { \"_id\": ObjectId(\"id_of_document_to_distinct\") }," + + " \"key\": \"_id\"," + + "}\n"; setDataValueSafelyInFormData(configMap, BODY, rawQuery); - return Collections.singletonList(new DatasourceStructure.Template( - "Distinct", - null, - configMap - )); + return Collections.singletonList(new DatasourceStructure.Template("Distinct", null, configMap)); } } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Find.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Find.java index 9eb30e5161a4..bc4732a226b4 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Find.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Find.java @@ -116,7 +116,8 @@ public List<DatasourceStructure.Template> generateTemplate(Map<String, Object> t return templates; } - private DatasourceStructure.Template generateFindTemplate(String collectionName, String filterFieldName, String filterFieldValue) { + private DatasourceStructure.Template generateFindTemplate( + String collectionName, String filterFieldName, String filterFieldValue) { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); @@ -125,30 +126,23 @@ private DatasourceStructure.Template generateFindTemplate(String collectionName, setDataValueSafelyInFormData(configMap, FIND_SORT, "{\"_id\": 1}"); setDataValueSafelyInFormData(configMap, FIND_LIMIT, "10"); - String query = filterFieldName == null ? "{}" : - "{ \"" + filterFieldName + "\": \"" + filterFieldValue + "\"}"; + String query = filterFieldName == null ? "{}" : "{ \"" + filterFieldName + "\": \"" + filterFieldValue + "\"}"; setDataValueSafelyInFormData(configMap, FIND_QUERY, query); - String rawQuery = "{\n" + - " \"find\": \"" + collectionName + "\",\n" + - ( - filterFieldName == null ? "" : - " \"filter\": {\n" + - " \"" + filterFieldName + "\": \"" + filterFieldValue + "\"\n" + - " },\n" - ) + - " \"sort\": {\n" + - " \"_id\": 1\n" + - " },\n" + - " \"limit\": 10\n" + - "}\n"; + String rawQuery = "{\n" + " \"find\": \"" + + collectionName + "\",\n" + + (filterFieldName == null + ? "" + : " \"filter\": {\n" + " \"" + filterFieldName + "\": \"" + filterFieldValue + "\"\n" + + " },\n") + + " \"sort\": {\n" + + " \"_id\": 1\n" + + " },\n" + + " \"limit\": 10\n" + + "}\n"; setDataValueSafelyInFormData(configMap, BODY, rawQuery); - return new DatasourceStructure.Template( - "Find", - null, - configMap - ); + return new DatasourceStructure.Template("Find", null, configMap); } private DatasourceStructure.Template generateFindByIdTemplate(String collectionName) { @@ -159,19 +153,14 @@ private DatasourceStructure.Template generateFindByIdTemplate(String collectionN setDataValueSafelyInFormData(configMap, FIND_QUERY, "{\"_id\": ObjectId(\"id_to_query_with\")}"); setDataValueSafelyInFormData(configMap, COLLECTION, collectionName); - String rawQuery = "{\n" + - " \"find\": \"" + collectionName + "\",\n" + - " \"filter\": {\n" + - " \"_id\": ObjectId(\"id_to_query_with\")\n" + - " }\n" + - "}\n"; + String rawQuery = "{\n" + " \"find\": \"" + + collectionName + "\",\n" + " \"filter\": {\n" + + " \"_id\": ObjectId(\"id_to_query_with\")\n" + + " }\n" + + "}\n"; setDataValueSafelyInFormData(configMap, BODY, rawQuery); - return new DatasourceStructure.Template( - "Find by ID", - null, - configMap - ); + return new DatasourceStructure.Template("Find by ID", null, configMap); } /** diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Insert.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Insert.java index 0de511a1678a..09b3b5355915 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Insert.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/Insert.java @@ -79,7 +79,10 @@ public Document parseCommand() { commandDocument.put("documents", arrayListFromInput); } } catch (JsonParseException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, MongoPluginErrorMessages.DOCUMENTS_NOT_PARSABLE_INTO_JSON_ARRAY_ERROR_MSG, e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + MongoPluginErrorMessages.DOCUMENTS_NOT_PARSABLE_INTO_JSON_ARRAY_ERROR_MSG, + e.getMessage()); } } else { // The command expects the documents to be sent in an array. Parse and create a single element array @@ -110,21 +113,16 @@ public List<DatasourceStructure.Template> generateTemplate(Map<String, Object> t setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, "[{" + sampleInsertDocuments + "}]"); setDataValueSafelyInFormData(configMap, COLLECTION, collectionName); - String rawQuery = "{\n" + - " \"insert\": \"" + collectionName + "\",\n" + - " \"documents\": [\n" + - " {\n" + - sampleInsertDocuments + - " }\n" + - " ]\n" + - "}\n"; + String rawQuery = "{\n" + " \"insert\": \"" + + collectionName + "\",\n" + " \"documents\": [\n" + + " {\n" + + sampleInsertDocuments + + " }\n" + + " ]\n" + + "}\n"; setDataValueSafelyInFormData(configMap, BODY, rawQuery); - return Collections.singletonList(new DatasourceStructure.Template( - "Insert", - null, - configMap - )); + return Collections.singletonList(new DatasourceStructure.Template("Insert", null, configMap)); } /** diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/MongoCommand.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/MongoCommand.java index ceb5bd8b6665..4fe80a2fc27b 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/MongoCommand.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/MongoCommand.java @@ -54,14 +54,20 @@ public Boolean isValid() { } public Document parseCommand() { - throw new AppsmithPluginException(MongoPluginError.UNSUPPORTED_OPERATION, MongoPluginErrorMessages.UNSUPPORTED_OPERATION_PARSE_COMMAND_ERROR_MSG); + throw new AppsmithPluginException( + MongoPluginError.UNSUPPORTED_OPERATION, + MongoPluginErrorMessages.UNSUPPORTED_OPERATION_PARSE_COMMAND_ERROR_MSG); } public List<DatasourceStructure.Template> generateTemplate(Map<String, Object> templateConfiguration) { - throw new AppsmithPluginException(MongoPluginError.UNSUPPORTED_OPERATION, MongoPluginErrorMessages.UNSUPPORTED_OPERATION_GENERATE_TEMPLATE_ERROR_MSG); + throw new AppsmithPluginException( + MongoPluginError.UNSUPPORTED_OPERATION, + MongoPluginErrorMessages.UNSUPPORTED_OPERATION_GENERATE_TEMPLATE_ERROR_MSG); } public String getRawQuery() { - throw new AppsmithPluginException(MongoPluginError.UNSUPPORTED_OPERATION, MongoPluginErrorMessages.UNSUPPORTED_OPERATION_GET_RAW_QUERY_ERROR_MSG); + throw new AppsmithPluginException( + MongoPluginError.UNSUPPORTED_OPERATION, + MongoPluginErrorMessages.UNSUPPORTED_OPERATION_GET_RAW_QUERY_ERROR_MSG); } } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/UpdateMany.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/UpdateMany.java index c03ff3131750..4e7e92c798d2 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/UpdateMany.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/commands/UpdateMany.java @@ -111,27 +111,23 @@ public List<DatasourceStructure.Template> generateTemplate(Map<String, Object> t setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); setDataValueSafelyInFormData(configMap, COLLECTION, collectionName); setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{ \"_id\": ObjectId(\"id_of_document_to_update\") }"); - setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "{ \"$set\": { \"" + filterFieldName + "\": \"new value\" } }"); + setDataValueSafelyInFormData( + configMap, UPDATE_OPERATION, "{ \"$set\": { \"" + filterFieldName + "\": \"new value\" } }"); setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "ALL"); - String rawQuery = "{\n" + - " \"update\": \"" + collectionName + "\",\n" + - " \"updates\": [\n" + - " {\n" + - " \"q\": {\n" + - " \"_id\": ObjectId(\"id_of_document_to_update\")\n" + - " },\n" + - " \"u\": { \"$set\": { \"" + filterFieldName + "\": \"new value\" } }\n" + - " }\n" + - " ]\n" + - "}\n"; + String rawQuery = "{\n" + " \"update\": \"" + + collectionName + "\",\n" + " \"updates\": [\n" + + " {\n" + + " \"q\": {\n" + + " \"_id\": ObjectId(\"id_of_document_to_update\")\n" + + " },\n" + + " \"u\": { \"$set\": { \"" + + filterFieldName + "\": \"new value\" } }\n" + " }\n" + + " ]\n" + + "}\n"; setDataValueSafelyInFormData(configMap, BODY, rawQuery); - return Collections.singletonList(new DatasourceStructure.Template( - "Update", - null, - configMap - )); + return Collections.singletonList(new DatasourceStructure.Template("Update", null, configMap)); } /** diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/constants/FieldName.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/constants/FieldName.java index ca7da8056906..e93a52a50626 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/constants/FieldName.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/constants/FieldName.java @@ -45,7 +45,6 @@ public class FieldName { public static final String FIND_SKIP = FIND + "." + SKIP; public static final String UPDATE_LIMIT = UPDATE_MANY + "." + LIMIT; - public static final String RAW = "RAW"; public static final String DATA = "data"; public static final String STATUS = "status"; diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/constants/MongoSpecialDataTypes.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/constants/MongoSpecialDataTypes.java index f4d86c3c6551..1df02f865003 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/constants/MongoSpecialDataTypes.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/constants/MongoSpecialDataTypes.java @@ -22,8 +22,8 @@ public boolean isQuotesRequiredAroundParameter() { return false; } }, - // BinData - not sure about this - ; +// BinData - not sure about this +; /** * Some data types require their argument to be wrapped inside quotes whereas the others don't. This method is diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/datatypes/BsonType.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/datatypes/BsonType.java index d38f2f52cbfb..dab6431f959d 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/datatypes/BsonType.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/datatypes/BsonType.java @@ -5,6 +5,7 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; import org.bson.json.JsonParseException; + import java.util.regex.Matcher; public class BsonType implements AppsmithType { diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/datatypes/MongoSpecificDataTypes.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/datatypes/MongoSpecificDataTypes.java index 36e6092d860d..1967344e96ee 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/datatypes/MongoSpecificDataTypes.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/datatypes/MongoSpecificDataTypes.java @@ -30,12 +30,9 @@ public class MongoSpecificDataTypes { pluginSpecificTypes.put(ClientDataType.ARRAY, List.of(new ArrayType())); - pluginSpecificTypes.put(ClientDataType.NUMBER, List.of( - new IntegerType(), - new LongType(), - new DoubleType(), - new BigDecimalType() - )); + pluginSpecificTypes.put( + ClientDataType.NUMBER, + List.of(new IntegerType(), new LongType(), new DoubleType(), new BigDecimalType())); /* BSON is the superset of JSON with more data types. @@ -43,11 +40,7 @@ public class MongoSpecificDataTypes { */ pluginSpecificTypes.put(ClientDataType.OBJECT, List.of(new JsonObjectType(), new BsonType())); - pluginSpecificTypes.put(ClientDataType.STRING, List.of( - new TimeType(), - new DateType(), - new TimestampType(), - new StringType() - )); + pluginSpecificTypes.put( + ClientDataType.STRING, List.of(new TimeType(), new DateType(), new TimestampType(), new StringType())); } } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/exceptions/MongoPluginError.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/exceptions/MongoPluginError.java index 7baf2930f6b5..fb6790f07cae 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/exceptions/MongoPluginError.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/exceptions/MongoPluginError.java @@ -17,8 +17,7 @@ public enum MongoPluginError implements BasePluginError { "Unsupported operation", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), QUERY_EXECUTION_FAILED( 500, "PE-MNG-5000", @@ -27,8 +26,7 @@ public enum MongoPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), FORM_TO_NATIVE_TRANSLATION_ERROR( 500, "PE-MNG-5001", @@ -37,8 +35,7 @@ public enum MongoPluginError implements BasePluginError { "Query configuration error", ErrorType.INTERNAL_ERROR, "{0}", - "{1}" - ), + "{1}"), ; private final Integer httpErrorCode; @@ -52,8 +49,15 @@ public enum MongoPluginError implements BasePluginError { private final String downstreamErrorCode; - MongoPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + MongoPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -68,7 +72,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/exceptions/MongoPluginErrorMessages.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/exceptions/MongoPluginErrorMessages.java index b44026acfe48..0cdae56be06f 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/exceptions/MongoPluginErrorMessages.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/exceptions/MongoPluginErrorMessages.java @@ -2,76 +2,93 @@ public class MongoPluginErrorMessages { private MongoPluginErrorMessages() { - //Prevents instantiation + // Prevents instantiation } + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Your Mongo query failed to execute."; - public static final String CONNECTION_STRING_PARSING_FAILED_ERROR_MSG = "The Appsmith server has failed to parse the Mongo connection string URI."; + public static final String CONNECTION_STRING_PARSING_FAILED_ERROR_MSG = + "The Appsmith server has failed to parse the Mongo connection string URI."; public static final String NO_CONNECTION_STRING_URI_ERROR_MSG = "Could not find any Mongo connection string URI."; - public static final String UNEXPECTED_SSL_OPTION_ERROR_MSG = "The Appsmith server has found an unexpected SSL option: %s. Please reach out to" + - " Appsmith customer support to resolve this."; + public static final String UNEXPECTED_SSL_OPTION_ERROR_MSG = + "The Appsmith server has found an unexpected SSL option: %s. Please reach out to" + + " Appsmith customer support to resolve this."; - public static final String UNPARSABLE_FIELDNAME_ERROR_MSG = "%s has an invalid JSON format."; + public static final String UNPARSABLE_FIELDNAME_ERROR_MSG = "%s has an invalid JSON format."; public static final String NO_VALID_MONGO_COMMAND_FOUND_ERROR_MSG = "No valid mongo command found."; public static final String FIELD_WITH_NO_CONFIGURATION_ERROR_MSG = "Try again after configuring the fields : %s"; - public static final String PIPELINE_ARRAY_PARSING_FAILED_ERROR_MSG = "Array of pipelines could not be parsed into expected Mongo BSON Array format."; + public static final String PIPELINE_ARRAY_PARSING_FAILED_ERROR_MSG = + "Array of pipelines could not be parsed into expected Mongo BSON Array format."; public static final String PIPELINE_STAGE_NOT_VALID_ERROR_MSG = "Pipeline stage is not a valid JSON object."; - public static final String DOCUMENTS_NOT_PARSABLE_INTO_JSON_ARRAY_ERROR_MSG = "Documents could not be parsed into expected JSON Array format."; + public static final String DOCUMENTS_NOT_PARSABLE_INTO_JSON_ARRAY_ERROR_MSG = + "Documents could not be parsed into expected JSON Array format."; - public static final String UNSUPPORTED_OPERATION_PARSE_COMMAND_ERROR_MSG = "Unsupported Operation : All mongo commands must implement parseCommand."; + public static final String UNSUPPORTED_OPERATION_PARSE_COMMAND_ERROR_MSG = + "Unsupported Operation : All mongo commands must implement parseCommand."; - public static final String UNSUPPORTED_OPERATION_GENERATE_TEMPLATE_ERROR_MSG = "Unsupported Operation : All mongo commands must implement generateTemplate."; + public static final String UNSUPPORTED_OPERATION_GENERATE_TEMPLATE_ERROR_MSG = + "Unsupported Operation : All mongo commands must implement generateTemplate."; - public static final String UNSUPPORTED_OPERATION_GET_RAW_QUERY_ERROR_MSG = "Unsupported Operation : All mongo commands must implement getRawQuery."; + public static final String UNSUPPORTED_OPERATION_GET_RAW_QUERY_ERROR_MSG = + "Unsupported Operation : All mongo commands must implement getRawQuery."; public static final String QUERY_INVALID_ERROR_MSG = "Your query is invalid"; public static final String MONGO_CLIENT_NULL_ERROR_MSG = "Mongo client object is null."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ - public static final String DS_CREATION_FAILED_ERROR_MSG = "One or more arguments in the datasource configuration is invalid."; + public static final String DS_CREATION_FAILED_ERROR_MSG = + "One or more arguments in the datasource configuration is invalid."; - public static final String DS_TIMEOUT_ERROR_MSG = "Connection timed out. Please check if the datasource configuration fields have " + - "been filled correctly."; + public static final String DS_TIMEOUT_ERROR_MSG = + "Connection timed out. Please check if the datasource configuration fields have " + + "been filled correctly."; - public static final String DS_GET_STRUCTURE_ERROR_MSG = "Appsmith has failed to get database structure. Please provide read permission on" + - " the database to fix this."; + public static final String DS_GET_STRUCTURE_ERROR_MSG = + "Appsmith has failed to get database structure. Please provide read permission on" + + " the database to fix this."; - public static final String DS_DEFAULT_DATABASE_NAME_INVALID_ERROR_MSG = "Default database name is invalid, no database found with this name."; + public static final String DS_DEFAULT_DATABASE_NAME_INVALID_ERROR_MSG = + "Default database name is invalid, no database found with this name."; - public static final String DS_EMPTY_CONNECTION_URI_ERROR_MSG = "'Mongo Connection string URI' field is empty. Please edit the 'Mongo Connection " + - "URI' field to provide a connection uri to connect with."; + public static final String DS_EMPTY_CONNECTION_URI_ERROR_MSG = + "'Mongo Connection string URI' field is empty. Please edit the 'Mongo Connection " + + "URI' field to provide a connection uri to connect with."; - public static final String DS_INVALID_CONNECTION_STRING_URI_ERROR_MSG = "Mongo Connection string URI does not seem to be in the correct format. Please " + - "check the URI once."; + public static final String DS_INVALID_CONNECTION_STRING_URI_ERROR_MSG = + "Mongo Connection string URI does not seem to be in the correct format. Please " + "check the URI once."; public static final String DS_MISSING_DEFAULT_DATABASE_NAME_ERROR_MSG = "Missing default database name."; - public static final String DS_INVALID_AUTH_DATABASE_NAME = "Authentication database name is invalid, no database found with this name."; + public static final String DS_INVALID_AUTH_DATABASE_NAME = + "Authentication database name is invalid, no database found with this name."; public static final String DS_MISSING_ENDPOINTS_ERROR_MSG = "Missing endpoint(s)."; - public static final String DS_NO_PORT_EXPECTED_IN_REPLICA_SET_CONNECTION_ERROR_MSG = "REPLICA_SET connections should not be given a port." + - " If you are trying to specify all the shards, please add more than one."; - - public static final String DS_USING_URI_BUT_EXPECTED_FORM_FIELDS_ERROR_MSG = "It seems that you are trying to use a mongo connection string URI. Please " + - "extract relevant fields and fill the form with extracted values. For " + - "details, please check out the Appsmith's documentation for Mongo database. " + - "Alternatively, you may use 'Import from connection string URI' option from the " + - "dropdown labelled 'Use mongo connection string URI' to use the URI connection string" + - " directly."; + public static final String DS_NO_PORT_EXPECTED_IN_REPLICA_SET_CONNECTION_ERROR_MSG = + "REPLICA_SET connections should not be given a port." + + " If you are trying to specify all the shards, please add more than one."; + + public static final String DS_USING_URI_BUT_EXPECTED_FORM_FIELDS_ERROR_MSG = + "It seems that you are trying to use a mongo connection string URI. Please " + + "extract relevant fields and fill the form with extracted values. For " + + "details, please check out the Appsmith's documentation for Mongo database. " + + "Alternatively, you may use 'Import from connection string URI' option from the " + + "dropdown labelled 'Use mongo connection string URI' to use the URI connection string" + + " directly."; public static final String DS_INVALID_AUTH_TYPE_ERROR_MSG = "Invalid authType. Must be one of %s"; - public static final String DS_SSL_CONFIGURATION_FETCHING_ERROR_MSG = "Appsmith server has failed to fetch SSL configuration from datasource configuration " + - "form. Please reach out to Appsmith customer support to resolve this."; + public static final String DS_SSL_CONFIGURATION_FETCHING_ERROR_MSG = + "Appsmith server has failed to fetch SSL configuration from datasource configuration " + + "form. Please reach out to Appsmith customer support to resolve this."; } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/DatasourceUtils.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/DatasourceUtils.java index 23c6f3ee8a77..9f7644f8b98c 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/DatasourceUtils.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/DatasourceUtils.java @@ -31,8 +31,8 @@ public class DatasourceUtils { * - mongodb://user:pass@some-url:port,some-url:port,.../some-db... * - It has been grouped like this: (mongodb+srv://)(user):(pass)@(some-url)/(some-db...)?(params...) */ - public static final String MONGO_URI_REGEX = "^(mongodb(?:\\+srv)?://)(?:((.+):(.+))?@)?([^/?]+)/?([^?]+)?\\??(" + - ".+)?$"; + public static final String MONGO_URI_REGEX = + "^(mongodb(?:\\+srv)?://)(?:((.+):(.+))?@)?([^/?]+)/?([^?]+)?\\??(" + ".+)?$"; private static final int REGEX_GROUP_HEAD = 1; @@ -66,9 +66,12 @@ public class DatasourceUtils { public static boolean isUsingURI(DatasourceConfiguration datasourceConfiguration) { List<Property> properties = datasourceConfiguration.getProperties(); - if (properties != null && properties.size() > DATASOURCE_CONFIG_USE_MONGO_URI_PROPERTY_INDEX + if (properties != null + && properties.size() > DATASOURCE_CONFIG_USE_MONGO_URI_PROPERTY_INDEX && properties.get(DATASOURCE_CONFIG_USE_MONGO_URI_PROPERTY_INDEX) != null - && YES.equals(properties.get(DATASOURCE_CONFIG_USE_MONGO_URI_PROPERTY_INDEX).getValue())) { + && YES.equals(properties + .get(DATASOURCE_CONFIG_USE_MONGO_URI_PROPERTY_INDEX) + .getValue())) { return true; } @@ -77,9 +80,12 @@ public static boolean isUsingURI(DatasourceConfiguration datasourceConfiguration public static boolean hasNonEmptyURI(DatasourceConfiguration datasourceConfiguration) { List<Property> properties = datasourceConfiguration.getProperties(); - if (properties != null && properties.size() > DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX + if (properties != null + && properties.size() > DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX && properties.get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX) != null - && !StringUtils.isEmpty(properties.get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX).getValue())) { + && !StringUtils.isEmpty(properties + .get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX) + .getValue())) { return true; } @@ -115,26 +121,23 @@ public static String buildURIFromExtractedInfo(Map extractedInfo, String passwor userInfo += "@"; } - final String dbInfo = "/" + (extractedInfo.get(KEY_URI_DEFAULT_DBNAME) == null ? "" : extractedInfo.get(KEY_URI_DEFAULT_DBNAME)); + final String dbInfo = "/" + + (extractedInfo.get(KEY_URI_DEFAULT_DBNAME) == null ? "" : extractedInfo.get(KEY_URI_DEFAULT_DBNAME)); String tailInfo = (String) (extractedInfo.get(KEY_URI_TAIL) == null ? "" : extractedInfo.get(KEY_URI_TAIL)); tailInfo = "?" + buildURITail(tailInfo); - return extractedInfo.get(KEY_URI_HEAD) - + userInfo - + extractedInfo.get(KEY_HOST_PORT) - + dbInfo - + tailInfo; + return extractedInfo.get(KEY_URI_HEAD) + userInfo + extractedInfo.get(KEY_HOST_PORT) + dbInfo + tailInfo; } private static String buildURITail(String tailInfo) { Map<String, String> optionsMap = new HashMap<>(); for (final String part : tailInfo.split("[&;]")) { - if (part.length() == 0) { + if (part.isEmpty()) { continue; } - int idx = part.indexOf("="); + int idx = part.indexOf('='); if (idx >= 0) { String key = part.substring(0, idx).toLowerCase(); String value = part.substring(idx + 1); @@ -145,9 +148,7 @@ private static String buildURITail(String tailInfo) { } optionsMap.putIfAbsent("authsource", "admin"); optionsMap.put("minpoolsize", "0"); - return optionsMap - .entrySet() - .stream() + return optionsMap.entrySet().stream() .map(entry -> { if (StringUtils.hasLength(entry.getValue())) { return entry.getKey() + "=" + entry.getValue(); @@ -158,12 +159,14 @@ private static String buildURITail(String tailInfo) { .collect(Collectors.joining("&")); } - public static String buildClientURI(DatasourceConfiguration datasourceConfiguration) throws AppsmithPluginException { + public static String buildClientURI(DatasourceConfiguration datasourceConfiguration) + throws AppsmithPluginException { List<Property> properties = datasourceConfiguration.getProperties(); if (isUsingURI(datasourceConfiguration)) { if (hasNonEmptyURI(datasourceConfiguration)) { - String uriWithHiddenPassword = - (String) properties.get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX).getValue(); + String uriWithHiddenPassword = (String) properties + .get(DATASOURCE_CONFIG_MONGO_URI_PROPERTY_INDEX) + .getValue(); Map extractedInfo = extractInfoFromConnectionStringURI(uriWithHiddenPassword, MONGO_URI_REGEX); if (extractedInfo != null) { String password = ((DBAuth) datasourceConfiguration.getAuthentication()).getPassword(); @@ -171,14 +174,12 @@ public static String buildClientURI(DatasourceConfiguration datasourceConfigurat } else { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - MongoPluginErrorMessages.CONNECTION_STRING_PARSING_FAILED_ERROR_MSG - ); + MongoPluginErrorMessages.CONNECTION_STRING_PARSING_FAILED_ERROR_MSG); } } else { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - MongoPluginErrorMessages.NO_CONNECTION_STRING_URI_ERROR_MSG - ); + MongoPluginErrorMessages.NO_CONNECTION_STRING_URI_ERROR_MSG); } } @@ -240,14 +241,14 @@ public static String buildClientURI(DatasourceConfiguration datasourceConfigurat || datasourceConfiguration.getConnection().getSsl().getAuthType() == null) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - MongoPluginErrorMessages.DS_SSL_CONFIGURATION_FETCHING_ERROR_MSG - ); + MongoPluginErrorMessages.DS_SSL_CONFIGURATION_FETCHING_ERROR_MSG); } /* * - By default, the driver configures SSL in the preferred mode. */ - SSLDetails.AuthType sslAuthType = datasourceConfiguration.getConnection().getSsl().getAuthType(); + SSLDetails.AuthType sslAuthType = + datasourceConfiguration.getConnection().getSsl().getAuthType(); switch (sslAuthType) { case ENABLED: queryParams.add("ssl=true"); @@ -264,12 +265,12 @@ public static String buildClientURI(DatasourceConfiguration datasourceConfigurat default: throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - MongoPluginErrorMessages.UNEXPECTED_SSL_OPTION_ERROR_MSG - ); + MongoPluginErrorMessages.UNEXPECTED_SSL_OPTION_ERROR_MSG); } if (hasUsername && authentication.getAuthType() != null) { - queryParams.add("authMechanism=" + authentication.getAuthType().name().replace('_', '-')); + queryParams.add( + "authMechanism=" + authentication.getAuthType().name().replace('_', '-')); } if (!queryParams.isEmpty()) { @@ -301,8 +302,10 @@ public static boolean isHostStringConnectionURI(Endpoint endpoint) { } public static boolean isAuthenticated(DBAuth authentication, String mongoUri) { - if (authentication != null && authentication.getUsername() != null - && authentication.getPassword() != null && mongoUri.contains("****")) { + if (authentication != null + && authentication.getUsername() != null + && authentication.getPassword() != null + && mongoUri.contains("****")) { return true; } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoErrorUtils.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoErrorUtils.java index 9f5608abbc5b..7457c9f82166 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoErrorUtils.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoErrorUtils.java @@ -35,8 +35,7 @@ public String getReadableError(Throwable error) { } externalError = ((AppsmithPluginException) error).getExternalError(); - } - else { + } else { externalError = error; } @@ -44,7 +43,8 @@ public String getReadableError(Throwable error) { MongoCommandException mongoCommandError = (MongoCommandException) externalError; int errorCode = mongoCommandError.getCode(); - // Error codes ref: https://github.com/mongodb/mongo/blob/50dc6dbe394c42d03659aa3410954f1e3ff46740/src/mongo/base/error_codes.err#L12 + // Error codes ref: + // https://github.com/mongodb/mongo/blob/50dc6dbe394c42d03659aa3410954f1e3ff46740/src/mongo/base/error_codes.err#L12 switch (errorCode) { case 9: // FailedToParse error @@ -55,7 +55,8 @@ public String getReadableError(Throwable error) { * * Return string: 'limit' field must be numeric. */ - return getLast(mongoCommandError.getErrorMessage().split("\\.")).trim() + "."; + return getLast(mongoCommandError.getErrorMessage().split("\\.")) + .trim() + "."; default: /** @@ -68,8 +69,7 @@ public String getReadableError(Throwable error) { */ return mongoCommandError.getErrorMessage().split("\\.")[0].trim() + "."; } - } - else if (externalError instanceof MongoSecurityException) { + } else if (externalError instanceof MongoSecurityException) { MongoSecurityException mongoSecurityError = (MongoSecurityException) externalError; int errorCode = mongoSecurityError.getCode(); switch (errorCode) { diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoPluginUtils.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoPluginUtils.java index ea8efab90115..09db94b71a9c 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoPluginUtils.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoPluginUtils.java @@ -15,7 +15,6 @@ import com.external.plugins.commands.Insert; import com.external.plugins.commands.MongoCommand; import com.external.plugins.commands.UpdateMany; - import com.external.plugins.exceptions.MongoPluginErrorMessages; import org.bson.BsonInvalidOperationException; import org.bson.Document; @@ -24,7 +23,6 @@ import org.bson.types.ObjectId; import org.json.JSONArray; import org.json.JSONException; -import org.json.JSONObject; import org.springframework.util.StringUtils; import java.net.URLEncoder; @@ -50,26 +48,32 @@ public static Document parseSafely(String fieldName, String input) { try { return Document.parse(input); } catch (JsonParseException | BsonInvalidOperationException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(MongoPluginErrorMessages.UNPARSABLE_FIELDNAME_ERROR_MSG, fieldName), e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format(MongoPluginErrorMessages.UNPARSABLE_FIELDNAME_ERROR_MSG, fieldName), + e.getMessage()); } } - public static Object parseSafelyDocumentAndArrayOfDocuments(String fieldName, String input){ + public static Object parseSafelyDocumentAndArrayOfDocuments(String fieldName, String input) { try { return parseSafely(fieldName, input); } catch (AppsmithPluginException e) { try { List<Document> parsedDocumentList = new ArrayList<>(); - JSONArray rawInputJsonArray = new JSONArray(input); - for (int i=0; i < rawInputJsonArray.length(); i++) { - parsedDocumentList.add(parseSafely(fieldName, rawInputJsonArray.getJSONObject(i).toString())); + JSONArray rawInputJsonArray = new JSONArray(input); + for (int i = 0; i < rawInputJsonArray.length(); i++) { + parsedDocumentList.add(parseSafely( + fieldName, rawInputJsonArray.getJSONObject(i).toString())); } return parsedDocumentList; } catch (JSONException ne) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(MongoPluginErrorMessages.UNPARSABLE_FIELDNAME_ERROR_MSG, fieldName), e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format(MongoPluginErrorMessages.UNPARSABLE_FIELDNAME_ERROR_MSG, fieldName), + e.getMessage()); } } - } public static Boolean isRawCommand(Map<String, Object> formData) { @@ -85,7 +89,11 @@ public static String convertMongoFormInputToRawCommand(ActionConfiguration actio // Parse the commands into raw appropriately MongoCommand command = getMongoCommand(actionConfiguration); if (!command.isValid()) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(MongoPluginErrorMessages.FIELD_WITH_NO_CONFIGURATION_ERROR_MSG, command.getFieldNamesWithNoConfiguration())); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format( + MongoPluginErrorMessages.FIELD_WITH_NO_CONFIGURATION_ERROR_MSG, + command.getFieldNamesWithNoConfiguration())); } return command.parseCommand().toJson(); @@ -97,7 +105,8 @@ public static String convertMongoFormInputToRawCommand(ActionConfiguration actio return PluginUtils.getDataValueSafelyFromFormData(formData, BODY, PluginUtils.STRING_TYPE); } - private static MongoCommand getMongoCommand(ActionConfiguration actionConfiguration) throws AppsmithPluginException { + private static MongoCommand getMongoCommand(ActionConfiguration actionConfiguration) + throws AppsmithPluginException { Map<String, Object> formData = actionConfiguration.getFormData(); MongoCommand command; switch (getDataValueSafelyFromFormData(formData, COMMAND, STRING_TYPE, "")) { @@ -123,8 +132,9 @@ private static MongoCommand getMongoCommand(ActionConfiguration actionConfigurat command = new Aggregate(actionConfiguration); break; default: - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, MongoPluginErrorMessages.NO_VALID_MONGO_COMMAND_FOUND_ERROR_MSG - ); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + MongoPluginErrorMessages.NO_VALID_MONGO_COMMAND_FOUND_ERROR_MSG); } return command; @@ -145,16 +155,19 @@ public static String getDatabaseName(DatasourceConfiguration datasourceConfigura } if (databaseName == null) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, MongoPluginErrorMessages.DS_MISSING_DEFAULT_DATABASE_NAME_ERROR_MSG); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + MongoPluginErrorMessages.DS_MISSING_DEFAULT_DATABASE_NAME_ERROR_MSG); } return databaseName; } - public static void generateTemplatesAndStructureForACollection(String collectionName, - Document document, - ArrayList<DatasourceStructure.Column> columns, - ArrayList<DatasourceStructure.Template> templates) { + public static void generateTemplatesAndStructureForACollection( + String collectionName, + Document document, + ArrayList<DatasourceStructure.Column> columns, + ArrayList<DatasourceStructure.Template> templates) { String filterFieldName = null; String filterFieldValue = null; Map<String, String> sampleInsertValues = new LinkedHashMap<>(); @@ -212,35 +225,19 @@ public static void generateTemplatesAndStructureForACollection(String collection templateConfiguration.put("filterFieldValue", filterFieldValue); templateConfiguration.put("sampleInsertValues", sampleInsertValues); - templates.addAll( - new Find().generateTemplate(templateConfiguration) - ); - + templates.addAll(new Find().generateTemplate(templateConfiguration)); - templates.addAll( - new Insert().generateTemplate(templateConfiguration) - ); + templates.addAll(new Insert().generateTemplate(templateConfiguration)); - templates.addAll( - new UpdateMany().generateTemplate(templateConfiguration) - ); + templates.addAll(new UpdateMany().generateTemplate(templateConfiguration)); - templates.addAll( - new Delete().generateTemplate(templateConfiguration) - ); + templates.addAll(new Delete().generateTemplate(templateConfiguration)); - templates.addAll( - new Count().generateTemplate(templateConfiguration) - ); + templates.addAll(new Count().generateTemplate(templateConfiguration)); - templates.addAll( - new Distinct().generateTemplate(templateConfiguration) - ); - - templates.addAll( - new Aggregate().generateTemplate(templateConfiguration) - ); + templates.addAll(new Distinct().generateTemplate(templateConfiguration)); + templates.addAll(new Aggregate().generateTemplate(templateConfiguration)); } public static String urlEncode(String text) { @@ -251,5 +248,4 @@ public static String getRawQuery(ActionConfiguration actionConfiguration) { MongoCommand command = getMongoCommand(actionConfiguration); return command.getRawQuery(); } - } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginDataTypeTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginDataTypeTest.java index 2ae8b4b6cdb4..29d8dfaf9b6a 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginDataTypeTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginDataTypeTest.java @@ -36,12 +36,9 @@ public class MongoPluginDataTypeTest { pluginSpecificTypes.put(ClientDataType.ARRAY, List.of(new ArrayType())); - pluginSpecificTypes.put(ClientDataType.NUMBER, List.of( - new IntegerType(), - new LongType(), - new DoubleType(), - new BigDecimalType() - )); + pluginSpecificTypes.put( + ClientDataType.NUMBER, + List.of(new IntegerType(), new LongType(), new DoubleType(), new BigDecimalType())); /* BSON is the superset of JSON with more data types. @@ -49,29 +46,55 @@ public class MongoPluginDataTypeTest { */ pluginSpecificTypes.put(ClientDataType.OBJECT, List.of(new JsonObjectType(), new BsonType())); - pluginSpecificTypes.put(ClientDataType.STRING, List.of( - new TimeType(), - new DateType(), - new TimestampType(), - new StringType() - )); + pluginSpecificTypes.put( + ClientDataType.STRING, List.of(new TimeType(), new DateType(), new TimestampType(), new StringType())); } + @Test public void testBsonTypes() { - // Streams that include multiple top-level values. With strict parsing, each stream must contain exactly one top-level value. - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT,"{}{}", pluginSpecificTypes).type()); - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT,"{}[]null", pluginSpecificTypes).type()); + // Streams that include multiple top-level values. With strict parsing, each stream must contain exactly one + // top-level value. + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{}{}", pluginSpecificTypes) + .type()); + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{}[]null", pluginSpecificTypes) + .type()); // Numbers may be NaNs or infinities. - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT,"{\"number\": NaN}", pluginSpecificTypes).type()); - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT,"{\"number\": Infinity}", pluginSpecificTypes).type()); + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"number\": NaN}", pluginSpecificTypes) + .type()); + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType( + ClientDataType.OBJECT, "{\"number\": Infinity}", pluginSpecificTypes) + .type()); // Names that are unquoted or 'single quoted'. - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT,"{a: 1}", pluginSpecificTypes).type()); - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT,"{'a': 1}", pluginSpecificTypes).type()); + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{a: 1}", pluginSpecificTypes) + .type()); + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{'a': 1}", pluginSpecificTypes) + .type()); // Strings that are unquoted or 'single quoted'. - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT,"{\"a\": ''}", pluginSpecificTypes).type()); + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": ''}", pluginSpecificTypes) + .type()); // Unnecessary array separators. These are interpreted as if null was the omitted value. - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": [1,]}", pluginSpecificTypes).type()); + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": [1,]}", pluginSpecificTypes) + .type()); - assertEquals(DataType.BSON, DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT,"{\"a\": 0,}", pluginSpecificTypes).type()); + assertEquals( + DataType.BSON, + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, "{\"a\": 0,}", pluginSpecificTypes) + .type()); } } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginDatasourceTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginDatasourceTest.java index 8b717f922a7e..cc804950f612 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginDatasourceTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginDatasourceTest.java @@ -57,7 +57,6 @@ /** * Unit tests for MongoPlugin */ - @Testcontainers public class MongoPluginDatasourceTest { MongoPlugin.MongoPluginExecutor pluginExecutor = new MongoPlugin.MongoPluginExecutor(); @@ -155,9 +154,9 @@ public void testDatasourceFailWithEmptyDefaultDatabaseNameAndInvalidAuthDBName() StepVerifier.create(pluginExecutor.testDatasource(dsConfig)) .assertNext(datasourceTestResult -> { assertNotNull(datasourceTestResult); - assertTrue(datasourceTestResult.getInvalids().stream().anyMatch(error -> - error.contains("Authentication database name is invalid, " + - "no database found with this name."))); + assertTrue(datasourceTestResult.getInvalids().stream() + .anyMatch(error -> error.contains("Authentication database name is invalid, " + + "no database found with this name."))); assertFalse(datasourceTestResult.isSuccess()); }) .verifyComplete(); @@ -190,8 +189,9 @@ public void testDatasourceWithUnauthorizedException() { MongoCommandException mockMongoCommandException = mock(MongoCommandException.class); when(mockMongoCommandException.getErrorCodeName()).thenReturn("Unauthorized"); when(mockMongoCommandException.getMessage()).thenReturn("Mock Unauthorized Exception"); - when(mockMongoCommandException.getErrorMessage()).thenReturn("Mock error : Expected 'something' , but got something else.\n" + - "Doc = [{find mockAction} {filter mockFilter} {limit 10} {$db mockDB} ...]"); + when(mockMongoCommandException.getErrorMessage()) + .thenReturn("Mock error : Expected 'something' , but got something else.\n" + + "Doc = [{find mockAction} {filter mockFilter} {limit 10} {$db mockDB} ...]"); /* * 1. Spy MongoPluginExecutor class. @@ -203,14 +203,15 @@ public void testDatasourceWithUnauthorizedException() { /* Please check this out before modifying this line: https://stackoverflow * .com/questions/11620103/mockito-trying-to-spy-on-method-is-calling-the-original-method */ - doReturn(Mono.error(mockMongoCommandException)).when(spyMongoPluginExecutor).datasourceCreate(any()); + doReturn(Mono.error(mockMongoCommandException)) + .when(spyMongoPluginExecutor) + .datasourceCreate(any()); /* * 1. Test that MongoCommandException with error code "Unauthorized" is not successful because of invalid credentials. */ DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - StepVerifier - .create(spyMongoPluginExecutor.testDatasource(dsConfig)) + StepVerifier.create(spyMongoPluginExecutor.testDatasource(dsConfig)) .assertNext(datasourceTestResult -> { assertFalse(datasourceTestResult.isSuccess()); }) @@ -233,12 +234,8 @@ public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { assertTrue(datasourceTestResult.getInvalids().isEmpty()); }) .verifyComplete(); - } - - - @Test public void testTestDatasourceTimeoutError() { String badHost = "mongo-bad-url.mongodb.net"; @@ -251,13 +248,10 @@ public void testTestDatasourceTimeoutError() { .assertNext(result -> { assertFalse(result.isSuccess()); assertTrue(result.getInvalids().size() == 1); - assertTrue(result - .getInvalids() - .stream() + assertTrue(result.getInvalids().stream() .anyMatch(error -> error.contains( - "Connection timed out. Please check if the datasource configuration fields have " + - "been filled correctly." - ))); + "Connection timed out. Please check if the datasource configuration fields have " + + "been filled correctly."))); }) .verifyComplete(); } @@ -267,26 +261,18 @@ public void testSslToggleMissingError() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); datasourceConfiguration.getConnection().getSsl().setAuthType(null); - Mono<Set<String>> invalidsMono = Mono.just(pluginExecutor) - .map(executor -> executor.validateDatasource(datasourceConfiguration)); - + Mono<Set<String>> invalidsMono = + Mono.just(pluginExecutor).map(executor -> executor.validateDatasource(datasourceConfiguration)); StepVerifier.create(invalidsMono) .assertNext(invalids -> { - String expectedError = "Appsmith server has failed to fetch SSL configuration from datasource " + - "configuration form. Please reach out to Appsmith customer support to resolve this."; - assertTrue(invalids - .stream() - .anyMatch(error -> expectedError.equals(error)) - ); + String expectedError = "Appsmith server has failed to fetch SSL configuration from datasource " + + "configuration form. Please reach out to Appsmith customer support to resolve this."; + assertTrue(invalids.stream().anyMatch(error -> expectedError.equals(error))); }) .verifyComplete(); } - - - - @Test public void testSslDefault() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); @@ -297,19 +283,19 @@ public void testSslDefault() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " filter: { age: { $gte: 30 } },\n" + - " sort: { id: 1 },\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " find: \"users\",\n" + + " filter: { age: { $gte: 30 } },\n" + + " sort: { id: 1 },\n" + + " limit: 10,\n" + + " }"); actionConfiguration.setFormData(configMap); Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), - datasourceConfiguration, - actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), datasourceConfiguration, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -319,9 +305,9 @@ public void testSslDefault() { assertNotNull(result.getBody()); assertEquals(2, ((ArrayNode) result.getBody()).size()); assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), - result.getDataTypes().toString() - ); + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); }) .verifyComplete(); } @@ -336,19 +322,19 @@ public void testSslDisabled() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " filter: { age: { $gte: 30 } },\n" + - " sort: { id: 1 },\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " find: \"users\",\n" + + " filter: { age: { $gte: 30 } },\n" + + " sort: { id: 1 },\n" + + " limit: 10,\n" + + " }"); actionConfiguration.setFormData(configMap); Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), - datasourceConfiguration, - actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), datasourceConfiguration, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -358,9 +344,9 @@ public void testSslDisabled() { assertNotNull(result.getBody()); assertEquals(2, ((ArrayNode) result.getBody()).size()); assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), - result.getDataTypes().toString() - ); + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); }) .verifyComplete(); } @@ -375,19 +361,19 @@ public void testSslEnabled() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " filter: { age: { $gte: 30 } },\n" + - " sort: { id: 1 },\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " find: \"users\",\n" + + " filter: { age: { $gte: 30 } },\n" + + " sort: { id: 1 },\n" + + " limit: 10,\n" + + " }"); actionConfiguration.setFormData(configMap); Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), - datasourceConfiguration, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), datasourceConfiguration, actionConfiguration)); /* * - This test case is exactly same as the one's used in DEFAULT and DISABLED tests. @@ -401,7 +387,6 @@ public void testSslEnabled() { .verifyComplete(); } - @Test public void testValidateDatasource_withoutDefaultDBInURIString_returnsInvalid() { final DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); @@ -418,8 +403,8 @@ public void testValidateDatasource_withoutDefaultDBInURIString_returnsInvalid() @Test public void testURIRegexPassWithValidURIWithUsernamePassword() { - String uri = "mongodb://user:pass@localhost:28017/mongo_samples?w=majority&retrywrites=true&authsource=admin" + - "&minpoolsize=0"; + String uri = "mongodb://user:pass@localhost:28017/mongo_samples?w=majority&retrywrites=true&authsource=admin" + + "&minpoolsize=0"; Map extractedInfo = extractInfoFromConnectionStringURI(uri, MONGO_URI_REGEX); assertEquals("mongodb://", extractedInfo.get(KEY_URI_HEAD)); assertEquals("user", extractedInfo.get(KEY_USERNAME)); @@ -431,8 +416,8 @@ public void testURIRegexPassWithValidURIWithUsernamePassword() { @Test public void testURIRegexPassWithValidURIWithoutUsernamePassword() { - String uri = "mongodb://@localhost:28017/mongo_samples?w=majority&retrywrites=true&authsource=admin" + - "&minpoolsize=0"; + String uri = "mongodb://@localhost:28017/mongo_samples?w=majority&retrywrites=true&authsource=admin" + + "&minpoolsize=0"; Map extractedInfo = extractInfoFromConnectionStringURI(uri, MONGO_URI_REGEX); assertEquals("mongodb://", extractedInfo.get(KEY_URI_HEAD)); assertEquals(null, extractedInfo.get(KEY_USERNAME)); @@ -444,8 +429,8 @@ public void testURIRegexPassWithValidURIWithoutUsernamePassword() { @Test public void testURIRegexPassWithValidURIWithoutAtUsernamePassword() { - String uri = "mongodb://localhost:28017/mongo_samples?w=majority&retrywrites=true&authsource=admin" + - "&minpoolsize=0"; + String uri = "mongodb://localhost:28017/mongo_samples?w=majority&retrywrites=true&authsource=admin" + + "&minpoolsize=0"; Map extractedInfo = extractInfoFromConnectionStringURI(uri, MONGO_URI_REGEX); assertEquals("mongodb://", extractedInfo.get(KEY_URI_HEAD)); assertEquals(null, extractedInfo.get(KEY_USERNAME)); @@ -454,4 +439,4 @@ public void testURIRegexPassWithValidURIWithoutAtUsernamePassword() { assertEquals("mongo_samples", extractedInfo.get(KEY_URI_DEFAULT_DBNAME)); assertEquals("w=majority&retrywrites=true&authsource=admin&minpoolsize=0", extractedInfo.get(KEY_URI_TAIL)); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginErrorsTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginErrorsTest.java index 3d903b8d6321..3b399f06e4cb 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginErrorsTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginErrorsTest.java @@ -1,5 +1,37 @@ package com.external.plugins; +import com.appsmith.external.dtos.ExecuteActionDTO; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; +import com.appsmith.external.models.ActionConfiguration; +import com.appsmith.external.models.ActionExecutionResult; +import com.appsmith.external.models.Connection; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.Endpoint; +import com.appsmith.external.models.ParsedDataType; +import com.appsmith.external.models.Property; +import com.appsmith.external.models.SSLDetails; +import com.external.plugins.exceptions.MongoPluginError; +import com.external.plugins.exceptions.MongoPluginErrorMessages; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.mongodb.MongoCommandException; +import com.mongodb.MongoSecurityException; +import com.mongodb.reactivestreams.client.MongoClient; +import com.mongodb.reactivestreams.client.MongoClients; +import com.mongodb.reactivestreams.client.MongoDatabase; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.*; +import java.util.stream.Collectors; + import static com.appsmith.external.constants.DisplayDataType.JSON; import static com.appsmith.external.constants.DisplayDataType.RAW; import static com.appsmith.external.helpers.PluginUtils.setDataValueSafelyInFormData; @@ -24,44 +56,9 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -import java.util.*; -import java.util.stream.Collectors; - -import com.external.plugins.exceptions.MongoPluginError; -import com.external.plugins.exceptions.MongoPluginErrorMessages; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -import com.appsmith.external.dtos.ExecuteActionDTO; -import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; -import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; -import com.appsmith.external.models.ActionConfiguration; -import com.appsmith.external.models.ActionExecutionResult; -import com.appsmith.external.models.Connection; -import com.appsmith.external.models.DatasourceConfiguration; -import com.appsmith.external.models.DatasourceStructure; -import com.appsmith.external.models.Endpoint; -import com.appsmith.external.models.ParsedDataType; -import com.appsmith.external.models.Property; -import com.appsmith.external.models.SSLDetails; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.mongodb.MongoCommandException; -import com.mongodb.MongoSecurityException; -import com.mongodb.reactivestreams.client.MongoClient; -import com.mongodb.reactivestreams.client.MongoClients; -import com.mongodb.reactivestreams.client.MongoDatabase; - -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - /** * Unit tests for MongoPlugin */ - @Testcontainers public class MongoPluginErrorsTest { MongoPlugin.MongoPluginExecutor pluginExecutor = new MongoPlugin.MongoPluginExecutor(); @@ -81,7 +78,6 @@ public static void setUp() { port = mongoContainer.getFirstMappedPort(); String uri = "mongodb://" + address + ":" + port; mongoClient = MongoClients.create(uri); - } private DatasourceConfiguration createDatasourceConfiguration() { @@ -103,9 +99,6 @@ private DatasourceConfiguration createDatasourceConfiguration() { return dsConfig; } - - - @Test public void testErrorMessageOnSrvUriWithFormInterface() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); @@ -115,14 +108,13 @@ public void testErrorMessageOnSrvUriWithFormInterface() { StepVerifier.create(invalidsMono) .assertNext(invalids -> { - assertTrue(invalids - .stream() - .anyMatch(error -> error.contains("It seems that you are trying to use a mongo connection" + - " string URI. Please extract relevant fields and fill the form with extracted " + - "values. For details, please check out the Appsmith's documentation for Mongo " + - "database. Alternatively, you may use 'Import from connection string URI' option " + - "from the dropdown labelled 'Use mongo connection string URI' to use the URI " + - "connection string directly."))); + assertTrue(invalids.stream() + .anyMatch(error -> error.contains("It seems that you are trying to use a mongo connection" + + " string URI. Please extract relevant fields and fill the form with extracted " + + "values. For details, please check out the Appsmith's documentation for Mongo " + + "database. Alternatively, you may use 'Import from connection string URI' option " + + "from the dropdown labelled 'Use mongo connection string URI' to use the URI " + + "connection string directly."))); }) .verifyComplete(); } @@ -141,14 +133,13 @@ public void testErrorMessageOnNonSrvUri() { StepVerifier.create(invalidsMono) .assertNext(invalids -> { - assertTrue(invalids - .stream() - .anyMatch(error -> error.contains("It seems that you are trying to use a mongo connection" + - " string URI. Please extract relevant fields and fill the form with extracted " + - "values. For details, please check out the Appsmith's documentation for Mongo " + - "database. Alternatively, you may use 'Import from connection string URI' option " + - "from the dropdown labelled 'Use mongo connection string URI' to use the URI " + - "connection string directly."))); + assertTrue(invalids.stream() + .anyMatch(error -> error.contains("It seems that you are trying to use a mongo connection" + + " string URI. Please extract relevant fields and fill the form with extracted " + + "values. For details, please check out the Appsmith's documentation for Mongo " + + "database. Alternatively, you may use 'Import from connection string URI' option " + + "from the dropdown labelled 'Use mongo connection string URI' to use the URI " + + "connection string directly."))); }) .verifyComplete(); } @@ -161,10 +152,12 @@ public void testInvalidsOnMissingUri() { StepVerifier.create(invalidsMono) .assertNext(invalids -> { - assertTrue(invalids - .stream() - .anyMatch(error -> error.contains("'Mongo Connection string URI' field is empty. Please " + - "edit the 'Mongo Connection URI' field to provide a connection uri to connect with."))); + assertTrue( + invalids.stream() + .anyMatch( + error -> error.contains( + "'Mongo Connection string URI' field is empty. Please " + + "edit the 'Mongo Connection URI' field to provide a connection uri to connect with."))); }) .verifyComplete(); } @@ -180,10 +173,9 @@ public void testInvalidsOnBadSrvUriFormat() { StepVerifier.create(invalidsMono) .assertNext(invalids -> { - assertTrue(invalids - .stream() - .anyMatch(error -> error.contains("Mongo Connection string URI does not seem to be in the" + - " correct format. Please check the URI once."))); + assertTrue(invalids.stream() + .anyMatch(error -> error.contains("Mongo Connection string URI does not seem to be in the" + + " correct format. Please check the URI once."))); }) .verifyComplete(); } @@ -199,10 +191,9 @@ public void testInvalidsOnBadNonSrvUriFormat() { StepVerifier.create(invalidsMono) .assertNext(invalids -> { - assertTrue(invalids - .stream() - .anyMatch(error -> error.contains("Mongo Connection string URI does not seem to be in the" + - " correct format. Please check the URI once."))); + assertTrue(invalids.stream() + .anyMatch(error -> error.contains("Mongo Connection string URI does not seem to be in the" + + " correct format. Please check the URI once."))); }) .verifyComplete(); } @@ -239,9 +230,6 @@ public void testInvalidsEmptyOnCorrectNonSrvUriFormat() { .verifyComplete(); } - - - @Test public void testGetStructureReadPermissionError() { MongoClient mockConnection = mock(MongoClient.class); @@ -253,22 +241,18 @@ public void testGetStructureReadPermissionError() { when(mockMongoCmdException.getErrorCode()).thenReturn(13); DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<DatasourceStructure> structureMono = pluginExecutor.datasourceCreate(dsConfig) + Mono<DatasourceStructure> structureMono = pluginExecutor + .datasourceCreate(dsConfig) .flatMap(connection -> pluginExecutor.getStructure(mockConnection, dsConfig)); - StepVerifier.create(structureMono) - .verifyErrorSatisfies(error -> { - assertTrue(error instanceof AppsmithPluginException); - String expectedMessage = "Appsmith has failed to get database structure. Please provide read permission on" + - " the database to fix this."; - assertTrue(expectedMessage.equals(error.getMessage())); - }); + StepVerifier.create(structureMono).verifyErrorSatisfies(error -> { + assertTrue(error instanceof AppsmithPluginException); + String expectedMessage = "Appsmith has failed to get database structure. Please provide read permission on" + + " the database to fix this."; + assertTrue(expectedMessage.equals(error.getMessage())); + }); } - - - - @Test public void testReadableErrorWithFilterKeyError() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); @@ -280,15 +264,14 @@ public void testReadableErrorWithFilterKeyError() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); // Set bad attribute for limit key - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " filter: \"filter\",\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " find: \"users\",\n" + " filter: \"filter\",\n" + " limit: 10,\n" + " }"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -314,14 +297,12 @@ public void testReadableErrorWithMongoFailedToParseError() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); // Set bad attribute for limit key - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " limit: [10],\n" + - " }"); + setDataValueSafelyInFormData( + configMap, BODY, "{\n" + " find: \"users\",\n" + " limit: [10],\n" + " }"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -347,14 +328,12 @@ public void testReadableErrorWithMongoBadKeyError() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); // Set unrecognized key limitx - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " limitx: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, BODY, "{\n" + " find: \"users\",\n" + " limitx: 10,\n" + " }"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -374,13 +353,16 @@ public void testReadableErrorOnTestDatasourceFailWithBadCredentials() { // Mock exception on authentication failure. MongoSecurityException mockMongoSecurityException = mock(MongoSecurityException.class); when(mockMongoSecurityException.getCode()).thenReturn(-4); - when(mockMongoSecurityException.getMessage()).thenReturn("Exception authenticating " + - "MongoCredential{mechanism=SCRAM-SHA-1, userName='username', source='admin', password=<hidden>," + - " mechanismProperties=<hidden>}"); + when(mockMongoSecurityException.getMessage()) + .thenReturn("Exception authenticating " + + "MongoCredential{mechanism=SCRAM-SHA-1, userName='username', source='admin', password=<hidden>," + + " mechanismProperties=<hidden>}"); // Throw mock error on datasource create method call. MongoPlugin.MongoPluginExecutor spyMongoPluginExecutor = spy(pluginExecutor); - doReturn(Mono.error(mockMongoSecurityException)).when(spyMongoPluginExecutor).datasourceCreate(any()); + doReturn(Mono.error(mockMongoSecurityException)) + .when(spyMongoPluginExecutor) + .datasourceCreate(any()); DatasourceConfiguration dsConfig = createDatasourceConfiguration(); StepVerifier.create(spyMongoPluginExecutor.testDatasource(dsConfig)) @@ -390,7 +372,9 @@ public void testReadableErrorOnTestDatasourceFailWithBadCredentials() { // Verify readable error. String expectedReadableError = "Exception authenticating MongoCredential."; - assertEquals(expectedReadableError, datasourceTestResult.getInvalids().toArray()[0]); + assertEquals( + expectedReadableError, + datasourceTestResult.getInvalids().toArray()[0]); }) .verifyComplete(); } @@ -412,8 +396,8 @@ public void testAggregateCommandWithInvalidQuery() { actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .expectErrorMatches(throwable -> { boolean sameClass = throwable.getClass().equals(AppsmithPluginException.class); @@ -435,51 +419,54 @@ public void testInsertAndFindInvalidDatetime() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, "[\n" + - " {\n" + - " \"name\": {\n" + - " \"first\": \"John\",\n" + - " \"last\": \"Backus\"\n" + - " },\n" + - " \"birth\": ISODate(\"0001-01-01T00:00:00.000+00:00\"),\n" + - " \"death\": ISODate(\"2007-03-17T04:00:00Z\"),\n" + - " \"issue\": 13285\n" + - " },\n" + - " {\n" + - " \"name\": {\n" + - " \"first\": \"John\",\n" + - " \"last\": \"McCarthy\"\n" + - " },\n" + - " \"birth\": ISODate(\"1927-09-04T04:00:00Z\"),\n" + - " \"death\": ISODate(\"2011-12-24T05:00:00Z\"),\n" + - " \"issue\": 13285\n" + - " },\n" + - " {\n" + - " \"name\": {\n" + - " \"first\": \"Grace\",\n" + - " \"last\": \"Hopper\"\n" + - " },\n" + - " \"title\": \"Rear Admiral\",\n" + - " \"birth\": ISODate(\"1906-12-09T05:00:00Z\"),\n" + - " \"death\": ISODate(\"1992-01-01T05:00:00Z\"),\n" + - " \"issue\": 13285\n" + - " },\n" + - " {\n" + - " \"name\": {\n" + - " \"first\": \"Kristen\",\n" + - " \"last\": \"Nygaard\"\n" + - " },\n" + - " \"birth\": ISODate(\"1926-08-27T04:00:00Z\"),\n" + - " \"death\": ISODate(\"2002-08-10T04:00:00Z\"),\n" + - " \"issue\": 13285\n" + - " }\n" + - "]"); + setDataValueSafelyInFormData( + configMap, + INSERT_DOCUMENT, + "[\n" + " {\n" + + " \"name\": {\n" + + " \"first\": \"John\",\n" + + " \"last\": \"Backus\"\n" + + " },\n" + + " \"birth\": ISODate(\"0001-01-01T00:00:00.000+00:00\"),\n" + + " \"death\": ISODate(\"2007-03-17T04:00:00Z\"),\n" + + " \"issue\": 13285\n" + + " },\n" + + " {\n" + + " \"name\": {\n" + + " \"first\": \"John\",\n" + + " \"last\": \"McCarthy\"\n" + + " },\n" + + " \"birth\": ISODate(\"1927-09-04T04:00:00Z\"),\n" + + " \"death\": ISODate(\"2011-12-24T05:00:00Z\"),\n" + + " \"issue\": 13285\n" + + " },\n" + + " {\n" + + " \"name\": {\n" + + " \"first\": \"Grace\",\n" + + " \"last\": \"Hopper\"\n" + + " },\n" + + " \"title\": \"Rear Admiral\",\n" + + " \"birth\": ISODate(\"1906-12-09T05:00:00Z\"),\n" + + " \"death\": ISODate(\"1992-01-01T05:00:00Z\"),\n" + + " \"issue\": 13285\n" + + " },\n" + + " {\n" + + " \"name\": {\n" + + " \"first\": \"Kristen\",\n" + + " \"last\": \"Nygaard\"\n" + + " },\n" + + " \"birth\": ISODate(\"1926-08-27T04:00:00Z\"),\n" + + " \"death\": ISODate(\"2002-08-10T04:00:00Z\"),\n" + + " \"issue\": 13285\n" + + " }\n" + + "]"); actionConfiguration.setFormData(configMap); DatasourceConfiguration dsConfig = createDatasourceConfiguration(); Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -487,13 +474,13 @@ public void testInsertAndFindInvalidDatetime() { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), - result.getDataTypes().toString() - ); + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); }) .verifyComplete(); - //Find query + // Find query configMap.clear(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); @@ -503,7 +490,8 @@ public void testInsertAndFindInvalidDatetime() { actionConfiguration.setFormData(configMap); - executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -512,9 +500,9 @@ public void testInsertAndFindInvalidDatetime() { assertNotNull(result.getBody()); assertEquals(4, ((ArrayNode) result.getBody()).size()); assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), - result.getDataTypes().toString() - ); + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); }) .verifyComplete(); @@ -528,17 +516,25 @@ public void testInsertAndFindInvalidDatetime() { actionConfiguration.setFormData(configMap); // Run the delete command - dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)).block(); + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); } @Test public void verifyUniquenessOfMongoPluginErrorCode() { - assert (Arrays.stream(MongoPluginError.values()).map(MongoPluginError::getAppErrorCode).distinct().count() == MongoPluginError.values().length); - - assert (Arrays.stream(MongoPluginError.values()).map(MongoPluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-MNG")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(MongoPluginError.values()) + .map(MongoPluginError::getAppErrorCode) + .distinct() + .count() + == MongoPluginError.values().length); + + assert (Arrays.stream(MongoPluginError.values()) + .map(MongoPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-MNG")) + .collect(Collectors.toList()) + .size() + == 0); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginFormsTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginFormsTest.java index 164cc99b464a..9619c186f766 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginFormsTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginFormsTest.java @@ -1,5 +1,38 @@ package com.external.plugins; +import com.appsmith.external.datatypes.ClientDataType; +import com.appsmith.external.dtos.ExecuteActionDTO; +import com.appsmith.external.models.ActionConfiguration; +import com.appsmith.external.models.ActionExecutionRequest; +import com.appsmith.external.models.ActionExecutionResult; +import com.appsmith.external.models.Connection; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.Endpoint; +import com.appsmith.external.models.Param; +import com.appsmith.external.models.ParsedDataType; +import com.appsmith.external.models.RequestParamDTO; +import com.appsmith.external.models.SSLDetails; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.mongodb.reactivestreams.client.MongoClient; +import com.mongodb.reactivestreams.client.MongoClients; +import com.mongodb.reactivestreams.client.MongoCollection; +import org.bson.Document; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static com.appsmith.external.constants.DisplayDataType.JSON; import static com.appsmith.external.constants.DisplayDataType.RAW; import static com.appsmith.external.helpers.PluginUtils.STRING_TYPE; @@ -26,1563 +59,1520 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.bson.Document; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -import com.appsmith.external.datatypes.ClientDataType; -import com.appsmith.external.dtos.ExecuteActionDTO; -import com.appsmith.external.models.ActionConfiguration; -import com.appsmith.external.models.ActionExecutionRequest; -import com.appsmith.external.models.ActionExecutionResult; -import com.appsmith.external.models.Connection; -import com.appsmith.external.models.DatasourceConfiguration; -import com.appsmith.external.models.Endpoint; -import com.appsmith.external.models.Param; -import com.appsmith.external.models.ParsedDataType; -import com.appsmith.external.models.RequestParamDTO; -import com.appsmith.external.models.SSLDetails; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.mongodb.reactivestreams.client.MongoClient; -import com.mongodb.reactivestreams.client.MongoClients; -import com.mongodb.reactivestreams.client.MongoCollection; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - /** * Unit tests for MongoPlugin */ - @Testcontainers public class MongoPluginFormsTest { - MongoPlugin.MongoPluginExecutor pluginExecutor = new MongoPlugin.MongoPluginExecutor(); - - private static String address; - private static Integer port; - private JsonNode value; - private static MongoClient mongoClient; - - @SuppressWarnings("rawtypes") - @Container - public static GenericContainer mongoContainer = new MongoTestContainer(); - - @BeforeAll - public static void setUp() { - address = mongoContainer.getContainerIpAddress(); - port = mongoContainer.getFirstMappedPort(); - String uri = "mongodb://" + address + ":" + port; - mongoClient = MongoClients.create(uri); - - } - - private DatasourceConfiguration createDatasourceConfiguration() { - Endpoint endpoint = new Endpoint(); - endpoint.setHost(address); - endpoint.setPort(port.longValue()); - - Connection connection = new Connection(); - connection.setMode(Connection.Mode.READ_WRITE); - connection.setType(Connection.Type.DIRECT); - connection.setDefaultDatabaseName("test"); - connection.setSsl(new SSLDetails()); - connection.getSsl().setAuthType(SSLDetails.AuthType.DEFAULT); - - DatasourceConfiguration dsConfig = new DatasourceConfiguration(); - dsConfig.setConnection(connection); - dsConfig.setEndpoints(List.of(endpoint)); - - return dsConfig; - } - - @Test - public void testBsonSmartSubstitution_withBSONValue() { - DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: {{Input4.text}},\n" + - " filter: \"{{Input1.text}}\",\n" + - " sort: { id: {{Input2.text}} },\n" + - " limit: {{Input3.text}}\n" + - " }"); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("{ age: { \"$gte\": 30 } }"); - param1.setClientDataType(ClientDataType.OBJECT); - params.add(param1); - Param param3 = new Param(); - param3.setKey("Input2.text"); - param3.setValue("1"); - param3.setClientDataType(ClientDataType.NUMBER); - params.add(param3); - Param param4 = new Param(); - param4.setKey("Input3.text"); - param4.setValue("10"); - param4.setClientDataType(ClientDataType.NUMBER); - params.add(param4); - Param param5 = new Param(); - param5.setKey("Input4.text"); - param5.setValue("users"); - param5.setClientDataType(ClientDataType.STRING); - params.add(param5); - executeActionDTO.setParams(params); - - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, - datasourceConfiguration, - actionConfiguration)); - - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(2, ((ArrayNode) result.getBody()).size()); - - // Assert the debug request parameters are getting set. - ActionExecutionRequest request = result.getRequest(); - List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) request - .getProperties().get("smart-substitution-parameters"); - assertEquals(parameters.size(), 4); - - Map.Entry<String, String> parameterEntry = parameters.get(0); - assertEquals(parameterEntry.getKey(), "users"); - assertEquals(parameterEntry.getValue(), "STRING"); - - parameterEntry = parameters.get(1); - assertEquals(parameterEntry.getKey(), "{ age: { \"$gte\": 30 } }"); - assertEquals(parameterEntry.getValue(), "BSON"); - - parameterEntry = parameters.get(2); - assertEquals(parameterEntry.getKey(), "1"); - assertEquals(parameterEntry.getValue(), "INTEGER"); - - parameterEntry = parameters.get(3); - assertEquals(parameterEntry.getKey(), "10"); - assertEquals(parameterEntry.getValue(), "INTEGER"); - - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - - String expectedQuery = "{\n" + - " find: \"users\",\n" + - " filter: { age: { \"$gte\": 30 } },\n" + - " sort: { id: 1 },\n" + - " limit: 10\n" + - " }"; - // check that bindings are not replaced with actual values and not '$i' or '?' - assertEquals(expectedQuery, - ((RequestParamDTO) (((List) result.getRequest() - .getRequestParams())).get(0)).getValue()); - }) - .verifyComplete(); - } - - @Test - public void testBsonSmartSubstitution_withEscapedStringValue() { - DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: {{Input4.text}},\n" + - " filter: { age: { {{Input1.text}} : 30 } },\n" + - " sort: { id: {{Input2.text}} },\n" + - " limit: {{Input3.text}}\n" + - " }"); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("$gte"); - param1.setClientDataType(ClientDataType.STRING); - params.add(param1); - Param param3 = new Param(); - param3.setKey("Input2.text"); - param3.setValue("1"); - param3.setClientDataType(ClientDataType.NUMBER); - params.add(param3); - Param param4 = new Param(); - param4.setKey("Input3.text"); - param4.setValue("10"); - param4.setClientDataType(ClientDataType.NUMBER); - params.add(param4); - Param param5 = new Param(); - param5.setKey("Input4.text"); - param5.setValue("users"); - param5.setClientDataType(ClientDataType.STRING); - params.add(param5); - executeActionDTO.setParams(params); - - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, - datasourceConfiguration, - actionConfiguration)); - - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(2, ((ArrayNode) result.getBody()).size()); - - // Assert the debug request parameters are getting set. - ActionExecutionRequest request = result.getRequest(); - List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) request - .getProperties().get("smart-substitution-parameters"); - assertEquals(parameters.size(), 4); - - Map.Entry<String, String> parameterEntry = parameters.get(0); - assertEquals(parameterEntry.getKey(), "users"); - assertEquals(parameterEntry.getValue(), "STRING"); - - parameterEntry = parameters.get(1); - assertEquals(parameterEntry.getKey(), "$gte"); - assertEquals(parameterEntry.getValue(), "STRING"); - - parameterEntry = parameters.get(2); - assertEquals(parameterEntry.getKey(), "1"); - assertEquals(parameterEntry.getValue(), "INTEGER"); - - parameterEntry = parameters.get(3); - assertEquals(parameterEntry.getKey(), "10"); - assertEquals(parameterEntry.getValue(), "INTEGER"); - - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - - String expectedQuery = "{\n" + - " find: \"users\",\n" + - " filter: { age: { \"$gte\" : 30 } },\n" + - " sort: { id: 1 },\n" + - " limit: 10\n" + - " }"; - // check that bindings are not replaced with actual values and not '$i' or '?' - assertEquals(expectedQuery, - ((RequestParamDTO) (((List) result.getRequest() - .getRequestParams())).get(0)).getValue()); - }) - .verifyComplete(); - } - - @Test - public void testFindFormCommand() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); - setDataValueSafelyInFormData(configMap, FIND_QUERY, "{ age: { \"$gte\": 30 } }"); - setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: 1 }"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - - actionConfiguration.setFormData(configMap); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(2, ((ArrayNode) result.getBody()).size()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - } - - @Test - public void testInsertFormCommandArrayDocuments() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, - "[{name : \"ZZZ Insert Form Array Test 1\", gender : \"F\", age : 40, tag : \"test\"}," - + - "{name : \"ZZZ Insert Form Array Test 2\", gender : \"F\", age : 40, tag : \"test\"}" - + - "]"); - - actionConfiguration.setFormData(configMap); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - - // Clean up this newly inserted value - configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{\"tag\" : \"test\"}"); - setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); - - actionConfiguration.setFormData(configMap); - // Run the delete command - dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)).block(); - } - - @Test - public void testInsertFormCommandSingleDocument() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, - "{\"name\" : \"ZZZ Insert Form Single Test\", \"gender\" : \"F\", \"age\" : 40, \"tag\" : \"test\"}"); - - actionConfiguration.setFormData(configMap); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - - // Clean up this newly inserted value - configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{\"tag\" : \"test\"}"); - setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); - - actionConfiguration.setFormData(configMap); - - // Run the delete command - dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)).block(); - } - - @Test - public void testUpdateOneFormCommand() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{ name: \"Alden Cantrell\" }"); - setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "{ $set: { age: 31 }}}"); - setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "SINGLE"); - - actionConfiguration.setFormData(configMap); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); - assertEquals(value.asText(), "1"); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - } - - @Test - public void testUpdateManyFormCommand() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - // Query for all the documents in the collection - setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{}"); - setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "{ $set: { updatedByCommand: true }}}"); - setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "ALL"); - - actionConfiguration.setFormData(configMap); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); - assertEquals("3", value.asText()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - } - - @Test - public void testUpdateManyFormCommandWithArrayInput() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - // Query for all the documents in the collection - setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{}"); - setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "[{ \"$set\": { \"department\": \"app\" } }" + - ",{ \"$set\": { \"department\": \"design\" } }]"); - setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "ALL"); - - actionConfiguration.setFormData(configMap); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); - assertEquals("3", value.asText()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - - //After update fetching to document to verify if the value is updated properly - ActionConfiguration actionConfiguration1 = new ActionConfiguration(); - Map<String, Object> configMap1 = new HashMap<>(); - setDataValueSafelyInFormData(configMap1, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap1, COMMAND, "FIND"); - setDataValueSafelyInFormData(configMap1, COLLECTION, "users"); - // Query for all the documents in the collection - setDataValueSafelyInFormData(configMap1, FIND_QUERY, "{\"department\":\"design\"}"); - actionConfiguration1.setFormData(configMap1); - Mono<Object> executeMono1 = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration1)); - StepVerifier.create(executeMono1) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - int value =((ArrayNode)result.getBody()).size(); - assertEquals(3, value); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - } + MongoPlugin.MongoPluginExecutor pluginExecutor = new MongoPlugin.MongoPluginExecutor(); + + private static String address; + private static Integer port; + private JsonNode value; + private static MongoClient mongoClient; + + @SuppressWarnings("rawtypes") + @Container + public static GenericContainer mongoContainer = new MongoTestContainer(); + + @BeforeAll + public static void setUp() { + address = mongoContainer.getContainerIpAddress(); + port = mongoContainer.getFirstMappedPort(); + String uri = "mongodb://" + address + ":" + port; + mongoClient = MongoClients.create(uri); + } + + private DatasourceConfiguration createDatasourceConfiguration() { + Endpoint endpoint = new Endpoint(); + endpoint.setHost(address); + endpoint.setPort(port.longValue()); + + Connection connection = new Connection(); + connection.setMode(Connection.Mode.READ_WRITE); + connection.setType(Connection.Type.DIRECT); + connection.setDefaultDatabaseName("test"); + connection.setSsl(new SSLDetails()); + connection.getSsl().setAuthType(SSLDetails.AuthType.DEFAULT); + + DatasourceConfiguration dsConfig = new DatasourceConfiguration(); + dsConfig.setConnection(connection); + dsConfig.setEndpoints(List.of(endpoint)); + + return dsConfig; + } + + @Test + public void testBsonSmartSubstitution_withBSONValue() { + DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " find: {{Input4.text}},\n" + + " filter: \"{{Input1.text}}\",\n" + + " sort: { id: {{Input2.text}} },\n" + + " limit: {{Input3.text}}\n" + + " }"); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("{ age: { \"$gte\": 30 } }"); + param1.setClientDataType(ClientDataType.OBJECT); + params.add(param1); + Param param3 = new Param(); + param3.setKey("Input2.text"); + param3.setValue("1"); + param3.setClientDataType(ClientDataType.NUMBER); + params.add(param3); + Param param4 = new Param(); + param4.setKey("Input3.text"); + param4.setValue("10"); + param4.setClientDataType(ClientDataType.NUMBER); + params.add(param4); + Param param5 = new Param(); + param5.setKey("Input4.text"); + param5.setValue("users"); + param5.setClientDataType(ClientDataType.STRING); + params.add(param5); + executeActionDTO.setParams(params); + + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized( + conn, executeActionDTO, datasourceConfiguration, actionConfiguration)); + + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(2, ((ArrayNode) result.getBody()).size()); + + // Assert the debug request parameters are getting set. + ActionExecutionRequest request = result.getRequest(); + List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) + request.getProperties().get("smart-substitution-parameters"); + assertEquals(parameters.size(), 4); + + Map.Entry<String, String> parameterEntry = parameters.get(0); + assertEquals(parameterEntry.getKey(), "users"); + assertEquals(parameterEntry.getValue(), "STRING"); + + parameterEntry = parameters.get(1); + assertEquals(parameterEntry.getKey(), "{ age: { \"$gte\": 30 } }"); + assertEquals(parameterEntry.getValue(), "BSON"); + + parameterEntry = parameters.get(2); + assertEquals(parameterEntry.getKey(), "1"); + assertEquals(parameterEntry.getValue(), "INTEGER"); + + parameterEntry = parameters.get(3); + assertEquals(parameterEntry.getKey(), "10"); + assertEquals(parameterEntry.getValue(), "INTEGER"); + + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + + String expectedQuery = "{\n" + " find: \"users\",\n" + + " filter: { age: { \"$gte\": 30 } },\n" + + " sort: { id: 1 },\n" + + " limit: 10\n" + + " }"; + // check that bindings are not replaced with actual values and not '$i' or '?' + assertEquals( + expectedQuery, + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getValue()); + }) + .verifyComplete(); + } + + @Test + public void testBsonSmartSubstitution_withEscapedStringValue() { + DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " find: {{Input4.text}},\n" + + " filter: { age: { {{Input1.text}} : 30 } },\n" + + " sort: { id: {{Input2.text}} },\n" + + " limit: {{Input3.text}}\n" + + " }"); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("$gte"); + param1.setClientDataType(ClientDataType.STRING); + params.add(param1); + Param param3 = new Param(); + param3.setKey("Input2.text"); + param3.setValue("1"); + param3.setClientDataType(ClientDataType.NUMBER); + params.add(param3); + Param param4 = new Param(); + param4.setKey("Input3.text"); + param4.setValue("10"); + param4.setClientDataType(ClientDataType.NUMBER); + params.add(param4); + Param param5 = new Param(); + param5.setKey("Input4.text"); + param5.setValue("users"); + param5.setClientDataType(ClientDataType.STRING); + params.add(param5); + executeActionDTO.setParams(params); + + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized( + conn, executeActionDTO, datasourceConfiguration, actionConfiguration)); + + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(2, ((ArrayNode) result.getBody()).size()); + + // Assert the debug request parameters are getting set. + ActionExecutionRequest request = result.getRequest(); + List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) + request.getProperties().get("smart-substitution-parameters"); + assertEquals(parameters.size(), 4); + + Map.Entry<String, String> parameterEntry = parameters.get(0); + assertEquals(parameterEntry.getKey(), "users"); + assertEquals(parameterEntry.getValue(), "STRING"); + + parameterEntry = parameters.get(1); + assertEquals(parameterEntry.getKey(), "$gte"); + assertEquals(parameterEntry.getValue(), "STRING"); + + parameterEntry = parameters.get(2); + assertEquals(parameterEntry.getKey(), "1"); + assertEquals(parameterEntry.getValue(), "INTEGER"); + + parameterEntry = parameters.get(3); + assertEquals(parameterEntry.getKey(), "10"); + assertEquals(parameterEntry.getValue(), "INTEGER"); + + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + + String expectedQuery = "{\n" + " find: \"users\",\n" + + " filter: { age: { \"$gte\" : 30 } },\n" + + " sort: { id: 1 },\n" + + " limit: 10\n" + + " }"; + // check that bindings are not replaced with actual values and not '$i' or '?' + assertEquals( + expectedQuery, + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getValue()); + }) + .verifyComplete(); + } + + @Test + public void testFindFormCommand() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); + setDataValueSafelyInFormData(configMap, FIND_QUERY, "{ age: { \"$gte\": 30 } }"); + setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: 1 }"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + + actionConfiguration.setFormData(configMap); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(2, ((ArrayNode) result.getBody()).size()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + } + + @Test + public void testInsertFormCommandArrayDocuments() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData( + configMap, + INSERT_DOCUMENT, + "[{name : \"ZZZ Insert Form Array Test 1\", gender : \"F\", age : 40, tag : \"test\"}," + + "{name : \"ZZZ Insert Form Array Test 2\", gender : \"F\", age : 40, tag : \"test\"}" + + "]"); + + actionConfiguration.setFormData(configMap); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + + // Clean up this newly inserted value + configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{\"tag\" : \"test\"}"); + setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); + + actionConfiguration.setFormData(configMap); + // Run the delete command + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); + } + + @Test + public void testInsertFormCommandSingleDocument() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData( + configMap, + INSERT_DOCUMENT, + "{\"name\" : \"ZZZ Insert Form Single Test\", \"gender\" : \"F\", \"age\" : 40, \"tag\" : \"test\"}"); + + actionConfiguration.setFormData(configMap); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + + // Clean up this newly inserted value + configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{\"tag\" : \"test\"}"); + setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); + + actionConfiguration.setFormData(configMap); + + // Run the delete command + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); + } + + @Test + public void testUpdateOneFormCommand() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{ name: \"Alden Cantrell\" }"); + setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "{ $set: { age: 31 }}}"); + setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "SINGLE"); + + actionConfiguration.setFormData(configMap); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); + assertEquals(value.asText(), "1"); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + } + + @Test + public void testUpdateManyFormCommand() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + // Query for all the documents in the collection + setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{}"); + setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "{ $set: { updatedByCommand: true }}}"); + setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "ALL"); + + actionConfiguration.setFormData(configMap); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); + assertEquals("3", value.asText()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + } + + @Test + public void testUpdateManyFormCommandWithArrayInput() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + // Query for all the documents in the collection + setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{}"); + setDataValueSafelyInFormData( + configMap, + UPDATE_OPERATION, + "[{ \"$set\": { \"department\": \"app\" } }" + ",{ \"$set\": { \"department\": \"design\" } }]"); + setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "ALL"); + + actionConfiguration.setFormData(configMap); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); + assertEquals("3", value.asText()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + + // After update fetching to document to verify if the value is updated properly + ActionConfiguration actionConfiguration1 = new ActionConfiguration(); + Map<String, Object> configMap1 = new HashMap<>(); + setDataValueSafelyInFormData(configMap1, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap1, COMMAND, "FIND"); + setDataValueSafelyInFormData(configMap1, COLLECTION, "users"); + // Query for all the documents in the collection + setDataValueSafelyInFormData(configMap1, FIND_QUERY, "{\"department\":\"design\"}"); + actionConfiguration1.setFormData(configMap1); + Mono<Object> executeMono1 = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration1)); + StepVerifier.create(executeMono1) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + int value = ((ArrayNode) result.getBody()).size(); + assertEquals(3, value); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + } + + @Test + public void testDeleteFormCommandSingleDocument() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + // Insert multiple documents which would match the delete criterion + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData( + configMap, + INSERT_DOCUMENT, + "[{\"name\" : \"To Delete1\", \"tag\" : \"delete\"}, {\"name\" : \"To Delete2\", \"tag\" : \"delete\"}]"); + + actionConfiguration.setFormData(configMap); + + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); + + // Now that the documents have been inserted, lets delete one of them + configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{tag : \"delete\"}"); + setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "SINGLE"); + + actionConfiguration.setFormData(configMap); + + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("n"); + // Assert that only one document out of the two gets deleted + assertEquals(value.asInt(), 1); + }) + .verifyComplete(); + + // Run this delete command again to ensure that both the documents added are + // deleted post this test. + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); + } + + @Test + public void testDeleteFormCommandMultipleDocument() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + // Insert multiple documents which would match the delete criterion + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData( + configMap, + INSERT_DOCUMENT, + "[{\"name\" : \"To Delete1\", \"tag\" : \"delete\"}, {\"name\" : \"To Delete2\", \"tag\" : \"delete\"}]"); + + actionConfiguration.setFormData(configMap); + + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); + + // Now that the documents have been inserted, lets delete both of them + configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{tag : \"delete\"}"); + setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); + + actionConfiguration.setFormData(configMap); + + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("n"); + assertEquals(value.asInt(), 2); + }) + .verifyComplete(); + } + + @Test + public void testBsonSmartSubstitutionMongoForm() { + DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); + setDataValueSafelyInFormData(configMap, FIND_QUERY, "\"{{Input1.text}}\""); + setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: {{Input2.text}} }"); + setDataValueSafelyInFormData(configMap, FIND_LIMIT, "{{Input3.text}}"); + setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input4.text}}"); + + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("{ age: { \"$gte\": 30 } }"); + param1.setClientDataType(ClientDataType.OBJECT); + params.add(param1); + Param param3 = new Param(); + param3.setKey("Input2.text"); + param3.setValue("1"); + param3.setClientDataType(ClientDataType.NUMBER); + params.add(param3); + Param param4 = new Param(); + param4.setKey("Input3.text"); + param4.setValue("10"); + param4.setClientDataType(ClientDataType.NUMBER); + params.add(param4); + Param param5 = new Param(); + param5.setKey("Input4.text"); + param5.setValue("users"); + param5.setClientDataType(ClientDataType.STRING); + params.add(param5); + executeActionDTO.setParams(params); + + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized( + conn, executeActionDTO, datasourceConfiguration, actionConfiguration)); + + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(2, ((ArrayNode) result.getBody()).size()); + + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + + String expectedQuery = + "{\"find\": \"users\", \"filter\": {\"age\": {\"$gte\": 30}}, \"sort\": {\"id\": 1}, \"limit\": 10, \"batchSize\": 10}"; + assertEquals( + expectedQuery, + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getValue()); + }) + .verifyComplete(); + } + @Test + public void testFormSmartInputFind() { + DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); + // Skip adding the query + setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: {{Input2.text}} }"); + // Skip adding limit + setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input4.text}}"); + + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input2.text"); + param1.setValue("1"); + param1.setClientDataType(ClientDataType.NUMBER); + params.add(param1); + Param param2 = new Param(); + param2.setKey("Input4.text"); + param2.setValue("users"); + param2.setClientDataType(ClientDataType.STRING); + params.add(param2); + executeActionDTO.setParams(params); + + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized( + conn, executeActionDTO, datasourceConfiguration, actionConfiguration)); + + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(3, ((ArrayNode) result.getBody()).size()); + + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + + String expectedQuery = + "{\"find\": \"users\", \"filter\": {}, \"sort\": {\"id\": 1}, \"limit\": 10, \"batchSize\": 10}"; + assertEquals( + expectedQuery, + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getValue()); + }) + .verifyComplete(); + } + + @Test + public void testFormSmartInputCount() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "COUNT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + // Skip adding the query + + actionConfiguration.setFormData(configMap); + + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("n"); + assertEquals(value.asInt(), 3); + }) + .verifyComplete(); + } + + @Test + public void testFormSmartInputDistinct() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "DISTINCT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + // Skip adding the query + setDataValueSafelyInFormData(configMap, DISTINCT_KEY, "name"); + + actionConfiguration.setFormData(configMap); + + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + ArrayNode valuesNode = (ArrayNode) ((ObjectNode) result.getBody()).get("values"); + int valuesSize = valuesNode.size(); + assertEquals(valuesSize, 3); + }) + .verifyComplete(); + } + + @Test + public void testSmartSubstitutionEvaluatedValueContainingQuestionMark() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData( + configMap, + INSERT_DOCUMENT, + "{\"name\" : {{Input1.text}}, \"gender\" : {{Input2.text}}, \"age\" : 40, \"tag\" : \"test\"}"); + + actionConfiguration.setFormData(configMap); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("This string contains ? symbol"); + params.add(param1); + Param param3 = new Param(); + param3.setKey("Input2.text"); + param3.setValue("F"); + params.add(param3); + executeActionDTO.setParams(params); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + + // Clean up this newly inserted value + + configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{\"tag\" : \"test\"}"); + setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); + + actionConfiguration.setFormData(configMap); + + // Run the delete command + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); + } + + @Test + public void testSmartSubstitutionWithObjectIdInDoubleQuotes() { + final MongoCollection<Document> usersCollection = + mongoClient.getDatabase("test").getCollection("users"); + List<String> documentIds = new ArrayList<>(); + Flux.from(usersCollection.find()) + .map(doc -> documentIds.add(doc.get("_id").toString())) + .collectList() + .block(); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + String findQuery = "{\n" + " \"find\": \"users\",\n" + + " \"filter\": {\n" + + " \"_id\": {\n" + + " $in: {{Input1.text}}\n" + + " }\n" + + " }\n" + + "}"; + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + StringBuilder sb = new StringBuilder(); + documentIds.stream().forEach(id -> sb.append(" \"ObjectId(\\\"" + id + "\\\")\",")); + sb.setLength(sb.length() - 1); + String objectIdsAsArray = "[" + sb + "]"; + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData(configMap, BODY, findQuery); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue(objectIdsAsArray); + params.add(param1); + executeActionDTO.setParams(params); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(3, ((ArrayNode) result.getBody()).size()); + }) + .verifyComplete(); + } + + @Test + public void testSmartSubstitutionWithObjectIdInSingleQuotes() { + final MongoCollection<Document> usersCollection = + mongoClient.getDatabase("test").getCollection("users"); + List<String> documentIds = new ArrayList<>(); + Flux.from(usersCollection.find()) + .map(doc -> documentIds.add(doc.get("_id").toString())) + .collectList() + .block(); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + String findQuery = "{\n" + " \"find\": \"users\",\n" + + " \"filter\": {\n" + + " \"_id\": {\n" + + " $in: {{Input1.text}}\n" + + " }\n" + + " }\n" + + "}"; + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + StringBuilder sb = new StringBuilder(); + documentIds.stream().forEach(id -> sb.append(" \'ObjectId(\\\"" + id + "\\\")\',")); + sb.setLength(sb.length() - 1); + String objectIdsAsArray = "[" + sb + "]"; + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData(configMap, BODY, findQuery); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue(objectIdsAsArray); + param1.setClientDataType(ClientDataType.ARRAY); + param1.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); + params.add(param1); + executeActionDTO.setParams(params); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(3, ((ArrayNode) result.getBody()).size()); + }) + .verifyComplete(); + } + + @Test + public void testFormToNativeQueryConversionForFindCommand() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); + setDataValueSafelyInFormData(configMap, FIND_QUERY, "{{Input1.text}}"); + setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: 1 }"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("{ age: { \"$gte\": 30 } }"); + params.add(param1); + executeActionDTO.setParams(params); + + pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, BODY, getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(2, ((ArrayNode) result.getBody()).size()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + } + + @Test + public void testFormToNativeQueryConversionForInsertCommand() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input1.text}}"); + setDataValueSafelyInFormData( + configMap, + INSERT_DOCUMENT, + "[{name : \"ZZZ Insert Form Array Test 1\", gender : " + + "\"F\", age : 40, tag : \"test\"}, {name : \"ZZZ Insert Form Array Test 2\", gender : \"F\", age : " + + "40, tag : \"test\"}]"); + + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("users"); + params.add(param1); + executeActionDTO.setParams(params); + + pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, BODY, getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + + // Clean up this newly inserted value + configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{\"tag\" : \"test\"}"); + setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); + + actionConfiguration.setFormData(configMap); + // Run the delete command + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); + } @Test - public void testDeleteFormCommandSingleDocument() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - // Insert multiple documents which would match the delete criterion - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, - "[{\"name\" : \"To Delete1\", \"tag\" : \"delete\"}, {\"name\" : \"To Delete2\", \"tag\" : \"delete\"}]"); - - actionConfiguration.setFormData(configMap); - - dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)).block(); - - // Now that the documents have been inserted, lets delete one of them - configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{tag : \"delete\"}"); - setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "SINGLE"); - - actionConfiguration.setFormData(configMap); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("n"); - // Assert that only one document out of the two gets deleted - assertEquals(value.asInt(), 1); - }) - .verifyComplete(); - - // Run this delete command again to ensure that both the documents added are - // deleted post this test. - dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)).block(); - - } - - @Test - public void testDeleteFormCommandMultipleDocument() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - // Insert multiple documents which would match the delete criterion - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, - "[{\"name\" : \"To Delete1\", \"tag\" : \"delete\"}, {\"name\" : \"To Delete2\", \"tag\" : \"delete\"}]"); - - actionConfiguration.setFormData(configMap); - - dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)).block(); - - // Now that the documents have been inserted, lets delete both of them - configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{tag : \"delete\"}"); - setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); - - actionConfiguration.setFormData(configMap); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("n"); - assertEquals(value.asInt(), 2); - }) - .verifyComplete(); - } - - @Test - public void testBsonSmartSubstitutionMongoForm() { - DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); - setDataValueSafelyInFormData(configMap, FIND_QUERY, "\"{{Input1.text}}\""); - setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: {{Input2.text}} }"); - setDataValueSafelyInFormData(configMap, FIND_LIMIT, "{{Input3.text}}"); - setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input4.text}}"); - - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("{ age: { \"$gte\": 30 } }"); - param1.setClientDataType(ClientDataType.OBJECT); - params.add(param1); - Param param3 = new Param(); - param3.setKey("Input2.text"); - param3.setValue("1"); - param3.setClientDataType(ClientDataType.NUMBER); - params.add(param3); - Param param4 = new Param(); - param4.setKey("Input3.text"); - param4.setValue("10"); - param4.setClientDataType(ClientDataType.NUMBER); - params.add(param4); - Param param5 = new Param(); - param5.setKey("Input4.text"); - param5.setValue("users"); - param5.setClientDataType(ClientDataType.STRING); - params.add(param5); - executeActionDTO.setParams(params); - - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, - datasourceConfiguration, - actionConfiguration)); - - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(2, ((ArrayNode) result.getBody()).size()); - - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - - String expectedQuery = "{\"find\": \"users\", \"filter\": {\"age\": {\"$gte\": 30}}, \"sort\": {\"id\": 1}, \"limit\": 10, \"batchSize\": 10}"; - assertEquals(expectedQuery, - ((RequestParamDTO) (((List) result.getRequest() - .getRequestParams())).get(0)).getValue()); - }) - .verifyComplete(); - } - - @Test - public void testFormSmartInputFind() { - DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); - // Skip adding the query - setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: {{Input2.text}} }"); - // Skip adding limit - setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input4.text}}"); - - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input2.text"); - param1.setValue("1"); - param1.setClientDataType(ClientDataType.NUMBER); - params.add(param1); - Param param2 = new Param(); - param2.setKey("Input4.text"); - param2.setValue("users"); - param2.setClientDataType(ClientDataType.STRING); - params.add(param2); - executeActionDTO.setParams(params); - - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, - datasourceConfiguration, - actionConfiguration)); - - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(3, ((ArrayNode) result.getBody()).size()); - - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - - String expectedQuery = "{\"find\": \"users\", \"filter\": {}, \"sort\": {\"id\": 1}, \"limit\": 10, \"batchSize\": 10}"; - assertEquals(expectedQuery, - ((RequestParamDTO) (((List) result.getRequest() - .getRequestParams())).get(0)).getValue()); - }) - .verifyComplete(); - } - - @Test - public void testFormSmartInputCount() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "COUNT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - // Skip adding the query - - actionConfiguration.setFormData(configMap); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("n"); - assertEquals(value.asInt(), 3); - }) - .verifyComplete(); - } - - @Test - public void testFormSmartInputDistinct() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "DISTINCT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - // Skip adding the query - setDataValueSafelyInFormData(configMap, DISTINCT_KEY, "name"); - - actionConfiguration.setFormData(configMap); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - ArrayNode valuesNode = (ArrayNode) ((ObjectNode) result.getBody()) - .get("values"); - int valuesSize = valuesNode.size(); - assertEquals(valuesSize, 3); - }) - .verifyComplete(); - } - - @Test - public void testSmartSubstitutionEvaluatedValueContainingQuestionMark() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, - "{\"name\" : {{Input1.text}}, \"gender\" : {{Input2.text}}, \"age\" : 40, \"tag\" : \"test\"}"); - - actionConfiguration.setFormData(configMap); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("This string contains ? symbol"); - params.add(param1); - Param param3 = new Param(); - param3.setKey("Input2.text"); - param3.setValue("F"); - params.add(param3); - executeActionDTO.setParams(params); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - - // Clean up this newly inserted value - - configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{\"tag\" : \"test\"}"); - setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); - - actionConfiguration.setFormData(configMap); - - // Run the delete command - dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)).block(); - } - - @Test - public void testSmartSubstitutionWithObjectIdInDoubleQuotes() { - final MongoCollection<Document> usersCollection = mongoClient.getDatabase("test") - .getCollection("users"); - List<String> documentIds = new ArrayList<>(); - Flux.from(usersCollection.find()) - .map(doc -> documentIds.add(doc.get("_id").toString())) - .collectList() - .block(); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - String findQuery = "{\n" + - " \"find\": \"users\",\n" + - " \"filter\": {\n" + - " \"_id\": {\n" + - " $in: {{Input1.text}}\n" + - " }\n" + - " }\n" + - "}"; - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - StringBuilder sb = new StringBuilder(); - documentIds.stream() - .forEach(id -> sb.append(" \"ObjectId(\\\"" + id + "\\\")\",")); - sb.setLength(sb.length() - 1); - String objectIdsAsArray = "[" + sb + "]"; - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, findQuery); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue(objectIdsAsArray); - params.add(param1); - executeActionDTO.setParams(params); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(3, ((ArrayNode) result.getBody()).size()); - }) - .verifyComplete(); - - } - - @Test - public void testSmartSubstitutionWithObjectIdInSingleQuotes() { - final MongoCollection<Document> usersCollection = mongoClient.getDatabase("test") - .getCollection("users"); - List<String> documentIds = new ArrayList<>(); - Flux.from(usersCollection.find()) - .map(doc -> documentIds.add(doc.get("_id").toString())) - .collectList() - .block(); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - String findQuery = "{\n" + - " \"find\": \"users\",\n" + - " \"filter\": {\n" + - " \"_id\": {\n" + - " $in: {{Input1.text}}\n" + - " }\n" + - " }\n" + - "}"; - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - StringBuilder sb = new StringBuilder(); - documentIds.stream() - .forEach(id -> sb.append(" \'ObjectId(\\\"" + id + "\\\")\',")); - sb.setLength(sb.length() - 1); - String objectIdsAsArray = "[" + sb + "]"; - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, findQuery); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue(objectIdsAsArray); - param1.setClientDataType(ClientDataType.ARRAY); - param1.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); - params.add(param1); - executeActionDTO.setParams(params); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(3, ((ArrayNode) result.getBody()).size()); - }) - .verifyComplete(); - - } - - @Test - public void testFormToNativeQueryConversionForFindCommand() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); - setDataValueSafelyInFormData(configMap, FIND_QUERY, "{{Input1.text}}"); - setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: 1 }"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("{ age: { \"$gte\": 30 } }"); - params.add(param1); - executeActionDTO.setParams(params); - - pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, - getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, - dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(2, ((ArrayNode) result.getBody()).size()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - } - - @Test - public void testFormToNativeQueryConversionForInsertCommand() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input1.text}}"); - setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, - "[{name : \"ZZZ Insert Form Array Test 1\", gender : " + - "\"F\", age : 40, tag : \"test\"}, {name : \"ZZZ Insert Form Array Test 2\", gender : \"F\", age : " - + - "40, tag : \"test\"}]"); - - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("users"); - params.add(param1); - executeActionDTO.setParams(params); - - pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, - getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - - // Clean up this newly inserted value - configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{\"tag\" : \"test\"}"); - setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); - - actionConfiguration.setFormData(configMap); - // Run the delete command - dsConnectionMono.flatMap( - conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, - actionConfiguration)) - .block(); - } - - @Test - public void testFormToNativeQueryConversionForUpdateCommand() { - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - // Query for all the documents in the collection - setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{}"); - setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "{{Input1.text}}"); - setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "ALL"); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("{ $set: { \"updatedByCommand\": false }}"); - params.add(param1); - executeActionDTO.setParams(params); - - pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, - getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); - assertEquals("3", value.asText()); - assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) - .toString(), - result.getDataTypes().toString()); - }) - .verifyComplete(); - } - - @Test - public void testFormToNativeQueryConversionForDeleteCommand() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - // Insert multiple documents which would match the delete criterion - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, INSERT_DOCUMENT, - "[{\"name\" : \"To Delete1\", \"tag\" : \"delete\"}, " + - "{\"name\" : \"To Delete2\", \"tag\" : \"delete\"}]"); - - actionConfiguration.setFormData(configMap); - - dsConnectionMono.flatMap( - conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, - actionConfiguration)) - .block(); - - // Now that the documents have been inserted, lets delete both of them - configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{{Input1.text}}"); - setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); - setDataValueSafelyInFormData(configMap, BODY, ""); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("{tag : \"delete\"}"); - params.add(param1); - executeActionDTO.setParams(params); - - pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, - getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("n"); - assertEquals(value.asInt(), 2); - }) - .verifyComplete(); - } - - @Test - public void testFormToNativeQueryConversionForCountCommand() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "COUNT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input1.text}}"); - setDataValueSafelyInFormData(configMap, COUNT_QUERY, "{}"); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("users"); - params.add(param1); - executeActionDTO.setParams(params); - - pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, - getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ObjectNode) result.getBody()).get("n"); - assertEquals(value.asInt(), 3); - }) - .verifyComplete(); - } - - @Test - public void testFormToNativeQueryConversionForDistinctCommand() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "DISTINCT"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, DISTINCT_QUERY, "{}"); - setDataValueSafelyInFormData(configMap, DISTINCT_KEY, "{{Input1.text}}"); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("name"); - params.add(param1); - executeActionDTO.setParams(params); - - pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, - getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", - STRING_TYPE)); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - ArrayNode valuesNode = (ArrayNode) ((ObjectNode) result.getBody()) - .get("values"); - int valuesSize = valuesNode.size(); - assertEquals(valuesSize, 3); - }) - .verifyComplete(); - } - - @Test - public void testFormToNativeQueryConversionForAggregateCommand() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); - setDataValueSafelyInFormData(configMap, COMMAND, "AGGREGATE"); - setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, AGGREGATE_PIPELINES, "{{Input1.text}}"); - actionConfiguration.setFormData(configMap); - - pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, - getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("[ {$sort :{ _id : 1 }}, { $project: { age : 1}}, {$count: \"userCount\"} ]"); - params.add(param1); - executeActionDTO.setParams(params); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - JsonNode value = ((ArrayNode) result.getBody()).get(0).get("userCount"); - assertEquals(value.asInt(), 3); - }) - .verifyComplete(); - } - - @Test - public void testSmartSubstitutionWithMongoTypesWithRawCommand1() { - final MongoCollection<Document> usersCollection = mongoClient.getDatabase("test") - .getCollection("users"); - List<String> documentIds = new ArrayList<>(); - Flux.from(usersCollection.find()) - .filter(doc -> doc.containsKey("aLong")) - .map(doc -> documentIds.add(doc.get("_id").toString())) - .collectList() - .block(); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - final String findQuery = "" + - "{\n" + - " \"find\": \"users\",\n" + - " \"filter\": {\n" + - " \"_id\":{ $in: {{Input0}} },\n" + - " \"dob\":{ $in: {{Input1}} },\n" + - " \"netWorth\":{ $in: {{Input2}} },\n" + - " \"aLong\": {{Input3}},\n" + - " \"ts\":{ $in: {{Input4}} },\n" + - " },\n" + - "}"; - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, findQuery); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - final List<Param> params = new ArrayList<>(); - final Param id = new Param("Input0", "[\"ObjectId('" + documentIds.get(0) + "')\"]"); - id.setClientDataType(ClientDataType.ARRAY); - id.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); - params.add(id); - final Param dob = new Param("Input1", "[\"ISODate('1970-01-01T00:00:00.000Z')\"]"); - dob.setClientDataType(ClientDataType.ARRAY); - dob.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); - params.add(dob); - final Param netWorth = new Param("Input2", "['NumberDecimal(\"123456.789012\")']"); - netWorth.setClientDataType(ClientDataType.ARRAY); - netWorth.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); - params.add(netWorth); - final Param aLong = new Param("Input3", "\"NumberLong(9000000000000000000)\""); - aLong.setClientDataType(ClientDataType.OBJECT); - params.add(aLong); - final Param ts = new Param("Input4", "[\"Timestamp(1421006159, 4)\"]"); - ts.setClientDataType(ClientDataType.ARRAY); - ts.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); - params.add(ts); - executeActionDTO.setParams(params); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(1, ((ArrayNode) result.getBody()).size()); - }) - .verifyComplete(); - } - - @Test - public void testBsonSmartSubstitutionWithMongoTypesWithFindCommand() { - DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); - setDataValueSafelyInFormData(configMap, FIND_QUERY, "\"{{Input1.text}}\""); - setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: {{Input2.text}} }"); - setDataValueSafelyInFormData(configMap, FIND_LIMIT, "{{Input3.text}}"); - setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input4.text}}"); - - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - List<Param> params = new ArrayList<>(); - Param param1 = new Param(); - param1.setKey("Input1.text"); - param1.setValue("{ " + - "\"dob\": { \"$gte\": \"ISODate('2000-01-01T00:00:00.000Z')\" }, " + - "\"netWorth\": { \"$in\": [\"NumberDecimal(123456.789012)\"] } " + - "}"); - param1.setClientDataType(ClientDataType.OBJECT); - params.add(param1); - Param param3 = new Param(); - param3.setKey("Input2.text"); - param3.setValue("1"); - param3.setClientDataType(ClientDataType.NUMBER); - params.add(param3); - Param param4 = new Param(); - param4.setKey("Input3.text"); - param4.setValue("10"); - param4.setClientDataType(ClientDataType.NUMBER); - params.add(param4); - Param param5 = new Param(); - param5.setKey("Input4.text"); - param5.setValue("users"); - param5.setClientDataType(ClientDataType.STRING); - params.add(param5); - executeActionDTO.setParams(params); - - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, - datasourceConfiguration, - actionConfiguration)); - - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(1, ((ArrayNode) result.getBody()).size()); - }) - .verifyComplete(); - } - - @Test - public void testSmartSubstitutionWithMongoTypes2() { - final MongoCollection<Document> usersCollection = mongoClient.getDatabase("test") - .getCollection("users"); - List<String> documentIds = new ArrayList<>(); - Flux.from(usersCollection.find()) - .filter(doc -> doc.containsKey("aLong")) - .map(doc -> documentIds.add(doc.get("_id").toString())) - .collectList() - .block(); - - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - final String findQuery = "" + - "{\n" + - " \"find\": \"users\",\n" + - " \"filter\": {\n" + - " \"_id\": {{Input0}},\n" + - " \"dob\": {{Input1}},\n" + - " \"netWorth\": {{Input2}},\n" + - " \"aLong\": {{Input3}},\n" + - " \"ts\": {{Input4}},\n" + - " },\n" + - "}"; - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, findQuery); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - final List<Param> params = new ArrayList<>(); - final Param id = new Param("Input0", "\"ObjectId(\\\"" + documentIds.get(0) + "\\\")\""); - params.add(id); - final Param dob = new Param("Input1", "\"ISODate(\\\"1970-01-01T00:00:00.000Z\\\")\""); - params.add(dob); - final Param netWorth = new Param("Input2", "\"NumberDecimal(\\\"123456.789012\\\")\""); - params.add(netWorth); - final Param aLong = new Param("Input3", "\"NumberLong(9000000000000000000)\""); - params.add(aLong); - final Param ts = new Param("Input4", "\"Timestamp(1421006159, 4)\""); - params.add(ts); - executeActionDTO.setParams(params); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(1, ((ArrayNode) result.getBody()).size()); - }) - .verifyComplete(); - } - - @Test - public void testSmartSubstitutionWithMongoTypes3() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - - final String findQuery = "" + - "{\n" + - " \"find\": \"users\",\n" + - " \"filter\": {{Input1}}\n" + - "}"; - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - - Map<String, Object> configMap = new HashMap<>(); - setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); - setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, findQuery); - actionConfiguration.setFormData(configMap); - - ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - final List<Param> params = new ArrayList<>(); - final Param dob = new Param("Input1", "{\"dob\": \"ISODate(\\\"1970-01-01T00:00:00.000Z\\\")\"}"); - params.add(dob); - executeActionDTO.setParams(params); - - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .assertNext(obj -> { - ActionExecutionResult result = (ActionExecutionResult) obj; - assertNotNull(result); - assertTrue(result.getIsExecutionSuccess()); - assertNotNull(result.getBody()); - assertEquals(1, ((ArrayNode) result.getBody()).size()); - }) - .verifyComplete(); - } + public void testFormToNativeQueryConversionForUpdateCommand() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + // Query for all the documents in the collection + setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{}"); + setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "{{Input1.text}}"); + setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "ALL"); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("{ $set: { \"updatedByCommand\": false }}"); + params.add(param1); + executeActionDTO.setParams(params); + + pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, BODY, getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); + assertEquals("3", value.asText()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + } + @Test + public void testFormToNativeQueryConversionForDeleteCommand() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + // Insert multiple documents which would match the delete criterion + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "INSERT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData( + configMap, + INSERT_DOCUMENT, + "[{\"name\" : \"To Delete1\", \"tag\" : \"delete\"}, " + + "{\"name\" : \"To Delete2\", \"tag\" : \"delete\"}]"); + + actionConfiguration.setFormData(configMap); + + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); + + // Now that the documents have been inserted, lets delete both of them + configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "DELETE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, DELETE_QUERY, "{{Input1.text}}"); + setDataValueSafelyInFormData(configMap, DELETE_LIMIT, "ALL"); + setDataValueSafelyInFormData(configMap, BODY, ""); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("{tag : \"delete\"}"); + params.add(param1); + executeActionDTO.setParams(params); + + pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, BODY, getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("n"); + assertEquals(value.asInt(), 2); + }) + .verifyComplete(); + } + + @Test + public void testFormToNativeQueryConversionForCountCommand() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "COUNT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input1.text}}"); + setDataValueSafelyInFormData(configMap, COUNT_QUERY, "{}"); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("users"); + params.add(param1); + executeActionDTO.setParams(params); + + pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, BODY, getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("n"); + assertEquals(value.asInt(), 3); + }) + .verifyComplete(); + } + + @Test + public void testFormToNativeQueryConversionForDistinctCommand() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "DISTINCT"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, DISTINCT_QUERY, "{}"); + setDataValueSafelyInFormData(configMap, DISTINCT_KEY, "{{Input1.text}}"); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("name"); + params.add(param1); + executeActionDTO.setParams(params); + + pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, BODY, getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + ArrayNode valuesNode = (ArrayNode) ((ObjectNode) result.getBody()).get("values"); + int valuesSize = valuesNode.size(); + assertEquals(valuesSize, 3); + }) + .verifyComplete(); + } + + @Test + public void testFormToNativeQueryConversionForAggregateCommand() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "AGGREGATE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + setDataValueSafelyInFormData(configMap, AGGREGATE_PIPELINES, "{{Input1.text}}"); + actionConfiguration.setFormData(configMap); + + pluginExecutor.extractAndSetNativeQueryFromFormData(actionConfiguration); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData( + configMap, BODY, getDataValueSafelyFromFormData(configMap, "misc.formToNativeQuery", STRING_TYPE)); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("[ {$sort :{ _id : 1 }}, { $project: { age : 1}}, {$count: \"userCount\"} ]"); + params.add(param1); + executeActionDTO.setParams(params); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ArrayNode) result.getBody()).get(0).get("userCount"); + assertEquals(value.asInt(), 3); + }) + .verifyComplete(); + } + + @Test + public void testSmartSubstitutionWithMongoTypesWithRawCommand1() { + final MongoCollection<Document> usersCollection = + mongoClient.getDatabase("test").getCollection("users"); + List<String> documentIds = new ArrayList<>(); + Flux.from(usersCollection.find()) + .filter(doc -> doc.containsKey("aLong")) + .map(doc -> documentIds.add(doc.get("_id").toString())) + .collectList() + .block(); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + final String findQuery = "" + "{\n" + + " \"find\": \"users\",\n" + + " \"filter\": {\n" + + " \"_id\":{ $in: {{Input0}} },\n" + + " \"dob\":{ $in: {{Input1}} },\n" + + " \"netWorth\":{ $in: {{Input2}} },\n" + + " \"aLong\": {{Input3}},\n" + + " \"ts\":{ $in: {{Input4}} },\n" + + " },\n" + + "}"; + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData(configMap, BODY, findQuery); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + final List<Param> params = new ArrayList<>(); + final Param id = new Param("Input0", "[\"ObjectId('" + documentIds.get(0) + "')\"]"); + id.setClientDataType(ClientDataType.ARRAY); + id.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); + params.add(id); + final Param dob = new Param("Input1", "[\"ISODate('1970-01-01T00:00:00.000Z')\"]"); + dob.setClientDataType(ClientDataType.ARRAY); + dob.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); + params.add(dob); + final Param netWorth = new Param("Input2", "['NumberDecimal(\"123456.789012\")']"); + netWorth.setClientDataType(ClientDataType.ARRAY); + netWorth.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); + params.add(netWorth); + final Param aLong = new Param("Input3", "\"NumberLong(9000000000000000000)\""); + aLong.setClientDataType(ClientDataType.OBJECT); + params.add(aLong); + final Param ts = new Param("Input4", "[\"Timestamp(1421006159, 4)\"]"); + ts.setClientDataType(ClientDataType.ARRAY); + ts.setDataTypesOfArrayElements(List.of(ClientDataType.OBJECT)); + params.add(ts); + executeActionDTO.setParams(params); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(1, ((ArrayNode) result.getBody()).size()); + }) + .verifyComplete(); + } + + @Test + public void testBsonSmartSubstitutionWithMongoTypesWithFindCommand() { + DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "FIND"); + setDataValueSafelyInFormData(configMap, FIND_QUERY, "\"{{Input1.text}}\""); + setDataValueSafelyInFormData(configMap, FIND_SORT, "{ id: {{Input2.text}} }"); + setDataValueSafelyInFormData(configMap, FIND_LIMIT, "{{Input3.text}}"); + setDataValueSafelyInFormData(configMap, COLLECTION, "{{Input4.text}}"); + + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + List<Param> params = new ArrayList<>(); + Param param1 = new Param(); + param1.setKey("Input1.text"); + param1.setValue("{ " + "\"dob\": { \"$gte\": \"ISODate('2000-01-01T00:00:00.000Z')\" }, " + + "\"netWorth\": { \"$in\": [\"NumberDecimal(123456.789012)\"] } " + + "}"); + param1.setClientDataType(ClientDataType.OBJECT); + params.add(param1); + Param param3 = new Param(); + param3.setKey("Input2.text"); + param3.setValue("1"); + param3.setClientDataType(ClientDataType.NUMBER); + params.add(param3); + Param param4 = new Param(); + param4.setKey("Input3.text"); + param4.setValue("10"); + param4.setClientDataType(ClientDataType.NUMBER); + params.add(param4); + Param param5 = new Param(); + param5.setKey("Input4.text"); + param5.setValue("users"); + param5.setClientDataType(ClientDataType.STRING); + params.add(param5); + executeActionDTO.setParams(params); + + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized( + conn, executeActionDTO, datasourceConfiguration, actionConfiguration)); + + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(1, ((ArrayNode) result.getBody()).size()); + }) + .verifyComplete(); + } + + @Test + public void testSmartSubstitutionWithMongoTypes2() { + final MongoCollection<Document> usersCollection = + mongoClient.getDatabase("test").getCollection("users"); + List<String> documentIds = new ArrayList<>(); + Flux.from(usersCollection.find()) + .filter(doc -> doc.containsKey("aLong")) + .map(doc -> documentIds.add(doc.get("_id").toString())) + .collectList() + .block(); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + final String findQuery = "" + "{\n" + + " \"find\": \"users\",\n" + + " \"filter\": {\n" + + " \"_id\": {{Input0}},\n" + + " \"dob\": {{Input1}},\n" + + " \"netWorth\": {{Input2}},\n" + + " \"aLong\": {{Input3}},\n" + + " \"ts\": {{Input4}},\n" + + " },\n" + + "}"; + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData(configMap, BODY, findQuery); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + final List<Param> params = new ArrayList<>(); + final Param id = new Param("Input0", "\"ObjectId(\\\"" + documentIds.get(0) + "\\\")\""); + params.add(id); + final Param dob = new Param("Input1", "\"ISODate(\\\"1970-01-01T00:00:00.000Z\\\")\""); + params.add(dob); + final Param netWorth = new Param("Input2", "\"NumberDecimal(\\\"123456.789012\\\")\""); + params.add(netWorth); + final Param aLong = new Param("Input3", "\"NumberLong(9000000000000000000)\""); + params.add(aLong); + final Param ts = new Param("Input4", "\"Timestamp(1421006159, 4)\""); + params.add(ts); + executeActionDTO.setParams(params); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(1, ((ArrayNode) result.getBody()).size()); + }) + .verifyComplete(); + } + + @Test + public void testSmartSubstitutionWithMongoTypes3() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + + final String findQuery = "" + "{\n" + " \"find\": \"users\",\n" + " \"filter\": {{Input1}}\n" + "}"; + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); + setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); + setDataValueSafelyInFormData(configMap, BODY, findQuery); + actionConfiguration.setFormData(configMap); + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + final List<Param> params = new ArrayList<>(); + final Param dob = new Param("Input1", "{\"dob\": \"ISODate(\\\"1970-01-01T00:00:00.000Z\\\")\"}"); + params.add(dob); + executeActionDTO.setParams(params); + + Mono<Object> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + assertEquals(1, ((ArrayNode) result.getBody()).size()); + }) + .verifyComplete(); + } } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginQueriesTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginQueriesTest.java index 9919dc0785b0..b4817987e04f 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginQueriesTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginQueriesTest.java @@ -1,5 +1,37 @@ package com.external.plugins; +import com.appsmith.external.dtos.ExecuteActionDTO; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; +import com.appsmith.external.helpers.PluginUtils; +import com.appsmith.external.models.ActionConfiguration; +import com.appsmith.external.models.ActionExecutionResult; +import com.appsmith.external.models.Connection; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.Endpoint; +import com.appsmith.external.models.ParsedDataType; +import com.appsmith.external.models.RequestParamDTO; +import com.appsmith.external.models.SSLDetails; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.mongodb.reactivestreams.client.MongoClient; +import com.mongodb.reactivestreams.client.MongoClients; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static com.appsmith.external.constants.ActionConstants.ACTION_CONFIGURATION_BODY; import static com.appsmith.external.constants.DisplayDataType.JSON; import static com.appsmith.external.constants.DisplayDataType.RAW; @@ -29,45 +61,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -import com.appsmith.external.dtos.ExecuteActionDTO; -import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; -import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; -import com.appsmith.external.helpers.PluginUtils; -import com.appsmith.external.models.ActionConfiguration; -import com.appsmith.external.models.ActionExecutionResult; -import com.appsmith.external.models.Connection; -import com.appsmith.external.models.DatasourceConfiguration; -import com.appsmith.external.models.DatasourceStructure; -import com.appsmith.external.models.Endpoint; -import com.appsmith.external.models.ParsedDataType; -import com.appsmith.external.models.RequestParamDTO; -import com.appsmith.external.models.SSLDetails; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.mongodb.reactivestreams.client.MongoClient; -import com.mongodb.reactivestreams.client.MongoClients; - -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - /** * Unit tests for MongoPlugin */ - @Testcontainers public class MongoPluginQueriesTest { MongoPlugin.MongoPluginExecutor pluginExecutor = new MongoPlugin.MongoPluginExecutor(); @@ -87,7 +83,6 @@ public static void setUp() { port = mongoContainer.getFirstMappedPort(); String uri = "mongodb://" + address + ":" + port; mongoClient = MongoClients.create(uri); - } private DatasourceConfiguration createDatasourceConfiguration() { @@ -109,8 +104,6 @@ private DatasourceConfiguration createDatasourceConfiguration() { return dsConfig; } - - /** * Test for DBRef after codec implementation */ @@ -124,13 +117,12 @@ public void testExecuteQueryDBRef() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"address\",\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, BODY, "{\n" + " find: \"address\",\n" + " limit: 10,\n" + " }"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -154,12 +146,10 @@ public void testExecuteQueryDBRef() { } catch (JsonProcessingException e) { assert false; } - }) .verifyComplete(); } - @Test public void testExecuteReadQuery() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); @@ -170,15 +160,18 @@ public void testExecuteReadQuery() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " filter: { \"age\": { \"$gte\": 30 } },\n" + - " sort: { id: 1 },\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " find: \"users\",\n" + + " filter: { \"age\": { \"$gte\": 30 } },\n" + + " sort: { id: 1 },\n" + + " limit: 10,\n" + + " }"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -188,18 +181,22 @@ public void testExecuteReadQuery() { assertNotNull(result.getBody()); assertEquals(2, ((ArrayNode) result.getBody()).size()); assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), - result.getDataTypes().toString() - ); - + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); /* * - RequestParamDTO object only have attributes configProperty and value at this point. * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), BODY, OBJECT_TYPE), null, null, null)); + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), BODY, OBJECT_TYPE), + null, + null, + null)); assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -215,15 +212,18 @@ public void testExecuteInvalidReadQuery() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " filter: { $is: {} },\n" + - " sort: { id: 1 },\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " find: \"users\",\n" + + " filter: { $is: {} },\n" + + " sort: { id: 1 },\n" + + " limit: 10,\n" + + " }"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -231,7 +231,9 @@ public void testExecuteInvalidReadQuery() { assertNotNull(result); assertFalse(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - assertEquals("unknown top level operator: $is.", result.getPluginErrorDetails().getDownstreamErrorMessage()); + assertEquals( + "unknown top level operator: $is.", + result.getPluginErrorDetails().getDownstreamErrorMessage()); assertEquals(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR.getTitle(), result.getTitle()); /* @@ -239,8 +241,13 @@ public void testExecuteInvalidReadQuery() { * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - PluginUtils.getDataValueSafelyFromFormData(actionConfiguration.getFormData(), BODY, OBJECT_TYPE), null, null, null)); + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, + PluginUtils.getDataValueSafelyFromFormData( + actionConfiguration.getFormData(), BODY, OBJECT_TYPE), + null, + null, + null)); assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -256,20 +263,23 @@ public void testExecuteWriteQuery() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " insert: \"users\",\n" + - " documents: [\n" + - " {\n" + - " name: \"John Smith\",\n" + - " email: [\"[email protected]](mailto:%[email protected])\"],\n" + - " gender: \"M\",\n" + - " age: \"50\",\n" + - " },\n" + - " ],\n" + - " }"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " insert: \"users\",\n" + + " documents: [\n" + + " {\n" + + " name: \"John Smith\",\n" + + " email: [\"[email protected]](mailto:%[email protected])\"],\n" + + " gender: \"M\",\n" + + " age: \"50\",\n" + + " },\n" + + " ],\n" + + " }"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -278,9 +288,9 @@ public void testExecuteWriteQuery() { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), - result.getDataTypes().toString() - ); + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); }) .verifyComplete(); @@ -294,7 +304,10 @@ public void testExecuteWriteQuery() { actionConfiguration.setFormData(configMap); // Run the delete command - dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)).block(); + dsConnectionMono + .flatMap(conn -> pluginExecutor.executeParameterized( + conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)) + .block(); } @Test @@ -307,17 +320,20 @@ public void testFindAndModify() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " findAndModify: \"users\",\n" + - " query: " + - "{ " + - "name: \"Alden Cantrell\"" + - " },\n" + - " update: { $set: { gender: \"F\" }}\n" + - "}"); + setDataValueSafelyInFormData( + configMap, + BODY, + "{\n" + " findAndModify: \"users\",\n" + + " query: " + + "{ " + + "name: \"Alden Cantrell\"" + + " },\n" + + " update: { $set: { gender: \"F\" }}\n" + + "}"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -331,9 +347,9 @@ public void testFindAndModify() { assertEquals("Alden Cantrell", value.get("name").asText()); assertEquals(30, value.get("age").asInt()); assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), - result.getDataTypes().toString() - ); + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); }) .verifyComplete(); } @@ -348,13 +364,12 @@ public void testCleanUp() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"users\",\n" + - " limit: 1,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, BODY, "{\n" + " find: \"users\",\n" + " limit: 1,\n" + " }"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { @@ -370,9 +385,9 @@ public void testCleanUp() { assertEquals("2018-12-31T00:00:00Z", node.get("dob").asText()); assertEquals("123456.789012", node.get("netWorth").toString()); assertEquals( - List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), - result.getDataTypes().toString() - ); + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); }) .verifyComplete(); } @@ -381,196 +396,269 @@ public void testCleanUp() { @Test public void testStructure() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<DatasourceStructure> structureMono = pluginExecutor.datasourceCreate(dsConfig) + Mono<DatasourceStructure> structureMono = pluginExecutor + .datasourceCreate(dsConfig) .flatMap(connection -> pluginExecutor.getStructure(connection, dsConfig)); StepVerifier.create(structureMono) .assertNext(structure -> { - //Sort the Tables since one more table is added and to maintain sequence - structure.getTables().sort( - (DatasourceStructure.Table t1, DatasourceStructure.Table t2) - -> t2.getName().compareTo(t1.getName()) - ); + // Sort the Tables since one more table is added and to maintain sequence + structure + .getTables() + .sort((DatasourceStructure.Table t1, DatasourceStructure.Table t2) -> + t2.getName().compareTo(t1.getName())); assertNotNull(structure); assertEquals(3, structure.getTables().size()); // now there are three tables named <users, teams, address> - final DatasourceStructure.Table usersTable = structure.getTables().get(0); + final DatasourceStructure.Table usersTable = + structure.getTables().get(0); assertEquals("users", usersTable.getName()); assertEquals(DatasourceStructure.TableType.COLLECTION, usersTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("_id", "ObjectId", null, true), - new DatasourceStructure.Column("age", "Integer", null, false), - new DatasourceStructure.Column("dob", "Date", null, false), - new DatasourceStructure.Column("gender", "String", null, false), - new DatasourceStructure.Column("luckyNumber", "Long", null, false), - new DatasourceStructure.Column("name", "String", null, false), - new DatasourceStructure.Column("netWorth", "BigDecimal", null, false), - new DatasourceStructure.Column("updatedByCommand", "Object", null, false), + new DatasourceStructure.Column[] { + new DatasourceStructure.Column("_id", "ObjectId", null, true), + new DatasourceStructure.Column("age", "Integer", null, false), + new DatasourceStructure.Column("dob", "Date", null, false), + new DatasourceStructure.Column("gender", "String", null, false), + new DatasourceStructure.Column("luckyNumber", "Long", null, false), + new DatasourceStructure.Column("name", "String", null, false), + new DatasourceStructure.Column("netWorth", "BigDecimal", null, false), + new DatasourceStructure.Column("updatedByCommand", "Object", null, false), }, - usersTable.getColumns().toArray() - ); + usersTable.getColumns().toArray()); assertArrayEquals( - new DatasourceStructure.Key[]{}, - usersTable.getKeys().toArray() - ); + new DatasourceStructure.Key[] {}, + usersTable.getKeys().toArray()); List<DatasourceStructure.Template> templates = usersTable.getTemplates(); - //Assert Find command + // Assert Find command DatasourceStructure.Template findTemplate = templates.get(0); assertEquals("Find", findTemplate.getTitle()); - assertEquals("{\n" + - " \"find\": \"users\",\n" + - " \"filter\": {\n" + - " \"gender\": \"F\"\n" + - " },\n" + - " \"sort\": {\n" + - " \"_id\": 1\n" + - " },\n" + - " \"limit\": 10\n" + - "}\n", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) findTemplate.getConfiguration(), BODY, STRING_TYPE)); - assertEquals("FIND", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) findTemplate.getConfiguration(), COMMAND, STRING_TYPE)); - - assertEquals("{ \"gender\": \"F\"}", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) findTemplate.getConfiguration(), FIND_QUERY, STRING_TYPE)); - assertEquals("{\"_id\": 1}", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) findTemplate.getConfiguration(), FIND_SORT, STRING_TYPE)); - - //Assert Find By Id command + assertEquals( + "{\n" + " \"find\": \"users\",\n" + + " \"filter\": {\n" + + " \"gender\": \"F\"\n" + + " },\n" + + " \"sort\": {\n" + + " \"_id\": 1\n" + + " },\n" + + " \"limit\": 10\n" + + "}\n", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) findTemplate.getConfiguration(), BODY, STRING_TYPE)); + assertEquals( + "FIND", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) findTemplate.getConfiguration(), COMMAND, STRING_TYPE)); + + assertEquals( + "{ \"gender\": \"F\"}", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) findTemplate.getConfiguration(), FIND_QUERY, STRING_TYPE)); + assertEquals( + "{\"_id\": 1}", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) findTemplate.getConfiguration(), FIND_SORT, STRING_TYPE)); + + // Assert Find By Id command DatasourceStructure.Template findByIdTemplate = templates.get(1); assertEquals("Find by ID", findByIdTemplate.getTitle()); - assertEquals("{\n" + - " \"find\": \"users\",\n" + - " \"filter\": {\n" + - " \"_id\": ObjectId(\"id_to_query_with\")\n" + - " }\n" + - "}\n", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) findByIdTemplate.getConfiguration(), BODY, STRING_TYPE)); - assertEquals("FIND", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) findByIdTemplate.getConfiguration(), COMMAND, STRING_TYPE)); - assertEquals("{\"_id\": ObjectId(\"id_to_query_with\")}", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) findByIdTemplate.getConfiguration(), FIND_QUERY, STRING_TYPE)); + assertEquals( + "{\n" + " \"find\": \"users\",\n" + + " \"filter\": {\n" + + " \"_id\": ObjectId(\"id_to_query_with\")\n" + + " }\n" + + "}\n", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) findByIdTemplate.getConfiguration(), BODY, STRING_TYPE)); + assertEquals( + "FIND", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) findByIdTemplate.getConfiguration(), COMMAND, STRING_TYPE)); + assertEquals( + "{\"_id\": ObjectId(\"id_to_query_with\")}", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) findByIdTemplate.getConfiguration(), + FIND_QUERY, + STRING_TYPE)); // Assert Insert command DatasourceStructure.Template insertTemplate = templates.get(2); assertEquals("Insert", insertTemplate.getTitle()); - assertEquals("{\n" + - " \"insert\": \"users\",\n" + - " \"documents\": [\n" + - " {\n" + - " \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n" + - " \"age\": 1,\n" + - " \"dob\": new Date(\"2019-07-01\"),\n" + - " \"gender\": \"new value\",\n" + - " \"luckyNumber\": NumberLong(\"1\"),\n" + - " \"name\": \"new value\",\n" + - " \"netWorth\": NumberDecimal(\"1\"),\n" + - " \"updatedByCommand\": {},\n" + - " }\n" + - " ]\n" + - "}\n", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) insertTemplate.getConfiguration(), BODY, STRING_TYPE)); - assertEquals("INSERT", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) insertTemplate.getConfiguration(), COMMAND, STRING_TYPE)); - assertEquals("[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n" + - " \"age\": 1,\n" + - " \"dob\": new Date(\"2019-07-01\"),\n" + - " \"gender\": \"new value\",\n" + - " \"luckyNumber\": NumberLong(\"1\"),\n" + - " \"name\": \"new value\",\n" + - " \"netWorth\": NumberDecimal(\"1\"),\n" + - " \"updatedByCommand\": {},\n" + - "}]", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) insertTemplate.getConfiguration(), INSERT_DOCUMENT, STRING_TYPE)); + assertEquals( + "{\n" + " \"insert\": \"users\",\n" + + " \"documents\": [\n" + + " {\n" + + " \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n" + + " \"age\": 1,\n" + + " \"dob\": new Date(\"2019-07-01\"),\n" + + " \"gender\": \"new value\",\n" + + " \"luckyNumber\": NumberLong(\"1\"),\n" + + " \"name\": \"new value\",\n" + + " \"netWorth\": NumberDecimal(\"1\"),\n" + + " \"updatedByCommand\": {},\n" + + " }\n" + + " ]\n" + + "}\n", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) insertTemplate.getConfiguration(), BODY, STRING_TYPE)); + assertEquals( + "INSERT", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) insertTemplate.getConfiguration(), COMMAND, STRING_TYPE)); + assertEquals( + "[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n" + " \"age\": 1,\n" + + " \"dob\": new Date(\"2019-07-01\"),\n" + + " \"gender\": \"new value\",\n" + + " \"luckyNumber\": NumberLong(\"1\"),\n" + + " \"name\": \"new value\",\n" + + " \"netWorth\": NumberDecimal(\"1\"),\n" + + " \"updatedByCommand\": {},\n" + + "}]", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) insertTemplate.getConfiguration(), + INSERT_DOCUMENT, + STRING_TYPE)); // Assert Update command DatasourceStructure.Template updateTemplate = templates.get(3); assertEquals("Update", updateTemplate.getTitle()); - assertEquals("{\n" + - " \"update\": \"users\",\n" + - " \"updates\": [\n" + - " {\n" + - " \"q\": {\n" + - " \"_id\": ObjectId(\"id_of_document_to_update\")\n" + - " },\n" + - " \"u\": { \"$set\": { \"gender\": \"new value\" } }\n" + - " }\n" + - " ]\n" + - "}\n", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) updateTemplate.getConfiguration(), BODY, STRING_TYPE)); - assertEquals("UPDATE", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) updateTemplate.getConfiguration(), COMMAND, STRING_TYPE)); - assertEquals("{ \"_id\": ObjectId(\"id_of_document_to_update\") }", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) updateTemplate.getConfiguration(), UPDATE_QUERY, STRING_TYPE)); - assertEquals("{ \"$set\": { \"gender\": \"new value\" } }", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) updateTemplate.getConfiguration(), UPDATE_OPERATION, STRING_TYPE)); + assertEquals( + "{\n" + " \"update\": \"users\",\n" + + " \"updates\": [\n" + + " {\n" + + " \"q\": {\n" + + " \"_id\": ObjectId(\"id_of_document_to_update\")\n" + + " },\n" + + " \"u\": { \"$set\": { \"gender\": \"new value\" } }\n" + + " }\n" + + " ]\n" + + "}\n", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) updateTemplate.getConfiguration(), BODY, STRING_TYPE)); + assertEquals( + "UPDATE", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) updateTemplate.getConfiguration(), COMMAND, STRING_TYPE)); + assertEquals( + "{ \"_id\": ObjectId(\"id_of_document_to_update\") }", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) updateTemplate.getConfiguration(), + UPDATE_QUERY, + STRING_TYPE)); + assertEquals( + "{ \"$set\": { \"gender\": \"new value\" } }", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) updateTemplate.getConfiguration(), + UPDATE_OPERATION, + STRING_TYPE)); // Assert Delete Command DatasourceStructure.Template deleteTemplate = templates.get(4); assertEquals("Delete", deleteTemplate.getTitle()); - assertEquals("{\n" + - " \"delete\": \"users\",\n" + - " \"deletes\": [\n" + - " {\n" + - " \"q\": {\n" + - " \"_id\": \"id_of_document_to_delete\"\n" + - " },\n" + - " \"limit\": 1\n" + - " }\n" + - " ]\n" + - "}\n", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) deleteTemplate.getConfiguration(), BODY, STRING_TYPE)); - assertEquals("DELETE", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) deleteTemplate.getConfiguration(), COMMAND, STRING_TYPE)); - assertEquals("{ \"_id\": ObjectId(\"id_of_document_to_delete\") }", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) deleteTemplate.getConfiguration(), DELETE_QUERY, STRING_TYPE)); - assertEquals("SINGLE", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) deleteTemplate.getConfiguration(), DELETE_LIMIT, STRING_TYPE)); + assertEquals( + "{\n" + " \"delete\": \"users\",\n" + + " \"deletes\": [\n" + + " {\n" + + " \"q\": {\n" + + " \"_id\": \"id_of_document_to_delete\"\n" + + " },\n" + + " \"limit\": 1\n" + + " }\n" + + " ]\n" + + "}\n", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) deleteTemplate.getConfiguration(), BODY, STRING_TYPE)); + assertEquals( + "DELETE", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) deleteTemplate.getConfiguration(), COMMAND, STRING_TYPE)); + assertEquals( + "{ \"_id\": ObjectId(\"id_of_document_to_delete\") }", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) deleteTemplate.getConfiguration(), + DELETE_QUERY, + STRING_TYPE)); + assertEquals( + "SINGLE", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) deleteTemplate.getConfiguration(), + DELETE_LIMIT, + STRING_TYPE)); // Assert Count Command DatasourceStructure.Template countTemplate = templates.get(5); assertEquals("Count", countTemplate.getTitle()); - assertEquals("{\n" + - " \"count\": \"users\",\n" + - " \"query\": " + "{\"_id\": {\"$exists\": true}} \n" + - "}\n", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) countTemplate.getConfiguration(), BODY, STRING_TYPE)); - assertEquals("COUNT", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) countTemplate.getConfiguration(), COMMAND, STRING_TYPE)); - assertEquals("{\"_id\": {\"$exists\": true}}", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) countTemplate.getConfiguration(), COUNT_QUERY, STRING_TYPE)); + assertEquals( + "{\n" + " \"count\": \"users\",\n" + + " \"query\": " + + "{\"_id\": {\"$exists\": true}} \n" + "}\n", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) countTemplate.getConfiguration(), BODY, STRING_TYPE)); + assertEquals( + "COUNT", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) countTemplate.getConfiguration(), COMMAND, STRING_TYPE)); + assertEquals( + "{\"_id\": {\"$exists\": true}}", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) countTemplate.getConfiguration(), COUNT_QUERY, STRING_TYPE)); // Assert Distinct Command DatasourceStructure.Template distinctTemplate = templates.get(6); assertEquals("Distinct", distinctTemplate.getTitle()); - assertEquals("{\n" + - " \"distinct\": \"users\",\n" + - " \"query\": { \"_id\": ObjectId(\"id_of_document_to_distinct\") }," + - " \"key\": \"_id\"," + - "}\n", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) distinctTemplate.getConfiguration(), BODY, STRING_TYPE)); - assertEquals("DISTINCT", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) distinctTemplate.getConfiguration(), COMMAND, STRING_TYPE)); - assertEquals("{ \"_id\": ObjectId(\"id_of_document_to_distinct\") }", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) distinctTemplate.getConfiguration(), DISTINCT_QUERY, STRING_TYPE)); - assertEquals("_id", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) distinctTemplate.getConfiguration(), DISTINCT_KEY, STRING_TYPE)); + assertEquals( + "{\n" + " \"distinct\": \"users\",\n" + + " \"query\": { \"_id\": ObjectId(\"id_of_document_to_distinct\") }," + + " \"key\": \"_id\"," + + "}\n", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) distinctTemplate.getConfiguration(), BODY, STRING_TYPE)); + assertEquals( + "DISTINCT", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) distinctTemplate.getConfiguration(), COMMAND, STRING_TYPE)); + assertEquals( + "{ \"_id\": ObjectId(\"id_of_document_to_distinct\") }", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) distinctTemplate.getConfiguration(), + DISTINCT_QUERY, + STRING_TYPE)); + assertEquals( + "_id", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) distinctTemplate.getConfiguration(), + DISTINCT_KEY, + STRING_TYPE)); // Assert Aggregate Command DatasourceStructure.Template aggregateTemplate = templates.get(7); assertEquals("Aggregate", aggregateTemplate.getTitle()); - assertEquals("{\n" + - " \"aggregate\": \"users\",\n" + - " \"pipeline\": " + "[ {\"$sort\" : {\"_id\": 1} } ],\n" + - " \"limit\": 10,\n" + - " \"explain\": \"true\"\n" + - "}\n", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) aggregateTemplate.getConfiguration(), BODY, STRING_TYPE)); - - assertEquals("AGGREGATE", PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) aggregateTemplate.getConfiguration(), COMMAND, STRING_TYPE)); - assertEquals("[ {\"$sort\" : {\"_id\": 1} } ]", - PluginUtils.getDataValueSafelyFromFormData((Map<String, Object>) aggregateTemplate.getConfiguration(), AGGREGATE_PIPELINES, STRING_TYPE)); - + assertEquals( + "{\n" + " \"aggregate\": \"users\",\n" + + " \"pipeline\": " + + "[ {\"$sort\" : {\"_id\": 1} } ],\n" + " \"limit\": 10,\n" + + " \"explain\": \"true\"\n" + + "}\n", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) aggregateTemplate.getConfiguration(), BODY, STRING_TYPE)); + assertEquals( + "AGGREGATE", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) aggregateTemplate.getConfiguration(), COMMAND, STRING_TYPE)); + assertEquals( + "[ {\"$sort\" : {\"_id\": 1} } ]", + PluginUtils.getDataValueSafelyFromFormData( + (Map<String, Object>) aggregateTemplate.getConfiguration(), + AGGREGATE_PIPELINES, + STRING_TYPE)); }) .verifyComplete(); } - - - @Test public void testCountCommand() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); @@ -586,7 +674,8 @@ public void testCountCommand() { actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -615,7 +704,8 @@ public void testDistinctCommand() { actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -640,12 +730,14 @@ public void testAggregateCommand() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); setDataValueSafelyInFormData(configMap, COMMAND, "AGGREGATE"); setDataValueSafelyInFormData(configMap, COLLECTION, "users"); - setDataValueSafelyInFormData(configMap, AGGREGATE_PIPELINES, "[ {$sort :{ _id : 1 }}, { $project: { age : 1}}]"); + setDataValueSafelyInFormData( + configMap, AGGREGATE_PIPELINES, "[ {$sort :{ _id : 1 }}, { $project: { age : 1}}]"); setDataValueSafelyInFormData(configMap, AGGREGATE_LIMIT, "2"); actionConfiguration.setFormData(configMap); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -658,8 +750,6 @@ public void testAggregateCommand() { .verifyComplete(); } - - @Test public void testFindCommandProjection() { ActionConfiguration actionConfiguration = new ActionConfiguration(); @@ -676,7 +766,8 @@ public void testFindCommandProjection() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -689,9 +780,4 @@ public void testFindCommandProjection() { }) .verifyComplete(); } - - - - - } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginRegexTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginRegexTest.java index 51757087335e..782bf80fb451 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginRegexTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginRegexTest.java @@ -1,25 +1,5 @@ package com.external.plugins; -import static com.appsmith.external.constants.DisplayDataType.JSON; -import static com.appsmith.external.constants.DisplayDataType.RAW; -import static com.appsmith.external.helpers.PluginUtils.setDataValueSafelyInFormData; -import static com.external.plugins.constants.FieldName.BODY; -import static com.external.plugins.constants.FieldName.COMMAND; -import static com.external.plugins.constants.FieldName.SMART_SUBSTITUTION; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - import com.appsmith.external.dtos.ExecuteActionDTO; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionResult; @@ -33,14 +13,31 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; - +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.appsmith.external.constants.DisplayDataType.JSON; +import static com.appsmith.external.constants.DisplayDataType.RAW; +import static com.appsmith.external.helpers.PluginUtils.setDataValueSafelyInFormData; +import static com.external.plugins.constants.FieldName.BODY; +import static com.external.plugins.constants.FieldName.COMMAND; +import static com.external.plugins.constants.FieldName.SMART_SUBSTITUTION; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Unit tests for MongoPlugin */ - @Testcontainers public class MongoPluginRegexTest { MongoPlugin.MongoPluginExecutor pluginExecutor = new MongoPlugin.MongoPluginExecutor(); @@ -60,7 +57,6 @@ public static void setUp() { port = mongoContainer.getFirstMappedPort(); String uri = "mongodb://" + address + ":" + port; mongoClient = MongoClients.create(uri); - } private DatasourceConfiguration createDatasourceConfiguration() { @@ -82,8 +78,6 @@ private DatasourceConfiguration createDatasourceConfiguration() { return dsConfig; } - - @Test public void testRegexStringQueryWithSmartSubstitution() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); @@ -96,30 +90,28 @@ public void testRegexStringQueryWithSmartSubstitution() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - - String rawFind = "{ find: \"users\", \n " + - "filter: {\"name\":{$regex: \"{{appsmith.store.variable}}\"}}}"; + String rawFind = "{ find: \"users\", \n " + "filter: {\"name\":{$regex: \"{{appsmith.store.variable}}\"}}}"; setDataValueSafelyInFormData(configMap, BODY, rawFind); actionConfiguration.setFormData(configMap); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(List.of(new Param("appsmith.store.variable", "[a-zA-Z]{0,3}.*Ci.*"))); - Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> pluginExecutor.executeParameterized(clientConnection, - executeActionDTO, - dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> + pluginExecutor.executeParameterized(clientConnection, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { assertNotNull(actionExecutionResult); assertTrue(actionExecutionResult.getIsExecutionSuccess()); assertEquals(1, ((ArrayNode) actionExecutionResult.getBody()).size()); - assertEquals(List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), actionExecutionResult.getDataTypes().toString()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + actionExecutionResult.getDataTypes().toString()); }) .verifyComplete(); } - @Test public void testRegexNumberQueryWithSmartSubstitution() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); @@ -132,25 +124,26 @@ public void testRegexNumberQueryWithSmartSubstitution() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - String rawFind = "{ find: \"teams\", \n " + - "filter: {\"goals_allowed\":{$regex: \"{{appsmith.store.variable}}\"}}}"; + String rawFind = + "{ find: \"teams\", \n " + "filter: {\"goals_allowed\":{$regex: \"{{appsmith.store.variable}}\"}}}"; setDataValueSafelyInFormData(configMap, BODY, rawFind); actionConfiguration.setFormData(configMap); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(List.of(new Param("appsmith.store.variable", "35"))); - Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> pluginExecutor.executeParameterized(clientConnection, - executeActionDTO, - dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> + pluginExecutor.executeParameterized(clientConnection, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { assertNotNull(actionExecutionResult); assertTrue(actionExecutionResult.getIsExecutionSuccess()); assertEquals(1, ((ArrayNode) actionExecutionResult.getBody()).size()); - assertEquals(List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), actionExecutionResult.getDataTypes().toString()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + actionExecutionResult.getDataTypes().toString()); }) .verifyComplete(); } @@ -167,26 +160,26 @@ public void testRegexStringWithNumbersQueryWithSmartSubstitution() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - - String rawFind = "{ find: \"teams\", \n " + - "filter: {\"best_scoreline\":{$regex: \"{{appsmith.store.variable}}\"}}}"; + String rawFind = + "{ find: \"teams\", \n " + "filter: {\"best_scoreline\":{$regex: \"{{appsmith.store.variable}}\"}}}"; setDataValueSafelyInFormData(configMap, BODY, rawFind); actionConfiguration.setFormData(configMap); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(List.of(new Param("appsmith.store.variable", "5-.*"))); - Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> pluginExecutor.executeParameterized(clientConnection, - executeActionDTO, - dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> + pluginExecutor.executeParameterized(clientConnection, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { assertNotNull(actionExecutionResult); assertTrue(actionExecutionResult.getIsExecutionSuccess()); System.out.println(actionExecutionResult.getBody()); assertEquals(1, ((ArrayNode) actionExecutionResult.getBody()).size()); - assertEquals(List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), actionExecutionResult.getDataTypes().toString()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + actionExecutionResult.getDataTypes().toString()); }) .verifyComplete(); } @@ -203,31 +196,30 @@ public void testRegexNegativeNumbersQueryWithSmartSubstitution() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - - String rawFind = "{ find: \"teams\", \n " + - "filter: {\"goal_difference\":{$regex: \"{{appsmith.store.variable}}\"}}}"; + String rawFind = + "{ find: \"teams\", \n " + "filter: {\"goal_difference\":{$regex: \"{{appsmith.store.variable}}\"}}}"; setDataValueSafelyInFormData(configMap, BODY, rawFind); actionConfiguration.setFormData(configMap); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(List.of(new Param("appsmith.store.variable", "-7"))); - Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> pluginExecutor.executeParameterized(clientConnection, - executeActionDTO, - dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> + pluginExecutor.executeParameterized(clientConnection, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { assertNotNull(actionExecutionResult); assertTrue(actionExecutionResult.getIsExecutionSuccess()); System.out.println(actionExecutionResult.getBody()); assertEquals(1, ((ArrayNode) actionExecutionResult.getBody()).size()); - assertEquals(List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), actionExecutionResult.getDataTypes().toString()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + actionExecutionResult.getDataTypes().toString()); }) .verifyComplete(); } - @Test public void testRegexNegativeDecimalNumberQueryWithSmartSubstitution() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); @@ -240,28 +232,26 @@ public void testRegexNegativeDecimalNumberQueryWithSmartSubstitution() { setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - - String rawFind = "{ find: \"teams\", \n " + - "filter: {\"xGD\":{$regex: \"{{appsmith.store.variable}}\"}}}"; + String rawFind = "{ find: \"teams\", \n " + "filter: {\"xGD\":{$regex: \"{{appsmith.store.variable}}\"}}}"; setDataValueSafelyInFormData(configMap, BODY, rawFind); actionConfiguration.setFormData(configMap); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setParams(List.of(new Param("appsmith.store.variable", "-2.5"))); - Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> pluginExecutor.executeParameterized(clientConnection, - executeActionDTO, - dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = dsConnectionMono.flatMap(clientConnection -> + pluginExecutor.executeParameterized(clientConnection, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { assertNotNull(actionExecutionResult); assertTrue(actionExecutionResult.getIsExecutionSuccess()); System.out.println(actionExecutionResult.getBody()); assertEquals(1, ((ArrayNode) actionExecutionResult.getBody()).size()); - assertEquals(List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)).toString(), actionExecutionResult.getDataTypes().toString()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + actionExecutionResult.getDataTypes().toString()); }) .verifyComplete(); } - } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginStaleConnTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginStaleConnTest.java index b34e8f0d38d6..a6fdb5d44cd6 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginStaleConnTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginStaleConnTest.java @@ -1,25 +1,5 @@ package com.external.plugins; -import static com.appsmith.external.helpers.PluginUtils.setDataValueSafelyInFormData; -import static com.external.plugins.constants.FieldName.BODY; -import static com.external.plugins.constants.FieldName.COMMAND; -import static com.external.plugins.constants.FieldName.SMART_SUBSTITUTION; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.spy; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionResult; @@ -33,14 +13,31 @@ import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoDatabase; - +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.appsmith.external.helpers.PluginUtils.setDataValueSafelyInFormData; +import static com.external.plugins.constants.FieldName.BODY; +import static com.external.plugins.constants.FieldName.COMMAND; +import static com.external.plugins.constants.FieldName.SMART_SUBSTITUTION; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; + /** * Unit tests for MongoPlugin */ - @Testcontainers public class MongoPluginStaleConnTest { MongoPlugin.MongoPluginExecutor pluginExecutor = new MongoPlugin.MongoPluginExecutor(); @@ -60,7 +57,6 @@ public static void setUp() { port = mongoContainer.getFirstMappedPort(); String uri = "mongodb://" + address + ":" + port; mongoClient = MongoClients.create(uri); - } private DatasourceConfiguration createDatasourceConfiguration() { @@ -82,8 +78,6 @@ private DatasourceConfiguration createDatasourceConfiguration() { return dsConfig; } - - @Test public void testStaleConnectionOnIllegalStateExceptionOnQueryExecution() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); @@ -91,10 +85,8 @@ public void testStaleConnectionOnIllegalStateExceptionOnQueryExecution() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"address\",\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, BODY, "{\n" + " find: \"address\",\n" + " limit: 10,\n" + " }"); actionConfiguration.setFormData(configMap); MongoClient spyMongoClient = spy(MongoClient.class); @@ -102,8 +94,8 @@ public void testStaleConnectionOnIllegalStateExceptionOnQueryExecution() { doReturn(spyMongoDatabase).when(spyMongoClient).getDatabase(anyString()); doReturn(Mono.error(new IllegalStateException())).when(spyMongoDatabase).runCommand(any()); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeCommon(spyMongoClient, dsConfig, - actionConfiguration, new ArrayList<>()); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeCommon(spyMongoClient, dsConfig, actionConfiguration, new ArrayList<>()); StepVerifier.create(resultMono) .expectErrorMatches(throwable -> throwable instanceof StaleConnectionException) .verify(); @@ -116,19 +108,19 @@ public void testStaleConnectionOnMongoSocketWriteExceptionOnQueryExecution() { Map<String, Object> configMap = new HashMap<>(); setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.TRUE); setDataValueSafelyInFormData(configMap, COMMAND, "RAW"); - setDataValueSafelyInFormData(configMap, BODY, "{\n" + - " find: \"address\",\n" + - " limit: 10,\n" + - " }"); + setDataValueSafelyInFormData( + configMap, BODY, "{\n" + " find: \"address\",\n" + " limit: 10,\n" + " }"); actionConfiguration.setFormData(configMap); MongoClient spyMongoClient = spy(MongoClient.class); MongoDatabase spyMongoDatabase = spy(MongoDatabase.class); doReturn(spyMongoDatabase).when(spyMongoClient).getDatabase(anyString()); - doReturn(Mono.error(new MongoSocketWriteException("", null, null))).when(spyMongoDatabase).runCommand(any()); + doReturn(Mono.error(new MongoSocketWriteException("", null, null))) + .when(spyMongoDatabase) + .runCommand(any()); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeCommon(spyMongoClient, dsConfig, - actionConfiguration, new ArrayList<>()); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeCommon(spyMongoClient, dsConfig, actionConfiguration, new ArrayList<>()); StepVerifier.create(resultMono) .expectErrorMatches(throwable -> throwable instanceof StaleConnectionException) .verify(); @@ -153,7 +145,9 @@ public void testStaleConnectionOnMongoSocketWriteExceptionOnGetStructure() { MongoClient spyMongoClient = spy(MongoClient.class); MongoDatabase spyMongoDatabase = spy(MongoDatabase.class); doReturn(spyMongoDatabase).when(spyMongoClient).getDatabase(anyString()); - doReturn(Mono.error(new MongoSocketWriteException("", null, null))).when(spyMongoDatabase).listCollectionNames(); + doReturn(Mono.error(new MongoSocketWriteException("", null, null))) + .when(spyMongoDatabase) + .listCollectionNames(); DatasourceConfiguration dsConfig = createDatasourceConfiguration(); Mono<DatasourceStructure> structureMono = pluginExecutor.getStructure(spyMongoClient, dsConfig); @@ -161,6 +155,4 @@ public void testStaleConnectionOnMongoSocketWriteExceptionOnGetStructure() { .expectErrorMatches(throwable -> throwable instanceof StaleConnectionException) .verify(); } - - } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoTestContainer.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoTestContainer.java index 4019ca9129e7..7893b993a45b 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoTestContainer.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoTestContainer.java @@ -1,113 +1,120 @@ package com.external.plugins; -import java.math.BigDecimal; -import java.sql.Date; -import java.time.LocalDate; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -import org.bson.Document; -import org.bson.types.BSONTimestamp; -import org.bson.types.Decimal128; -import org.testcontainers.containers.GenericContainer; - import com.github.dockerjava.api.command.InspectContainerResponse; import com.mongodb.DBRef; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoCollection; - +import org.bson.Document; +import org.bson.types.BSONTimestamp; +import org.bson.types.Decimal128; +import org.testcontainers.containers.GenericContainer; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -public class MongoTestContainer extends GenericContainer { +import java.math.BigDecimal; +import java.sql.Date; +import java.time.LocalDate; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; - private static MongoClient mongoClient; +public class MongoTestContainer extends GenericContainer { - public MongoTestContainer() { - super(CompletableFuture.completedFuture("mongo:4.4")); - addExposedPorts(27017); - } + private static MongoClient mongoClient; - /* - * this is overridden to prepare Mongo with sample dataset after the test container is started - */ - @Override - protected void containerIsStarted(InspectContainerResponse containerInfo) { + public MongoTestContainer() { + super(CompletableFuture.completedFuture("mongo:4.4")); + addExposedPorts(27017); + } - String uri = "mongodb://" + getHost() + ":" + getFirstMappedPort(); - mongoClient = MongoClients.create(uri); + /* + * this is overridden to prepare Mongo with sample dataset after the test container is started + */ + @Override + protected void containerIsStarted(InspectContainerResponse containerInfo) { - Flux.from(mongoClient.getDatabase("test").listCollectionNames()).collectList() - .flatMap(collectionNamesList -> { - if (collectionNamesList.size() == 0) { - final MongoCollection<Document> usersCollection = mongoClient - .getDatabase("test").getCollection( - "users"); - Mono.from(usersCollection.insertMany(List.of( - new Document(Map.of( - "name", "Cierra Vega", - "gender", "F", - "age", 20, - "luckyNumber", 987654321L, - "dob", LocalDate.of(2018, 12, 31), - "netWorth", - new BigDecimal("123456.789012"), - "updatedByCommand", false)), - new Document(Map.of( - "name", "Alden Cantrell", - "gender", "M", - "age", 30, - "dob", new Date(0), - "netWorth", - Decimal128.parse("123456.789012"), - "updatedByCommand", false, - "aLong", 9_000_000_000_000_000_000L, - "ts", - new BSONTimestamp(1421006159, 4))), - new Document(Map.of("name", "Kierra Gentry", "gender", - "F", "age", 40))))) - .block(); + String uri = "mongodb://" + getHost() + ":" + getFirstMappedPort(); + mongoClient = MongoClients.create(uri); - final MongoCollection<Document> addressCollection = mongoClient - .getDatabase("test") - .getCollection("address"); - Mono.from(addressCollection.insertMany(List.of( - new Document(Map.of( - "user", new DBRef("test", "users", "1"), - "street", "First Street", - "city", "Line One", - "state", "UP")), - new Document(Map.of( - "user", new DBRef("AAA", "BBB", "2000"), - "street", "Second Street", - "city", "Line Two", - "state", "UP"))))) - .block(); + Flux.from(mongoClient.getDatabase("test").listCollectionNames()) + .collectList() + .flatMap(collectionNamesList -> { + if (collectionNamesList.size() == 0) { + final MongoCollection<Document> usersCollection = + mongoClient.getDatabase("test").getCollection("users"); + Mono.from(usersCollection.insertMany(List.of( + new Document(Map.of( + "name", + "Cierra Vega", + "gender", + "F", + "age", + 20, + "luckyNumber", + 987654321L, + "dob", + LocalDate.of(2018, 12, 31), + "netWorth", + new BigDecimal("123456.789012"), + "updatedByCommand", + false)), + new Document(Map.of( + "name", + "Alden Cantrell", + "gender", + "M", + "age", + 30, + "dob", + new Date(0), + "netWorth", + Decimal128.parse("123456.789012"), + "updatedByCommand", + false, + "aLong", + 9_000_000_000_000_000_000L, + "ts", + new BSONTimestamp(1421006159, 4))), + new Document(Map.of("name", "Kierra Gentry", "gender", "F", "age", 40))))) + .block(); - final MongoCollection<Document> teamCollection = mongoClient - .getDatabase("test") - .getCollection("teams"); - Mono.from(teamCollection.insertMany(List.of( - new Document(Map.of( - "name", "Noisy Neighbours 2", - "goals_allowed", "20", - "goals_forwarded", "41", - "goal_difference", "+21", - "xGD", "-2.5", - "best_scoreline", "5-2")), - new Document(Map.of( - "name", "Red Side of the city", - "goals_allowed", "35", - "goals_forwarded", "28", - "goal_difference", "-7", - "xGD", "+3.6", - "best_scoreline", "8-3"))))) - .block(); - } - return Mono.empty(); - }).block(); - } + final MongoCollection<Document> addressCollection = + mongoClient.getDatabase("test").getCollection("address"); + Mono.from(addressCollection.insertMany(List.of( + new Document(Map.of( + "user", new DBRef("test", "users", "1"), + "street", "First Street", + "city", "Line One", + "state", "UP")), + new Document(Map.of( + "user", new DBRef("AAA", "BBB", "2000"), + "street", "Second Street", + "city", "Line Two", + "state", "UP"))))) + .block(); + final MongoCollection<Document> teamCollection = + mongoClient.getDatabase("test").getCollection("teams"); + Mono.from(teamCollection.insertMany(List.of( + new Document(Map.of( + "name", "Noisy Neighbours 2", + "goals_allowed", "20", + "goals_forwarded", "41", + "goal_difference", "+21", + "xGD", "-2.5", + "best_scoreline", "5-2")), + new Document(Map.of( + "name", "Red Side of the city", + "goals_allowed", "35", + "goals_forwarded", "28", + "goal_difference", "-7", + "xGD", "+3.6", + "best_scoreline", "8-3"))))) + .block(); + } + return Mono.empty(); + }) + .block(); + } } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/utils/DatasourceUtilsTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/utils/DatasourceUtilsTest.java index 467daa7e3df0..3516815e2a54 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/utils/DatasourceUtilsTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/utils/DatasourceUtilsTest.java @@ -22,15 +22,11 @@ public void testBuildClientURI_withoutDbInfoAndPortsAndParams() { final DBAuth dbAuth = new DBAuth(); dbAuth.setPassword("newPass"); datasourceConfiguration.setAuthentication(dbAuth); - datasourceConfiguration.setProperties(List.of( - new Property("0", "Yes"), - new Property("1", testUri) - )); + datasourceConfiguration.setProperties(List.of(new Property("0", "Yes"), new Property("1", testUri))); final String clientURI = buildClientURI(datasourceConfiguration); assertEquals(resultUri, clientURI); } - @Test public void testBuildClientURI_withoutUserInfoAndAuthSource() { @@ -40,10 +36,7 @@ public void testBuildClientURI_withoutUserInfoAndAuthSource() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); final DBAuth dbAuth = new DBAuth(); datasourceConfiguration.setAuthentication(dbAuth); - datasourceConfiguration.setProperties(List.of( - new Property("0", "Yes"), - new Property("1", testUri) - )); + datasourceConfiguration.setProperties(List.of(new Property("0", "Yes"), new Property("1", testUri))); final String clientURI = buildClientURI(datasourceConfiguration); assertEquals(resultUri, clientURI); } @@ -58,12 +51,8 @@ public void testBuildClientURI_withUserInfoAndAuthSource() { final DBAuth dbAuth = new DBAuth(); dbAuth.setPassword("newPass"); datasourceConfiguration.setAuthentication(dbAuth); - datasourceConfiguration.setProperties(List.of( - new Property("0", "Yes"), - new Property("1", testUri) - )); + datasourceConfiguration.setProperties(List.of(new Property("0", "Yes"), new Property("1", testUri))); final String clientURI = buildClientURI(datasourceConfiguration); assertEquals(resultUri, clientURI); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/utils/MongoPluginUtilsTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/utils/MongoPluginUtilsTest.java index 6445c483622a..41320d06ccbf 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/utils/MongoPluginUtilsTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/utils/MongoPluginUtilsTest.java @@ -13,11 +13,9 @@ public class MongoPluginUtilsTest { @Test void testGetDatabaseName_withoutDatabaseName_throwsDatasourceError() { final AppsmithPluginException exception = assertThrows( - AppsmithPluginException.class, - () -> MongoPluginUtils.getDatabaseName(new DatasourceConfiguration())); + AppsmithPluginException.class, () -> MongoPluginUtils.getDatabaseName(new DatasourceConfiguration())); assertEquals("Missing default database name.", exception.getMessage()); - } @Test @@ -27,25 +25,28 @@ void testParseSafely_Success() { @Test void testParseSafely_FailureOnArrayValues() { - assertThrows(AppsmithPluginException.class, + assertThrows( + AppsmithPluginException.class, () -> MongoPluginUtils.parseSafely("field", "[{\"$set\":{name: \"Ram singh\"}},{\"$set\":{age: 40}}]")); } @Test void testParseSafelyDocumentAndArrayOfDocuments_Success() { - assertNotNull(MongoPluginUtils.parseSafelyDocumentAndArrayOfDocuments("field", "{\"$set\":{name: \"Ram singh\"}}")); + assertNotNull( + MongoPluginUtils.parseSafelyDocumentAndArrayOfDocuments("field", "{\"$set\":{name: \"Ram singh\"}}")); } @Test void testParseSafelyDocumentAndArrayOfDocumentst_FailureOnNonJsonValue() { - assertThrows(AppsmithPluginException.class, + assertThrows( + AppsmithPluginException.class, () -> MongoPluginUtils.parseSafelyDocumentAndArrayOfDocuments("field", "{abc, pqr}")); } @Test void testParseSafelyDocumentAndArrayOfDocuments_OnArrayValues_Success() { - assertNotNull(MongoPluginUtils.parseSafelyDocumentAndArrayOfDocuments("field", - "[{\"$set\":{name: \"Ram singh\"}},{\"$set\":{age: 40}}]")); + assertNotNull(MongoPluginUtils.parseSafelyDocumentAndArrayOfDocuments( + "field", "[{\"$set\":{name: \"Ram singh\"}},{\"$set\":{age: 40}}]")); } @Test @@ -55,8 +56,8 @@ void testParseSafelyDocumentAndArrayOfDocuments_OnArrayValues_EmptyArray_Success @Test void testParseSafelyDocumentAndArrayOfDocuments_onArrayValues_FailureOnNonJsonValue() { - assertThrows(AppsmithPluginException.class, + assertThrows( + AppsmithPluginException.class, () -> MongoPluginUtils.parseSafelyDocumentAndArrayOfDocuments("field", "[abc, pqr]")); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/pom.xml b/app/server/appsmith-plugins/mssqlPlugin/pom.xml index 3ed26981c726..aa618ad6ec26 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/pom.xml +++ b/app/server/appsmith-plugins/mssqlPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>mssqlPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -62,10 +61,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java index e67a194ded75..24763f2ae36a 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java @@ -11,9 +11,9 @@ import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionRequest; import com.appsmith.external.models.ActionExecutionResult; +import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceStructure; -import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.Endpoint; import com.appsmith.external.models.MustacheBindingToken; import com.appsmith.external.models.Param; @@ -124,15 +124,17 @@ public static class MssqlPluginExecutor implements PluginExecutor<HikariDataSour * @return */ @Override - public Mono<ActionExecutionResult> executeParameterized(HikariDataSource hikariDSConnection, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> executeParameterized( + HikariDataSource hikariDSConnection, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { String query = actionConfiguration.getBody(); // Check for query parameter before performing the probably expensive fetch connection from the pool op. - if (! StringUtils.hasLength(query)) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, MssqlErrorMessages.MISSING_QUERY_ERROR_MSG)); + if (!StringUtils.hasLength(query)) { + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, MssqlErrorMessages.MISSING_QUERY_ERROR_MSG)); } Boolean isPreparedStatement; @@ -160,7 +162,7 @@ public Mono<ActionExecutionResult> executeParameterized(HikariDataSource hikariD return executeCommon(hikariDSConnection, actionConfiguration, FALSE, null, null); } - //Prepared Statement + // Prepared Statement // First extract all the bindings in order List<MustacheBindingToken> mustacheKeysInOrder = MustacheHelper.extractMustacheKeysInOrder(query); // Replace all the bindings with a `?` as expected in a prepared statement. @@ -169,11 +171,12 @@ public Mono<ActionExecutionResult> executeParameterized(HikariDataSource hikariD return executeCommon(hikariDSConnection, actionConfiguration, TRUE, mustacheKeysInOrder, executeActionDTO); } - public Mono<ActionExecutionResult> executeCommon(HikariDataSource hikariDSConnection, - ActionConfiguration actionConfiguration, - Boolean preparedStatement, - List<MustacheBindingToken> mustacheValuesInOrder, - ExecuteActionDTO executeActionDTO) { + public Mono<ActionExecutionResult> executeCommon( + HikariDataSource hikariDSConnection, + ActionConfiguration actionConfiguration, + Boolean preparedStatement, + List<MustacheBindingToken> mustacheValuesInOrder, + ExecuteActionDTO executeActionDTO) { final Map<String, Object> requestData = new HashMap<>(); requestData.put("preparedStatement", TRUE.equals(preparedStatement) ? true : false); @@ -181,11 +184,10 @@ public Mono<ActionExecutionResult> executeCommon(HikariDataSource hikariDSConnec String query = actionConfiguration.getBody(); Map<String, Object> psParams = preparedStatement ? new LinkedHashMap<>() : null; String transformedQuery = preparedStatement ? replaceQuestionMarkWithDollarIndex(query) : query; - List<RequestParamDTO> requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - transformedQuery, null, null, psParams)); + List<RequestParamDTO> requestParams = + List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, transformedQuery, null, null, psParams)); return Mono.fromCallable(() -> { - boolean isResultSet; Connection sqlConnectionFromPool; Statement statement = null; @@ -195,29 +197,31 @@ public Mono<ActionExecutionResult> executeCommon(HikariDataSource hikariDSConnec final List<String> columnsList = new ArrayList<>(); try { - sqlConnectionFromPool = - mssqlDatasourceUtils.getConnectionFromHikariConnectionPool(hikariDSConnection, - MSSQL_PLUGIN_NAME); + sqlConnectionFromPool = mssqlDatasourceUtils.getConnectionFromHikariConnectionPool( + hikariDSConnection, MSSQL_PLUGIN_NAME); } catch (SQLException | StaleConnectionException e) { - // The function can throw either StaleConnectionException or SQLException. The underlying hikari + // The function can throw either StaleConnectionException or SQLException. The underlying + // hikari // library throws SQLException in case the pool is closed or there is an issue initializing // the connection pool which can also be translated in our world to StaleConnectionException // and should then trigger the destruction and recreation of the pool. - return Mono.error(e instanceof StaleConnectionException ? e : - new StaleConnectionException(e.getMessage())); + return Mono.error( + e instanceof StaleConnectionException + ? e + : new StaleConnectionException(e.getMessage())); } try { - if (sqlConnectionFromPool == null || sqlConnectionFromPool.isClosed() || !sqlConnectionFromPool.isValid(VALIDITY_CHECK_TIMEOUT)) { + if (sqlConnectionFromPool == null + || sqlConnectionFromPool.isClosed() + || !sqlConnectionFromPool.isValid(VALIDITY_CHECK_TIMEOUT)) { log.info("Encountered stale connection in MsSQL plugin. Reporting back."); if (sqlConnectionFromPool == null) { return Mono.error(new StaleConnectionException(CONNECTION_NULL_ERROR_MSG)); - } - else if (sqlConnectionFromPool.isClosed()) { + } else if (sqlConnectionFromPool.isClosed()) { return Mono.error(new StaleConnectionException(CONNECTION_CLOSED_ERROR_MSG)); - } - else { + } else { /** * Not adding explicit `!sqlConnectionFromPool.isValid(VALIDITY_CHECK_TIMEOUT)` * check here because this check may take few seconds to complete hence adding @@ -227,14 +231,16 @@ else if (sqlConnectionFromPool.isClosed()) { } } } catch (SQLException error) { - // This exception is thrown only when the timeout to `isValid` is negative. Since, that's not the case, + // This exception is thrown only when the timeout to `isValid` is negative. Since, that's + // not the case, // here, this should never happen. log.error("Error checking validity of MsSQL connection.", error); } // Log HikariCP status - logHikariCPStatus(MessageFormat.format("Before executing Mssql query [{0}]", query), - hikariDSConnection);; + logHikariCPStatus( + MessageFormat.format("Before executing Mssql query [{0}]", query), hikariDSConnection); + ; try { if (FALSE.equals(preparedStatement)) { @@ -245,32 +251,42 @@ else if (sqlConnectionFromPool.isClosed()) { preparedQuery = sqlConnectionFromPool.prepareStatement(query); List<Map.Entry<String, String>> parameters = new ArrayList<>(); - preparedQuery = (PreparedStatement) smartSubstitutionOfBindings(preparedQuery, - mustacheValuesInOrder, - executeActionDTO.getParams(), - parameters); + preparedQuery = (PreparedStatement) smartSubstitutionOfBindings( + preparedQuery, mustacheValuesInOrder, executeActionDTO.getParams(), parameters); requestData.put("ps-parameters", parameters); IntStream.range(0, parameters.size()) - .forEachOrdered(i -> - psParams.put( - getPSParamLabel(i + 1), - new PsParameterDTO(parameters.get(i).getKey(), parameters.get(i).getValue()))); + .forEachOrdered(i -> psParams.put( + getPSParamLabel(i + 1), + new PsParameterDTO( + parameters.get(i).getKey(), + parameters.get(i).getValue()))); isResultSet = preparedQuery.execute(); resultSet = preparedQuery.getResultSet(); } - MssqlExecuteUtils.populateRowsAndColumns(rowsList, columnsList, resultSet, isResultSet, preparedStatement, - statement, preparedQuery); + MssqlExecuteUtils.populateRowsAndColumns( + rowsList, + columnsList, + resultSet, + isResultSet, + preparedStatement, + statement, + preparedQuery); } catch (SQLException e) { - return Mono.error(new AppsmithPluginException(MssqlPluginError.QUERY_EXECUTION_FAILED, MssqlErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage(), "SQLSTATE: "+ e.getSQLState())); + return Mono.error(new AppsmithPluginException( + MssqlPluginError.QUERY_EXECUTION_FAILED, + MssqlErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage(), + "SQLSTATE: " + e.getSQLState())); } finally { // Log HikariCP status - logHikariCPStatus(MessageFormat.format("After executing Mssql query [{0}]", query), + logHikariCPStatus( + MessageFormat.format("After executing Mssql query [{0}]", query), hikariDSConnection); closeConnectionPostExecution(resultSet, statement, preparedQuery, sqlConnectionFromPool); @@ -314,9 +330,10 @@ private Set<String> populateHintMessages(List<String> columnNames) { List<String> identicalColumns = getIdenticalColumns(columnNames); if (!CollectionUtils.isEmpty(identicalColumns)) { - messages.add("Your MsSQL query result may not have all the columns because duplicate column names " + - "were found for the column(s): " + String.join(", ", identicalColumns) + ". You may use the " + - "SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); + messages.add("Your MsSQL query result may not have all the columns because duplicate column names " + + "were found for the column(s): " + + String.join(", ", identicalColumns) + ". You may use the " + + "SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); } return messages; @@ -363,18 +380,21 @@ public Set<String> validateDatasource(@NonNull DatasourceConfiguration datasourc if (StringUtils.isEmpty(auth.getPassword())) { invalids.add(MssqlErrorMessages.DS_MISSING_PASSWORD_ERROR_MSG); } - } return invalids; } @Override - public Mono<ActionExecutionResult> execute(HikariDataSource connection, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + HikariDataSource connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Unused function - return Mono.error(new AppsmithPluginException(MssqlPluginError.QUERY_EXECUTION_FAILED, MssqlErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, "Unsupported Operation")); + return Mono.error(new AppsmithPluginException( + MssqlPluginError.QUERY_EXECUTION_FAILED, + MssqlErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + "Unsupported Operation")); } @Override @@ -384,12 +404,14 @@ public Mono<DatasourceStructure> getStructure( } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) throws AppsmithPluginException { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) + throws AppsmithPluginException { PreparedStatement preparedStatement = (PreparedStatement) input; Param param = (Param) args[0]; @@ -454,7 +476,10 @@ public Object substituteValueInInput(int index, } } catch (SQLException | IllegalArgumentException | IOException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(MssqlErrorMessages.QUERY_PREPARATION_FAILED_ERROR_MSG, binding), e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format(MssqlErrorMessages.QUERY_PREPARATION_FAILED_ERROR_MSG, binding), + e.getMessage()); } return preparedStatement; @@ -476,7 +501,8 @@ public static long getPort(Endpoint endpoint) { * @param datasourceConfiguration * @return connection pool */ - private static HikariDataSource createConnectionPool(DatasourceConfiguration datasourceConfiguration) throws AppsmithPluginException { + private static HikariDataSource createConnectionPool(DatasourceConfiguration datasourceConfiguration) + throws AppsmithPluginException { DBAuth authentication = null; StringBuilder urlBuilder = null; @@ -491,7 +517,6 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat // should get tracked (may be falsely for long running queries) as leaked connection hikariConfig.setLeakDetectionThreshold(LEAK_DETECTION_TIME_MS); - authentication = (DBAuth) datasourceConfiguration.getAuthentication(); if (authentication.getUsername() != null) { hikariConfig.setUsername(authentication.getUsername()); @@ -517,17 +542,11 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat } if (StringUtils.hasLength(authentication.getUsername())) { - urlBuilder - .append("user=") - .append(authentication.getUsername()) - .append(";"); + urlBuilder.append("user=").append(authentication.getUsername()).append(";"); } if (StringUtils.hasLength(authentication.getPassword())) { - urlBuilder - .append("password=") - .append(authentication.getPassword()) - .append(";"); + urlBuilder.append("password=").append(authentication.getPassword()).append(";"); } addSslOptionsToUrlBuilder(datasourceConfiguration, urlBuilder); @@ -537,14 +556,17 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat try { hikariDatasource = new HikariDataSource(hikariConfig); } catch (HikariPool.PoolInitializationException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, MssqlErrorMessages.CONNECTION_POOL_CREATION_FAILED_ERROR_MSG, e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + MssqlErrorMessages.CONNECTION_POOL_CREATION_FAILED_ERROR_MSG, + e.getMessage()); } return hikariDatasource; } - private static void addSslOptionsToUrlBuilder(DatasourceConfiguration datasourceConfiguration, - StringBuilder urlBuilder) throws AppsmithPluginException { + private static void addSslOptionsToUrlBuilder( + DatasourceConfiguration datasourceConfiguration, StringBuilder urlBuilder) throws AppsmithPluginException { /* * - Ideally, it is never expected to be null because the SSL dropdown is set to a initial value. */ @@ -553,14 +575,15 @@ private static void addSslOptionsToUrlBuilder(DatasourceConfiguration datasource || datasourceConfiguration.getConnection().getSsl().getAuthType() == null) { throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_ERROR, - "Appsmith server has failed to fetch SSL configuration from datasource configuration form. " + - "Please reach out to Appsmith customer support to resolve this."); + "Appsmith server has failed to fetch SSL configuration from datasource configuration form. " + + "Please reach out to Appsmith customer support to resolve this."); } /* * - By default, the driver configures SSL in the no verify mode. */ - SSLDetails.AuthType sslAuthType = datasourceConfiguration.getConnection().getSsl().getAuthType(); + SSLDetails.AuthType sslAuthType = + datasourceConfiguration.getConnection().getSsl().getAuthType(); switch (sslAuthType) { case DISABLE: urlBuilder.append("encrypt=false;"); @@ -574,8 +597,8 @@ private static void addSslOptionsToUrlBuilder(DatasourceConfiguration datasource default: throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_ERROR, - "Appsmith server has found an unexpected SSL option: " + sslAuthType + ". Please reach out to" + - " Appsmith customer support to resolve this."); + "Appsmith server has found an unexpected SSL option: " + sslAuthType + ". Please reach out to" + + " Appsmith customer support to resolve this."); } } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java index 8c39e16b4bea..6be7871af6d2 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java @@ -8,20 +8,23 @@ public class MssqlErrorMessages extends BasePluginErrorMessages { public static final String MISSING_QUERY_ERROR_MSG = "Missing required parameter: Query."; - public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Your query failed to execute. Please check more information in the error details."; + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = + "Your query failed to execute. Please check more information in the error details."; public static final String QUERY_PREPARATION_FAILED_ERROR_MSG = "Query preparation failed while inserting value: %s" + " for binding: {{%s}}. Please check the query again."; - public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = "Exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid. Please check your datasource configuration."; + public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = + "Exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid. Please check your datasource configuration."; - public static final String GET_STRUCTURE_ERROR_MSG = "The Appsmith server has failed to fetch the structure of your schema."; + public static final String GET_STRUCTURE_ERROR_MSG = + "The Appsmith server has failed to fetch the structure of your schema."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ public static final String DS_MISSING_ENDPOINT_ERROR_MSG = "Missing endpoint."; public static final String DS_MISSING_CONNECTION_MODE_ERROR_MSG = "Missing connection mode."; diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlPluginError.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlPluginError.java index 4b181228dbac..8e8b0de1f462 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlPluginError.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlPluginError.java @@ -17,8 +17,7 @@ public enum MssqlPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; private final String appErrorCode; @@ -31,8 +30,15 @@ public enum MssqlPluginError implements BasePluginError { private final String downstreamErrorCode; - MssqlPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + MssqlPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -47,7 +53,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java index 51ae861a0997..ce9e057a3962 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java @@ -48,18 +48,16 @@ public class MssqlDatasourceUtils { * +------------+-----------+--------------+--------------+ * </pre> */ - private static final String QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE = "SELECT \n" + - " col.name AS column_name,\n" + - " typ.name AS column_type,\n" + - " tbl.name AS table_name,\n" + - " sch.name AS schema_name\n" + - "FROM sys.columns col\n" + - " INNER JOIN sys.tables tbl ON col.object_id = tbl.object_id\n" + - " INNER JOIN sys.types typ ON col.user_type_id = typ.user_type_id\n" + - " INNER JOIN sys.schemas sch ON tbl.schema_id = sch.schema_id\n" + - "WHERE tbl.is_ms_shipped = 0\n" + - "ORDER BY tbl.name, col.column_id;\n"; - + private static final String QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE = "SELECT \n" + " col.name AS column_name,\n" + + " typ.name AS column_type,\n" + + " tbl.name AS table_name,\n" + + " sch.name AS schema_name\n" + + "FROM sys.columns col\n" + + " INNER JOIN sys.tables tbl ON col.object_id = tbl.object_id\n" + + " INNER JOIN sys.types typ ON col.user_type_id = typ.user_type_id\n" + + " INNER JOIN sys.schemas sch ON tbl.schema_id = sch.schema_id\n" + + "WHERE tbl.is_ms_shipped = 0\n" + + "ORDER BY tbl.name, col.column_id;\n"; /** * Example output: @@ -72,40 +70,42 @@ public class MssqlDatasourceUtils { * +------------+-----------+-----------------+-----------------+-------------+ * </pre> */ - private static final String QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS = "SELECT \n" + - " cols.table_name,\n" + - " cols.column_name,\n" + - " cols.constraint_schema as schema_name,\n" + - " cons.constraint_type,\n" + - " cons.constraint_name\n" + - "FROM \n" + - " INFORMATION_SCHEMA.KEY_COLUMN_USAGE cols\n" + - " JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS cons\n" + - " ON cols.CONSTRAINT_SCHEMA = cons.CONSTRAINT_SCHEMA\n" + - " AND cols.CONSTRAINT_NAME = cons.CONSTRAINT_NAME\n" + - "WHERE \n" + - " cons.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY')\n" + - " AND cols.CONSTRAINT_SCHEMA = 'dbo'\n" + - "ORDER BY \n" + - " cols.table_name,\n" + - " cols.ordinal_position\n"; - - public static Mono<DatasourceStructure> getStructure(HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { + private static final String QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS = "SELECT \n" + " cols.table_name,\n" + + " cols.column_name,\n" + + " cols.constraint_schema as schema_name,\n" + + " cons.constraint_type,\n" + + " cons.constraint_name\n" + + "FROM \n" + + " INFORMATION_SCHEMA.KEY_COLUMN_USAGE cols\n" + + " JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS cons\n" + + " ON cols.CONSTRAINT_SCHEMA = cons.CONSTRAINT_SCHEMA\n" + + " AND cols.CONSTRAINT_NAME = cons.CONSTRAINT_NAME\n" + + "WHERE \n" + + " cons.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY')\n" + + " AND cols.CONSTRAINT_SCHEMA = 'dbo'\n" + + "ORDER BY \n" + + " cols.table_name,\n" + + " cols.ordinal_position\n"; + + public static Mono<DatasourceStructure> getStructure( + HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { final DatasourceStructure structure = new DatasourceStructure(); final Map<String, DatasourceStructure.Table> tableNameToTableMap = new LinkedHashMap<>(); return Mono.fromSupplier(() -> { Connection connectionFromPool; try { - connectionFromPool = mssqlDatasourceUtils.getConnectionFromHikariConnectionPool(connection, - MSSQL_PLUGIN_NAME); + connectionFromPool = mssqlDatasourceUtils.getConnectionFromHikariConnectionPool( + connection, MSSQL_PLUGIN_NAME); } catch (SQLException | StaleConnectionException e) { // The function can throw either StaleConnectionException or SQLException. The // underlying hikari library throws SQLException in case the pool is closed or there is an issue // initializing the connection pool which can also be translated in our world to // StaleConnectionException and should then trigger the destruction and recreation of the pool. - return Mono.error(e instanceof StaleConnectionException ? e : - new StaleConnectionException(e.getMessage())); + return Mono.error( + e instanceof StaleConnectionException + ? e + : new StaleConnectionException(e.getMessage())); } logHikariCPStatus("Before getting Mssql DB schema", connection); @@ -118,13 +118,16 @@ public static Mono<DatasourceStructure> getStructure(HikariDataSource connection setPrimaryAndForeignKeyInfoInTables(statement, tableNameToTableMap); } catch (SQLException throwable) { - return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, - MssqlErrorMessages.GET_STRUCTURE_ERROR_MSG, throwable.getCause(), + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + MssqlErrorMessages.GET_STRUCTURE_ERROR_MSG, + throwable.getCause(), "SQLSTATE: " + throwable.getSQLState())); } finally { logHikariCPStatus("After getting Oracle DB schema", connection); - safelyCloseSingleConnectionFromHikariCP(connectionFromPool, "Error returning Oracle connection to pool " + - "during get structure"); + safelyCloseSingleConnectionFromHikariCP( + connectionFromPool, + "Error returning Oracle connection to pool " + "during get structure"); } // Set SQL query templates @@ -151,7 +154,8 @@ public static void logHikariCPStatus(String logPrefix, HikariDataSource connecti int activeConnections = poolProxy.getActiveConnections(); int totalConnections = poolProxy.getTotalConnections(); int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug(MessageFormat.format("{0}: Hikari Pool stats : active - {1} , idle - {2}, awaiting - {3} , total - {4}", + log.debug(MessageFormat.format( + "{0}: Hikari Pool stats : active - {1} , idle - {2}, awaiting - {3} , total - {4}", logPrefix, activeConnections, idleConnections, threadsAwaitingConnection, totalConnections)); } @@ -170,19 +174,20 @@ private static void setTableNamesAndColumnNamesAndColumnTypes( final String schemaName = columnsResultSet.getString("schema_name"); final String fullTableName = schemaName + "." + tableName; if (!tableNameToTableMap.containsKey(fullTableName)) { - tableNameToTableMap.put(fullTableName, new DatasourceStructure.Table( - DatasourceStructure.TableType.TABLE, - schemaName, + tableNameToTableMap.put( fullTableName, - new ArrayList<>(), - new ArrayList<>(), - new ArrayList<>())); + new DatasourceStructure.Table( + DatasourceStructure.TableType.TABLE, + schemaName, + fullTableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); } final DatasourceStructure.Table table = tableNameToTableMap.get(fullTableName); - table.getColumns().add( - new DatasourceStructure.Column(columnName, columnType, null, false)); + table.getColumns().add(new DatasourceStructure.Column(columnName, columnType, null, false)); } } } @@ -192,7 +197,7 @@ private static void setTableNamesAndColumnNamesAndColumnTypes( * primary or foreign key. * Please check the SQL query macro definition to find a sample response as comment. */ - private static void setPrimaryAndForeignKeyInfoInTables ( + private static void setPrimaryAndForeignKeyInfoInTables( Statement statement, Map<String, DatasourceStructure.Table> tableNameToTableMap) throws SQLException { Map<String, String> primaryKeyConstraintNameToTableNameMap = new HashMap<>(); Map<String, String> primaryKeyConstraintNameToColumnNameMap = new HashMap<>(); @@ -226,8 +231,7 @@ private static void setPrimaryAndForeignKeyInfoInTables ( String tableName = primaryKeyConstraintNameToTableNameMap.get(constraintName); DatasourceStructure.Table table = tableNameToTableMap.get(tableName); String columnName = primaryKeyConstraintNameToColumnNameMap.get(constraintName); - table.getKeys().add(new DatasourceStructure.PrimaryKey(constraintName, - List.of(columnName))); + table.getKeys().add(new DatasourceStructure.PrimaryKey(constraintName, List.of(columnName))); }); foreignKeyConstraintNameToColumnNameMap.keySet().stream() @@ -239,38 +243,39 @@ private static void setPrimaryAndForeignKeyInfoInTables ( String tableName = foreignKeyConstraintNameToTableNameMap.get(constraintName); DatasourceStructure.Table table = tableNameToTableMap.get(tableName); String columnName = foreignKeyConstraintNameToColumnNameMap.get(constraintName); - table.getKeys().add(new DatasourceStructure.ForeignKey(constraintName, - List.of(columnName), new ArrayList<>())); + table.getKeys() + .add(new DatasourceStructure.ForeignKey( + constraintName, List.of(columnName), new ArrayList<>())); }); } private static void setSQLQueryTemplates(Map<String, DatasourceStructure.Table> tableNameToTableMap) { - tableNameToTableMap.values() - .forEach(table -> { - LinkedHashMap<String, String> columnNameToSampleColumnDataMap = - new LinkedHashMap<>(); - table.getColumns() - .forEach(column -> columnNameToSampleColumnDataMap.put(column.getName(), - getSampleColumnData(column.getType()))); - - String selectQueryTemplate = MessageFormat.format("SELECT TOP 10 * FROM {0}", table.getName()); - String insertQueryTemplate = MessageFormat.format("INSERT INTO {0} ({1}) " + - "VALUES ({2})", table.getName(), - getSampleColumnNamesCSVString(columnNameToSampleColumnDataMap), - getSampleColumnDataCSVString(columnNameToSampleColumnDataMap)); - String updateQueryTemplate = MessageFormat.format("UPDATE {0} SET {1} WHERE " + - "1=0 -- Specify a valid condition here. Removing the condition may " + - "update every row in the table!", table.getName(), - getSampleOneColumnUpdateString(columnNameToSampleColumnDataMap)); - String deleteQueryTemplate = MessageFormat.format("DELETE FROM {0} WHERE 1=0" + - " -- Specify a valid condition here. Removing the condition may " + - "delete everything in the table!", table.getName()); - - table.getTemplates().add(new DatasourceStructure.Template("SELECT", selectQueryTemplate)); - table.getTemplates().add(new DatasourceStructure.Template("INSERT", insertQueryTemplate)); - table.getTemplates().add(new DatasourceStructure.Template("UPDATE", updateQueryTemplate)); - table.getTemplates().add(new DatasourceStructure.Template("DELETE", deleteQueryTemplate)); - }); + tableNameToTableMap.values().forEach(table -> { + LinkedHashMap<String, String> columnNameToSampleColumnDataMap = new LinkedHashMap<>(); + table.getColumns() + .forEach(column -> columnNameToSampleColumnDataMap.put( + column.getName(), getSampleColumnData(column.getType()))); + + String selectQueryTemplate = MessageFormat.format("SELECT TOP 10 * FROM {0}", table.getName()); + String insertQueryTemplate = MessageFormat.format( + "INSERT INTO {0} ({1}) " + "VALUES ({2})", + table.getName(), + getSampleColumnNamesCSVString(columnNameToSampleColumnDataMap), + getSampleColumnDataCSVString(columnNameToSampleColumnDataMap)); + String updateQueryTemplate = MessageFormat.format( + "UPDATE {0} SET {1} WHERE " + "1=0 -- Specify a valid condition here. Removing the condition may " + + "update every row in the table!", + table.getName(), getSampleOneColumnUpdateString(columnNameToSampleColumnDataMap)); + String deleteQueryTemplate = MessageFormat.format( + "DELETE FROM {0} WHERE 1=0" + " -- Specify a valid condition here. Removing the condition may " + + "delete everything in the table!", + table.getName()); + + table.getTemplates().add(new DatasourceStructure.Template("SELECT", selectQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("INSERT", insertQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("UPDATE", updateQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("DELETE", deleteQueryTemplate)); + }); } private static String getSampleColumnData(String type) { @@ -294,27 +299,30 @@ private static String getSampleColumnDataCSVString(LinkedHashMap<String, String> return String.join(", ", columnNameToSampleColumnDataMap.values()); } - private static String getSampleOneColumnUpdateString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { - return MessageFormat.format("{0}={1}", columnNameToSampleColumnDataMap.keySet().stream().findFirst().orElse( - "id"), columnNameToSampleColumnDataMap.values().stream().findFirst().orElse("'uid'")); + private static String getSampleOneColumnUpdateString( + LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return MessageFormat.format( + "{0}={1}", + columnNameToSampleColumnDataMap.keySet().stream().findFirst().orElse("id"), + columnNameToSampleColumnDataMap.values().stream().findFirst().orElse("'uid'")); } - public void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) throws StaleConnectionException { + public void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) + throws StaleConnectionException { if (connectionPool == null || connectionPool.isClosed() || !connectionPool.isRunning()) { - String printMessage = MessageFormat.format(Thread.currentThread().getName() + - ": Encountered stale connection pool in {0} plugin. Reporting back.", pluginName); + String printMessage = MessageFormat.format( + Thread.currentThread().getName() + + ": Encountered stale connection pool in {0} plugin. Reporting back.", + pluginName); System.out.println(printMessage); if (connectionPool == null) { throw new StaleConnectionException(CONNECTION_POOL_NULL_ERROR_MSG); - } - else if (connectionPool.isClosed()) { + } else if (connectionPool.isClosed()) { throw new StaleConnectionException(CONNECTION_POOL_CLOSED_ERROR_MSG); - } - else if (!connectionPool.isRunning()) { + } else if (!connectionPool.isRunning()) { throw new StaleConnectionException(CONNECTION_POOL_NOT_RUNNING_ERROR_MSG); - } - else { + } else { /** * Ideally, code flow is never expected to reach here. However, this section has been added to catch * those cases wherein a developer updates the parent if condition but does not update the nested @@ -325,8 +333,8 @@ else if (!connectionPool.isRunning()) { } } - public Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, - String pluginName) throws SQLException { + public Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, String pluginName) + throws SQLException { checkHikariCPConnectionPoolValidity(connectionPool, pluginName); return connectionPool.getConnection(); } diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java index f26a5d1df21b..7a08b0648baf 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java @@ -4,8 +4,8 @@ import java.sql.Connection; import java.sql.PreparedStatement; -import java.sql.ResultSetMetaData; import java.sql.ResultSet; +import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.text.MessageFormat; @@ -29,15 +29,14 @@ public class MssqlExecuteUtils { private static final String TIMETZ_TYPE_NAME = "timetz"; private static final String INTERVAL_TYPE_NAME = "interval"; - - public static void closeConnectionPostExecution(ResultSet resultSet, Statement statement, - PreparedStatement preparedQuery, Connection connectionFromPool) { + public static void closeConnectionPostExecution( + ResultSet resultSet, Statement statement, PreparedStatement preparedQuery, Connection connectionFromPool) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { - System.out.println(Thread.currentThread().getName() + - ": Execute Error closing Mssql ResultSet" + e.getMessage()); + System.out.println( + Thread.currentThread().getName() + ": Execute Error closing Mssql ResultSet" + e.getMessage()); } } @@ -45,8 +44,8 @@ public static void closeConnectionPostExecution(ResultSet resultSet, Statement s try { statement.close(); } catch (SQLException e) { - System.out.println(Thread.currentThread().getName() + - ": Execute Error closing Mssql Statement" + e.getMessage()); + System.out.println( + Thread.currentThread().getName() + ": Execute Error closing Mssql Statement" + e.getMessage()); } } @@ -54,21 +53,32 @@ public static void closeConnectionPostExecution(ResultSet resultSet, Statement s try { preparedQuery.close(); } catch (SQLException e) { - System.out.println(Thread.currentThread().getName() + - ": Execute Error closing Mssql Statement" + e.getMessage()); + System.out.println( + Thread.currentThread().getName() + ": Execute Error closing Mssql Statement" + e.getMessage()); } } - safelyCloseSingleConnectionFromHikariCP(connectionFromPool, MessageFormat.format("{0}: Execute Error returning " + - "Oracle connection to pool", Thread.currentThread().getName())); + safelyCloseSingleConnectionFromHikariCP( + connectionFromPool, + MessageFormat.format( + "{0}: Execute Error returning " + "Oracle connection to pool", + Thread.currentThread().getName())); } - public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, List<String> columnsList, ResultSet resultSet, boolean isResultSet, Boolean preparedStatement, Statement statement, PreparedStatement preparedQuery) throws SQLException { + public static void populateRowsAndColumns( + List<Map<String, Object>> rowsList, + List<String> columnsList, + ResultSet resultSet, + boolean isResultSet, + Boolean preparedStatement, + Statement statement, + PreparedStatement preparedQuery) + throws SQLException { if (!isResultSet) { - Object updateCount = FALSE.equals(preparedStatement) ? - ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) : - ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); + Object updateCount = FALSE.equals(preparedStatement) + ? ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) + : ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); rowsList.add(Map.of("affectedRows", updateCount)); } else { @@ -88,22 +98,20 @@ public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, Li value = null; } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE.format(resultSet.getDate(i).toLocalDate()); + value = DateTimeFormatter.ISO_DATE.format( + resultSet.getDate(i).toLocalDate()); } else if (TIMESTAMP_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - LocalDateTime.of( + value = DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.of( resultSet.getDate(i).toLocalDate(), - resultSet.getTime(i).toLocalTime() - ) - ) + "Z"; + resultSet.getTime(i).toLocalTime())) + + "Z"; } else if (TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - resultSet.getObject(i, OffsetDateTime.class) - ); + value = DateTimeFormatter.ISO_DATE_TIME.format(resultSet.getObject(i, OffsetDateTime.class)); - } else if (TIME_TYPE_NAME.equalsIgnoreCase(typeName) || TIMETZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + } else if (TIME_TYPE_NAME.equalsIgnoreCase(typeName) + || TIMETZ_TYPE_NAME.equalsIgnoreCase(typeName)) { value = resultSet.getString(i); } else if (INTERVAL_TYPE_NAME.equalsIgnoreCase(typeName)) { @@ -111,7 +119,6 @@ public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, Li } else { value = resultSet.getObject(i); - } row.put(metaData.getColumnName(i), value); @@ -119,7 +126,6 @@ public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, Li rowsList.add(row); } - } } } diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java index 369f7d566204..4434a3a1c3f6 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java @@ -24,21 +24,19 @@ @Testcontainers public class MssqlGetDBSchemaTest { public static final String SQL_QUERY_TO_CREATE_TABLE_WITH_PRIMARY_KEY = - "CREATE TABLE supplier\n" + - "( supplier_id int not null,\n" + - " supplier_name varchar(50) not null,\n" + - " contact_name varchar(50),\n" + - " CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)\n" + - ")"; + "CREATE TABLE supplier\n" + "( supplier_id int not null,\n" + + " supplier_name varchar(50) not null,\n" + + " contact_name varchar(50),\n" + + " CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)\n" + + ")"; public static final String SQL_QUERY_TO_CREATE_TABLE_WITH_FOREIGN_KEY = - "CREATE TABLE products\n" + - "( product_id int not null,\n" + - " supplier_id int not null,\n" + - " CONSTRAINT fk_supplier\n" + - " FOREIGN KEY (supplier_id)\n" + - " REFERENCES supplier(supplier_id)\n" + - ")"; + "CREATE TABLE products\n" + "( product_id int not null,\n" + + " supplier_id int not null,\n" + + " CONSTRAINT fk_supplier\n" + + " FOREIGN KEY (supplier_id)\n" + + " REFERENCES supplier(supplier_id)\n" + + ")"; @SuppressWarnings("rawtypes") // The type parameter for the container type is just itself and is pseudo-optional. @Container @@ -48,15 +46,16 @@ public class MssqlGetDBSchemaTest { @BeforeAll public static void setup() throws SQLException { - sharedConnectionPool = mssqlPluginExecutor.datasourceCreate(createDatasourceConfiguration(container)).block(); + sharedConnectionPool = mssqlPluginExecutor + .datasourceCreate(createDatasourceConfiguration(container)) + .block(); createTablesForTest(); } @Test public void testDBSchemaShowsAllTables() { Mono<DatasourceStructure> datasourceStructureMono = - mssqlPluginExecutor.getStructure(sharedConnectionPool, - createDatasourceConfiguration(container)); + mssqlPluginExecutor.getStructure(sharedConnectionPool, createDatasourceConfiguration(container)); StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { @@ -65,7 +64,9 @@ public void testDBSchemaShowsAllTables() { .map(String::toLowerCase) .collect(Collectors.toSet()); - assertTrue(setOfAllTableNames.equals(Set.of("dbo.supplier","dbo.products")), setOfAllTableNames.toString()); + assertTrue( + setOfAllTableNames.equals(Set.of("dbo.supplier", "dbo.products")), + setOfAllTableNames.toString()); }) .verifyComplete(); } @@ -73,8 +74,7 @@ public void testDBSchemaShowsAllTables() { @Test public void testDBSchemaShowsAllColumnsAndTypesInATable() { Mono<DatasourceStructure> datasourceStructureMono = - mssqlPluginExecutor.getStructure(sharedConnectionPool, - createDatasourceConfiguration(container)); + mssqlPluginExecutor.getStructure(sharedConnectionPool, createDatasourceConfiguration(container)); StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { @@ -91,21 +91,19 @@ public void testDBSchemaShowsAllColumnsAndTypesInATable() { Set<String> expectedColumnNames = Set.of("supplier_id", "supplier_name", "contact_name"); assertEquals(expectedColumnNames, allColumnNames, allColumnNames.toString()); - supplierTable.get().getColumns() - .forEach(column -> { - String columnName = column.getName().toLowerCase(); - String columnType = column.getType().toLowerCase(); - String expectedColumnType; + supplierTable.get().getColumns().forEach(column -> { + String columnName = column.getName().toLowerCase(); + String columnType = column.getType().toLowerCase(); + String expectedColumnType; - if ("supplier_id".equals(columnName)) { - expectedColumnType = "int"; - } - else { - expectedColumnType = "varchar"; - } + if ("supplier_id".equals(columnName)) { + expectedColumnType = "int"; + } else { + expectedColumnType = "varchar"; + } - assertEquals(expectedColumnType, columnType, columnType); - }); + assertEquals(expectedColumnType, columnType, columnType); + }); }) .verifyComplete(); } @@ -113,8 +111,7 @@ public void testDBSchemaShowsAllColumnsAndTypesInATable() { @Test public void testDynamicSqlTemplateQueriesForATable() { Mono<DatasourceStructure> datasourceStructureMono = - mssqlPluginExecutor.getStructure(sharedConnectionPool, - createDatasourceConfiguration(container)); + mssqlPluginExecutor.getStructure(sharedConnectionPool, createDatasourceConfiguration(container)); StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { @@ -125,7 +122,8 @@ public void testDynamicSqlTemplateQueriesForATable() { assertTrue(supplierTable.isPresent(), "supplier table not found in DB schema"); supplierTable.get().getTemplates().stream() - .filter(template -> "select".equalsIgnoreCase(template.getTitle()) || "delete".equalsIgnoreCase(template.getTitle())) + .filter(template -> "select".equalsIgnoreCase(template.getTitle()) + || "delete".equalsIgnoreCase(template.getTitle())) .forEach(template -> { /* @@ -137,15 +135,16 @@ public void testDynamicSqlTemplateQueriesForATable() { String expectedQueryTemplate = null; if ("select".equalsIgnoreCase(template.getTitle())) { expectedQueryTemplate = "select top 10 * from dbo.supplier"; - } - else if ("delete".equalsIgnoreCase(template.getTitle())) { - expectedQueryTemplate = "delete from dbo.supplier where 1=0 -- specify a valid" + - " condition here. removing the condition may delete everything in the " + - "table!"; + } else if ("delete".equalsIgnoreCase(template.getTitle())) { + expectedQueryTemplate = "delete from dbo.supplier where 1=0 -- specify a valid" + + " condition here. removing the condition may delete everything in the " + + "table!"; } String templateQuery = template.getBody(); - assertEquals(expectedQueryTemplate, templateQuery.toLowerCase(), + assertEquals( + expectedQueryTemplate, + templateQuery.toLowerCase(), templateQuery.toLowerCase()); }); }) diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java index 7735c37c4a1a..0929cc3302b2 100755 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java @@ -32,7 +32,6 @@ import reactor.test.StepVerifier; import java.sql.SQLException; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -59,37 +58,42 @@ public class MssqlPluginTest { private static HikariDataSource sharedConnectionPool = null; - private static final String CREATE_USER_TABLE_QUERY = "CREATE TABLE users (\n" + - " id int identity (1, 1) NOT NULL,\n" + - " username VARCHAR (50),\n" + - " password VARCHAR (50),\n" + - " email VARCHAR (355),\n" + - " spouse_dob DATE,\n" + - " dob DATE NOT NULL,\n" + - " time1 TIME NOT NULL,\n" + - " constraint pk_users_id primary key (id)\n" + - ")"; + private static final String CREATE_USER_TABLE_QUERY = + "CREATE TABLE users (\n" + " id int identity (1, 1) NOT NULL,\n" + + " username VARCHAR (50),\n" + + " password VARCHAR (50),\n" + + " email VARCHAR (355),\n" + + " spouse_dob DATE,\n" + + " dob DATE NOT NULL,\n" + + " time1 TIME NOT NULL,\n" + + " constraint pk_users_id primary key (id)\n" + + ")"; private static final String SET_IDENTITY_INSERT_USERS_QUERY = "SET IDENTITY_INSERT users ON;"; - private static final String INSERT_USER1_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31'," + - " '18:32:45'" + - ")"; + private static final String INSERT_USER1_QUERY = + "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31'," + + " '18:32:45'" + + ")"; - private static final String INSERT_USER2_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31'," + - " '15:45:30'" + - ")"; + private static final String INSERT_USER2_QUERY = + "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31'," + + " '15:45:30'" + + ")"; - private static final String INSERT_USER3_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "3, 'JackJill', 'jaji', '[email protected]', NULL, '2021-01-31'," + - " '15:45:30'" + - ")"; + private static final String INSERT_USER3_QUERY = + "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "3, 'JackJill', 'jaji', '[email protected]', NULL, '2021-01-31'," + + " '15:45:30'" + + ")"; @BeforeAll public static void setUp() throws SQLException { - sharedConnectionPool = mssqlPluginExecutor.datasourceCreate(createDatasourceConfiguration(container)).block(); + sharedConnectionPool = mssqlPluginExecutor + .datasourceCreate(createDatasourceConfiguration(container)) + .block(); createTablesForTest(); } @@ -137,7 +141,6 @@ public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { assertTrue(datasourceTestResult.getInvalids().isEmpty()); }) .verifyComplete(); - } @Test @@ -148,21 +151,18 @@ public void testAliasColumnNames() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT id as user_id FROM users WHERE id = 1"); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "user_id" - }, + new String[] {"user_id"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); }) .verifyComplete(); } @@ -175,8 +175,8 @@ public void testExecute() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users WHERE id = 1"); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -191,28 +191,21 @@ public void testExecute() { // Check the order of the columns. assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", + new String[] { + "id", "username", "password", "email", "spouse_dob", "dob", "time1", }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); /* * - RequestParamDTO object only have attributes configProperty and value at this point. * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - actionConfiguration.getBody(), null, null, new HashMap<>())); + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, actionConfiguration.getBody(), null, null, new HashMap<>())); assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -255,10 +248,11 @@ public void testPreparedStatementWithoutQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -274,24 +268,18 @@ public void testPreparedStatementWithoutQuotes() { // Check the order of the columns. // Check the order of the columns. assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", + new String[] { + "id", "username", "password", "email", "spouse_dob", "dob", "time1", }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); // Assert the debug request parameters are getting set. ActionExecutionRequest request = result.getRequest(); - List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) request.getProperties().get("ps-parameters"); + List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) + request.getProperties().get("ps-parameters"); assertEquals(parameters.size(), 1); Map.Entry<String, String> parameterEntry = parameters.get(0); assertEquals(parameterEntry.getKey(), "1"); @@ -320,14 +308,14 @@ public void testPreparedStatementWithDoubleQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { - assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); @@ -339,20 +327,13 @@ public void testPreparedStatementWithDoubleQuotes() { // Check the order of the columns. assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", + new String[] { + "id", "username", "password", "email", "spouse_dob", "dob", "time1", }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); /* * - Check if request params are sent back properly. @@ -361,12 +342,15 @@ public void testPreparedStatementWithDoubleQuotes() { */ // check if '?' is replaced by $i. - assertEquals("SELECT * FROM users where id = $1;", + assertEquals( + "SELECT * FROM users where id = $1;", ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getValue()); PsParameterDTO expectedPsParam = new PsParameterDTO("1", "INTEGER"); - PsParameterDTO returnedPsParam = - (PsParameterDTO) ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getSubstitutedParams().get("$1"); + PsParameterDTO returnedPsParam = (PsParameterDTO) + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)) + .getSubstitutedParams() + .get("$1"); // Check if prepared stmt param value is correctly sent back. assertEquals(expectedPsParam.getValue(), returnedPsParam.getValue()); // check if prepared stmt param type is correctly sent back. @@ -395,14 +379,14 @@ public void testPreparedStatementWithSingleQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { - assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); @@ -414,21 +398,13 @@ public void testPreparedStatementWithSingleQuotes() { // Check the order of the columns. assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", + new String[] { + "id", "username", "password", "email", "spouse_dob", "dob", "time1", }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); - + .toArray()); }) .verifyComplete(); } @@ -438,11 +414,10 @@ public void testPreparedStatementWithNullStringValue() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("UPDATE users set " + - "username = {{binding1}}, " + - "password = {{binding1}},\n" + - "email = {{binding1}}" + - " where id = 2;"); + actionConfiguration.setBody("UPDATE users set " + "username = {{binding1}}, " + + "password = {{binding1}},\n" + + "email = {{binding1}}" + + " where id = 2;"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -457,10 +432,11 @@ public void testPreparedStatementWithNullStringValue() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -469,8 +445,8 @@ public void testPreparedStatementWithNullStringValue() { .verifyComplete(); actionConfiguration.setBody("SELECT * FROM users where id = 2;"); - resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -488,13 +464,11 @@ public void testPreparedStatementWithNullStringValue() { public void testPreparedStatementWithNullValue() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); - ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("UPDATE users set " + - "username = {{binding1}}, " + - "password = {{binding1}}, " + - "email = {{binding1}}" + - " where id = 3;"); + actionConfiguration.setBody("UPDATE users set " + "username = {{binding1}}, " + + "password = {{binding1}}, " + + "email = {{binding1}}" + + " where id = 3;"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -509,10 +483,11 @@ public void testPreparedStatementWithNullValue() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -521,8 +496,8 @@ public void testPreparedStatementWithNullValue() { .verifyComplete(); actionConfiguration.setBody("SELECT * FROM users where id = 3;"); - resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -544,25 +519,22 @@ public void testDuplicateColumnNames() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT id, username as id, password, email as password FROM users WHERE id = 1"); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { assertNotEquals(0, result.getMessages().size()); - String expectedMessage = "Your MsSQL query result may not have all the columns because duplicate " + - "column names were found for the column(s)"; - assertTrue( - result.getMessages().stream() - .anyMatch(message -> message.contains(expectedMessage)) - ); + String expectedMessage = "Your MsSQL query result may not have all the columns because duplicate " + + "column names were found for the column(s)"; + assertTrue(result.getMessages().stream().anyMatch(message -> message.contains(expectedMessage))); /* * - Check if all the duplicate column names are reported. */ - Set<String> expectedColumnNames = Stream.of("id", "password") - .collect(Collectors.toCollection(HashSet::new)); + Set<String> expectedColumnNames = + Stream.of("id", "password").collect(Collectors.toCollection(HashSet::new)); Set<String> foundColumnNames = new HashSet<>(); result.getMessages().stream() .filter(message -> message.contains(expectedMessage)) @@ -591,10 +563,11 @@ public void testLimitQuery() { List<Param> params = new ArrayList<>(); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -623,20 +596,18 @@ public void testNumericStringHavingLeadingZeroWithPreparedStatement() { params.add(param1); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "numeric_string" - }, + new String[] {"numeric_string"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() @@ -645,31 +616,34 @@ public void testNumericStringHavingLeadingZeroWithPreparedStatement() { // Verify value assertEquals(JsonNodeType.STRING, node.get("numeric_string").getNodeType()); assertEquals(param1.getValue(), node.get("numeric_string").asText()); - }) .verifyComplete(); } @Test public void verifyUniquenessOfMssqlPluginErrorCode() { - assert (Arrays.stream(MssqlPluginError.values()).map(MssqlPluginError::getAppErrorCode).distinct().count() == MssqlPluginError.values().length); - - assert (Arrays.stream(MssqlPluginError.values()).map(MssqlPluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-MSS")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(MssqlPluginError.values()) + .map(MssqlPluginError::getAppErrorCode) + .distinct() + .count() + == MssqlPluginError.values().length); + + assert (Arrays.stream(MssqlPluginError.values()) + .map(MssqlPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-MSS")) + .collect(Collectors.toList()) + .size() + == 0); } @Test public void testSSLNoVerifyConnectionIsEncrypted() { ActionConfiguration actionConfiguration = new ActionConfiguration(); - String queryToFetchEncryptionStatusOfSelfConnection = - "SELECT \n" + - " c.encrypt_option \n" + - "FROM sys.dm_exec_connections AS c \n" + - "JOIN sys.dm_exec_sessions AS s \n" + - " ON c.session_id = s.session_id \n" + - "WHERE c.session_id = @@SPID;"; + String queryToFetchEncryptionStatusOfSelfConnection = "SELECT \n" + " c.encrypt_option \n" + + "FROM sys.dm_exec_connections AS c \n" + + "JOIN sys.dm_exec_sessions AS s \n" + + " ON c.session_id = s.session_id \n" + + "WHERE c.session_id = @@SPID;"; actionConfiguration.setBody(queryToFetchEncryptionStatusOfSelfConnection); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); @@ -684,8 +658,8 @@ public void testSSLNoVerifyConnectionIsEncrypted() { dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY); Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -699,13 +673,11 @@ public void testSSLNoVerifyConnectionIsEncrypted() { @Test public void testSSLDisabledConnectionIsNotEncrypted() { ActionConfiguration actionConfiguration = new ActionConfiguration(); - String queryToFetchEncryptionStatusOfSelfConnection = - "SELECT \n" + - " c.encrypt_option \n" + - "FROM sys.dm_exec_connections AS c \n" + - "JOIN sys.dm_exec_sessions AS s \n" + - " ON c.session_id = s.session_id \n" + - "WHERE c.session_id = @@SPID;"; + String queryToFetchEncryptionStatusOfSelfConnection = "SELECT \n" + " c.encrypt_option \n" + + "FROM sys.dm_exec_connections AS c \n" + + "JOIN sys.dm_exec_sessions AS s \n" + + " ON c.session_id = s.session_id \n" + + "WHERE c.session_id = @@SPID;"; actionConfiguration.setBody(queryToFetchEncryptionStatusOfSelfConnection); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); @@ -720,8 +692,8 @@ public void testSSLDisabledConnectionIsNotEncrypted() { dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.DISABLE); Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> + mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -731,5 +703,4 @@ public void testSSLDisabledConnectionIsNotEncrypted() { }) .verifyComplete(); } - } diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java index ac8c02a596ad..4f1395027618 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java @@ -24,8 +24,8 @@ public class MssqlTestDBContainerManager { @SuppressWarnings("rawtypes") public static MSSQLServerContainer getMssqlDBForTest() { - return new MSSQLServerContainer<>( - DockerImageName.parse("mcr.microsoft.com/azure-sql-edge:1.0.3").asCompatibleSubstituteFor("mcr.microsoft.com/mssql/server:2017-latest")) + return new MSSQLServerContainer<>(DockerImageName.parse("mcr.microsoft.com/azure-sql-edge:1.0.3") + .asCompatibleSubstituteFor("mcr.microsoft.com/mssql/server:2017-latest")) .acceptLicense() .withExposedPorts(1433) .withPassword("Mssql123"); diff --git a/app/server/appsmith-plugins/mysqlPlugin/pom.xml b/app/server/appsmith-plugins/mysqlPlugin/pom.xml index 725c77bf9eeb..e82732a17c8d 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/pom.xml +++ b/app/server/appsmith-plugins/mysqlPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>mysqlPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -43,17 +42,17 @@ <dependency> <groupId>io.netty</groupId> <artifactId>netty-resolver-dns-native-macos</artifactId> - <scope>runtime</scope> - <classifier>osx-x86_64</classifier> <version>4.1.75.Final</version> + <classifier>osx-x86_64</classifier> + <scope>runtime</scope> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-resolver-dns-native-macos</artifactId> - <scope>runtime</scope> - <classifier>osx-aarch_64</classifier> <version>4.1.75.Final</version> + <classifier>osx-aarch_64</classifier> + <scope>runtime</scope> </dependency> <dependency> @@ -124,10 +123,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java index b2909a43805d..034b1388293b 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java @@ -94,21 +94,21 @@ public class MySqlPlugin extends BasePlugin { * | test | 4 | lastname | varchar | 1 | | | * +------------+-----------+-------------+-------------+-------------+------------+----------------+ */ - private static final String COLUMNS_QUERY = "select tab.table_name as table_name,\n" + - " col.ordinal_position as column_id,\n" + - " col.column_name as column_name,\n" + - " col.data_type as column_type,\n" + - " col.is_nullable = 'YES' as is_nullable,\n" + - " col.column_key,\n" + - " col.extra\n" + - "from information_schema.tables as tab\n" + - " inner join information_schema.columns as col\n" + - " on col.table_schema = tab.table_schema\n" + - " and col.table_name = tab.table_name\n" + - "where tab.table_type = 'BASE TABLE'\n" + - " and tab.table_schema = database()\n" + - "order by tab.table_name,\n" + - " col.ordinal_position;"; + private static final String COLUMNS_QUERY = + "select tab.table_name as table_name,\n" + " col.ordinal_position as column_id,\n" + + " col.column_name as column_name,\n" + + " col.data_type as column_type,\n" + + " col.is_nullable = 'YES' as is_nullable,\n" + + " col.column_key,\n" + + " col.extra\n" + + "from information_schema.tables as tab\n" + + " inner join information_schema.columns as col\n" + + " on col.table_schema = tab.table_schema\n" + + " and col.table_name = tab.table_name\n" + + "where tab.table_type = 'BASE TABLE'\n" + + " and tab.table_schema = database()\n" + + "order by tab.table_name,\n" + + " col.ordinal_position;"; /** * Example output for KEYS_QUERY: @@ -118,22 +118,22 @@ public class MySqlPlugin extends BasePlugin { * | PRIMARY | mytestdb | test | p | id | NULL | NULL | NULL | * +-----------------+-------------+------------+-----------------+-------------+----------------+---------------+----------------+ */ - private static final String KEYS_QUERY = "select i.constraint_name,\n" + - " i.TABLE_SCHEMA as self_schema,\n" + - " i.table_name as self_table,\n" + - " if(i.constraint_type = 'FOREIGN KEY', 'f', 'p') as constraint_type,\n" + - " k.column_name as self_column, -- k.ordinal_position, k.position_in_unique_constraint,\n" + - " k.referenced_table_schema as foreign_schema,\n" + - " k.referenced_table_name as foreign_table,\n" + - " k.referenced_column_name as foreign_column\n" + - "from information_schema.table_constraints i\n" + - " left join information_schema.key_column_usage k\n" + - " on i.constraint_name = k.constraint_name and i.table_name = k.table_name\n" + - "where i.table_schema = database()\n" + - " and k.constraint_schema = database()\n" + + private static final String KEYS_QUERY = "select i.constraint_name,\n" + " i.TABLE_SCHEMA as self_schema,\n" + + " i.table_name as self_table,\n" + + " if(i.constraint_type = 'FOREIGN KEY', 'f', 'p') as constraint_type,\n" + + " k.column_name as self_column, -- k.ordinal_position, k.position_in_unique_constraint,\n" + + " k.referenced_table_schema as foreign_schema,\n" + + " k.referenced_table_name as foreign_table,\n" + + " k.referenced_column_name as foreign_column\n" + + "from information_schema.table_constraints i\n" + + " left join information_schema.key_column_usage k\n" + + " on i.constraint_name = k.constraint_name and i.table_name = k.table_name\n" + + "where i.table_schema = database()\n" + + " and k.constraint_schema = database()\n" + + // " and i.enforced = 'YES'\n" + // Looks like this is not available on all versions of MySQL. - " and i.constraint_type in ('FOREIGN KEY', 'PRIMARY KEY')\n" + - "order by i.table_name, i.constraint_name, k.position_in_unique_constraint;"; + " and i.constraint_type in ('FOREIGN KEY', 'PRIMARY KEY')\n" + + "order by i.table_name, i.constraint_name, k.position_in_unique_constraint;"; public MySqlPlugin(PluginWrapper wrapper) { super(wrapper); @@ -160,10 +160,11 @@ public static class MySqlPluginExecutor implements PluginExecutor<ConnectionPool * @return */ @Override - public Mono<ActionExecutionResult> executeParameterized(ConnectionPool connection, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> executeParameterized( + ConnectionPool connection, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final Map<String, Object> requestData = new HashMap<>(); @@ -190,10 +191,12 @@ public Mono<ActionExecutionResult> executeParameterized(ConnectionPool connectio String query = actionConfiguration.getBody(); // Check for query parameter before performing the probably expensive fetch connection from the pool op. - if (! StringUtils.hasLength(query)) { + if (!StringUtils.hasLength(query)) { ActionExecutionResult errorResult = new ActionExecutionResult(); errorResult.setIsExecutionSuccess(false); - errorResult.setErrorInfo(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, MySQLErrorMessages.MISSING_PARAMETER_QUERY_ERROR_MSG)); + errorResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + MySQLErrorMessages.MISSING_PARAMETER_QUERY_ERROR_MSG)); ActionExecutionRequest actionExecutionRequest = new ActionExecutionRequest(); actionExecutionRequest.setProperties(requestData); errorResult.setRequest(actionExecutionRequest); @@ -208,22 +211,24 @@ public Mono<ActionExecutionResult> executeParameterized(ConnectionPool connectio return executeCommon(connection, actionConfiguration, FALSE, null, null, requestData); } - //This has to be executed as Prepared Statement + // This has to be executed as Prepared Statement // First extract all the bindings in order List<MustacheBindingToken> mustacheKeysInOrder = MustacheHelper.extractMustacheKeysInOrder(query); // Replace all the bindings with a ? as expected in a prepared statement. String updatedQuery = MustacheHelper.replaceMustacheWithQuestionMark(query, mustacheKeysInOrder); // Set the query with bindings extracted and replaced with '?' back in config actionConfiguration.setBody(updatedQuery); - return executeCommon(connection, actionConfiguration, TRUE, mustacheKeysInOrder, executeActionDTO, requestData); + return executeCommon( + connection, actionConfiguration, TRUE, mustacheKeysInOrder, executeActionDTO, requestData); } - public Mono<ActionExecutionResult> executeCommon(ConnectionPool connectionPool, - ActionConfiguration actionConfiguration, - Boolean preparedStatement, - List<MustacheBindingToken> mustacheValuesInOrder, - ExecuteActionDTO executeActionDTO, - Map<String, Object> requestData) { + public Mono<ActionExecutionResult> executeCommon( + ConnectionPool connectionPool, + ActionConfiguration actionConfiguration, + Boolean preparedStatement, + List<MustacheBindingToken> mustacheValuesInOrder, + ExecuteActionDTO executeActionDTO, + Map<String, Object> requestData) { String query = actionConfiguration.getBody(); /** @@ -236,12 +241,9 @@ public Mono<ActionExecutionResult> executeCommon(ConnectionPool connectionPool, String finalQuery = QueryUtils.removeQueryComments(query); if (preparedStatement && isIsOperatorUsed(finalQuery)) { - return Mono.error( - new AppsmithPluginException( - MySQLPluginError.IS_KEYWORD_NOT_ALLOWED_IN_PREPARED_STATEMENT, - MySQLErrorMessages.IS_KEYWORD_NOT_SUPPORTED_IN_PS_ERROR_MSG - ) - ); + return Mono.error(new AppsmithPluginException( + MySQLPluginError.IS_KEYWORD_NOT_ALLOWED_IN_PREPARED_STATEMENT, + MySQLErrorMessages.IS_KEYWORD_NOT_SUPPORTED_IN_PS_ERROR_MSG)); } boolean isSelectOrShowOrDescQuery = getIsSelectOrShowOrDescQuery(finalQuery); @@ -250,125 +252,141 @@ public Mono<ActionExecutionResult> executeCommon(ConnectionPool connectionPool, final List<String> columnsList = new ArrayList<>(); Map<String, Object> psParams = preparedStatement ? new LinkedHashMap<>() : null; String transformedQuery = preparedStatement ? replaceQuestionMarkWithDollarIndex(finalQuery) : finalQuery; - List<RequestParamDTO> requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - transformedQuery, null, null, psParams)); + List<RequestParamDTO> requestParams = + List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, transformedQuery, null, null, psParams)); return Mono.usingWhen( - connectionPool.create(), - connection -> { - // TODO: add JUnit TC for the `connection.validate` check. Not sure how to do it at the moment. - Flux<Result> resultFlux = Mono.from(connection.validate(ValidationDepth.LOCAL)) - .timeout(Duration.ofSeconds(VALIDATION_CHECK_TIMEOUT)) - .onErrorMap(TimeoutException.class, error -> new StaleConnectionException(error.getMessage())) - .flatMapMany(isValid -> { - if (isValid) { - return createAndExecuteQueryFromConnection(finalQuery, - connection, - preparedStatement, - mustacheValuesInOrder, - executeActionDTO, - requestData, - psParams); - } - return Flux.error(new StaleConnectionException(CONNECTION_VALIDITY_CHECK_FAILED_ERROR_MSG)); - }); - - Mono<List<Map<String, Object>>> resultMono; - if (isSelectOrShowOrDescQuery) { - resultMono = resultFlux - .flatMap(result -> - result.map((row, meta) -> { - rowsList.add(getRow(row, meta)); - - if (columnsList.isEmpty()) { - meta.getColumnMetadatas().stream().forEach(columnMetadata -> columnsList.add(columnMetadata.getName())); - } - - return result; - } - ) - ) - .collectList() - .thenReturn(rowsList); - } else { - resultMono = resultFlux - .flatMap(Result::getRowsUpdated) - .collectList() - .map(list -> list.get(list.size() - 1)) - .map(rowsUpdated -> { - rowsList.add( - Map.of( - "affectedRows", - ObjectUtils.defaultIfNull(rowsUpdated, 0) - ) - ); - return rowsList; - }); - } - - return resultMono - .map(res -> { - ActionExecutionResult result = new ActionExecutionResult(); - result.setBody(objectMapper.valueToTree(rowsList)); - result.setMessages(populateHintMessages(columnsList)); - result.setIsExecutionSuccess(true); - log.debug("In the MySqlPlugin, got action execution result"); - return result; - }) - .onErrorResume(error -> { - if (error instanceof StaleConnectionException) { - return Mono.error(error); - } else if (error instanceof R2dbcBadGrammarException) { - R2dbcBadGrammarException r2dbcBadGrammarException = ((R2dbcBadGrammarException) error); - error = new AppsmithPluginException(MySQLPluginError.INVALID_QUERY_SYNTAX, r2dbcBadGrammarException.getMessage(), "SQLSTATE: " +r2dbcBadGrammarException.getSqlState()); - } else if (error instanceof R2dbcPermissionDeniedException) { - R2dbcPermissionDeniedException r2dbcPermissionDeniedException = (R2dbcPermissionDeniedException) error; - error = new AppsmithPluginException(MySQLPluginError.MISSING_REQUIRED_PERMISSION, r2dbcPermissionDeniedException.getMessage(), "SQLSTATE: " + r2dbcPermissionDeniedException.getSqlState()); - } else if (error instanceof R2dbcException) { - R2dbcException r2dbcException = (R2dbcException) error; - error = new AppsmithPluginException(MySQLPluginError.QUERY_EXECUTION_FAILED, MySQLErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, r2dbcException.getMessage(), "SQLSTATE: " + r2dbcException.getSqlState()); - } else if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(MySQLPluginError.QUERY_EXECUTION_FAILED, MySQLErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error); - } - ActionExecutionResult result = new ActionExecutionResult(); - result.setIsExecutionSuccess(false); - result.setErrorInfo(error); - return Mono.just(result); - }) - // Now set the request in the result to be returned to the server - .map(actionExecutionResult -> { - ActionExecutionRequest request = new ActionExecutionRequest(); - request.setQuery(finalQuery); - request.setProperties(requestData); - request.setRequestParams(requestParams); - ActionExecutionResult result = actionExecutionResult; - result.setRequest(request); - - return result; - }); - }, - Connection::close - ) - .onErrorMap(TimeoutException.class, error -> new StaleConnectionException(error.getMessage())) - .onErrorMap(PoolShutdownException.class, error -> new StaleConnectionException(error.getMessage())) - .onErrorMap(R2dbcNonTransientResourceException.class, error -> new StaleConnectionException(error.getMessage())) - .onErrorMap(IllegalStateException.class, error -> new StaleConnectionException(error.getMessage())) - .subscribeOn(scheduler); + connectionPool.create(), + connection -> { + // TODO: add JUnit TC for the `connection.validate` check. Not sure how to do it at the + // moment. + Flux<Result> resultFlux = Mono.from(connection.validate(ValidationDepth.LOCAL)) + .timeout(Duration.ofSeconds(VALIDATION_CHECK_TIMEOUT)) + .onErrorMap( + TimeoutException.class, + error -> new StaleConnectionException(error.getMessage())) + .flatMapMany(isValid -> { + if (isValid) { + return createAndExecuteQueryFromConnection( + finalQuery, + connection, + preparedStatement, + mustacheValuesInOrder, + executeActionDTO, + requestData, + psParams); + } + return Flux.error(new StaleConnectionException( + CONNECTION_VALIDITY_CHECK_FAILED_ERROR_MSG)); + }); + + Mono<List<Map<String, Object>>> resultMono; + if (isSelectOrShowOrDescQuery) { + resultMono = resultFlux + .flatMap(result -> result.map((row, meta) -> { + rowsList.add(getRow(row, meta)); + + if (columnsList.isEmpty()) { + meta.getColumnMetadatas().stream() + .forEach(columnMetadata -> + columnsList.add(columnMetadata.getName())); + } + + return result; + })) + .collectList() + .thenReturn(rowsList); + } else { + resultMono = resultFlux + .flatMap(Result::getRowsUpdated) + .collectList() + .map(list -> list.get(list.size() - 1)) + .map(rowsUpdated -> { + rowsList.add(Map.of( + "affectedRows", ObjectUtils.defaultIfNull(rowsUpdated, 0))); + return rowsList; + }); + } + + return resultMono + .map(res -> { + ActionExecutionResult result = new ActionExecutionResult(); + result.setBody(objectMapper.valueToTree(rowsList)); + result.setMessages(populateHintMessages(columnsList)); + result.setIsExecutionSuccess(true); + log.debug("In the MySqlPlugin, got action execution result"); + return result; + }) + .onErrorResume(error -> { + if (error instanceof StaleConnectionException) { + return Mono.error(error); + } else if (error instanceof R2dbcBadGrammarException) { + R2dbcBadGrammarException r2dbcBadGrammarException = + ((R2dbcBadGrammarException) error); + error = new AppsmithPluginException( + MySQLPluginError.INVALID_QUERY_SYNTAX, + r2dbcBadGrammarException.getMessage(), + "SQLSTATE: " + r2dbcBadGrammarException.getSqlState()); + } else if (error instanceof R2dbcPermissionDeniedException) { + R2dbcPermissionDeniedException r2dbcPermissionDeniedException = + (R2dbcPermissionDeniedException) error; + error = new AppsmithPluginException( + MySQLPluginError.MISSING_REQUIRED_PERMISSION, + r2dbcPermissionDeniedException.getMessage(), + "SQLSTATE: " + r2dbcPermissionDeniedException.getSqlState()); + } else if (error instanceof R2dbcException) { + R2dbcException r2dbcException = (R2dbcException) error; + error = new AppsmithPluginException( + MySQLPluginError.QUERY_EXECUTION_FAILED, + MySQLErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + r2dbcException.getMessage(), + "SQLSTATE: " + r2dbcException.getSqlState()); + } else if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + MySQLPluginError.QUERY_EXECUTION_FAILED, + MySQLErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error); + } + ActionExecutionResult result = new ActionExecutionResult(); + result.setIsExecutionSuccess(false); + result.setErrorInfo(error); + return Mono.just(result); + }) + // Now set the request in the result to be returned to the server + .map(actionExecutionResult -> { + ActionExecutionRequest request = new ActionExecutionRequest(); + request.setQuery(finalQuery); + request.setProperties(requestData); + request.setRequestParams(requestParams); + ActionExecutionResult result = actionExecutionResult; + result.setRequest(request); + + return result; + }); + }, + Connection::close) + .onErrorMap(TimeoutException.class, error -> new StaleConnectionException(error.getMessage())) + .onErrorMap(PoolShutdownException.class, error -> new StaleConnectionException(error.getMessage())) + .onErrorMap( + R2dbcNonTransientResourceException.class, + error -> new StaleConnectionException(error.getMessage())) + .onErrorMap(IllegalStateException.class, error -> new StaleConnectionException(error.getMessage())) + .subscribeOn(scheduler); } boolean isIsOperatorUsed(String query) { String queryKeyWordsOnly = query.replaceAll(MATCH_QUOTED_WORDS_REGEX, ""); - return Arrays.stream(queryKeyWordsOnly.split("\\s")) - .anyMatch(word -> IS_KEY.equalsIgnoreCase(word.trim())); + return Arrays.stream(queryKeyWordsOnly.split("\\s")).anyMatch(word -> IS_KEY.equalsIgnoreCase(word.trim())); } - private Flux<Result> createAndExecuteQueryFromConnection(String query, - Connection connection, - Boolean preparedStatement, - List<MustacheBindingToken> mustacheValuesInOrder, - ExecuteActionDTO executeActionDTO, - Map<String, Object> requestData, - Map psParams) { + private Flux<Result> createAndExecuteQueryFromConnection( + String query, + Connection connection, + Boolean preparedStatement, + List<MustacheBindingToken> mustacheValuesInOrder, + ExecuteActionDTO executeActionDTO, + Map<String, Object> requestData, + Map psParams) { Statement connectionStatement = connection.createStatement(query); if (FALSE.equals(preparedStatement) || mustacheValuesInOrder == null || mustacheValuesInOrder.isEmpty()) { @@ -379,26 +397,23 @@ private Flux<Result> createAndExecuteQueryFromConnection(String query, List<Map.Entry<String, String>> parameters = new ArrayList<>(); try { - connectionStatement = (Statement) this.smartSubstitutionOfBindings(connectionStatement, - mustacheValuesInOrder, - executeActionDTO.getParams(), - parameters); + connectionStatement = (Statement) this.smartSubstitutionOfBindings( + connectionStatement, mustacheValuesInOrder, executeActionDTO.getParams(), parameters); requestData.put("ps-parameters", parameters); IntStream.range(0, parameters.size()) - .forEachOrdered(i -> - psParams.put( - getPSParamLabel(i + 1), - new PsParameterDTO(parameters.get(i).getKey(), parameters.get(i).getValue()))); + .forEachOrdered(i -> psParams.put( + getPSParamLabel(i + 1), + new PsParameterDTO( + parameters.get(i).getKey(), + parameters.get(i).getValue()))); } catch (AppsmithPluginException e) { return Flux.error(e); } - return Flux.from(connectionStatement.execute()); - } @Override @@ -407,22 +422,25 @@ public Mono<DatasourceTestResult> testDatasource(ConnectionPool pool) { .flatMap(p -> p.create()) .flatMap(conn -> Mono.from(conn.close())) .then(Mono.just(new DatasourceTestResult())) - .onErrorResume(error -> Mono.just(new DatasourceTestResult( - mySqlErrorUtils.getReadableError(error)))); + .onErrorResume( + error -> Mono.just(new DatasourceTestResult(mySqlErrorUtils.getReadableError(error)))); } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) { Statement connectionStatement = (Statement) input; Param param = (Param) args[0]; - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(param.getClientDataType(), value, MySQLSpecificDataTypes.pluginSpecificTypes); - Map.Entry<String, String> parameter = new SimpleEntry<>(value, appsmithType.type().toString()); + AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType( + param.getClientDataType(), value, MySQLSpecificDataTypes.pluginSpecificTypes); + Map.Entry<String, String> parameter = + new SimpleEntry<>(value, appsmithType.type().toString()); insertedParams.add(parameter); switch (appsmithType.type()) { @@ -458,9 +476,10 @@ private Set<String> populateHintMessages(List<String> columnNames) { List<String> identicalColumns = getIdenticalColumns(columnNames); if (!CollectionUtils.isEmpty(identicalColumns)) { - messages.add("Your MySQL query result may not have all the columns because duplicate column names " + - "were found for the column(s): " + String.join(", ", identicalColumns) + ". You may use the " + - "SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); + messages.add("Your MySQL query result may not have all the columns because duplicate column names " + + "were found for the column(s): " + + String.join(", ", identicalColumns) + ". You may use the " + + "SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); } return messages; @@ -471,7 +490,8 @@ private Set<String> populateHintMessages(List<String> columnNames) { * 2. Return the row as a map {column_name -> column_value}. */ private Map<String, Object> getRow(Row row, RowMetadata meta) { - Iterator<ColumnDefinitionPacket> iterator = (Iterator<ColumnDefinitionPacket>) meta.getColumnMetadatas().iterator(); + Iterator<ColumnDefinitionPacket> iterator = + (Iterator<ColumnDefinitionPacket>) meta.getColumnMetadatas().iterator(); Map<String, Object> processedRow = new LinkedHashMap<>(); while (iterator.hasNext()) { @@ -483,16 +503,14 @@ private Map<String, Object> getRow(Row row, RowMetadata meta) { if (java.time.LocalDate.class.toString().equalsIgnoreCase(javaTypeName) && columnValue != null) { columnValue = DateTimeFormatter.ISO_DATE.format(row.get(columnName, LocalDate.class)); - } else if ((java.time.LocalDateTime.class.toString().equalsIgnoreCase(javaTypeName)) && columnValue != null) { - columnValue = DateTimeFormatter.ISO_DATE_TIME.format( - LocalDateTime.of( + } else if ((java.time.LocalDateTime.class.toString().equalsIgnoreCase(javaTypeName)) + && columnValue != null) { + columnValue = DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.of( row.get(columnName, LocalDateTime.class).toLocalDate(), - row.get(columnName, LocalDateTime.class).toLocalTime() - ) - ) + "Z"; + row.get(columnName, LocalDateTime.class).toLocalTime())) + + "Z"; } else if (java.time.LocalTime.class.toString().equalsIgnoreCase(javaTypeName) && columnValue != null) { - columnValue = DateTimeFormatter.ISO_TIME.format(row.get(columnName, - LocalTime.class)); + columnValue = DateTimeFormatter.ISO_TIME.format(row.get(columnName, LocalTime.class)); } else if (java.time.Year.class.toString().equalsIgnoreCase(javaTypeName) && columnValue != null) { columnValue = row.get(columnName, LocalDate.class).getYear(); } else if (JSON_DB_TYPE.equals(sqlColumnType)) { @@ -532,16 +550,20 @@ boolean getIsSelectOrShowOrDescQuery(String query) { String lastQuery = queries[queries.length - 1].trim(); - return - Arrays.asList("select", "show", "describe", "desc") - .contains(lastQuery.trim().split("\\s+")[0].toLowerCase()); + return Arrays.asList("select", "show", "describe", "desc") + .contains(lastQuery.trim().split("\\s+")[0].toLowerCase()); } @Override - public Mono<ActionExecutionResult> execute(ConnectionPool connection, - DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + ConnectionPool connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Unused function - return Mono.error(new AppsmithPluginException(MySQLPluginError.QUERY_EXECUTION_FAILED, MySQLErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, "Unsupported Operation")); + return Mono.error(new AppsmithPluginException( + MySQLPluginError.QUERY_EXECUTION_FAILED, + MySQLErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + "Unsupported Operation")); } @Override @@ -554,10 +576,12 @@ public Mono<ConnectionPool> datasourceCreate(DatasourceConfiguration datasourceC } return Mono.just(pool); } + @Override public void datasourceDestroy(ConnectionPool connectionPool) { if (connectionPool != null) { - connectionPool.disposeLater() + connectionPool + .disposeLater() .onErrorResume(exception -> { log.debug("In datasourceDestroy function error mode.", exception); return Mono.empty(); @@ -573,64 +597,70 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur } @Override - public Mono<DatasourceStructure> getStructure(ConnectionPool connectionPool, - DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + ConnectionPool connectionPool, DatasourceConfiguration datasourceConfiguration) { final DatasourceStructure structure = new DatasourceStructure(); final Map<String, DatasourceStructure.Table> tablesByName = new LinkedHashMap<>(); final Map<String, DatasourceStructure.Key> keyRegistry = new HashMap<>(); return Mono.usingWhen( - connectionPool.create(), - connection -> Mono.from(connection.validate(ValidationDepth.REMOTE)) - .timeout(Duration.ofSeconds(VALIDATION_CHECK_TIMEOUT)) - .onErrorMap(TimeoutException.class, error -> new StaleConnectionException(error.getMessage())) - .flatMapMany(isValid -> { - if (isValid) { - return connection.createStatement(COLUMNS_QUERY).execute(); - } else { - return Flux.error(new StaleConnectionException(CONNECTION_VALIDITY_CHECK_FAILED_ERROR_MSG)); - } - }) - .flatMap(result -> { - return result.map((row, meta) -> { - getTableInfo(row, meta, tablesByName); - - return result; - }); - }) - .collectList() - .thenMany(Flux.from(connection.createStatement(KEYS_QUERY).execute())) - .flatMap(result -> { - return result.map((row, meta) -> { - getKeyInfo(row, meta, tablesByName, keyRegistry); - - return result; - }); - }) - .collectList() - .map(list -> { - /* Get templates for each table and put those in. */ - getTemplates(tablesByName); - structure.setTables(new ArrayList<>(tablesByName.values())); - for (DatasourceStructure.Table table : structure.getTables()) { - table.getKeys().sort(Comparator.naturalOrder()); - } - - return structure; - }) - .onErrorMap(e -> { - if (!(e instanceof AppsmithPluginException) && !(e instanceof StaleConnectionException)) { - return new AppsmithPluginException( - AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, - MySQLErrorMessages.GET_STRUCTURE_ERROR_MSG, - e.getMessage() - ); - } - - return e; - }), - Connection::close - ) + connectionPool.create(), + connection -> Mono.from(connection.validate(ValidationDepth.REMOTE)) + .timeout(Duration.ofSeconds(VALIDATION_CHECK_TIMEOUT)) + .onErrorMap( + TimeoutException.class, + error -> new StaleConnectionException(error.getMessage())) + .flatMapMany(isValid -> { + if (isValid) { + return connection + .createStatement(COLUMNS_QUERY) + .execute(); + } else { + return Flux.error(new StaleConnectionException( + CONNECTION_VALIDITY_CHECK_FAILED_ERROR_MSG)); + } + }) + .flatMap(result -> { + return result.map((row, meta) -> { + getTableInfo(row, meta, tablesByName); + + return result; + }); + }) + .collectList() + .thenMany(Flux.from(connection + .createStatement(KEYS_QUERY) + .execute())) + .flatMap(result -> { + return result.map((row, meta) -> { + getKeyInfo(row, meta, tablesByName, keyRegistry); + + return result; + }); + }) + .collectList() + .map(list -> { + /* Get templates for each table and put those in. */ + getTemplates(tablesByName); + structure.setTables(new ArrayList<>(tablesByName.values())); + for (DatasourceStructure.Table table : structure.getTables()) { + table.getKeys().sort(Comparator.naturalOrder()); + } + + return structure; + }) + .onErrorMap(e -> { + if (!(e instanceof AppsmithPluginException) + && !(e instanceof StaleConnectionException)) { + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + MySQLErrorMessages.GET_STRUCTURE_ERROR_MSG, + e.getMessage()); + } + + return e; + }), + Connection::close) .onErrorMap(TimeoutException.class, error -> new StaleConnectionException(error.getMessage())) .onErrorMap(PoolShutdownException.class, error -> new StaleConnectionException(error.getMessage())) .subscribeOn(scheduler); diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLDateTimeType.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLDateTimeType.java index 74eeec9c3baf..35c99e4469e0 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLDateTimeType.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLDateTimeType.java @@ -42,12 +42,7 @@ public String performSmartSubstitution(String s) { return Matcher.quoteReplacement(valueAsString); } catch (JsonProcessingException e) { throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - s, - e.getMessage() - ) - ); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, s, e.getMessage())); } } diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLDateType.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLDateType.java index 2f8d2c67864b..81ca9477b440 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLDateType.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLDateType.java @@ -26,4 +26,4 @@ public boolean test(String s) { return false; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLSpecificDataTypes.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLSpecificDataTypes.java index 626d1017b55d..36c5e2e54e64 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLSpecificDataTypes.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/datatypes/MySQLSpecificDataTypes.java @@ -24,23 +24,16 @@ public class MySQLSpecificDataTypes { pluginSpecificTypes.put(ClientDataType.BOOLEAN, List.of(new MySQLBooleanType())); - pluginSpecificTypes.put(ClientDataType.NUMBER, List.of( - new IntegerType(), - new LongType(), - new DoubleType(), - new BigDecimalType() - )); + pluginSpecificTypes.put( + ClientDataType.NUMBER, + List.of(new IntegerType(), new LongType(), new DoubleType(), new BigDecimalType())); pluginSpecificTypes.put(ClientDataType.OBJECT, List.of(new JsonObjectType())); - pluginSpecificTypes.put(ClientDataType.STRING, List.of( - new TimeType(), - new MySQLDateType(), - new MySQLDateTimeType(), - new StringType() - )); + pluginSpecificTypes.put( + ClientDataType.STRING, + List.of(new TimeType(), new MySQLDateType(), new MySQLDateTimeType(), new StringType())); pluginSpecificTypes.put(ClientDataType.ARRAY, List.of(new StringType())); } - } diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/exceptions/MySQLErrorMessages.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/exceptions/MySQLErrorMessages.java index 293fb32ec10c..1d29a3be24bf 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/exceptions/MySQLErrorMessages.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/exceptions/MySQLErrorMessages.java @@ -8,17 +8,20 @@ public class MySQLErrorMessages extends BasePluginErrorMessages { public static final String MISSING_PARAMETER_QUERY_ERROR_MSG = "Missing required parameter: Query."; - public static final String IS_KEYWORD_NOT_SUPPORTED_IN_PS_ERROR_MSG = "Appsmith currently does not support the IS keyword with the prepared statement " + - "setting turned ON. Please re-write your SQL query without the IS keyword"; + public static final String IS_KEYWORD_NOT_SUPPORTED_IN_PS_ERROR_MSG = + "Appsmith currently does not support the IS keyword with the prepared statement " + + "setting turned ON. Please re-write your SQL query without the IS keyword"; - public static final String GET_STRUCTURE_ERROR_MSG = "The Appsmith server has failed to fetch the structure of your schema."; + public static final String GET_STRUCTURE_ERROR_MSG = + "The Appsmith server has failed to fetch the structure of your schema."; public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Your MySQL query failed to execute."; - public static final String UNEXPECTED_SSL_OPTION_ERROR_MSG = "The Appsmith server has found an unexpected SSL option: %s."; - - public static final String SSL_CONFIGURATION_FETCHING_ERROR_MSG = "The Appsmith server has failed to fetch SSL configuration from datasource configuration form."; + public static final String UNEXPECTED_SSL_OPTION_ERROR_MSG = + "The Appsmith server has found an unexpected SSL option: %s."; + public static final String SSL_CONFIGURATION_FETCHING_ERROR_MSG = + "The Appsmith server has failed to fetch SSL configuration from datasource configuration form."; /* ************************************************************************************************************************************************ @@ -27,13 +30,15 @@ public class MySQLErrorMessages extends BasePluginErrorMessages { */ public static final String DS_MISSING_ENDPOINT_ERROR_MSG = "Missing endpoint and url"; public static final String DS_MISSING_HOSTNAME_ERROR_MSG = "Host value cannot be empty"; - public static final String DS_INVALID_HOSTNAME_ERROR_MSG = "Host value cannot contain `/` or `:` characters. Found `%s`."; + public static final String DS_INVALID_HOSTNAME_ERROR_MSG = + "Host value cannot contain `/` or `:` characters. Found `%s`."; public static final String DS_MISSING_AUTHENTICATION_DETAILS_ERROR_MSG = "Missing authentication details."; public static final String DS_MISSING_USERNAME_ERROR_MSG = "Missing username for authentication."; public static final String DS_MISSING_PASSWORD_ERROR_MSG = "Missing password for authentication."; public static final String DS_MISSING_DATABASE_NAME_ERROR_MSG = "Missing database name."; - public static final String DS_SSL_CONFIGURATION_FETCHING_FAILED_ERROR_MSG = "Appsmith server has failed to fetch SSL configuration from datasource configuration form. " + - "Please reach out to Appsmith customer support to resolve this."; - public static final String CONNECTION_VALIDITY_CHECK_FAILED_ERROR_MSG = "Connection obtained from connection pool" + - " is invalid."; + public static final String DS_SSL_CONFIGURATION_FETCHING_FAILED_ERROR_MSG = + "Appsmith server has failed to fetch SSL configuration from datasource configuration form. " + + "Please reach out to Appsmith customer support to resolve this."; + public static final String CONNECTION_VALIDITY_CHECK_FAILED_ERROR_MSG = + "Connection obtained from connection pool" + " is invalid."; } diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/exceptions/MySQLPluginError.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/exceptions/MySQLPluginError.java index a600bfe03833..6436f86b6bac 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/exceptions/MySQLPluginError.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/exceptions/MySQLPluginError.java @@ -17,8 +17,7 @@ public enum MySQLPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), MYSQL_PLUGIN_ERROR( 500, "PE-MYS-5001", @@ -27,8 +26,7 @@ public enum MySQLPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), IS_KEYWORD_NOT_ALLOWED_IN_PREPARED_STATEMENT( 500, "PE-MYS-4001", @@ -37,8 +35,7 @@ public enum MySQLPluginError implements BasePluginError { "Query configuration is invalid", ErrorType.ACTION_CONFIGURATION_ERROR, "{1}", - "{2}" - ), + "{2}"), INVALID_QUERY_SYNTAX( 400, "PE-MYS-4002", @@ -47,8 +44,7 @@ public enum MySQLPluginError implements BasePluginError { "Query syntax error", ErrorType.ACTION_CONFIGURATION_ERROR, "{0}", - "{1}" - ), + "{1}"), MISSING_REQUIRED_PERMISSION( 403, "PE-MYS-4003", @@ -57,8 +53,7 @@ public enum MySQLPluginError implements BasePluginError { "Required permission missing", ErrorType.AUTHENTICATION_ERROR, "{0}", - "{1}" - ), + "{1}"), ; private final Integer httpErrorCode; private final String appErrorCode; @@ -71,8 +66,15 @@ public enum MySQLPluginError implements BasePluginError { private final String downstreamErrorCode; - MySQLPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + MySQLPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -87,7 +89,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlDatasourceUtils.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlDatasourceUtils.java index f518283af605..9405191739b9 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlDatasourceUtils.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlDatasourceUtils.java @@ -78,7 +78,6 @@ public static ConnectionFactoryOptions.Builder getBuilder(DatasourceConfiguratio if (!StringUtils.isEmpty(authentication.getDatabaseName())) { urlBuilder.append(authentication.getDatabaseName()); } - } urlBuilder.append("?zeroDateTimeBehavior=convertToNull&allowMultiQueries=true"); @@ -94,15 +93,17 @@ public static ConnectionFactoryOptions.Builder getBuilder(DatasourceConfiguratio } ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(urlBuilder.toString()); - ConnectionFactoryOptions.Builder ob = ConnectionFactoryOptions.builder().from(baseOptions) + ConnectionFactoryOptions.Builder ob = ConnectionFactoryOptions.builder() + .from(baseOptions) .option(ConnectionFactoryOptions.USER, authentication.getUsername()) .option(ConnectionFactoryOptions.PASSWORD, authentication.getPassword()); return ob; } - public static ConnectionFactoryOptions.Builder addSslOptionsToBuilder(DatasourceConfiguration datasourceConfiguration, - ConnectionFactoryOptions.Builder ob) throws AppsmithPluginException { + public static ConnectionFactoryOptions.Builder addSslOptionsToBuilder( + DatasourceConfiguration datasourceConfiguration, ConnectionFactoryOptions.Builder ob) + throws AppsmithPluginException { /* * - Ideally, it is never expected to be null because the SSL dropdown is set to a initial value. */ @@ -110,20 +111,21 @@ public static ConnectionFactoryOptions.Builder addSslOptionsToBuilder(Datasource || datasourceConfiguration.getConnection().getSsl() == null || datasourceConfiguration.getConnection().getSsl().getAuthType() == null) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - MySQLErrorMessages.SSL_CONFIGURATION_FETCHING_ERROR_MSG - ); + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + MySQLErrorMessages.SSL_CONFIGURATION_FETCHING_ERROR_MSG); } /* * - By default, the driver configures SSL in the preferred mode. */ - SSLDetails.AuthType sslAuthType = datasourceConfiguration.getConnection().getSsl().getAuthType(); + SSLDetails.AuthType sslAuthType = + datasourceConfiguration.getConnection().getSsl().getAuthType(); switch (sslAuthType) { case REQUIRED: - ob = ob - .option(SSL, true) - .option(Option.valueOf("sslMode"), sslAuthType.toString().toLowerCase()); + ob = ob.option(SSL, true) + .option( + Option.valueOf("sslMode"), + sslAuthType.toString().toLowerCase()); break; case DISABLED: @@ -137,8 +139,7 @@ public static ConnectionFactoryOptions.Builder addSslOptionsToBuilder(Datasource default: throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - String.format(MySQLErrorMessages.UNEXPECTED_SSL_OPTION_ERROR_MSG, sslAuthType) - ); + String.format(MySQLErrorMessages.UNEXPECTED_SSL_OPTION_ERROR_MSG, sslAuthType)); } return ob; @@ -152,14 +153,15 @@ public static Set<String> validateDatasource(DatasourceConfiguration datasourceC invalids.add(MySQLErrorMessages.DS_MISSING_ENDPOINT_ERROR_MSG); } - if (StringUtils.isEmpty(datasourceConfiguration.getUrl()) && - CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) { + if (StringUtils.isEmpty(datasourceConfiguration.getUrl()) + && CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) { invalids.add(MySQLErrorMessages.DS_MISSING_ENDPOINT_ERROR_MSG); } else if (!CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) { for (final Endpoint endpoint : datasourceConfiguration.getEndpoints()) { if (endpoint.getHost() == null || endpoint.getHost().isBlank()) { invalids.add(MySQLErrorMessages.DS_MISSING_HOSTNAME_ERROR_MSG); - } else if (endpoint.getHost().contains("/") || endpoint.getHost().contains(":")) { + } else if (endpoint.getHost().contains("/") + || endpoint.getHost().contains(":")) { invalids.add(String.format(MySQLErrorMessages.DS_INVALID_HOSTNAME_ERROR_MSG, endpoint.getHost())); } } @@ -173,7 +175,8 @@ public static Set<String> validateDatasource(DatasourceConfiguration datasourceC invalids.add(MySQLErrorMessages.DS_MISSING_USERNAME_ERROR_MSG); } - if (StringUtils.isEmpty(authentication.getPassword()) && StringUtils.isEmpty(authentication.getUsername())) { + if (StringUtils.isEmpty(authentication.getPassword()) + && StringUtils.isEmpty(authentication.getUsername())) { invalids.add(MySQLErrorMessages.DS_MISSING_PASSWORD_ERROR_MSG); } else if (StringUtils.isEmpty(authentication.getPassword())) { // it is valid if it has the username but not the password @@ -197,14 +200,14 @@ public static Set<String> validateDatasource(DatasourceConfiguration datasourceC return invalids; } - public static ConnectionPool getNewConnectionPool(DatasourceConfiguration datasourceConfiguration) throws AppsmithPluginException { + public static ConnectionPool getNewConnectionPool(DatasourceConfiguration datasourceConfiguration) + throws AppsmithPluginException { ConnectionFactoryOptions.Builder ob = getBuilder(datasourceConfiguration); ob = addSslOptionsToBuilder(datasourceConfiguration, ob); MariadbConnectionFactory connectionFactory = - MariadbConnectionFactory.from( - MariadbConnectionConfiguration.fromOptions(ob.build()) - .allowPublicKeyRetrieval(true).build() - ); + MariadbConnectionFactory.from(MariadbConnectionConfiguration.fromOptions(ob.build()) + .allowPublicKeyRetrieval(true) + .build()); /** * The pool configuration object does not seem to have any option to set the minimum pool size, hence could diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlErrorUtils.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlErrorUtils.java index c196bc187c9d..b87662bc35bd 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlErrorUtils.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlErrorUtils.java @@ -34,8 +34,7 @@ public String getReadableError(Throwable error) { } externalError = ((AppsmithPluginException) error).getExternalError(); - } - else { + } else { externalError = error; } @@ -43,17 +42,18 @@ public String getReadableError(Throwable error) { /** *@param [9000] [H1000] Fail to establish connection to [host:port] : - Access denied for user 'username'@'host' (using password: NO) + * Access denied for user 'username'@'host' (using password: NO) *@return Access denied for user 'username'@'host' */ - - R2dbcNonTransientResourceException r2dbcNonTransientResourceException = (R2dbcNonTransientResourceException) externalError; - return r2dbcNonTransientResourceException.getMessage().split(" : ")[1]. - split(" \\(")[0].trim(); - + R2dbcNonTransientResourceException r2dbcNonTransientResourceException = + (R2dbcNonTransientResourceException) externalError; + return r2dbcNonTransientResourceException + .getMessage() + .split(" : ")[1] + .split(" \\(")[0] + .trim(); } return externalError.getMessage(); } } - diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlGetStructureUtils.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlGetStructureUtils.java index 7bd5c6f4039c..20de30b2f36f 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlGetStructureUtils.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/utils/MySqlGetStructureUtils.java @@ -23,23 +23,24 @@ public static void getTableInfo(Row row, RowMetadata meta, Map<String, Datasourc final String tableName = row.get("table_name", String.class); if (!tablesByName.containsKey(tableName)) { - tablesByName.put(tableName, new DatasourceStructure.Table( - DatasourceStructure.TableType.TABLE, - null, + tablesByName.put( tableName, - new ArrayList<>(), - new ArrayList<>(), - new ArrayList<>() - )); + new DatasourceStructure.Table( + DatasourceStructure.TableType.TABLE, + null, + tableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); } final DatasourceStructure.Table table = tablesByName.get(tableName); - table.getColumns().add(new DatasourceStructure.Column( - row.get("column_name", String.class), - row.get("column_type", String.class), - null, - row.get("extra", String.class).contains("auto_increment") - )); + table.getColumns() + .add(new DatasourceStructure.Column( + row.get("column_name", String.class), + row.get("column_type", String.class), + null, + row.get("extra", String.class).contains("auto_increment"))); return; } @@ -48,14 +49,16 @@ public static void getTableInfo(Row row, RowMetadata meta, Map<String, Datasourc * 1. Parse results obtained by running KEYS_QUERY defined on top of the page. * 2. A sample mysql output for the query is also given near KEYS_QUERY definition on top of the page. */ - public static void getKeyInfo(Row row, RowMetadata meta, Map<String, DatasourceStructure.Table> tablesByName, - Map<String, DatasourceStructure.Key> keyRegistry) { + public static void getKeyInfo( + Row row, + RowMetadata meta, + Map<String, DatasourceStructure.Table> tablesByName, + Map<String, DatasourceStructure.Key> keyRegistry) { final String constraintName = row.get("constraint_name", String.class); final char constraintType = row.get("constraint_type", String.class).charAt(0); final String selfSchema = row.get("self_schema", String.class); final String tableName = row.get("self_table", String.class); - if (!tablesByName.containsKey(tableName)) { /* do nothing */ return; @@ -66,14 +69,13 @@ public static void getKeyInfo(Row row, RowMetadata meta, Map<String, DatasourceS if (constraintType == 'p') { if (!keyRegistry.containsKey(keyFullName)) { - final DatasourceStructure.PrimaryKey key = new DatasourceStructure.PrimaryKey( - constraintName, - new ArrayList<>() - ); + final DatasourceStructure.PrimaryKey key = + new DatasourceStructure.PrimaryKey(constraintName, new ArrayList<>()); keyRegistry.put(keyFullName, key); table.getKeys().add(key); } - ((DatasourceStructure.PrimaryKey) keyRegistry.get(keyFullName)).getColumnNames() + ((DatasourceStructure.PrimaryKey) keyRegistry.get(keyFullName)) + .getColumnNames() .add(row.get("self_column", String.class)); } else if (constraintType == 'f') { final String foreignSchema = row.get("foreign_schema", String.class); @@ -81,18 +83,17 @@ public static void getKeyInfo(Row row, RowMetadata meta, Map<String, DatasourceS + row.get("foreign_table", String.class) + "."; if (!keyRegistry.containsKey(keyFullName)) { - final DatasourceStructure.ForeignKey key = new DatasourceStructure.ForeignKey( - constraintName, - new ArrayList<>(), - new ArrayList<>() - ); + final DatasourceStructure.ForeignKey key = + new DatasourceStructure.ForeignKey(constraintName, new ArrayList<>(), new ArrayList<>()); keyRegistry.put(keyFullName, key); table.getKeys().add(key); } - ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)).getFromColumns() + ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)) + .getFromColumns() .add(row.get("self_column", String.class)); - ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)).getToColumns() + ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)) + .getToColumns() .add(prefix + row.get("foreign_column", String.class)); } @@ -104,8 +105,7 @@ public static void getKeyInfo(Row row, RowMetadata meta, Map<String, DatasourceS */ public static void getTemplates(Map<String, DatasourceStructure.Table> tablesByName) { for (DatasourceStructure.Table table : tablesByName.values()) { - final List<DatasourceStructure.Column> columnsWithoutDefault = table.getColumns() - .stream() + final List<DatasourceStructure.Column> columnsWithoutDefault = table.getColumns().stream() .filter(column -> column.getDefaultValue() == null) .collect(Collectors.toList()); @@ -128,8 +128,7 @@ public static void getTemplates(Map<String, DatasourceStructure.Table> tablesByN value = "1.0"; } else if (DATE_COLUMN_TYPE_NAME.equals(type)) { value = "'2019-07-01'"; - } else if (DATETIME_COLUMN_TYPE_NAME.equals(type) - || TIMESTAMP_COLUMN_TYPE_NAME.equals(type)) { + } else if (DATETIME_COLUMN_TYPE_NAME.equals(type) || TIMESTAMP_COLUMN_TYPE_NAME.equals(type)) { value = "'2019-07-01 10:00:00'"; } else { value = "''"; @@ -137,7 +136,12 @@ public static void getTemplates(Map<String, DatasourceStructure.Table> tablesByN columnNames.add(name); columnValues.add(value); - setFragments.append("\n ").append(name).append(" = ").append(value).append(","); + setFragments + .append("\n ") + .append(name) + .append(" = ") + .append(value) + .append(","); } // Delete the last comma @@ -146,17 +150,25 @@ public static void getTemplates(Map<String, DatasourceStructure.Table> tablesByN } final String tableName = table.getName(); - table.getTemplates().addAll(List.of( - new DatasourceStructure.Template("SELECT", "SELECT * FROM " + tableName + " LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO " + tableName - + " (" + String.join(", ", columnNames) + ")\n" - + " VALUES (" + String.join(", ", columnValues) + ");"), - new DatasourceStructure.Template("UPDATE", "UPDATE " + tableName + " SET" - + setFragments + "\n" - + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM " + tableName - + "\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!") - )); + table.getTemplates() + .addAll( + List.of( + new DatasourceStructure.Template( + "SELECT", "SELECT * FROM " + tableName + " LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO " + tableName + + " (" + String.join(", ", columnNames) + ")\n" + + " VALUES (" + String.join(", ", columnValues) + ");"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE " + tableName + " SET" + + setFragments + "\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM " + tableName + + "\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"))); } } } diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySQLPluginDataTypeTest.java b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySQLPluginDataTypeTest.java index 5bcef7e1dd2a..46799c1db777 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySQLPluginDataTypeTest.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySQLPluginDataTypeTest.java @@ -27,24 +27,22 @@ public class MySQLPluginDataTypeTest { public void shouldBeNullType() { String value = "null"; - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.NULL, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.NULL, value, pluginSpecificTypes); assertTrue(appsmithType instanceof NullType); assertEquals(appsmithType.performSmartSubstitution(value), null); } @Test public void shouldBeMySQLBooleanType() { - String[] values = { - "true", - "false" - }; + String[] values = {"true", "false"}; Map<String, String> booleanValueMap = Map.of( "true", "1", - "false", "0" - ); + "false", "0"); for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.BOOLEAN, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.BOOLEAN, value, pluginSpecificTypes); assertTrue(appsmithType instanceof MySQLBooleanType); assertEquals(appsmithType.performSmartSubstitution(value), booleanValueMap.get(value)); } @@ -52,15 +50,11 @@ public void shouldBeMySQLBooleanType() { @Test public void shouldBeIntegerType() { - String[] values = { - "0", - "7166", - String.valueOf(Integer.MIN_VALUE), - String.valueOf(Integer.MAX_VALUE) - }; + String[] values = {"0", "7166", String.valueOf(Integer.MIN_VALUE), String.valueOf(Integer.MAX_VALUE)}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); assertTrue(appsmithType instanceof IntegerType); assertEquals(appsmithType.performSmartSubstitution(value), value); } @@ -68,13 +62,11 @@ public void shouldBeIntegerType() { @Test public void shouldBeLongType() { - String[] values = { - "2147483648", - "-2147483649" - }; + String[] values = {"2147483648", "-2147483649"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); assertTrue(appsmithType instanceof LongType); assertEquals(appsmithType.performSmartSubstitution(value), value); } @@ -83,15 +75,16 @@ public void shouldBeLongType() { @Test public void shouldBeDoubleType() { String[] values = { - "323.23", - String.valueOf(Double.MIN_VALUE), - String.valueOf(Double.MAX_VALUE), - String.valueOf(Double.POSITIVE_INFINITY), - String.valueOf(Double.NEGATIVE_INFINITY) + "323.23", + String.valueOf(Double.MIN_VALUE), + String.valueOf(Double.MAX_VALUE), + String.valueOf(Double.POSITIVE_INFINITY), + String.valueOf(Double.NEGATIVE_INFINITY) }; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); assertTrue(appsmithType instanceof DoubleType); assertEquals(appsmithType.performSmartSubstitution(value), value); } @@ -99,39 +92,30 @@ public void shouldBeDoubleType() { @Test public void shouldBeJsonObjectTypeOrStringType() { - String[] values = { - "{\"a\":97,\"A\":65}", - "{\"a\":97,\"A\":65" - }; + String[] values = {"{\"a\":97,\"A\":65}", "{\"a\":97,\"A\":65"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, value, pluginSpecificTypes); assertTrue(appsmithType instanceof JsonObjectType || appsmithType instanceof FallbackType); } - } @Test public void shouldBeTimeType() { - String[] values = { - "10:15:30", - "10:15" - }; + String[] values = {"10:15:30", "10:15"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); assertTrue(appsmithType instanceof TimeType); } } @Test public void shouldBeDateType() { - String[] values = { - "2011-12-03", - "20111203", - "2022/09/25", - "220924" - }; + String[] values = {"2011-12-03", "20111203", "2022/09/25", "220924"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); assertTrue(appsmithType instanceof MySQLDateType); } } @@ -139,43 +123,32 @@ public void shouldBeDateType() { @Test public void shouldBeMySQLDateTimeType() { String[] values = { - "2021-03-24 14:05:34", - "2011-12-03T10:15:30+01:00", - "2022/09/05 23:55:33", - "20220905234556", - "220905234556" + "2021-03-24 14:05:34", "2011-12-03T10:15:30+01:00", "2022/09/05 23:55:33", "20220905234556", "220905234556" }; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); assertTrue(appsmithType instanceof MySQLDateTimeType); } } @Test public void shouldBeStringType() { - String[] values = { - "Hello, world!", - "123", - "098876", - "2022/09/252", - "", - "10:15:30+06:00", - "2021-03-24 14:05:343" + String[] values = {"Hello, world!", "123", "098876", "2022/09/252", "", "10:15:30+06:00", "2021-03-24 14:05:343" }; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); assertTrue(appsmithType instanceof StringType); } } @Test public void arrayTypeShouldBeStringType() { - String[] values = { - "[3,31,12]", - "[]" - }; + String[] values = {"[3,31,12]", "[]"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, value, pluginSpecificTypes); assertTrue(appsmithType instanceof StringType || appsmithType instanceof FallbackType); } } diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlPluginTest.java b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlPluginTest.java index d8744563f4d0..90065f179aed 100755 --- a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlPluginTest.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlPluginTest.java @@ -78,7 +78,7 @@ public class MySqlPluginTest { // pseudo-optional. @Container public static MySQLContainer mySQLContainer = new MySQLContainer( - DockerImageName.parse("mysql/mysql-server:8.0.25").asCompatibleSubstituteFor("mysql")) + DockerImageName.parse("mysql/mysql-server:8.0.25").asCompatibleSubstituteFor("mysql")) .withUsername("mysql") .withPassword("password") .withDatabaseName("test_db"); @@ -87,7 +87,7 @@ public class MySqlPluginTest { // pseudo-optional. @Container public static MySQLContainer mySQLContainerWithInvalidTimezone = (MySQLContainer) new MySQLContainer( - DockerImageName.parse("mysql/mysql-server:8.0.25").asCompatibleSubstituteFor("mysql")) + DockerImageName.parse("mysql/mysql-server:8.0.25").asCompatibleSubstituteFor("mysql")) .withUsername("root") .withPassword("") .withDatabaseName("test_db") @@ -101,7 +101,8 @@ public class MySqlPluginTest { private static String database; private static DatasourceConfiguration dsConfig; - private static Mono<org.mariadb.r2dbc.api.MariadbConnection> getConnectionMonoFromContainer(MySQLContainer mySQLContainer) { + private static Mono<org.mariadb.r2dbc.api.MariadbConnection> getConnectionMonoFromContainer( + MySQLContainer mySQLContainer) { ConnectionFactoryOptions baseOptions = MySQLR2DBCDatabaseContainer.getOptions(mySQLContainer); ConnectionFactoryOptions.Builder ob = ConnectionFactoryOptions.builder().from(baseOptions); MariadbConnectionConfiguration conf = MariadbConnectionConfiguration.fromOptions(ob.build()) @@ -122,49 +123,41 @@ public static void setUp() { Mono.from(getConnectionMonoFromContainer(mySQLContainer)) .map(connection -> { - return connection.createBatch() + return connection + .createBatch() .add("DROP TABLE IF EXISTS possessions") .add("DROP TABLE IF EXISTS users") - .add("create table users (\n" + - " id int auto_increment primary key,\n" + - " username varchar (250) unique not null,\n" - + - " password varchar (250) not null,\n" + - " email varchar (250) unique not null,\n" + - " spouse_dob date,\n" + - " dob date not null,\n" + - " yob year not null,\n" + - " time1 time not null,\n" + - " created_on timestamp not null,\n" + - " updated_on datetime not null,\n" + - " constraint unique index (username, email)\n" - + - ")") - .add("create table possessions (\n" + - " id int primary key,\n" + - " title varchar (250) not null,\n" + - " user_id int not null,\n" + - " username varchar (250) not null,\n" + - " email varchar (250) not null\n" + - ")") + .add("create table users (\n" + " id int auto_increment primary key,\n" + + " username varchar (250) unique not null,\n" + + " password varchar (250) not null,\n" + + " email varchar (250) unique not null,\n" + + " spouse_dob date,\n" + + " dob date not null,\n" + + " yob year not null,\n" + + " time1 time not null,\n" + + " created_on timestamp not null,\n" + + " updated_on datetime not null,\n" + + " constraint unique index (username, email)\n" + + ")") + .add("create table possessions (\n" + " id int primary key,\n" + + " title varchar (250) not null,\n" + + " user_id int not null,\n" + + " username varchar (250) not null,\n" + + " email varchar (250) not null\n" + + ")") .add("alter table possessions add foreign key (username, email) \n" - + - "references users (username, email)") + + "references users (username, email)") .add("SET SESSION sql_mode = '';\n") - .add("INSERT INTO users VALUES (" + - "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31', 2018," - + - " '18:32:45'," + - " '2018-11-30 20:45:15', '0000-00-00 00:00:00'" - + - ")") - .add("INSERT INTO users VALUES (" + - "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31', 2019," - + - " '15:45:30'," + - " '2019-11-30 23:59:59', '2019-11-30 23:59:59'" - + - ")"); + .add("INSERT INTO users VALUES (" + + "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31', 2018," + + " '18:32:45'," + + " '2018-11-30 20:45:15', '0000-00-00 00:00:00'" + + ")") + .add("INSERT INTO users VALUES (" + + "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31', 2019," + + " '15:45:30'," + + " '2019-11-30 23:59:59', '2019-11-30 23:59:59'" + + ")"); }) .flatMapMany(batch -> Flux.from(batch.execute())) .blockLast(); // wait until completion of all the queries @@ -215,8 +208,8 @@ public void testMySqlNoPasswordExceptionMessage() { Mono<ConnectionPool> connectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<DatasourceTestResult> datasourceTestResultMono = connectionMono - .flatMap(connectionPool -> pluginExecutor.testDatasource(connectionPool)); + Mono<DatasourceTestResult> datasourceTestResultMono = + connectionMono.flatMap(connectionPool -> pluginExecutor.testDatasource(connectionPool)); String gateway = mySQLContainer.getContainerInfo().getNetworkSettings().getGateway(); String expectedErrorMessage = new StringBuilder("Access denied for user 'mysql'@'") @@ -224,8 +217,7 @@ public void testMySqlNoPasswordExceptionMessage() { .append("'") .toString(); - StepVerifier - .create(datasourceTestResultMono) + StepVerifier.create(datasourceTestResultMono) .assertNext(result -> { assertTrue(result.getInvalids().contains(expectedErrorMessage)); }) @@ -236,8 +228,7 @@ public void testMySqlNoPasswordExceptionMessage() { public void testConnectMySQLContainerWithInvalidTimezone() { final DatasourceConfiguration dsConfig = createDatasourceConfigForContainerWithInvalidTZ(); - dsConfig.setProperties(List.of( - new Property("serverTimezone", "UTC"))); + dsConfig.setProperties(List.of(new Property("serverTimezone", "UTC"))); Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); @@ -299,15 +290,15 @@ public DatasourceConfiguration createDatasourceConfigForContainerWithInvalidTZ() @Test public void testDatasourceWithNullPassword() { // adding a user with empty password - String sqlCmd = "CREATE USER 'mysql'@'%' IDENTIFIED BY '';" + - "GRANT ALL PRIVILEGES ON *.* TO 'mysql'@'%' WITH GRANT OPTION;" + - "FLUSH PRIVILEGES;"; + String sqlCmd = "CREATE USER 'mysql'@'%' IDENTIFIED BY '';" + + "GRANT ALL PRIVILEGES ON *.* TO 'mysql'@'%' WITH GRANT OPTION;" + + "FLUSH PRIVILEGES;"; Mono.from(getConnectionMonoFromContainer(mySQLContainerWithInvalidTimezone)) - .map(connection -> connection.createBatch() + .map(connection -> connection + .createBatch() .add("CREATE USER 'mysql'@'%' IDENTIFIED BY '';") .add("GRANT ALL PRIVILEGES ON *.* TO 'mysql'@'%' WITH GRANT OPTION;") - .add("FLUSH PRIVILEGES;") - ) + .add("FLUSH PRIVILEGES;")) .flatMapMany(batch -> Flux.from(batch.execute())) .blockLast(); // wait until completion of all the queries @@ -333,8 +324,8 @@ public void testDatasourceWithNullPassword() { /* Expect no error */ StepVerifier.create(pluginExecutor.testDatasource(dsConfig)) - .assertNext(datasourceTestResult -> assertEquals(0, - datasourceTestResult.getInvalids().size())) + .assertNext(datasourceTestResult -> + assertEquals(0, datasourceTestResult.getInvalids().size())) .verifyComplete(); } @@ -359,10 +350,9 @@ public void testDatasourceWithRootUserAndNullPassword() { /* Expect no error */ StepVerifier.create(pluginExecutor.testDatasource(dsConfig)) - .assertNext(datasourceTestResult -> assertEquals(0, - datasourceTestResult.getInvalids().size())) + .assertNext(datasourceTestResult -> + assertEquals(0, datasourceTestResult.getInvalids().size())) .verifyComplete(); - } @Test @@ -372,8 +362,8 @@ public void testExecute() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("show databases"); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -392,8 +382,8 @@ public void testExecuteWithFormattingWithShowCmd() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("show\n\tdatabases"); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -414,8 +404,8 @@ public void testExecuteWithFormattingWithSelectCmd() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("select\n\t*\nfrom\nusers where id=1"); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -439,10 +429,9 @@ public void testExecuteWithFormattingWithSelectCmd() { * point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - actionConfiguration.getBody(), null, null, new HashMap<>())); - assertEquals(result.getRequest().getRequestParams().toString(), - expectedRequestParams.toString()); + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, actionConfiguration.getBody(), null, null, new HashMap<>())); + assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); } @@ -454,8 +443,8 @@ public void testExecuteWithLongRunningQuery() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT SLEEP(20);"); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -470,10 +459,11 @@ public void testExecuteWithLongRunningQuery() { public void testStaleConnectionCheck() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("show databases"); - ConnectionPool connectionPool = pluginExecutor.datasourceCreate(dsConfig).block(); + ConnectionPool connectionPool = + pluginExecutor.datasourceCreate(dsConfig).block(); Flux<ActionExecutionResult> resultFlux = Mono.from(connectionPool.disposeLater()) - .thenMany(pluginExecutor.executeParameterized(connectionPool, new ExecuteActionDTO(), - dsConfig, actionConfiguration)); + .thenMany(pluginExecutor.executeParameterized( + connectionPool, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(resultFlux) .expectErrorMatches(throwable -> throwable instanceof StaleConnectionException) @@ -496,27 +486,21 @@ public void testValidateDatasourceNullCredentials() { public void testValidateDatasourceMissingDBName() { ((DBAuth) dsConfig.getAuthentication()).setDatabaseName(""); Set<String> output = pluginExecutor.validateDatasource(dsConfig); - assertTrue(output - .stream() - .anyMatch(error -> error.contains("Missing database name."))); + assertTrue(output.stream().anyMatch(error -> error.contains("Missing database name."))); } @Test public void testValidateDatasourceNullEndpoint() { dsConfig.setEndpoints(null); Set<String> output = pluginExecutor.validateDatasource(dsConfig); - assertTrue(output - .stream() - .anyMatch(error -> error.contains("Missing endpoint and url"))); + assertTrue(output.stream().anyMatch(error -> error.contains("Missing endpoint and url"))); } @Test public void testValidateDatasource_NullHost() { dsConfig.setEndpoints(List.of(new Endpoint())); Set<String> output = pluginExecutor.validateDatasource(dsConfig); - assertTrue(output - .stream() - .anyMatch(error -> error.contains("Host value cannot be empty"))); + assertTrue(output.stream().anyMatch(error -> error.contains("Host value cannot be empty"))); Endpoint endpoint = new Endpoint(); endpoint.setHost(address); @@ -529,8 +513,7 @@ public void testValidateDatasourceInvalidEndpoint() { String hostname = "r2dbc:mysql://localhost"; dsConfig.getEndpoints().get(0).setHost(hostname); Set<String> output = pluginExecutor.validateDatasource(dsConfig); - assertTrue(output.contains( - "Host value cannot contain `/` or `:` characters. Found `" + hostname + "`.")); + assertTrue(output.contains("Host value cannot contain `/` or `:` characters. Found `" + hostname + "`.")); } @Test @@ -541,17 +524,14 @@ public void testAliasColumnNames() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT id as user_id FROM users WHERE id = 1"); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "user_id" - }, + new String[] {"user_id"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() @@ -593,22 +573,21 @@ public void testPreparedStatementErrorWithIsKeyword() { executeActionDTO.setParams(params); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); - StepVerifier.create(executeMono) - .verifyErrorSatisfies(error -> { - assertTrue(error instanceof AppsmithPluginException); - String expectedMessage = MySQLErrorMessages.IS_KEYWORD_NOT_SUPPORTED_IN_PS_ERROR_MSG; - assertTrue(expectedMessage.equals(error.getMessage())); - }); + StepVerifier.create(executeMono).verifyErrorSatisfies(error -> { + assertTrue(error instanceof AppsmithPluginException); + String expectedMessage = MySQLErrorMessages.IS_KEYWORD_NOT_SUPPORTED_IN_PS_ERROR_MSG; + assertTrue(expectedMessage.equals(error.getMessage())); + }); } @Test public void testPreparedStatementWithRealTypes() { Mono.from(getConnectionMonoFromContainer(mySQLContainer)) - .map(connection -> connection.createBatch() + .map(connection -> connection + .createBatch() .add("create table test_real_types(id int, c_float float, c_double double, c_real real)") .add("insert into test_real_types values (1, 1.123, 3.123, 5.123)") .add("insert into test_real_types values (2, 11.123, 13.123, 15.123)")) @@ -627,9 +606,8 @@ public void testPreparedStatementWithRealTypes() { * equality. * - Ref: https://dev.mysql.com/doc/refman/8.0/en/problems-with-float.html */ - actionConfiguration.setBody( - "SELECT id FROM test_real_types WHERE ABS(c_float - {{binding1}}) < 0.1 AND ABS" + - "(c_double - {{binding2}}) < 0.1 AND ABS(c_real - {{binding3}}) < 0.1;"); + actionConfiguration.setBody("SELECT id FROM test_real_types WHERE ABS(c_float - {{binding1}}) < 0.1 AND ABS" + + "(c_double - {{binding2}}) < 0.1 AND ABS(c_real - {{binding3}}) < 0.1;"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -657,9 +635,8 @@ public void testPreparedStatementWithRealTypes() { executeActionDTO.setParams(params); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -671,8 +648,7 @@ public void testPreparedStatementWithRealTypes() { .verifyComplete(); Mono.from(getConnectionMonoFromContainer(mySQLContainer)) - .map(connection -> connection.createBatch() - .add("drop table test_real_types")) + .map(connection -> connection.createBatch().add("drop table test_real_types")) .flatMapMany(batch -> Flux.from(batch.execute())) .blockLast(); // wait until completion of all the queries } @@ -685,7 +661,8 @@ private Publisher<? extends Connection> getConnectionFromBuilder(ConnectionFacto public void testPreparedStatementWithBooleanType() { // Create a new table with boolean type Mono.from(getConnectionMonoFromContainer(mySQLContainer)) - .map(connection -> connection.createBatch() + .map(connection -> connection + .createBatch() .add("create table test_boolean_type(id int, c_boolean boolean)") .add("insert into test_boolean_type values (1, True)") .add("insert into test_boolean_type values (2, True)") @@ -712,9 +689,8 @@ public void testPreparedStatementWithBooleanType() { params.add(param1); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -727,8 +703,7 @@ public void testPreparedStatementWithBooleanType() { .verifyComplete(); Mono.from(getConnectionMonoFromContainer(mySQLContainer)) - .map(connection -> connection.createBatch() - .add("drop table test_boolean_type")) + .map(connection -> connection.createBatch().add("drop table test_boolean_type")) .flatMapMany(batch -> Flux.from(batch.execute())) .blockLast(); // wait until completion of all the queries } @@ -739,8 +714,7 @@ public void testExecuteWithPreparedStatement() { Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration - .setBody("SELECT id FROM users WHERE id = {{binding1}} limit 1 offset {{binding2}};"); + actionConfiguration.setBody("SELECT id FROM users WHERE id = {{binding1}} limit 1 offset {{binding2}};"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -760,17 +734,14 @@ public void testExecuteWithPreparedStatement() { params.add(param2); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "id" - }, + new String[] {"id"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() @@ -787,15 +758,16 @@ public void testExecuteWithPreparedStatement() { */ // Check if '?' is replaced by $i. - assertEquals("SELECT id FROM users WHERE id = $1 limit 1 offset $2;", - ((RequestParamDTO) (((List) result.getRequest() - .getRequestParams())).get(0)).getValue()); + assertEquals( + "SELECT id FROM users WHERE id = $1 limit 1 offset $2;", + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getValue()); // Check 1st prepared statement parameter PsParameterDTO expectedPsParam1 = new PsParameterDTO("1", "INTEGER"); - PsParameterDTO returnedPsParam1 = (PsParameterDTO) ((RequestParamDTO) (((List) result - .getRequest().getRequestParams())).get(0)) - .getSubstitutedParams().get("$1"); + PsParameterDTO returnedPsParam1 = (PsParameterDTO) + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)) + .getSubstitutedParams() + .get("$1"); // Check if prepared stmt param value is correctly sent back. assertEquals(expectedPsParam1.getValue(), returnedPsParam1.getValue()); // Check if prepared stmt param type is correctly sent back. @@ -803,9 +775,10 @@ public void testExecuteWithPreparedStatement() { // Check 2nd prepared statement parameter PsParameterDTO expectedPsParam2 = new PsParameterDTO("0", "INTEGER"); - PsParameterDTO returnedPsParam2 = (PsParameterDTO) ((RequestParamDTO) (((List) result - .getRequest().getRequestParams())).get(0)) - .getSubstitutedParams().get("$2"); + PsParameterDTO returnedPsParam2 = (PsParameterDTO) + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)) + .getSubstitutedParams() + .get("$2"); // Check if prepared stmt param value is correctly sent back. assertEquals(expectedPsParam2.getValue(), returnedPsParam2.getValue()); // Check if prepared stmt param type is correctly sent back. @@ -824,9 +797,8 @@ public void testExecuteDataTypes() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users WHERE id = 1"); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -838,22 +810,21 @@ public void testExecuteDataTypes() { assertEquals("2018-12-31", node.get("dob").asText()); assertEquals("2018", node.get("yob").asText()); assertTrue(node.get("time1").asText().matches("\\d{2}:\\d{2}:\\d{2}")); - assertTrue(node.get("created_on").asText() - .matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z")); + assertTrue(node.get("created_on").asText().matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z")); assertTrue(node.get("updated_on").isNull()); assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "yob", - "time1", - "created_on", - "updated_on" + new String[] { + "id", + "username", + "password", + "email", + "spouse_dob", + "dob", + "yob", + "time1", + "created_on", + "updated_on" }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) @@ -877,45 +848,32 @@ public void testExecuteDataTypes() { @Test public void testExecuteDataTypesExtensive() throws AppsmithPluginException { String query_create_table_numeric_types = "create table test_numeric_types (c_integer INTEGER, c_smallint " - + - "SMALLINT, c_tinyint TINYINT, c_mediumint MEDIUMINT, c_bigint BIGINT, c_decimal DECIMAL, c_float " - + - "FLOAT, c_double DOUBLE, c_bit BIT(10));"; + + "SMALLINT, c_tinyint TINYINT, c_mediumint MEDIUMINT, c_bigint BIGINT, c_decimal DECIMAL, c_float " + + "FLOAT, c_double DOUBLE, c_bit BIT(10));"; String query_insert_into_table_numeric_types = "insert into test_numeric_types values (-1, 1, 1, 10, 2000, 1" - + - ".02345, 0.1234, 1.0102344, b'0101010');"; + + ".02345, 0.1234, 1.0102344, b'0101010');"; String query_create_table_date_time_types = "create table test_date_time_types (c_date DATE, c_datetime " - + - "DATETIME DEFAULT CURRENT_TIMESTAMP, c_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, c_time TIME, " - + - "c_year YEAR);"; + + "DATETIME DEFAULT CURRENT_TIMESTAMP, c_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, c_time TIME, " + + "c_year YEAR);"; String query_insert_into_table_date_time_types = "insert into test_date_time_types values ('2020-12-01', " - + - "'2020-12-01 20:20:20', '2020-12-01 20:20:20', '20:20:20', 2020);"; + + "'2020-12-01 20:20:20', '2020-12-01 20:20:20', '20:20:20', 2020);"; String query_create_table_data_types = "create table test_data_types (c_char CHAR(50), c_varchar VARCHAR(50)," - + - " c_binary BINARY(20), c_varbinary VARBINARY(20), c_tinyblob TINYBLOB, c_blob BLOB, c_mediumblob " - + - "MEDIUMBLOB, c_longblob LONGBLOB, c_tinytext TINYTEXT, c_text TEXT, c_mediumtext MEDIUMTEXT, " - + - "c_longtext LONGTEXT, c_enum ENUM('ONE'), c_set SET('a'));"; + + " c_binary BINARY(20), c_varbinary VARBINARY(20), c_tinyblob TINYBLOB, c_blob BLOB, c_mediumblob " + + "MEDIUMBLOB, c_longblob LONGBLOB, c_tinytext TINYTEXT, c_text TEXT, c_mediumtext MEDIUMTEXT, " + + "c_longtext LONGTEXT, c_enum ENUM('ONE'), c_set SET('a'));"; String query_insert_data_types = "insert into test_data_types values ('test', 'test', 'a\\0\\t', 'a\\0\\t', " - + - "'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'ONE', 'a');"; + + "'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'ONE', 'a');"; String query_create_table_json_data_type = "create table test_json_type (c_json JSON);"; - String query_insert_json_data_type = "insert into test_json_type values ('{\"key1\": \"value1\", \"key2\": " - + - "\"value2\"}');"; + String query_insert_json_data_type = + "insert into test_json_type values ('{\"key1\": \"value1\", \"key2\": " + "\"value2\"}');"; - String query_create_table_geometry_types = "create table test_geometry_types (c_geometry GEOMETRY, c_point " - + - "POINT);"; + String query_create_table_geometry_types = + "create table test_geometry_types (c_geometry GEOMETRY, c_point " + "POINT);"; String query_insert_geometry_types = "insert into test_geometry_types values (ST_GeomFromText('POINT(1 1)'), " - + - "ST_PointFromText('POINT(1 100)'));"; + + "ST_PointFromText('POINT(1 100)'));"; String query_select_from_test_numeric_types = "select * from test_numeric_types;"; String query_select_from_test_date_time_types = "select * from test_date_time_types;"; @@ -924,34 +882,26 @@ public void testExecuteDataTypesExtensive() throws AppsmithPluginException { String query_select_from_test_geometry_types = "select * from test_geometry_types;"; String expected_numeric_types_result = "[{\"c_integer\":-1,\"c_smallint\":1,\"c_tinyint\":1,\"" - + - "c_mediumint\":10,\"c_bigint\":2000,\"c_decimal\":1,\"c_float\":0.1234,\"c_double\":1.0102344," - + - "\"c_bit\":{\"empty\":false}}]"; + + "c_mediumint\":10,\"c_bigint\":2000,\"c_decimal\":1,\"c_float\":0.1234,\"c_double\":1.0102344," + + "\"c_bit\":{\"empty\":false}}]"; String expected_date_time_types_result = "[{\"c_date\":\"2020-12-01\",\"c_datetime\":\"2020-12-01T20:20:20Z\"," - + - "\"c_timestamp\":\"2020-12-01T20:20:20Z\",\"c_time\":\"20:20:20\",\"c_year\":2020}]"; + + "\"c_timestamp\":\"2020-12-01T20:20:20Z\",\"c_time\":\"20:20:20\",\"c_year\":2020}]"; String expected_data_types_result = "[{\"c_char\":\"test\",\"c_varchar\":\"test\"," - + - "\"c_binary\":\"YQAJAAAAAAAAAAAAAAAAAAAAAAA=\",\"c_varbinary\":\"YQAJ\",\"c_tinyblob\":\"dGVzdA==\"," - + - "\"c_blob\":\"dGVzdA==\",\"c_mediumblob\":\"dGVzdA==\",\"c_longblob\":\"dGVzdA==\",\"c_tinytext\":\"test\"," - + - "\"c_text\":\"test\",\"c_mediumtext\":\"test\",\"c_longtext\":\"test\",\"c_enum\":\"ONE\",\"c_set\":\"a\"}]"; + + "\"c_binary\":\"YQAJAAAAAAAAAAAAAAAAAAAAAAA=\",\"c_varbinary\":\"YQAJ\",\"c_tinyblob\":\"dGVzdA==\"," + + "\"c_blob\":\"dGVzdA==\",\"c_mediumblob\":\"dGVzdA==\",\"c_longblob\":\"dGVzdA==\",\"c_tinytext\":\"test\"," + + "\"c_text\":\"test\",\"c_mediumtext\":\"test\",\"c_longtext\":\"test\",\"c_enum\":\"ONE\",\"c_set\":\"a\"}]"; String expected_json_result = "[{\"c_json\":\"{\\\"key1\\\": \\\"value1\\\", \\\"key2\\\": \\\"value2\\\"}\"}]"; String expected_geometry_types_result = "[{\"c_geometry\":\"AAAAAAEBAAAAAAAAAAAA8D8AAAAAAADwPw==\"," - + - "\"c_point\":\"AAAAAAEBAAAAAAAAAAAA8D8AAAAAAABZQA==\"}]"; - - + + "\"c_point\":\"AAAAAAEBAAAAAAAAAAAA8D8AAAAAAABZQA==\"}]"; Mono.from(getConnectionMonoFromContainer(mySQLContainer)) .map(connection -> { - return connection.createBatch() + return connection + .createBatch() .add(query_create_table_numeric_types) .add(query_insert_into_table_numeric_types) .add(query_create_table_date_time_types) @@ -984,8 +934,8 @@ private void testExecute(String query, String expectedResult) { Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody(query); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -1002,7 +952,8 @@ private void testExecute(String query, String expectedResult) { @Test public void testStructure() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<DatasourceStructure> structureMono = pluginExecutor.datasourceCreate(dsConfig) + Mono<DatasourceStructure> structureMono = pluginExecutor + .datasourceCreate(dsConfig) .flatMap(connection -> pluginExecutor.getStructure(connection, dsConfig)); StepVerifier.create(structureMono) @@ -1010,141 +961,105 @@ public void testStructure() { assertNotNull(structure); assertEquals(2, structure.getTables().size()); - Optional<DatasourceStructure.Table> possessionsTableOptional = structure - .getTables() - .stream() - .filter(table -> table.getName() - .equalsIgnoreCase("possessions")) + Optional<DatasourceStructure.Table> possessionsTableOptional = structure.getTables().stream() + .filter(table -> table.getName().equalsIgnoreCase("possessions")) .findFirst(); assertTrue(possessionsTableOptional.isPresent()); - final DatasourceStructure.Table possessionsTable = possessionsTableOptional - .get(); + final DatasourceStructure.Table possessionsTable = possessionsTableOptional.get(); assertEquals(DatasourceStructure.TableType.TABLE, possessionsTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "int", - null, false), - new DatasourceStructure.Column("title", - "varchar", null, false), - new DatasourceStructure.Column("user_id", "int", - null, false), - new DatasourceStructure.Column("username", - "varchar", null, false), - new DatasourceStructure.Column("email", - "varchar", null, false), + new DatasourceStructure.Column[] { + new DatasourceStructure.Column("id", "int", null, false), + new DatasourceStructure.Column("title", "varchar", null, false), + new DatasourceStructure.Column("user_id", "int", null, false), + new DatasourceStructure.Column("username", "varchar", null, false), + new DatasourceStructure.Column("email", "varchar", null, false), }, possessionsTable.getColumns().toArray()); - final DatasourceStructure.PrimaryKey possessionsPrimaryKey = new DatasourceStructure.PrimaryKey( - "PRIMARY", List.of("id")); + final DatasourceStructure.PrimaryKey possessionsPrimaryKey = + new DatasourceStructure.PrimaryKey("PRIMARY", List.of("id")); final DatasourceStructure.ForeignKey possessionsUserForeignKey = new DatasourceStructure.ForeignKey( "possessions_ibfk_1", List.of("username", "email"), List.of("users.username", "users.email")); assertArrayEquals( - new DatasourceStructure.Key[]{possessionsPrimaryKey, - possessionsUserForeignKey}, + new DatasourceStructure.Key[] {possessionsPrimaryKey, possessionsUserForeignKey}, possessionsTable.getKeys().toArray()); assertArrayEquals( - new DatasourceStructure.Template[]{ - new DatasourceStructure.Template("SELECT", - "SELECT * FROM possessions LIMIT 10;"), - new DatasourceStructure.Template("INSERT", - "INSERT INTO possessions (id, title, user_id, username, email)\n" - + - " VALUES (1, '', 1, '', '');"), - new DatasourceStructure.Template("UPDATE", - "UPDATE possessions SET\n" + - " id = 1,\n" - + - " title = '',\n" - + - " user_id = 1,\n" - + - " username = '',\n" - + - " email = ''\n" - + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", - "DELETE FROM possessions\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), + new DatasourceStructure.Template[] { + new DatasourceStructure.Template("SELECT", "SELECT * FROM possessions LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO possessions (id, title, user_id, username, email)\n" + + " VALUES (1, '', 1, '', '');"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE possessions SET\n" + " id = 1,\n" + + " title = '',\n" + + " user_id = 1,\n" + + " username = '',\n" + + " email = ''\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM possessions\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), }, possessionsTable.getTemplates().toArray()); - Optional<DatasourceStructure.Table> usersTableOptional = structure.getTables() - .stream() + Optional<DatasourceStructure.Table> usersTableOptional = structure.getTables().stream() .filter(table -> table.getName().equalsIgnoreCase("users")) .findFirst(); assertTrue(usersTableOptional.isPresent()); final DatasourceStructure.Table usersTable = usersTableOptional.get(); assertEquals(DatasourceStructure.TableType.TABLE, usersTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "int", - null, true), - new DatasourceStructure.Column("username", - "varchar", null, false), - new DatasourceStructure.Column("password", - "varchar", null, false), - new DatasourceStructure.Column("email", - "varchar", null, false), - new DatasourceStructure.Column("spouse_dob", - "date", null, false), - new DatasourceStructure.Column("dob", "date", - null, false), - new DatasourceStructure.Column("yob", "year", - null, false), - new DatasourceStructure.Column("time1", "time", - null, false), - new DatasourceStructure.Column("created_on", - "timestamp", null, false), - new DatasourceStructure.Column("updated_on", - "datetime", null, false) + new DatasourceStructure.Column[] { + new DatasourceStructure.Column("id", "int", null, true), + new DatasourceStructure.Column("username", "varchar", null, false), + new DatasourceStructure.Column("password", "varchar", null, false), + new DatasourceStructure.Column("email", "varchar", null, false), + new DatasourceStructure.Column("spouse_dob", "date", null, false), + new DatasourceStructure.Column("dob", "date", null, false), + new DatasourceStructure.Column("yob", "year", null, false), + new DatasourceStructure.Column("time1", "time", null, false), + new DatasourceStructure.Column("created_on", "timestamp", null, false), + new DatasourceStructure.Column("updated_on", "datetime", null, false) }, usersTable.getColumns().toArray()); - final DatasourceStructure.PrimaryKey usersPrimaryKey = new DatasourceStructure.PrimaryKey( - "PRIMARY", List.of("id")); + final DatasourceStructure.PrimaryKey usersPrimaryKey = + new DatasourceStructure.PrimaryKey("PRIMARY", List.of("id")); assertArrayEquals( - new DatasourceStructure.Key[]{usersPrimaryKey}, + new DatasourceStructure.Key[] {usersPrimaryKey}, usersTable.getKeys().toArray()); assertArrayEquals( - new DatasourceStructure.Template[]{ - new DatasourceStructure.Template("SELECT", - "SELECT * FROM users LIMIT 10;"), - new DatasourceStructure.Template("INSERT", - "INSERT INTO users (id, username, password, email, spouse_dob, dob, yob, time1, created_on, updated_on)\n" - + - " VALUES (1, '', '', '', '2019-07-01', '2019-07-01', '', '', '2019-07-01 10:00:00', '2019-07-01 10:00:00');"), - new DatasourceStructure.Template("UPDATE", - "UPDATE users SET\n" + - " id = 1,\n" - + - " username = '',\n" - + - " password = '',\n" - + - " email = '',\n" - + - " spouse_dob = '2019-07-01',\n" - + - " dob = '2019-07-01',\n" - + - " yob = '',\n" - + - " time1 = '',\n" - + - " created_on = '2019-07-01 10:00:00',\n" - + - " updated_on = '2019-07-01 10:00:00'\n" - + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", - "DELETE FROM users\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), + new DatasourceStructure.Template[] { + new DatasourceStructure.Template("SELECT", "SELECT * FROM users LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO users (id, username, password, email, spouse_dob, dob, yob, time1, created_on, updated_on)\n" + + " VALUES (1, '', '', '', '2019-07-01', '2019-07-01', '', '', '2019-07-01 10:00:00', '2019-07-01 10:00:00');"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE users SET\n" + " id = 1,\n" + + " username = '',\n" + + " password = '',\n" + + " email = '',\n" + + " spouse_dob = '2019-07-01',\n" + + " dob = '2019-07-01',\n" + + " yob = '',\n" + + " time1 = '',\n" + + " created_on = '2019-07-01 10:00:00',\n" + + " updated_on = '2019-07-01 10:00:00'\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM users\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), }, usersTable.getTemplates().toArray()); }) @@ -1156,17 +1071,14 @@ public void testSslToggleMissingError() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); datasourceConfiguration.getConnection().getSsl().setAuthType(null); - Mono<Set<String>> invalidsMono = Mono.just(pluginExecutor) - .map(executor -> executor.validateDatasource(datasourceConfiguration)); + Mono<Set<String>> invalidsMono = + Mono.just(pluginExecutor).map(executor -> executor.validateDatasource(datasourceConfiguration)); StepVerifier.create(invalidsMono) .assertNext(invalids -> { String expectedError = "Appsmith server has failed to fetch SSL configuration from datasource " - + - "configuration form. Please reach out to Appsmith customer support to resolve this."; - assertTrue(invalids - .stream() - .anyMatch(error -> expectedError.equals(error))); + + "configuration form. Please reach out to Appsmith customer support to resolve this."; + assertTrue(invalids.stream().anyMatch(error -> expectedError.equals(error))); }) .verifyComplete(); } @@ -1179,10 +1091,8 @@ public void testSslDisabled() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); datasourceConfiguration.getConnection().getSsl().setAuthType(SSLDetails.AuthType.DISABLED); Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<Object> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, - actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -1190,8 +1100,7 @@ public void testSslDisabled() { assertTrue(result.getIsExecutionSuccess()); Object body = result.getBody(); assertNotNull(body); - assertEquals("[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"\"}]", - body.toString()); + assertEquals("[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"\"}]", body.toString()); }) .verifyComplete(); } @@ -1204,10 +1113,8 @@ public void testSslRequired() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); datasourceConfiguration.getConnection().getSsl().setAuthType(SSLDetails.AuthType.REQUIRED); Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<Object> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, - actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -1215,7 +1122,8 @@ public void testSslRequired() { assertTrue(result.getIsExecutionSuccess()); Object body = result.getBody(); assertNotNull(body); - assertEquals("[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"TLS_AES_128_GCM_SHA256\"}]", + assertEquals( + "[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"TLS_AES_128_GCM_SHA256\"}]", body.toString()); }) .verifyComplete(); @@ -1229,10 +1137,8 @@ public void testSslDefault() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); datasourceConfiguration.getConnection().getSsl().setAuthType(SSLDetails.AuthType.DEFAULT); Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - Mono<Object> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, - actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; @@ -1240,8 +1146,7 @@ public void testSslDefault() { assertTrue(result.getIsExecutionSuccess()); Object body = result.getBody(); assertNotNull(body); - assertEquals("[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"\"}]", - body.toString()); + assertEquals("[{\"Variable_name\":\"Ssl_cipher\",\"Value\":\"\"}]", body.toString()); }) .verifyComplete(); } @@ -1252,38 +1157,31 @@ public void testDuplicateColumnNames() { Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody( - "SELECT id, username as id, password, email as password FROM users WHERE id = 1"); + actionConfiguration.setBody("SELECT id, username as id, password, email as password FROM users WHERE id = 1"); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), - dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { assertNotEquals(0, result.getMessages().size()); - String expectedMessage = "Your MySQL query result may not have all the columns because duplicate column names " - + - "were found for the column(s)"; - assertTrue( - result.getMessages().stream() - .anyMatch(message -> message - .contains(expectedMessage))); + String expectedMessage = + "Your MySQL query result may not have all the columns because duplicate column names " + + "were found for the column(s)"; + assertTrue(result.getMessages().stream().anyMatch(message -> message.contains(expectedMessage))); /* * - Check if all of the duplicate column names are reported. */ - Set<String> expectedColumnNames = Stream.of("id", "password") - .collect(Collectors.toCollection(HashSet::new)); + Set<String> expectedColumnNames = + Stream.of("id", "password").collect(Collectors.toCollection(HashSet::new)); Set<String> foundColumnNames = new HashSet<>(); result.getMessages().stream() .filter(message -> message.contains(expectedMessage)) .forEach(message -> { - Arrays.stream(message.split(":")[1].split("\\.")[0] - .split(",")) - .forEach(columnName -> foundColumnNames - .add(columnName.trim())); + Arrays.stream(message.split(":")[1].split("\\.")[0].split(",")) + .forEach(columnName -> foundColumnNames.add(columnName.trim())); }); assertTrue(expectedColumnNames.equals(foundColumnNames)); }) @@ -1298,15 +1196,16 @@ public void testExecuteDescribeTableCmd() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("describe users"); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; assertNotNull(result); assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - String expectedBody = "[{\"Field\":\"id\",\"Type\":\"int\",\"Null\":\"NO\",\"Key\":\"PRI\",\"Default\":null,\"Extra\":\"auto_increment\"},{\"Field\":\"username\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"UNI\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"password\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"email\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"UNI\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"spouse_dob\",\"Type\":\"date\",\"Null\":\"YES\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"dob\",\"Type\":\"date\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"yob\",\"Type\":\"year\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"time1\",\"Type\":\"time\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"created_on\",\"Type\":\"timestamp\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"updated_on\",\"Type\":\"datetime\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"}]"; + String expectedBody = + "[{\"Field\":\"id\",\"Type\":\"int\",\"Null\":\"NO\",\"Key\":\"PRI\",\"Default\":null,\"Extra\":\"auto_increment\"},{\"Field\":\"username\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"UNI\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"password\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"email\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"UNI\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"spouse_dob\",\"Type\":\"date\",\"Null\":\"YES\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"dob\",\"Type\":\"date\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"yob\",\"Type\":\"year\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"time1\",\"Type\":\"time\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"created_on\",\"Type\":\"timestamp\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"updated_on\",\"Type\":\"datetime\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"}]"; assertEquals(expectedBody, result.getBody().toString()); }) .verifyComplete(); @@ -1320,15 +1219,16 @@ public void testExecuteDescTableCmd() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("desc users"); - Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, - new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(obj -> { ActionExecutionResult result = (ActionExecutionResult) obj; assertNotNull(result); assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - String expectedBody = "[{\"Field\":\"id\",\"Type\":\"int\",\"Null\":\"NO\",\"Key\":\"PRI\",\"Default\":null,\"Extra\":\"auto_increment\"},{\"Field\":\"username\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"UNI\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"password\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"email\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"UNI\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"spouse_dob\",\"Type\":\"date\",\"Null\":\"YES\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"dob\",\"Type\":\"date\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"yob\",\"Type\":\"year\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"time1\",\"Type\":\"time\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"created_on\",\"Type\":\"timestamp\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"updated_on\",\"Type\":\"datetime\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"}]"; + String expectedBody = + "[{\"Field\":\"id\",\"Type\":\"int\",\"Null\":\"NO\",\"Key\":\"PRI\",\"Default\":null,\"Extra\":\"auto_increment\"},{\"Field\":\"username\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"UNI\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"password\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"email\",\"Type\":\"varchar(250)\",\"Null\":\"NO\",\"Key\":\"UNI\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"spouse_dob\",\"Type\":\"date\",\"Null\":\"YES\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"dob\",\"Type\":\"date\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"yob\",\"Type\":\"year\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"time1\",\"Type\":\"time\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"created_on\",\"Type\":\"timestamp\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"},{\"Field\":\"updated_on\",\"Type\":\"datetime\",\"Null\":\"NO\",\"Key\":\"\",\"Default\":null,\"Extra\":\"\"}]"; assertEquals(expectedBody, result.getBody().toString()); }) .verifyComplete(); @@ -1342,14 +1242,13 @@ public void testNullObjectWithPreparedStatement() { Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("SELECT * from (\n" + - "\tselect 'Appsmith' as company_name, true as open_source\n" + - "\tunion\n" + - "\tselect 'Retool' as company_name, false as open_source\n" + - "\tunion\n" + - "\tselect 'XYZ' as company_name, null as open_source\n" + - ") t\n" + - "where t.open_source IS {{binding1}}"); + actionConfiguration.setBody("SELECT * from (\n" + "\tselect 'Appsmith' as company_name, true as open_source\n" + + "\tunion\n" + + "\tselect 'Retool' as company_name, false as open_source\n" + + "\tunion\n" + + "\tselect 'XYZ' as company_name, null as open_source\n" + + ") t\n" + + "where t.open_source IS {{binding1}}"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -1364,19 +1263,15 @@ public void testNullObjectWithPreparedStatement() { params.add(param1); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "company_name", - "open_source" - }, + new String[] {"company_name", "open_source"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() @@ -1384,7 +1279,6 @@ public void testNullObjectWithPreparedStatement() { // Verify value assertEquals(JsonNodeType.NULL, node.get("open_source").getNodeType()); - }) .verifyComplete(); } @@ -1395,14 +1289,13 @@ public void testNullAsStringWithPreparedStatement() { Mono<ConnectionPool> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("SELECT * from (\n" + - "\tselect 'Appsmith' as company_name, true as open_source\n" + - "\tunion\n" + - "\tselect 'Retool' as company_name, false as open_source\n" + - "\tunion\n" + - "\tselect 'XYZ' as company_name, 'null' as open_source\n" + - ") t\n" + - "where t.open_source = {{binding1}};"); + actionConfiguration.setBody("SELECT * from (\n" + "\tselect 'Appsmith' as company_name, true as open_source\n" + + "\tunion\n" + + "\tselect 'Retool' as company_name, false as open_source\n" + + "\tunion\n" + + "\tselect 'XYZ' as company_name, 'null' as open_source\n" + + ") t\n" + + "where t.open_source = {{binding1}};"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -1418,19 +1311,15 @@ public void testNullAsStringWithPreparedStatement() { executeActionDTO.setParams(params); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "company_name", - "open_source" - }, + new String[] {"company_name", "open_source"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() @@ -1438,7 +1327,6 @@ public void testNullAsStringWithPreparedStatement() { // Verify value assertEquals(JsonNodeType.STRING, node.get("open_source").getNodeType()); - }) .verifyComplete(); } @@ -1464,18 +1352,15 @@ public void testNumericValuesHavingLeadingZeroWithPreparedStatement() { params.add(param1); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "numeric_string" - }, + new String[] {"numeric_string"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() @@ -1484,7 +1369,6 @@ public void testNumericValuesHavingLeadingZeroWithPreparedStatement() { // Verify value assertEquals(JsonNodeType.STRING, node.get("numeric_string").getNodeType()); assertEquals(param1.getValue(), node.get("numeric_string").asText()); - }) .verifyComplete(); } @@ -1510,18 +1394,15 @@ public void testLongValueWithPreparedStatement() { params.add(param1); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + conn -> pluginExecutor.executeParameterized(conn, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "id" - }, + new String[] {"id"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() @@ -1529,7 +1410,6 @@ public void testLongValueWithPreparedStatement() { // Verify value assertEquals(JsonNodeType.NUMBER, node.get("id").getNodeType()); - }) .verifyComplete(); } @@ -1537,9 +1417,10 @@ public void testLongValueWithPreparedStatement() { @Test public void testDatasourceDestroy() { dsConfig = createDatasourceConfiguration(); - Mono<ConnectionPool> connPoolMonoCache = pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<DatasourceTestResult> testConnResultMono = connPoolMonoCache - .flatMap(conn -> pluginExecutor.testDatasource(conn)); + Mono<ConnectionPool> connPoolMonoCache = + pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<DatasourceTestResult> testConnResultMono = + connPoolMonoCache.flatMap(conn -> pluginExecutor.testDatasource(conn)); Mono<Tuple2<ConnectionPool, DatasourceTestResult>> zipMono = zip(connPoolMonoCache, testConnResultMono); StepVerifier.create(zipMono) .assertNext(tuple2 -> { @@ -1565,28 +1446,22 @@ public void testDatasourceDestroy() { } @Test - public void testExecuteCommon_queryWithComments_callValidationCallsAfterRemovingComments(){ + public void testExecuteCommon_queryWithComments_callValidationCallsAfterRemovingComments() { MySqlPlugin.MySqlPluginExecutor spyPlugin = spy(pluginExecutor); DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - ConnectionPool dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig).block(); + ConnectionPool dsConnectionMono = + pluginExecutor.datasourceCreate(dsConfig).block(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration - .setBody("SELECT id FROM users WHERE -- IS operator\nid = 1 limit 1;"); + actionConfiguration.setBody("SELECT id FROM users WHERE -- IS operator\nid = 1 limit 1;"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates); HashMap<String, Object> requestData = new HashMap<>(); - Mono<ActionExecutionResult> resultMono = spyPlugin.executeCommon( - dsConnectionMono, - actionConfiguration, - TRUE, - null, - null, - requestData - ); + Mono<ActionExecutionResult> resultMono = + spyPlugin.executeCommon(dsConnectionMono, actionConfiguration, TRUE, null, null, requestData); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1595,18 +1470,23 @@ public void testExecuteCommon_queryWithComments_callValidationCallsAfterRemoving verify(spyPlugin).isIsOperatorUsed("SELECT id FROM users WHERE \nid = 1 limit 1;"); verify(spyPlugin).getIsSelectOrShowOrDescQuery("SELECT id FROM users WHERE \nid = 1 limit 1;"); - }) .verifyComplete(); } @Test public void verifyUniquenessOfMySQLPluginErrorCode() { - assert (Arrays.stream(MySQLPluginError.values()).map(MySQLPluginError::getAppErrorCode).distinct().count() == MySQLPluginError.values().length); - - assert (Arrays.stream(MySQLPluginError.values()).map(MySQLPluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-MYS")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(MySQLPluginError.values()) + .map(MySQLPluginError::getAppErrorCode) + .distinct() + .count() + == MySQLPluginError.values().length); + + assert (Arrays.stream(MySQLPluginError.values()) + .map(MySQLPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-MYS")) + .collect(Collectors.toList()) + .size() + == 0); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlStaleConnectionErrorMessageTest.java b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlStaleConnectionErrorMessageTest.java index f956cad738a0..b03538cc1efe 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlStaleConnectionErrorMessageTest.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/plugins/MySqlStaleConnectionErrorMessageTest.java @@ -35,8 +35,8 @@ public void testStaleConnectionExceptionReturnsUpstreamErrorOnTimeoutError() thr ConnectionPool mockConnectionPool = mock(ConnectionPool.class); String expectedErrorMessage = "Timeout exception from MockConnectionPool"; when(mockConnectionPool.create()).thenReturn(Mono.error(new TimeoutException(expectedErrorMessage))); - Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon(mockConnectionPool, actionConfiguration, false, List.of(), - new ExecuteActionDTO(), new HashMap<>()); + Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon( + mockConnectionPool, actionConfiguration, false, List.of(), new ExecuteActionDTO(), new HashMap<>()); StepVerifier.create(actionExecutionResultMono) .expectErrorSatisfies(error -> { assertTrue(error instanceof StaleConnectionException); @@ -52,8 +52,8 @@ public void testStaleConnectionExceptionReturnsUpstreamErrorOnPoolShutdownError( ConnectionPool mockConnectionPool = mock(ConnectionPool.class); String expectedErrorMessage = "Timeout exception from MockConnectionPool"; when(mockConnectionPool.create()).thenReturn(Mono.error(new PoolShutdownException(expectedErrorMessage))); - Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon(mockConnectionPool, actionConfiguration, false, List.of(), - new ExecuteActionDTO(), new HashMap<>()); + Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon( + mockConnectionPool, actionConfiguration, false, List.of(), new ExecuteActionDTO(), new HashMap<>()); StepVerifier.create(actionExecutionResultMono) .expectErrorSatisfies(error -> { assertTrue(error instanceof StaleConnectionException); @@ -69,8 +69,8 @@ public void testStaleConnectionExceptionReturnsUpstreamErrorOnIllegalStateError( ConnectionPool mockConnectionPool = mock(ConnectionPool.class); String expectedErrorMessage = "Timeout exception from MockConnectionPool"; when(mockConnectionPool.create()).thenReturn(Mono.error(new IllegalStateException(expectedErrorMessage))); - Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon(mockConnectionPool, actionConfiguration, false, List.of(), - new ExecuteActionDTO(), new HashMap<>()); + Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon( + mockConnectionPool, actionConfiguration, false, List.of(), new ExecuteActionDTO(), new HashMap<>()); StepVerifier.create(actionExecutionResultMono) .expectErrorSatisfies(error -> { assertTrue(error instanceof StaleConnectionException); @@ -85,9 +85,10 @@ public void testStaleConnectionExceptionReturnsUpstreamErrorOnResourceError() th actionConfiguration.setBody("select 1;"); ConnectionPool mockConnectionPool = mock(ConnectionPool.class); String expectedErrorMessage = "Timeout exception from MockConnectionPool"; - when(mockConnectionPool.create()).thenReturn(Mono.error(new R2dbcNonTransientResourceException(expectedErrorMessage))); - Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon(mockConnectionPool, actionConfiguration, false, List.of(), - new ExecuteActionDTO(), new HashMap<>()); + when(mockConnectionPool.create()) + .thenReturn(Mono.error(new R2dbcNonTransientResourceException(expectedErrorMessage))); + Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon( + mockConnectionPool, actionConfiguration, false, List.of(), new ExecuteActionDTO(), new HashMap<>()); StepVerifier.create(actionExecutionResultMono) .expectErrorSatisfies(error -> { assertTrue(error instanceof StaleConnectionException); @@ -105,8 +106,8 @@ public void testStaleConnectionExceptionReturnsUpstreamErrorOnInvalidConnection( when(mockConnectionPool.create()).thenReturn(Mono.just(mockConnection)); when(mockConnection.validate(ValidationDepth.LOCAL)).thenReturn(Mono.just(false)); when(mockConnection.close()).thenReturn(Mono.empty()); - Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon(mockConnectionPool, actionConfiguration, false, List.of(), - new ExecuteActionDTO(), new HashMap<>()); + Mono<ActionExecutionResult> actionExecutionResultMono = pluginExecutor.executeCommon( + mockConnectionPool, actionConfiguration, false, List.of(), new ExecuteActionDTO(), new HashMap<>()); StepVerifier.create(actionExecutionResultMono) .expectErrorSatisfies(error -> { assertTrue(error instanceof StaleConnectionException); diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/utils/QueryUtilsTest.java b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/utils/QueryUtilsTest.java index 1bf67c19ba73..ef5d8b80f0b4 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/utils/QueryUtilsTest.java +++ b/app/server/appsmith-plugins/mysqlPlugin/src/test/java/com/external/utils/QueryUtilsTest.java @@ -50,4 +50,4 @@ public void testRemoveQueryComments_multilineWithMultiStatements_returnsSameStri final String s = QueryUtils.removeQueryComments(query); assertEquals(expected, s); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/oraclePlugin/pom.xml b/app/server/appsmith-plugins/oraclePlugin/pom.xml index 7d57a6ff2299..0426c6d34662 100755 --- a/app/server/appsmith-plugins/oraclePlugin/pom.xml +++ b/app/server/appsmith-plugins/oraclePlugin/pom.xml @@ -1,7 +1,6 @@ -<?xml version="1.0"?> -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" - xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> @@ -17,10 +16,10 @@ <url>http://maven.apache.org</url> <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>17</java.version> <maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.target>${java.version}</maven.compiler.target> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> @@ -61,10 +60,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/OraclePlugin.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/OraclePlugin.java index b836ac5ec4ed..f17c8e5a0f01 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/OraclePlugin.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/OraclePlugin.java @@ -84,6 +84,7 @@ public class OraclePlugin extends BasePlugin { public OraclePlugin(PluginWrapper wrapper) { super(wrapper); } + @Extension public static class OraclePluginExecutor implements SmartSubstitutionInterface, PluginExecutor<HikariDataSource> { public static final Scheduler scheduler = Schedulers.boundedElastic(); @@ -93,12 +94,13 @@ public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourc try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { - return Mono.error(new AppsmithPluginException(OraclePluginError.ORACLE_PLUGIN_ERROR, - OracleErrorMessages.ORACLE_JDBC_DRIVER_LOADING_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + OraclePluginError.ORACLE_PLUGIN_ERROR, + OracleErrorMessages.ORACLE_JDBC_DRIVER_LOADING_ERROR_MSG, + e.getMessage())); } - return Mono - .fromCallable(() -> { + return Mono.fromCallable(() -> { log.debug(Thread.currentThread().getName() + ": Connecting to Oracle db"); return createConnectionPool(datasourceConfiguration); }) @@ -116,29 +118,32 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur } @Override - public Mono<ActionExecutionResult> execute(HikariDataSource connection, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + HikariDataSource connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { return Mono.error( new AppsmithPluginException(OraclePluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); } @Override - public Mono<ActionExecutionResult> executeParameterized(HikariDataSource connectionPool, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> executeParameterized( + HikariDataSource connectionPool, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final Map<String, Object> formData = actionConfiguration.getFormData(); String query = getDataValueSafelyFromFormData(formData, BODY, STRING_TYPE, null); // Check for query parameter before performing the probably expensive fetch connection from the pool op. if (isBlank(query)) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, OracleErrorMessages.MISSING_QUERY_ERROR_MSG)); } Boolean isPreparedStatement = TRUE; - Object preparedStatementObject = getDataValueSafelyFromFormData(formData, PREPARED_STATEMENT, - OBJECT_TYPE, TRUE); + Object preparedStatementObject = + getDataValueSafelyFromFormData(formData, PREPARED_STATEMENT, OBJECT_TYPE, TRUE); if (preparedStatementObject instanceof Boolean) { isPreparedStatement = (Boolean) preparedStatementObject; } else if (preparedStatementObject instanceof String) { @@ -168,16 +173,22 @@ public Mono<ActionExecutionResult> executeParameterized(HikariDataSource connect updatedQuery = removeSemicolonFromQuery(updatedQuery); } setDataValueSafelyInFormData(formData, BODY, updatedQuery); - return executeCommon(connectionPool, datasourceConfiguration, actionConfiguration, TRUE, - mustacheKeysInOrder, executeActionDTO); + return executeCommon( + connectionPool, + datasourceConfiguration, + actionConfiguration, + TRUE, + mustacheKeysInOrder, + executeActionDTO); } - private Mono<ActionExecutionResult> executeCommon(HikariDataSource connectionPool, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration, - Boolean preparedStatement, - List<MustacheBindingToken> mustacheValuesInOrder, - ExecuteActionDTO executeActionDTO) { + private Mono<ActionExecutionResult> executeCommon( + HikariDataSource connectionPool, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration, + Boolean preparedStatement, + List<MustacheBindingToken> mustacheValuesInOrder, + ExecuteActionDTO executeActionDTO) { final Map<String, Object> requestData = new HashMap<>(); requestData.put("preparedStatement", TRUE.equals(preparedStatement) ? true : false); @@ -185,31 +196,34 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connectionPoo final Map<String, Object> formData = actionConfiguration.getFormData(); String query = getDataValueSafelyFromFormData(formData, BODY, STRING_TYPE, null); if (isBlank(query)) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, OracleErrorMessages.MISSING_QUERY_ERROR_MSG)); } Map<String, Object> psParams = preparedStatement ? new LinkedHashMap<>() : null; String transformedQuery = preparedStatement ? replaceQuestionMarkWithDollarIndex(query) : query; - List<RequestParamDTO> requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - transformedQuery, null, null, psParams)); + List<RequestParamDTO> requestParams = + List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, transformedQuery, null, null, psParams)); return Mono.fromCallable(() -> { Connection connectionFromPool; - try { - connectionFromPool = - oracleDatasourceUtils.getConnectionFromHikariConnectionPool(connectionPool, - ORACLE_PLUGIN_NAME); + try { + connectionFromPool = oracleDatasourceUtils.getConnectionFromHikariConnectionPool( + connectionPool, ORACLE_PLUGIN_NAME); } catch (SQLException | StaleConnectionException e) { - // The function can throw either StaleConnectionException or SQLException. The underlying hikari + // The function can throw either StaleConnectionException or SQLException. The underlying + // hikari // library throws SQLException in case the pool is closed or there is an issue initializing // the connection pool which can also be translated in our world to StaleConnectionException // and should then trigger the destruction and recreation of the pool. log.debug("Exception Occurred while getting connection from pool" + e.getMessage()); e.printStackTrace(System.out); - return Mono.error(e instanceof StaleConnectionException ? e : - new StaleConnectionException(e.getMessage())); + return Mono.error( + e instanceof StaleConnectionException + ? e + : new StaleConnectionException(e.getMessage())); } List<Map<String, Object>> rowsList = new ArrayList<>(50); @@ -221,8 +235,8 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connectionPoo boolean isResultSet; // Log HikariCP status - logHikariCPStatus(MessageFormat.format("Before executing Oracle query [{0}]", query), - connectionPool); + logHikariCPStatus( + MessageFormat.format("Before executing Oracle query [{0}]", query), connectionPool); try { if (FALSE.equals(preparedStatement)) { @@ -233,34 +247,42 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connectionPoo preparedQuery = connectionFromPool.prepareStatement(query); List<Map.Entry<String, String>> parameters = new ArrayList<>(); - preparedQuery = (PreparedStatement) smartSubstitutionOfBindings(preparedQuery, - mustacheValuesInOrder, - executeActionDTO.getParams(), - parameters); + preparedQuery = (PreparedStatement) smartSubstitutionOfBindings( + preparedQuery, mustacheValuesInOrder, executeActionDTO.getParams(), parameters); IntStream.range(0, parameters.size()) - .forEachOrdered(i -> - psParams.put( - getPSParamLabel(i+1), - new PsParameterDTO(parameters.get(i).getKey(),parameters.get(i).getValue()))); + .forEachOrdered(i -> psParams.put( + getPSParamLabel(i + 1), + new PsParameterDTO( + parameters.get(i).getKey(), + parameters.get(i).getValue()))); requestData.put("ps-parameters", parameters); isResultSet = preparedQuery.execute(); resultSet = preparedQuery.getResultSet(); } - populateRowsAndColumns(rowsList, columnsList, resultSet, isResultSet, preparedStatement, - statement, preparedQuery); + populateRowsAndColumns( + rowsList, + columnsList, + resultSet, + isResultSet, + preparedStatement, + statement, + preparedQuery); } catch (SQLException e) { - log.debug(Thread.currentThread().getName() + ": In the OraclePlugin, got action execution error"); + log.debug(Thread.currentThread().getName() + + ": In the OraclePlugin, got action execution error"); log.debug(e.getMessage()); - return Mono.error(new AppsmithPluginException(OraclePluginError.QUERY_EXECUTION_FAILED, - OracleErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage(), + return Mono.error(new AppsmithPluginException( + OraclePluginError.QUERY_EXECUTION_FAILED, + OracleErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage(), "SQLSTATE: " + e.getSQLState())); } finally { // Log HikariCP status - logHikariCPStatus(MessageFormat.format("After executing Oracle query [{0}]", query), - connectionPool); + logHikariCPStatus( + MessageFormat.format("After executing Oracle query [{0}]", query), connectionPool); closeConnectionPostExecution(resultSet, statement, preparedQuery, connectionFromPool); } @@ -269,7 +291,8 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connectionPoo result.setBody(objectMapper.valueToTree(rowsList)); result.setMessages(populateHintMessages(columnsList)); result.setIsExecutionSuccess(true); - log.debug(Thread.currentThread().getName() + ": In the OraclePlugin, got action execution result"); + log.debug(Thread.currentThread().getName() + + ": In the OraclePlugin, got action execution result"); return Mono.just(result); }) .flatMap(obj -> obj) @@ -297,8 +320,8 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connectionPoo } @Override - public Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, - DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + HikariDataSource connectionPool, DatasourceConfiguration datasourceConfiguration) { return OracleDatasourceUtils.getStructure(connectionPool, datasourceConfiguration); } @@ -307,27 +330,31 @@ private Set<String> populateHintMessages(List<String> columnNames) { List<String> identicalColumns = getIdenticalColumns(columnNames); if (!CollectionUtils.isEmpty(identicalColumns)) { - messages.add("Your OracleSQL query result may not have all the columns because duplicate column " + - "names were found for the column(s): " + String.join(", ", identicalColumns) + ". You may use" + - " the SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); + messages.add("Your OracleSQL query result may not have all the columns because duplicate column " + + "names were found for the column(s): " + + String.join(", ", identicalColumns) + ". You may use" + + " the SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); } return messages; } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) throws AppsmithPluginException { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) + throws AppsmithPluginException { PreparedStatement preparedStatement = (PreparedStatement) input; Param param = (Param) args[0]; DataType valueType; - valueType = DataTypeServiceUtils.getAppsmithType(param.getClientDataType(), value, - OracleSpecificDataTypes.pluginSpecificTypes).type(); + valueType = DataTypeServiceUtils.getAppsmithType( + param.getClientDataType(), value, OracleSpecificDataTypes.pluginSpecificTypes) + .type(); Map.Entry<String, String> parameter = new AbstractMap.SimpleEntry<>(value, valueType.toString()); insertedParams.add(parameter); @@ -391,7 +418,8 @@ public Object substituteValueInInput(int index, // set in the commented part of // the query. Ignore the exception } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(OracleErrorMessages.QUERY_PREPARATION_FAILED_ERROR_MSG, value, binding), e.getMessage()); } diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OracleErrorMessages.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OracleErrorMessages.java index 54618753d76f..23eac3e868f9 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OracleErrorMessages.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OracleErrorMessages.java @@ -12,29 +12,33 @@ public class OracleErrorMessages extends BasePluginErrorMessages { public static final String ORACLE_JDBC_DRIVER_LOADING_ERROR_MSG = "Your Oracle query failed to execute."; - public static final String GET_STRUCTURE_ERROR_MSG = "The Appsmith server has failed to fetch the structure of your schema."; + public static final String GET_STRUCTURE_ERROR_MSG = + "The Appsmith server has failed to fetch the structure of your schema."; - public static final String QUERY_PREPARATION_FAILED_ERROR_MSG = "Query preparation failed while inserting value: %s" - + " for binding: {{%s}}."; + public static final String QUERY_PREPARATION_FAILED_ERROR_MSG = + "Query preparation failed while inserting value: %s" + " for binding: {{%s}}."; - public static final String SSL_CONFIGURATION_ERROR_MSG = "The Appsmith server has failed to fetch SSL configuration from datasource configuration form. "; + public static final String SSL_CONFIGURATION_ERROR_MSG = + "The Appsmith server has failed to fetch SSL configuration from datasource configuration form. "; - public static final String INVALID_SSL_OPTION_ERROR_MSG = "The Appsmith server has found an unexpected SSL option: %s."; + public static final String INVALID_SSL_OPTION_ERROR_MSG = + "The Appsmith server has found an unexpected SSL option: %s."; - public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = "An exception occurred while creating " + - "connection pool. One or more arguments in the datasource configuration may be invalid."; + public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = "An exception occurred while creating " + + "connection pool. One or more arguments in the datasource configuration may be invalid."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ public static final String DS_MISSING_ENDPOINT_ERROR_MSG = "Missing endpoint."; public static final String DS_MISSING_HOSTNAME_ERROR_MSG = "Missing hostname."; - public static final String DS_INVALID_HOSTNAME_ERROR_MSG = "Host value cannot contain `/` or `:` characters. Found `%s`."; + public static final String DS_INVALID_HOSTNAME_ERROR_MSG = + "Host value cannot contain `/` or `:` characters. Found `%s`."; public static final String DS_MISSING_AUTHENTICATION_DETAILS_ERROR_MSG = "Missing authentication details."; diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OraclePluginError.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OraclePluginError.java index a5be33da0ad4..b565c0256c83 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OraclePluginError.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OraclePluginError.java @@ -17,8 +17,7 @@ public enum OraclePluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ORACLE_PLUGIN_ERROR( 500, "PE-ORC-5001", @@ -27,8 +26,7 @@ public enum OraclePluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), RESPONSE_SIZE_TOO_LARGE( 504, "PE-ORC-5009", @@ -37,8 +35,7 @@ public enum OraclePluginError implements BasePluginError { "Large Result Set Not Supported", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; private final String appErrorCode; @@ -51,8 +48,15 @@ public enum OraclePluginError implements BasePluginError { private final String downstreamErrorCode; - OraclePluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + OraclePluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -67,7 +71,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleDatasourceUtils.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleDatasourceUtils.java index 8254eeb618ab..7cc828a0c4c0 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleDatasourceUtils.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleDatasourceUtils.java @@ -64,10 +64,7 @@ public class OracleDatasourceUtils { * +------------+-----------+-----------------+ */ public static final String ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE = - "SELECT " + - "table_name, column_name, data_type " + - "FROM " + - "user_tab_cols"; + "SELECT " + "table_name, column_name, data_type " + "FROM " + "user_tab_cols"; /** * Example output: @@ -79,27 +76,26 @@ public class OracleDatasourceUtils { * +------------+-----------+-----------------+-----------------+-------------------+ */ public static final String ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS = - "SELECT " + - " cols.table_name, " + - " cols.column_name, " + - " cons.constraint_type, " + - " cons.constraint_name, " + - " cons.r_constraint_name " + - "FROM " + - " all_cons_columns cols " + - " JOIN all_constraints cons " + - " ON cols.owner = cons.owner " + - " AND cols.constraint_name = cons.constraint_name " + - " JOIN all_tab_cols tab_cols " + - " ON cols.owner = tab_cols.owner " + - " AND cols.table_name = tab_cols.table_name " + - " AND cols.column_name = tab_cols.column_name " + - "WHERE " + - " cons.constraint_type IN ('P', 'R') " + - " AND cons.owner = 'ADMIN' " + - "ORDER BY " + - " cols.table_name, " + - " cols.position"; + "SELECT " + " cols.table_name, " + + " cols.column_name, " + + " cons.constraint_type, " + + " cons.constraint_name, " + + " cons.r_constraint_name " + + "FROM " + + " all_cons_columns cols " + + " JOIN all_constraints cons " + + " ON cols.owner = cons.owner " + + " AND cols.constraint_name = cons.constraint_name " + + " JOIN all_tab_cols tab_cols " + + " ON cols.owner = tab_cols.owner " + + " AND cols.table_name = tab_cols.table_name " + + " AND cols.column_name = tab_cols.column_name " + + "WHERE " + + " cons.constraint_type IN ('P', 'R') " + + " AND cons.owner = 'ADMIN' " + + "ORDER BY " + + " cols.table_name, " + + " cols.position"; public static void datasourceDestroy(HikariDataSource connectionPool) { if (connectionPool != null) { @@ -117,7 +113,8 @@ public static Set<String> validateDatasource(DatasourceConfiguration datasourceC for (final Endpoint endpoint : datasourceConfiguration.getEndpoints()) { if (isBlank(endpoint.getHost())) { invalids.add(OracleErrorMessages.DS_MISSING_HOSTNAME_ERROR_MSG); - } else if (endpoint.getHost().contains("/") || endpoint.getHost().contains(":")) { + } else if (endpoint.getHost().contains("/") + || endpoint.getHost().contains(":")) { invalids.add(String.format(OracleErrorMessages.DS_INVALID_HOSTNAME_ERROR_MSG, endpoint.getHost())); } } @@ -153,23 +150,25 @@ public static Set<String> validateDatasource(DatasourceConfiguration datasourceC return invalids; } - public static Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, - DatasourceConfiguration datasourceConfiguration) { + public static Mono<DatasourceStructure> getStructure( + HikariDataSource connectionPool, DatasourceConfiguration datasourceConfiguration) { final DatasourceStructure structure = new DatasourceStructure(); final Map<String, DatasourceStructure.Table> tableNameToTableMap = new LinkedHashMap<>(); return Mono.fromSupplier(() -> { Connection connectionFromPool; try { - connectionFromPool = - oracleDatasourceUtils.getConnectionFromHikariConnectionPool(connectionPool, ORACLE_PLUGIN_NAME); + connectionFromPool = oracleDatasourceUtils.getConnectionFromHikariConnectionPool( + connectionPool, ORACLE_PLUGIN_NAME); } catch (SQLException | StaleConnectionException e) { // The function can throw either StaleConnectionException or SQLException. The // underlying hikari library throws SQLException in case the pool is closed or there is an issue // initializing the connection pool which can also be translated in our world to // StaleConnectionException and should then trigger the destruction and recreation of the pool. - return Mono.error(e instanceof StaleConnectionException ? e : - new StaleConnectionException(e.getMessage())); + return Mono.error( + e instanceof StaleConnectionException + ? e + : new StaleConnectionException(e.getMessage())); } logHikariCPStatus("Before getting Oracle DB schema", connectionPool); @@ -182,13 +181,16 @@ public static Mono<DatasourceStructure> getStructure(HikariDataSource connection setPrimaryAndForeignKeyInfoInTables(statement, tableNameToTableMap); } catch (SQLException throwable) { - return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, - OracleErrorMessages.GET_STRUCTURE_ERROR_MSG, throwable.getCause(), + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + OracleErrorMessages.GET_STRUCTURE_ERROR_MSG, + throwable.getCause(), "SQLSTATE: " + throwable.getSQLState())); } finally { logHikariCPStatus("After getting Oracle DB schema", connectionPool); - safelyCloseSingleConnectionFromHikariCP(connectionFromPool, "Error returning Oracle connection to pool " + - "during get structure"); + safelyCloseSingleConnectionFromHikariCP( + connectionFromPool, + "Error returning Oracle connection to pool " + "during get structure"); } // Set SQL query templates @@ -208,8 +210,8 @@ public static Mono<DatasourceStructure> getStructure(HikariDataSource connection * tables to which a foreign key is related to. * Please check the SQL query macro definition to find a sample response as comment. */ - private static void setPrimaryAndForeignKeyInfoInTables(Statement statement, Map<String, - DatasourceStructure.Table> tableNameToTableMap) throws SQLException { + private static void setPrimaryAndForeignKeyInfoInTables( + Statement statement, Map<String, DatasourceStructure.Table> tableNameToTableMap) throws SQLException { Map<String, String> primaryKeyConstraintNameToTableNameMap = new HashMap<>(); Map<String, String> primaryKeyConstraintNameToColumnNameMap = new HashMap<>(); Map<String, String> foreignKeyConstraintNameToTableNameMap = new HashMap<>(); @@ -217,7 +219,7 @@ private static void setPrimaryAndForeignKeyInfoInTables(Statement statement, Map Map<String, String> foreignKeyConstraintNameToRemoteConstraintNameMap = new HashMap<>(); try (ResultSet columnsResultSet = - statement.executeQuery(ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS)) { + statement.executeQuery(ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS)) { while (columnsResultSet.next()) { final String tableName = columnsResultSet.getString("TABLE_NAME"); final String columnName = columnsResultSet.getString("COLUMN_NAME"); @@ -228,8 +230,7 @@ private static void setPrimaryAndForeignKeyInfoInTables(Statement statement, Map if (ORACLE_PRIMARY_KEY_INDICATOR.equalsIgnoreCase(constraintType)) { primaryKeyConstraintNameToTableNameMap.put(constraintName, tableName); primaryKeyConstraintNameToColumnNameMap.put(constraintName, columnName); - } - else { + } else { foreignKeyConstraintNameToTableNameMap.put(constraintName, tableName); foreignKeyConstraintNameToColumnNameMap.put(constraintName, columnName); foreignKeyConstraintNameToRemoteConstraintNameMap.put(constraintName, remoteConstraintName); @@ -245,8 +246,7 @@ private static void setPrimaryAndForeignKeyInfoInTables(Statement statement, Map String tableName = primaryKeyConstraintNameToTableNameMap.get(constraintName); DatasourceStructure.Table table = tableNameToTableMap.get(tableName); String columnName = primaryKeyConstraintNameToColumnNameMap.get(constraintName); - table.getKeys().add(new DatasourceStructure.PrimaryKey(constraintName, - List.of(columnName))); + table.getKeys().add(new DatasourceStructure.PrimaryKey(constraintName, List.of(columnName))); }); foreignKeyConstraintNameToColumnNameMap.keySet().stream() @@ -261,8 +261,9 @@ private static void setPrimaryAndForeignKeyInfoInTables(Statement statement, Map String remoteConstraintName = foreignKeyConstraintNameToRemoteConstraintNameMap.get(constraintName); String remoteColumn = primaryKeyConstraintNameToColumnNameMap.get(remoteConstraintName); - table.getKeys().add(new DatasourceStructure.ForeignKey(constraintName, - List.of(columnName), List.of(remoteColumn))); + table.getKeys() + .add(new DatasourceStructure.ForeignKey( + constraintName, List.of(columnName), List.of(remoteColumn))); }); } } @@ -272,70 +273,77 @@ private static void setPrimaryAndForeignKeyInfoInTables(Statement statement, Map * Then read the response and populate Appsmith's Table object with the same. * Please check the SQL query macro definition to find a sample response as comment. */ - private static void setTableNamesAndColumnNamesAndColumnTypes(Statement statement, Map<String, - DatasourceStructure.Table> tableNameToTableMap) throws SQLException { - try (ResultSet columnsResultSet = - statement.executeQuery(ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE)) { + private static void setTableNamesAndColumnNamesAndColumnTypes( + Statement statement, Map<String, DatasourceStructure.Table> tableNameToTableMap) throws SQLException { + try (ResultSet columnsResultSet = statement.executeQuery(ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE)) { while (columnsResultSet.next()) { final String tableName = columnsResultSet.getString("TABLE_NAME"); if (!tableNameToTableMap.containsKey(tableName)) { - tableNameToTableMap.put(tableName, new DatasourceStructure.Table( - DatasourceStructure.TableType.TABLE, - "", + tableNameToTableMap.put( tableName, - new ArrayList<>(), - new ArrayList<>(), - new ArrayList<>())); + new DatasourceStructure.Table( + DatasourceStructure.TableType.TABLE, + "", + tableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); } final DatasourceStructure.Table table = tableNameToTableMap.get(tableName); - table.getColumns().add(new DatasourceStructure.Column( - columnsResultSet.getString("COLUMN_NAME"), - columnsResultSet.getString("DATA_TYPE"), - null, - false)); + table.getColumns() + .add(new DatasourceStructure.Column( + columnsResultSet.getString("COLUMN_NAME"), + columnsResultSet.getString("DATA_TYPE"), + null, + false)); } } } private static void setSQLQueryTemplates(Map<String, DatasourceStructure.Table> tableNameToTableMap) { - tableNameToTableMap.values().stream() - .forEach(table -> { - LinkedHashMap<String, String> columnNameToSampleColumnDataMap = - new LinkedHashMap<>(); - table.getColumns().stream() - .forEach(column -> { - columnNameToSampleColumnDataMap.put(column.getName(), - getSampleColumnData(column.getType())); - }); - - String selectQueryTemplate = MessageFormat.format("SELECT * FROM {0} WHERE " + - "ROWNUM < 10", table.getName()); - String insertQueryTemplate = MessageFormat.format("INSERT INTO {0} ({1}) " + - "VALUES ({2})", table.getName(), - getSampleColumnNamesCSVString(columnNameToSampleColumnDataMap), - getSampleColumnDataCSVString(columnNameToSampleColumnDataMap)); - String updateQueryTemplate = MessageFormat.format("UPDATE {0} SET {1} WHERE " + - "1=0 -- Specify a valid condition here. Removing the condition may " + - "update every row in the table!", table.getName(), - getSampleOneColumnUpdateString(columnNameToSampleColumnDataMap)); - String deleteQueryTemplate = MessageFormat.format("DELETE FROM {0} WHERE 1=0" + - " -- Specify a valid condition here. Removing the condition may " + - "delete everything in the table!", table.getName()); - - table.getTemplates().add(new DatasourceStructure.Template("SELECT", null, - Map.of("body", Map.of("data", selectQueryTemplate)))); - table.getTemplates().add(new DatasourceStructure.Template("INSERT", null, - Map.of("body", Map.of("data", insertQueryTemplate)))); - table.getTemplates().add(new DatasourceStructure.Template("UPDATE", null, - Map.of("body", Map.of("data", updateQueryTemplate)))); - table.getTemplates().add(new DatasourceStructure.Template("DELETE", null, - Map.of("body", Map.of("data", deleteQueryTemplate)))); - }); + tableNameToTableMap.values().stream().forEach(table -> { + LinkedHashMap<String, String> columnNameToSampleColumnDataMap = new LinkedHashMap<>(); + table.getColumns().stream().forEach(column -> { + columnNameToSampleColumnDataMap.put(column.getName(), getSampleColumnData(column.getType())); + }); + + String selectQueryTemplate = + MessageFormat.format("SELECT * FROM {0} WHERE " + "ROWNUM < 10", table.getName()); + String insertQueryTemplate = MessageFormat.format( + "INSERT INTO {0} ({1}) " + "VALUES ({2})", + table.getName(), + getSampleColumnNamesCSVString(columnNameToSampleColumnDataMap), + getSampleColumnDataCSVString(columnNameToSampleColumnDataMap)); + String updateQueryTemplate = MessageFormat.format( + "UPDATE {0} SET {1} WHERE " + "1=0 -- Specify a valid condition here. Removing the condition may " + + "update every row in the table!", + table.getName(), getSampleOneColumnUpdateString(columnNameToSampleColumnDataMap)); + String deleteQueryTemplate = MessageFormat.format( + "DELETE FROM {0} WHERE 1=0" + " -- Specify a valid condition here. Removing the condition may " + + "delete everything in the table!", + table.getName()); + + table.getTemplates() + .add(new DatasourceStructure.Template( + "SELECT", null, Map.of("body", Map.of("data", selectQueryTemplate)))); + table.getTemplates() + .add(new DatasourceStructure.Template( + "INSERT", null, Map.of("body", Map.of("data", insertQueryTemplate)))); + table.getTemplates() + .add(new DatasourceStructure.Template( + "UPDATE", null, Map.of("body", Map.of("data", updateQueryTemplate)))); + table.getTemplates() + .add(new DatasourceStructure.Template( + "DELETE", null, Map.of("body", Map.of("data", deleteQueryTemplate)))); + }); } - private static String getSampleOneColumnUpdateString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { - return MessageFormat.format("{0}={1}", columnNameToSampleColumnDataMap.keySet().stream().findFirst().orElse( - "id"), columnNameToSampleColumnDataMap.values().stream().findFirst().orElse("'uid'")); + private static String getSampleOneColumnUpdateString( + LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return MessageFormat.format( + "{0}={1}", + columnNameToSampleColumnDataMap.keySet().stream().findFirst().orElse("id"), + columnNameToSampleColumnDataMap.values().stream().findFirst().orElse("'uid'")); } private static String getSampleColumnNamesCSVString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { @@ -354,23 +362,24 @@ private static String getSampleColumnData(String type) { switch (type.toUpperCase()) { case "NUMBER": return "1"; - case "FLOAT": /* Fall through */ + case "FLOAT": /* Fall through */ case "DOUBLE": return "1.0"; - case "CHAR": /* Fall through */ - case "NCHAR": /* Fall through */ + case "CHAR": /* Fall through */ + case "NCHAR": /* Fall through */ case "VARCHAR": /* Fall through */ - case "VARCHAR2":/* Fall through */ - case "NVARCHAR":/* Fall through */ + case "VARCHAR2": /* Fall through */ + case "NVARCHAR": /* Fall through */ case "NVARCHAR2": return "'text'"; - case "NULL": /* Fall through */ + case "NULL": /* Fall through */ default: return "NULL"; } } - public static HikariDataSource createConnectionPool(DatasourceConfiguration datasourceConfiguration) throws AppsmithPluginException { + public static HikariDataSource createConnectionPool(DatasourceConfiguration datasourceConfiguration) + throws AppsmithPluginException { HikariConfig config = new HikariConfig(); config.setDriverClassName(JDBC_DRIVER); @@ -390,9 +399,7 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data // Set up the connection URL StringBuilder urlBuilder = new StringBuilder(ORACLE_URL_PREFIX); - List<String> hosts = datasourceConfiguration - .getEndpoints() - .stream() + List<String> hosts = datasourceConfiguration.getEndpoints().stream() .map(endpoint -> endpoint.getHost() + ":" + ObjectUtils.defaultIfNull(endpoint.getPort(), 1521L)) .collect(Collectors.toList()); @@ -408,11 +415,12 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data if (datasourceConfiguration.getConnection() == null || datasourceConfiguration.getConnection().getSsl() == null || datasourceConfiguration.getConnection().getSsl().getAuthType() == null) { - throw new AppsmithPluginException(OraclePluginError.ORACLE_PLUGIN_ERROR, - OracleErrorMessages.SSL_CONFIGURATION_ERROR_MSG); + throw new AppsmithPluginException( + OraclePluginError.ORACLE_PLUGIN_ERROR, OracleErrorMessages.SSL_CONFIGURATION_ERROR_MSG); } - SSLDetails.AuthType sslAuthType = datasourceConfiguration.getConnection().getSsl().getAuthType(); + SSLDetails.AuthType sslAuthType = + datasourceConfiguration.getConnection().getSsl().getAuthType(); switch (sslAuthType) { case DISABLE: /* do nothing */ @@ -424,7 +432,8 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data break; default: - throw new AppsmithPluginException(OraclePluginError.ORACLE_PLUGIN_ERROR, + throw new AppsmithPluginException( + OraclePluginError.ORACLE_PLUGIN_ERROR, String.format(OracleErrorMessages.INVALID_SSL_OPTION_ERROR_MSG, sslAuthType)); } @@ -440,8 +449,10 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data try { datasource = new HikariDataSource(config); } catch (HikariPool.PoolInitializationException e) { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - OracleErrorMessages.CONNECTION_POOL_CREATION_FAILED_ERROR_MSG, e.getMessage()); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + OracleErrorMessages.CONNECTION_POOL_CREATION_FAILED_ERROR_MSG, + e.getMessage()); } return datasource; @@ -453,26 +464,27 @@ public static void logHikariCPStatus(String logPrefix, HikariDataSource connecti int activeConnections = poolProxy.getActiveConnections(); int totalConnections = poolProxy.getTotalConnections(); int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug(MessageFormat.format("{0}: Hikari Pool stats : active - {1} , idle - {2}, awaiting - {3} , total - {4}", + log.debug(MessageFormat.format( + "{0}: Hikari Pool stats : active - {1} , idle - {2}, awaiting - {3} , total - {4}", logPrefix, activeConnections, idleConnections, threadsAwaitingConnection, totalConnections)); } - public void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) throws StaleConnectionException { + public void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) + throws StaleConnectionException { if (connectionPool == null || connectionPool.isClosed() || !connectionPool.isRunning()) { - String printMessage = MessageFormat.format(Thread.currentThread().getName() + - ": Encountered stale connection pool in {0} plugin. Reporting back.", pluginName); + String printMessage = MessageFormat.format( + Thread.currentThread().getName() + + ": Encountered stale connection pool in {0} plugin. Reporting back.", + pluginName); System.out.println(printMessage); if (connectionPool == null) { throw new StaleConnectionException(CONNECTION_POOL_NULL_ERROR_MSG); - } - else if (connectionPool.isClosed()) { + } else if (connectionPool.isClosed()) { throw new StaleConnectionException(CONNECTION_POOL_CLOSED_ERROR_MSG); - } - else if (!connectionPool.isRunning()) { + } else if (!connectionPool.isRunning()) { throw new StaleConnectionException(CONNECTION_POOL_NOT_RUNNING_ERROR_MSG); - } - else { + } else { /** * Ideally, code flow is never expected to reach here. However, this section has been added to catch * those cases wherein a developer updates the parent if condition but does not update the nested @@ -483,8 +495,8 @@ else if (!connectionPool.isRunning()) { } } - public Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, - String pluginName) throws SQLException { + public Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, String pluginName) + throws SQLException { checkHikariCPConnectionPoolValidity(connectionPool, pluginName); return connectionPool.getConnection(); } diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleExecuteUtils.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleExecuteUtils.java index e2876677ebc6..e9cbd42e9a48 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleExecuteUtils.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleExecuteUtils.java @@ -49,17 +49,19 @@ public class OracleExecuteUtils implements SmartSubstitutionInterface { * required. " * Ref: https://docs.oracle.com/cd/B14117_01/appdev.101/b10807/13_elems003.htm#:~:text=A%20PL%2FSQL%20block%20is,the%20executable%20part%20is%20required. */ - private static final String PLSQL_MATCH_REGEX = "(\\bdeclare\\b(\\s))|(\\bbegin\\b(\\s))|(\\bend\\b(\\s|;))|(\\bexception\\b(\\s))"; + private static final String PLSQL_MATCH_REGEX = + "(\\bdeclare\\b(\\s))|(\\bbegin\\b(\\s))|(\\bend\\b(\\s|;))|(\\bexception\\b(\\s))"; + private static final Pattern PL_SQL_MATCH_PATTERN = Pattern.compile(PLSQL_MATCH_REGEX); - public static void closeConnectionPostExecution(ResultSet resultSet, Statement statement, - PreparedStatement preparedQuery, Connection connectionFromPool) { + public static void closeConnectionPostExecution( + ResultSet resultSet, Statement statement, PreparedStatement preparedQuery, Connection connectionFromPool) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { - System.out.println(Thread.currentThread().getName() + - ": Execute Error closing Oracle ResultSet" + e.getMessage()); + System.out.println( + Thread.currentThread().getName() + ": Execute Error closing Oracle ResultSet" + e.getMessage()); } } @@ -67,8 +69,8 @@ public static void closeConnectionPostExecution(ResultSet resultSet, Statement s try { statement.close(); } catch (SQLException e) { - System.out.println(Thread.currentThread().getName() + - ": Execute Error closing Oracle Statement" + e.getMessage()); + System.out.println( + Thread.currentThread().getName() + ": Execute Error closing Oracle Statement" + e.getMessage()); } } @@ -76,13 +78,16 @@ public static void closeConnectionPostExecution(ResultSet resultSet, Statement s try { preparedQuery.close(); } catch (SQLException e) { - System.out.println(Thread.currentThread().getName() + - ": Execute Error closing Oracle Statement" + e.getMessage()); + System.out.println( + Thread.currentThread().getName() + ": Execute Error closing Oracle Statement" + e.getMessage()); } } - safelyCloseSingleConnectionFromHikariCP(connectionFromPool, MessageFormat.format("{0}: Execute Error returning " + - "Oracle connection to pool", Thread.currentThread().getName())); + safelyCloseSingleConnectionFromHikariCP( + connectionFromPool, + MessageFormat.format( + "{0}: Execute Error returning " + "Oracle connection to pool", + Thread.currentThread().getName())); } /** @@ -105,18 +110,24 @@ public static boolean isPLSQL(String query) { * Please don't use Java's String.matches(...) function here because it doesn't behave like normal regex * match. It returns true only if the entire string matches the regex as opposed to finding a substring * matching the pattern. - * Ref: https://stackoverflow.com/questions/8923398/regex-doesnt-work-in-string-matches + * Ref: https://stackoverflow.com/questions/8923398/regex-doesnt-work-in-string-matches */ return PL_SQL_MATCH_PATTERN.matcher(query.toLowerCase()).find(); } - public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, List<String> columnsList, - ResultSet resultSet, Boolean isResultSet, Boolean preparedStatement, - Statement statement, PreparedStatement preparedQuery) throws SQLException { + public static void populateRowsAndColumns( + List<Map<String, Object>> rowsList, + List<String> columnsList, + ResultSet resultSet, + Boolean isResultSet, + Boolean preparedStatement, + Statement statement, + PreparedStatement preparedQuery) + throws SQLException { if (!isResultSet) { - Object updateCount = FALSE.equals(preparedStatement) ? - ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) : - ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); + Object updateCount = FALSE.equals(preparedStatement) + ? ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) + : ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); rowsList.add(Map.of(AFFECTED_ROWS_KEY, updateCount)); } else { @@ -136,20 +147,22 @@ public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, Li value = null; } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE.format(resultSet.getDate(i).toLocalDate()); + value = DateTimeFormatter.ISO_DATE.format( + resultSet.getDate(i).toLocalDate()); - } else if (TIMESTAMP_TYPE_NAME.equalsIgnoreCase(typeName) || TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName) || TIMESTAMPLTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - resultSet.getObject(i, OffsetDateTime.class) - ); + } else if (TIMESTAMP_TYPE_NAME.equalsIgnoreCase(typeName) + || TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName) + || TIMESTAMPLTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE_TIME.format(resultSet.getObject(i, OffsetDateTime.class)); } else if (CLOB_TYPE_NAME.equalsIgnoreCase(typeName) || NCLOB_TYPE_NAME.equals(typeName)) { /** * clob, nclob are textual data. * Ref: https://docs.oracle.com/javadb/10.10.1.2/ref/rrefclob.html */ - value = String.valueOf(((CLOB)resultSet.getObject(i)).getTarget().getPrefetchedData()); + value = String.valueOf( + ((CLOB) resultSet.getObject(i)).getTarget().getPrefetchedData()); } else if (resultSet.getObject(i) instanceof OracleArray) { - value = ((OracleArray)resultSet.getObject(i)).getArray(); + value = ((OracleArray) resultSet.getObject(i)).getArray(); } else if (RAW_TYPE_NAME.equalsIgnoreCase(typeName)) { /** * Raw / Blob data cannot be interpreted as anything but a byte array. Hence, send it back as a @@ -158,18 +171,16 @@ public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, Li * select utl_raw.cast_to_varchar2(c_raw) as c_raw, utl_raw.cast_to_varchar2(c_blob) as c_blob from TYPESTEST4 */ value = Base64.getEncoder().encodeToString((byte[]) resultSet.getObject(i)); - } - else if (BLOB_TYPE_NAME.equalsIgnoreCase(typeName)) { + } else if (BLOB_TYPE_NAME.equalsIgnoreCase(typeName)) { /** * Raw / Blob data cannot be interpreted as anything but a byte array. Hence, send it back as a * base64 encoded string. The correct way to read the data for these types is for the user to * cast them to a type before reading them, example: * select utl_raw.cast_to_varchar2(c_raw) as c_raw, utl_raw.cast_to_varchar2(c_blob) as c_blob from TYPESTEST4 */ - value = ((OracleBlob)resultSet.getObject(i)).getBytes(1L, - (int) ((OracleBlob)resultSet.getObject(i)).length()); - } - else { + value = ((OracleBlob) resultSet.getObject(i)) + .getBytes(1L, (int) ((OracleBlob) resultSet.getObject(i)).length()); + } else { value = resultSet.getObject(i).toString(); } diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleSpecificDataTypes.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleSpecificDataTypes.java index 6cbd3798660f..6d6e70de929c 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleSpecificDataTypes.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleSpecificDataTypes.java @@ -21,33 +21,26 @@ import java.util.Map; public class OracleSpecificDataTypes { - public final static Map<ClientDataType, List<AppsmithType>> pluginSpecificTypes = new HashMap<>(); + public static final Map<ClientDataType, List<AppsmithType>> pluginSpecificTypes = new HashMap<>(); - static { + static { pluginSpecificTypes.put(ClientDataType.NULL, List.of(new NullType())); pluginSpecificTypes.put(ClientDataType.ARRAY, List.of(new NullArrayType(), new ArrayType())); pluginSpecificTypes.put(ClientDataType.BOOLEAN, List.of(new BooleanType())); - pluginSpecificTypes.put(ClientDataType.NUMBER, List.of( - new IntegerType(), - new LongType(), - new DoubleType(), - new BigDecimalType() - )); + pluginSpecificTypes.put( + ClientDataType.NUMBER, + List.of(new IntegerType(), new LongType(), new DoubleType(), new BigDecimalType())); /* - JsonObjectType is the preferred server-side data type when the client-side data type is of type OBJECT. - Fallback server-side data type for client-side OBJECT type is String. - */ + JsonObjectType is the preferred server-side data type when the client-side data type is of type OBJECT. + Fallback server-side data type for client-side OBJECT type is String. + */ pluginSpecificTypes.put(ClientDataType.OBJECT, List.of(new JsonObjectType())); - pluginSpecificTypes.put(ClientDataType.STRING, List.of( - new TimeType(), - new DateType(), - new TimestampType(), - new StringType() - )); + pluginSpecificTypes.put( + ClientDataType.STRING, List.of(new TimeType(), new DateType(), new TimestampType(), new StringType())); } } diff --git a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleExecutionTest.java b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleExecutionTest.java index d746687cbfbc..2e0f972cabda 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleExecutionTest.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleExecutionTest.java @@ -29,78 +29,77 @@ @Testcontainers public class OracleExecutionTest { - public static final String SQL_QUERY_CREATE_TABLE_FORMAT = - "create table {0} (\n" + - "c_varchar2 varchar2(20),\n" + - "c_nvarchar2 nvarchar2(20),\n" + - "c_number number,\n" + - "c_float float,\n" + - "c_date date,\n" + - "c_binary_float binary_float,\n" + - "c_binary_double binary_double,\n" + - "c_timestamp timestamp,\n" + - "c_timestamp_tz timestamp with time zone,\n" + - "c_timestamp_ltz timestamp with local time zone,\n" + - "c_interval_year interval year to month,\n" + - "c_interval_day interval day to second,\n" + - "c_rowid rowid,\n" + - "c_urowid urowid,\n" + - "c_char char(20),\n" + - "c_nchar nchar(20),\n" + - "c_clob clob,\n" + - "c_nclob nclob\n" + - ")\n"; - private static final String SQL_QUERY_TO_INSERT_ONE_ROW_FORMAT = - "insert into {0} values (\n" + - "''varchar2'',\n" + - "''nvarchar2'',\n" + - "{1},\n" + - "11.22,\n" + - "''03-OCT-02'',\n" + - "11.22,\n" + - "11.22,\n" + - "TIMESTAMP''1997-01-01 09:26:50.124'',\n" + - "TIMESTAMP''1997-01-01 09:26:56.66 +02:00'',\n" + - "TIMESTAMP''1999-04-05 8:00:00 US/Pacific'',\n" + - "INTERVAL ''1'' YEAR(3),\n" + - "INTERVAL ''1'' HOUR,\n" + - "''000001F8.0001.0006'',\n" + - "''000001F8.0001.0006'',\n" + - "''char'',\n" + - "''nchar'',\n" + - "''clob'',\n" + - "''nclob''\n" + - ")"; + public static final String SQL_QUERY_CREATE_TABLE_FORMAT = "create table {0} (\n" + "c_varchar2 varchar2(20),\n" + + "c_nvarchar2 nvarchar2(20),\n" + + "c_number number,\n" + + "c_float float,\n" + + "c_date date,\n" + + "c_binary_float binary_float,\n" + + "c_binary_double binary_double,\n" + + "c_timestamp timestamp,\n" + + "c_timestamp_tz timestamp with time zone,\n" + + "c_timestamp_ltz timestamp with local time zone,\n" + + "c_interval_year interval year to month,\n" + + "c_interval_day interval day to second,\n" + + "c_rowid rowid,\n" + + "c_urowid urowid,\n" + + "c_char char(20),\n" + + "c_nchar nchar(20),\n" + + "c_clob clob,\n" + + "c_nclob nclob\n" + + ")\n"; + private static final String SQL_QUERY_TO_INSERT_ONE_ROW_FORMAT = "insert into {0} values (\n" + "''varchar2'',\n" + + "''nvarchar2'',\n" + + "{1},\n" + + "11.22,\n" + + "''03-OCT-02'',\n" + + "11.22,\n" + + "11.22,\n" + + "TIMESTAMP''1997-01-01 09:26:50.124'',\n" + + "TIMESTAMP''1997-01-01 09:26:56.66 +02:00'',\n" + + "TIMESTAMP''1999-04-05 8:00:00 US/Pacific'',\n" + + "INTERVAL ''1'' YEAR(3),\n" + + "INTERVAL ''1'' HOUR,\n" + + "''000001F8.0001.0006'',\n" + + "''000001F8.0001.0006'',\n" + + "''char'',\n" + + "''nchar'',\n" + + "''clob'',\n" + + "''nclob''\n" + + ")"; private static final String SQL_QUERY_TO_INSERT_ONE_ROW_WITH_BINDING_FORMAT = - "insert into {0} values (\n" + - "'{{'binding1'}}',\n" + - "'{{'binding2'}}',\n" + - "'{{'binding3'}}',\n" + - "'{{'binding4'}}',\n" + - "'{{'binding5'}}',\n" + - "'{{'binding6'}}',\n" + - "'{{'binding7'}}',\n" + - "TO_TIMESTAMP('{{'binding8'}}', ''YYYY-MM-DD HH24:MI:SS.FF''),\n" + - "TO_TIMESTAMP('{{'binding9'}}', ''YYYY-MM-DD HH24:MI:SS.FF''),\n" + - "TO_TIMESTAMP('{{'binding10'}}', ''YYYY-MM-DD HH24:MI:SS.FF''),\n" + - "NUMTOYMINTERVAL('{{'binding11'}}', ''YEAR''),\n" + - "NUMTODSINTERVAL('{{'binding12'}}', ''HOUR''),\n" + - "'{{'binding13'}}',\n" + - "'{{'binding14'}}',\n" + - "'{{'binding15'}}',\n" + - "'{{'binding16'}}',\n" + - "'{{'binding17'}}',\n" + - "'{{'binding18'}}'\n" + - ")"; - - public static final String SELECT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME = "testSelectWithPreparedStatementWithoutAnyBinding"; + "insert into {0} values (\n" + "'{{'binding1'}}',\n" + + "'{{'binding2'}}',\n" + + "'{{'binding3'}}',\n" + + "'{{'binding4'}}',\n" + + "'{{'binding5'}}',\n" + + "'{{'binding6'}}',\n" + + "'{{'binding7'}}',\n" + + "TO_TIMESTAMP('{{'binding8'}}', ''YYYY-MM-DD HH24:MI:SS.FF''),\n" + + "TO_TIMESTAMP('{{'binding9'}}', ''YYYY-MM-DD HH24:MI:SS.FF''),\n" + + "TO_TIMESTAMP('{{'binding10'}}', ''YYYY-MM-DD HH24:MI:SS.FF''),\n" + + "NUMTOYMINTERVAL('{{'binding11'}}', ''YEAR''),\n" + + "NUMTODSINTERVAL('{{'binding12'}}', ''HOUR''),\n" + + "'{{'binding13'}}',\n" + + "'{{'binding14'}}',\n" + + "'{{'binding15'}}',\n" + + "'{{'binding16'}}',\n" + + "'{{'binding17'}}',\n" + + "'{{'binding18'}}'\n" + + ")"; + + public static final String SELECT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME = + "testSelectWithPreparedStatementWithoutAnyBinding"; public static final String SELECT_TEST_WITH_PREPARED_STMT_TABLE_NAME = "testSelectWithPreparedStatementWithBinding"; - public static final String INSERT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME = "testInsertWithPreparedStatementWithoutAnyBinding"; + public static final String INSERT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME = + "testInsertWithPreparedStatementWithoutAnyBinding"; public static final String INSERT_TEST_WITH_PREPARED_STMT_TABLE_NAME = "testInsertWithPreparedStatementWithBinding"; - public static final String UPDATE_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME = "testUpdateWithPreparedStatementWithoutAnyBinding"; + public static final String UPDATE_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME = + "testUpdateWithPreparedStatementWithoutAnyBinding"; public static final String UPDATE_TEST_WITH_PREPARED_STMT_TABLE_NAME = "testUpdateWithPreparedStatementWithBinding"; - public static final String DELETE_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME = "testDeleteWithPreparedStatementWithoutAnyBinding"; + public static final String DELETE_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME = + "testDeleteWithPreparedStatementWithoutAnyBinding"; public static final String DELETE_TEST_WITH_PREPARED_STMT_TABLE_NAME = "testDeleteWithPreparedStatementWithBinding"; @SuppressWarnings("rawtypes") // The type parameter for the container type is just itself and is pseudo-optional. @@ -111,7 +110,9 @@ public class OracleExecutionTest { @BeforeAll public static void setup() throws SQLException { - sharedConnectionPool = oraclePluginExecutor.datasourceCreate(getDefaultDatasourceConfig(oracleDB)).block(); + sharedConnectionPool = oraclePluginExecutor + .datasourceCreate(getDefaultDatasourceConfig(oracleDB)) + .block(); createTablesForTest(); } @@ -139,34 +140,35 @@ private static void createTableWithName(String tableName) throws SQLException { @Test public void testSelectQueryWithPreparedStatementWithoutAnyBinding() { - String sqlSelectQuery = MessageFormat.format("SELECT c_number FROM {0} ORDER BY c_number", - SELECT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME); + String sqlSelectQuery = MessageFormat.format( + "SELECT c_number FROM {0} ORDER BY c_number", SELECT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME); Map formData = setDataValueSafelyInFormData(null, "body", sqlSelectQuery); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setFormData(formData); - Mono<ActionExecutionResult> executionResultMono = oraclePluginExecutor.executeParameterized(sharedConnectionPool, new ExecuteActionDTO(), - getDefaultDatasourceConfig(oracleDB), actionConfig); + Mono<ActionExecutionResult> executionResultMono = oraclePluginExecutor.executeParameterized( + sharedConnectionPool, new ExecuteActionDTO(), getDefaultDatasourceConfig(oracleDB), actionConfig); String expectedResultString = "[{\"C_NUMBER\":\"1\"},{\"C_NUMBER\":\"2\"}]"; verifyColumnValue(executionResultMono, expectedResultString); } @Test public void testQueryWorksWithSemicolonInTheEnd() { - String sqlSelectQuery = MessageFormat.format("SELECT c_number FROM {0} ORDER BY c_number;", - SELECT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME); + String sqlSelectQuery = MessageFormat.format( + "SELECT c_number FROM {0} ORDER BY c_number;", SELECT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME); Map formData = setDataValueSafelyInFormData(null, "body", sqlSelectQuery); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setFormData(formData); - Mono<ActionExecutionResult> executionResultMono = oraclePluginExecutor.executeParameterized(sharedConnectionPool, new ExecuteActionDTO(), - getDefaultDatasourceConfig(oracleDB), actionConfig); + Mono<ActionExecutionResult> executionResultMono = oraclePluginExecutor.executeParameterized( + sharedConnectionPool, new ExecuteActionDTO(), getDefaultDatasourceConfig(oracleDB), actionConfig); String expectedResultString = "[{\"C_NUMBER\":\"1\"},{\"C_NUMBER\":\"2\"}]"; verifyColumnValue(executionResultMono, expectedResultString); } @Test public void testSelectQueryWithPreparedStatementWithBinding() { - String sqlSelectQuery = MessageFormat.format("SELECT c_number FROM {0} WHERE " + - "c_varchar2='{{'binding1'}}' ORDER BY c_number DESC", SELECT_TEST_WITH_PREPARED_STMT_TABLE_NAME); + String sqlSelectQuery = MessageFormat.format( + "SELECT c_number FROM {0} WHERE " + "c_varchar2='{{'binding1'}}' ORDER BY c_number DESC", + SELECT_TEST_WITH_PREPARED_STMT_TABLE_NAME); Map formData = setDataValueSafelyInFormData(null, "body", sqlSelectQuery); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setFormData(formData); @@ -176,74 +178,81 @@ public void testSelectQueryWithPreparedStatementWithBinding() { ExecuteActionDTO executeActionDTO = getExecuteDTOForTestWithBindingAndValueAndDataType(bindingNameToValueAndDataTypeMap); - Mono<ActionExecutionResult> executionResultMono = - oraclePluginExecutor.executeParameterized(sharedConnectionPool, executeActionDTO, - getDefaultDatasourceConfig(oracleDB), actionConfig); + Mono<ActionExecutionResult> executionResultMono = oraclePluginExecutor.executeParameterized( + sharedConnectionPool, executeActionDTO, getDefaultDatasourceConfig(oracleDB), actionConfig); String expectedResultString = "[{\"C_NUMBER\":\"2\"},{\"C_NUMBER\":\"1\"}]"; verifyColumnValue(executionResultMono, expectedResultString); } @Test public void testInsertQueryReturnValueWithPreparedStatementWithoutAnyBinding() { - String sqlInsertQuery = MessageFormat.format(SQL_QUERY_TO_INSERT_ONE_ROW_FORMAT, - INSERT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME, 3); + String sqlInsertQuery = MessageFormat.format( + SQL_QUERY_TO_INSERT_ONE_ROW_FORMAT, INSERT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME, 3); Map insertQueryFormData = setDataValueSafelyInFormData(null, "body", sqlInsertQuery); ActionConfiguration insertQueryActionConfig = new ActionConfiguration(); insertQueryActionConfig.setFormData(insertQueryFormData); - Mono<ActionExecutionResult> insertQueryExecutionResultMono = - oraclePluginExecutor.executeParameterized(sharedConnectionPool, new ExecuteActionDTO(), - getDefaultDatasourceConfig(oracleDB), insertQueryActionConfig); + Mono<ActionExecutionResult> insertQueryExecutionResultMono = oraclePluginExecutor.executeParameterized( + sharedConnectionPool, + new ExecuteActionDTO(), + getDefaultDatasourceConfig(oracleDB), + insertQueryActionConfig); String insertQueryExpectedResultString = "[{\"affectedRows\":1}]"; verifyColumnValue(insertQueryExecutionResultMono, insertQueryExpectedResultString); } @Test public void testInsertQueryVerifyNewRowAddedWithPreparedStatementWithoutAnyBinding() { - String sqlInsertQuery = MessageFormat.format(SQL_QUERY_TO_INSERT_ONE_ROW_FORMAT, - INSERT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME, 4); + String sqlInsertQuery = MessageFormat.format( + SQL_QUERY_TO_INSERT_ONE_ROW_FORMAT, INSERT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME, 4); Map insertQueryFormData = setDataValueSafelyInFormData(null, "body", sqlInsertQuery); ActionConfiguration insertQueryActionConfig = new ActionConfiguration(); insertQueryActionConfig.setFormData(insertQueryFormData); - oraclePluginExecutor.executeParameterized(sharedConnectionPool, new ExecuteActionDTO(), - getDefaultDatasourceConfig(oracleDB), insertQueryActionConfig).block(); + oraclePluginExecutor + .executeParameterized( + sharedConnectionPool, + new ExecuteActionDTO(), + getDefaultDatasourceConfig(oracleDB), + insertQueryActionConfig) + .block(); - String sqlSelectQuery = MessageFormat.format("SELECT * FROM {0} WHERE c_number=4", - INSERT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME); + String sqlSelectQuery = MessageFormat.format( + "SELECT * FROM {0} WHERE c_number=4", INSERT_TEST_WITHOUT_PREPARED_STMT_TABLE_NAME); Map selectQueryFormData = setDataValueSafelyInFormData(null, "body", sqlSelectQuery); ActionConfiguration selectQueryActionConfig = new ActionConfiguration(); selectQueryActionConfig.setFormData(selectQueryFormData); - Mono<ActionExecutionResult> selectQueryExecutionResultMono = - oraclePluginExecutor.executeParameterized(sharedConnectionPool, new ExecuteActionDTO(), - getDefaultDatasourceConfig(oracleDB), selectQueryActionConfig); - String selectQueryExpectedResultString = "[" + - "{" + - "\"C_VARCHAR2\":\"varchar2\"," + - "\"C_NVARCHAR2\":\"nvarchar2\"," + - "\"C_NUMBER\":\"4\"," + - "\"C_FLOAT\":\"11.22\"," + - "\"C_DATE\":\"2002-10-03\"," + - "\"C_BINARY_FLOAT\":\"11.22\"," + - "\"C_BINARY_DOUBLE\":\"11.22\"," + - "\"C_TIMESTAMP\":\"1997-01-01T09:26:50.124Z\"," + - "\"C_TIMESTAMP_TZ\":\"1997-01-01T09:26:56.66+02:00\"," + - "\"C_TIMESTAMP_LTZ\":\"1999-04-05T15:00:00Z\"," + - "\"C_INTERVAL_YEAR\":\"1-0\"," + - "\"C_INTERVAL_DAY\":\"0 1:0:0.0\"," + - "\"C_ROWID\":\"AAAAAAAAGAAAAH4AAB\"," + - "\"C_UROWID\":\"000001F8.0001.0006\"," + - "\"C_CHAR\":\"char \"," + - "\"C_NCHAR\":\"nchar \"," + - "\"C_CLOB\":\"clob\"," + - "\"C_NCLOB\":\"nclob\"" + - "}" + - "]"; + Mono<ActionExecutionResult> selectQueryExecutionResultMono = oraclePluginExecutor.executeParameterized( + sharedConnectionPool, + new ExecuteActionDTO(), + getDefaultDatasourceConfig(oracleDB), + selectQueryActionConfig); + String selectQueryExpectedResultString = "[" + "{" + + "\"C_VARCHAR2\":\"varchar2\"," + + "\"C_NVARCHAR2\":\"nvarchar2\"," + + "\"C_NUMBER\":\"4\"," + + "\"C_FLOAT\":\"11.22\"," + + "\"C_DATE\":\"2002-10-03\"," + + "\"C_BINARY_FLOAT\":\"11.22\"," + + "\"C_BINARY_DOUBLE\":\"11.22\"," + + "\"C_TIMESTAMP\":\"1997-01-01T09:26:50.124Z\"," + + "\"C_TIMESTAMP_TZ\":\"1997-01-01T09:26:56.66+02:00\"," + + "\"C_TIMESTAMP_LTZ\":\"1999-04-05T15:00:00Z\"," + + "\"C_INTERVAL_YEAR\":\"1-0\"," + + "\"C_INTERVAL_DAY\":\"0 1:0:0.0\"," + + "\"C_ROWID\":\"AAAAAAAAGAAAAH4AAB\"," + + "\"C_UROWID\":\"000001F8.0001.0006\"," + + "\"C_CHAR\":\"char \"," + + "\"C_NCHAR\":\"nchar \"," + + "\"C_CLOB\":\"clob\"," + + "\"C_NCLOB\":\"nclob\"" + + "}" + + "]"; verifyColumnValue(selectQueryExecutionResultMono, selectQueryExpectedResultString); } @Test public void testInsertQueryReturnValueWithPreparedStatementWithBinding() { - String sqlInsertQuery = MessageFormat.format(SQL_QUERY_TO_INSERT_ONE_ROW_WITH_BINDING_FORMAT, - INSERT_TEST_WITH_PREPARED_STMT_TABLE_NAME); + String sqlInsertQuery = MessageFormat.format( + SQL_QUERY_TO_INSERT_ONE_ROW_WITH_BINDING_FORMAT, INSERT_TEST_WITH_PREPARED_STMT_TABLE_NAME); Map insertQueryFormData = setDataValueSafelyInFormData(null, "body", sqlInsertQuery); ActionConfiguration insertQueryActionConfig = new ActionConfiguration(); insertQueryActionConfig.setFormData(insertQueryFormData); @@ -271,17 +280,16 @@ public void testInsertQueryReturnValueWithPreparedStatementWithBinding() { ExecuteActionDTO executeActionDTO = getExecuteDTOForTestWithBindingAndValueAndDataType(bindingNameToValueAndDataTypeMap); - Mono<ActionExecutionResult> insertQueryExecutionResultMono = - oraclePluginExecutor.executeParameterized(sharedConnectionPool, executeActionDTO, - getDefaultDatasourceConfig(oracleDB), insertQueryActionConfig); + Mono<ActionExecutionResult> insertQueryExecutionResultMono = oraclePluginExecutor.executeParameterized( + sharedConnectionPool, executeActionDTO, getDefaultDatasourceConfig(oracleDB), insertQueryActionConfig); String insertQueryExpectedResultString = "[{\"affectedRows\":1}]"; verifyColumnValue(insertQueryExecutionResultMono, insertQueryExpectedResultString); } @Test public void testInsertQueryVerifyNewRowAddedWithPreparedStatementWithBinding() { - String sqlInsertQuery = MessageFormat.format(SQL_QUERY_TO_INSERT_ONE_ROW_WITH_BINDING_FORMAT, - INSERT_TEST_WITH_PREPARED_STMT_TABLE_NAME); + String sqlInsertQuery = MessageFormat.format( + SQL_QUERY_TO_INSERT_ONE_ROW_WITH_BINDING_FORMAT, INSERT_TEST_WITH_PREPARED_STMT_TABLE_NAME); Map insertQueryFormData = setDataValueSafelyInFormData(null, "body", sqlInsertQuery); ActionConfiguration insertQueryActionConfig = new ActionConfiguration(); insertQueryActionConfig.setFormData(insertQueryFormData); @@ -308,48 +316,58 @@ public void testInsertQueryVerifyNewRowAddedWithPreparedStatementWithBinding() { ExecuteActionDTO executeActionDTO = getExecuteDTOForTestWithBindingAndValueAndDataType(bindingNameToValueAndDataTypeMap); - oraclePluginExecutor.executeParameterized(sharedConnectionPool, executeActionDTO, - getDefaultDatasourceConfig(oracleDB), insertQueryActionConfig).block(); + oraclePluginExecutor + .executeParameterized( + sharedConnectionPool, + executeActionDTO, + getDefaultDatasourceConfig(oracleDB), + insertQueryActionConfig) + .block(); - String sqlSelectQuery = MessageFormat.format("SELECT c_varchar2, c_nvarchar2, c_number, c_float, c_date, " + - "c_binary_float, c_binary_double, c_timestamp, c_interval_year, " + - "c_interval_day, c_rowid, c_urowid, c_char, c_nchar, c_clob, c_nclob FROM {0} WHERE c_number=5", + String sqlSelectQuery = MessageFormat.format( + "SELECT c_varchar2, c_nvarchar2, c_number, c_float, c_date, " + + "c_binary_float, c_binary_double, c_timestamp, c_interval_year, " + + "c_interval_day, c_rowid, c_urowid, c_char, c_nchar, c_clob, c_nclob FROM {0} WHERE c_number=5", INSERT_TEST_WITH_PREPARED_STMT_TABLE_NAME); Map selectQueryFormData = setDataValueSafelyInFormData(null, "body", sqlSelectQuery); ActionConfiguration selectQueryActionConfig = new ActionConfiguration(); selectQueryActionConfig.setFormData(selectQueryFormData); - Mono<ActionExecutionResult> selectQueryExecutionResultMono = - oraclePluginExecutor.executeParameterized(sharedConnectionPool, new ExecuteActionDTO(), - getDefaultDatasourceConfig(oracleDB), selectQueryActionConfig); - String selectQueryExpectedResultString = "[" + - "{" + - "\"C_VARCHAR2\":\"varchar2\"," + - "\"C_NVARCHAR2\":\"nvarchar2\"," + - "\"C_NUMBER\":\"5\"," + - "\"C_FLOAT\":\"11.22\"," + - "\"C_DATE\":\"2002-10-03\"," + - "\"C_BINARY_FLOAT\":\"11.22\"," + - "\"C_BINARY_DOUBLE\":\"11.22\"," + - "\"C_TIMESTAMP\":\"1997-01-01T09:26:50.124Z\"," + - "\"C_INTERVAL_YEAR\":\"1-0\"," + - "\"C_INTERVAL_DAY\":\"0 1:0:0.0\"," + - "\"C_ROWID\":\"AAAAAAAAGAAAAH4AAB\"," + - "\"C_UROWID\":\"000001F8.0001.0006\"," + - "\"C_CHAR\":\"char \"," + - "\"C_NCHAR\":\"nchar \"," + - "\"C_CLOB\":\"clob\"," + - "\"C_NCLOB\":\"nclob\"" + - "}" + - "]"; + Mono<ActionExecutionResult> selectQueryExecutionResultMono = oraclePluginExecutor.executeParameterized( + sharedConnectionPool, + new ExecuteActionDTO(), + getDefaultDatasourceConfig(oracleDB), + selectQueryActionConfig); + String selectQueryExpectedResultString = "[" + "{" + + "\"C_VARCHAR2\":\"varchar2\"," + + "\"C_NVARCHAR2\":\"nvarchar2\"," + + "\"C_NUMBER\":\"5\"," + + "\"C_FLOAT\":\"11.22\"," + + "\"C_DATE\":\"2002-10-03\"," + + "\"C_BINARY_FLOAT\":\"11.22\"," + + "\"C_BINARY_DOUBLE\":\"11.22\"," + + "\"C_TIMESTAMP\":\"1997-01-01T09:26:50.124Z\"," + + "\"C_INTERVAL_YEAR\":\"1-0\"," + + "\"C_INTERVAL_DAY\":\"0 1:0:0.0\"," + + "\"C_ROWID\":\"AAAAAAAAGAAAAH4AAB\"," + + "\"C_UROWID\":\"000001F8.0001.0006\"," + + "\"C_CHAR\":\"char \"," + + "\"C_NCHAR\":\"nchar \"," + + "\"C_CLOB\":\"clob\"," + + "\"C_NCLOB\":\"nclob\"" + + "}" + + "]"; verifyColumnValue(selectQueryExecutionResultMono, selectQueryExpectedResultString); } private void verifyColumnValue(Mono<ActionExecutionResult> executionResultMono, String expectedResult) { StepVerifier.create(executionResultMono) .assertNext(actionExecutionResult -> { - assertTrue(actionExecutionResult.getIsExecutionSuccess(), actionExecutionResult.getBody().toString()); + assertTrue( + actionExecutionResult.getIsExecutionSuccess(), + actionExecutionResult.getBody().toString()); if (expectedResult != null) { - assertEquals(expectedResult, actionExecutionResult.getBody().toString()); + assertEquals( + expectedResult, actionExecutionResult.getBody().toString()); } }) .verifyComplete(); diff --git a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleGetDBSchemaTest.java b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleGetDBSchemaTest.java index 86936a309141..38e55073bd94 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleGetDBSchemaTest.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleGetDBSchemaTest.java @@ -26,21 +26,19 @@ @Testcontainers public class OracleGetDBSchemaTest { public static final String SQL_QUERY_TO_CREATE_TABLE_WITH_PRIMARY_KEY = - "CREATE TABLE supplier\n" + - "( supplier_id numeric(10) not null,\n" + - " supplier_name varchar2(50) not null,\n" + - " contact_name varchar2(50),\n" + - " CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)\n" + - ")"; + "CREATE TABLE supplier\n" + "( supplier_id numeric(10) not null,\n" + + " supplier_name varchar2(50) not null,\n" + + " contact_name varchar2(50),\n" + + " CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)\n" + + ")"; public static final String SQL_QUERY_TO_CREATE_TABLE_WITH_FOREIGN_KEY = - "CREATE TABLE products\n" + - "( product_id numeric(10) not null,\n" + - " supplier_id numeric(10) not null,\n" + - " CONSTRAINT fk_supplier\n" + - " FOREIGN KEY (supplier_id)\n" + - " REFERENCES supplier(supplier_id)\n" + - ")"; + "CREATE TABLE products\n" + "( product_id numeric(10) not null,\n" + + " supplier_id numeric(10) not null,\n" + + " CONSTRAINT fk_supplier\n" + + " FOREIGN KEY (supplier_id)\n" + + " REFERENCES supplier(supplier_id)\n" + + ")"; @SuppressWarnings("rawtypes") // The type parameter for the container type is just itself and is pseudo-optional. @Container @@ -50,7 +48,9 @@ public class OracleGetDBSchemaTest { @BeforeAll public static void setup() throws SQLException { - sharedConnectionPool = oraclePluginExecutor.datasourceCreate(getDefaultDatasourceConfig(oracleDB)).block(); + sharedConnectionPool = oraclePluginExecutor + .datasourceCreate(getDefaultDatasourceConfig(oracleDB)) + .block(); createTablesForTest(); } @@ -62,8 +62,7 @@ private static void createTablesForTest() throws SQLException { @Test public void testDBSchemaShowsAllTables() { Mono<DatasourceStructure> datasourceStructureMono = - oraclePluginExecutor.getStructure(sharedConnectionPool, - getDefaultDatasourceConfig(oracleDB)); + oraclePluginExecutor.getStructure(sharedConnectionPool, getDefaultDatasourceConfig(oracleDB)); StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { @@ -72,7 +71,8 @@ public void testDBSchemaShowsAllTables() { .map(String::toLowerCase) .collect(Collectors.toSet()); - assertTrue(setOfAllTableNames.equals(Set.of("supplier","products")), setOfAllTableNames.toString()); + assertTrue( + setOfAllTableNames.equals(Set.of("supplier", "products")), setOfAllTableNames.toString()); }) .verifyComplete(); } @@ -80,8 +80,7 @@ public void testDBSchemaShowsAllTables() { @Test public void testDBSchemaShowsAllColumnsAndTypesInATable() { Mono<DatasourceStructure> datasourceStructureMono = - oraclePluginExecutor.getStructure(sharedConnectionPool, - getDefaultDatasourceConfig(oracleDB)); + oraclePluginExecutor.getStructure(sharedConnectionPool, getDefaultDatasourceConfig(oracleDB)); StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { @@ -99,21 +98,19 @@ public void testDBSchemaShowsAllColumnsAndTypesInATable() { Set<String> expectedColumnNames = Set.of("supplier_id", "supplier_name", "contact_name"); assertEquals(expectedColumnNames, allColumnNames, allColumnNames.toString()); - supplierTable.getColumns().stream() - .forEach(column -> { - String columnName = column.getName().toLowerCase(); - String columnType = column.getType().toLowerCase(); - String expectedColumnType = null; + supplierTable.getColumns().stream().forEach(column -> { + String columnName = column.getName().toLowerCase(); + String columnType = column.getType().toLowerCase(); + String expectedColumnType = null; - if ("supplier_id".equals(columnName)) { - expectedColumnType = "number"; - } - else { - expectedColumnType = "varchar2"; - } + if ("supplier_id".equals(columnName)) { + expectedColumnType = "number"; + } else { + expectedColumnType = "varchar2"; + } - assertEquals(expectedColumnType, columnType, columnType); - }); + assertEquals(expectedColumnType, columnType, columnType); + }); }) .verifyComplete(); } @@ -121,8 +118,7 @@ public void testDBSchemaShowsAllColumnsAndTypesInATable() { @Test public void testDynamicSqlTemplateQueriesForATable() { Mono<DatasourceStructure> datasourceStructureMono = - oraclePluginExecutor.getStructure(sharedConnectionPool, - getDefaultDatasourceConfig(oracleDB)); + oraclePluginExecutor.getStructure(sharedConnectionPool, getDefaultDatasourceConfig(oracleDB)); StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { @@ -134,27 +130,28 @@ public void testDynamicSqlTemplateQueriesForATable() { assertTrue(supplierTable != null, "supplier table not found in DB schema"); supplierTable.getTemplates().stream() - .filter(template -> "select".equalsIgnoreCase(template.getTitle()) || "delete".equalsIgnoreCase(template.getTitle())) + .filter(template -> "select".equalsIgnoreCase(template.getTitle()) + || "delete".equalsIgnoreCase(template.getTitle())) .forEach(template -> { /** * Not sure how to test query templates for insert and update queries as these * queries include column names in an order that is not fixed. Hence, skipping testing * them for now. */ - String expectedSelectQueryTemplate = null; if ("select".equalsIgnoreCase(template.getTitle())) { expectedSelectQueryTemplate = "select * from supplier where rownum < 10"; - } - else if ("delete".equalsIgnoreCase(template.getTitle())) { - expectedSelectQueryTemplate = "delete from supplier where 1=0 -- specify a valid" + - " condition here. removing the condition may delete everything in the " + - "table!"; + } else if ("delete".equalsIgnoreCase(template.getTitle())) { + expectedSelectQueryTemplate = "delete from supplier where 1=0 -- specify a valid" + + " condition here. removing the condition may delete everything in the " + + "table!"; } - String templateQuery = - getDataValueSafelyFromFormData((Map<String, Object>) template.getConfiguration(), "body", STRING_TYPE); - assertEquals(expectedSelectQueryTemplate, templateQuery.toLowerCase(), + String templateQuery = getDataValueSafelyFromFormData( + (Map<String, Object>) template.getConfiguration(), "body", STRING_TYPE); + assertEquals( + expectedSelectQueryTemplate, + templateQuery.toLowerCase(), templateQuery.toLowerCase()); }); }) diff --git a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginConnectionTest.java b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginConnectionTest.java index 30c8a5d87a7b..f8de9c7dbaf9 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginConnectionTest.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginConnectionTest.java @@ -1,10 +1,8 @@ package com.external.plugins; - import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceTestResult; -import com.external.plugins.exceptions.OraclePluginError; import org.junit.jupiter.api.Test; import org.testcontainers.containers.OracleContainer; import org.testcontainers.junit.jupiter.Container; @@ -12,9 +10,6 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import java.util.Arrays; -import java.util.stream.Collectors; - import static com.external.plugins.OracleTestDBContainerManager.getDefaultDatasourceConfig; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -43,15 +38,14 @@ public void testDatasourceConnectionTestPassWithValidConfig() { @Test public void testDatasourceConnectionTestFailWithInvalidPassword() { DatasourceConfiguration invalidDsConfig = getDefaultDatasourceConfig(oracleDB); - ((DBAuth)invalidDsConfig.getAuthentication()).setPassword("invalid_password"); + ((DBAuth) invalidDsConfig.getAuthentication()).setPassword("invalid_password"); - Mono<DatasourceTestResult> testDsResultMono = - oraclePluginExecutor.testDatasource(invalidDsConfig); + Mono<DatasourceTestResult> testDsResultMono = oraclePluginExecutor.testDatasource(invalidDsConfig); StepVerifier.create(testDsResultMono) .assertNext(testResult -> { assertNotEquals(0, testResult.getInvalids().size()); - String expectedError = "Failed to initialize pool: ORA-01017: invalid username/password; logon " + - "denied"; + String expectedError = + "Failed to initialize pool: ORA-01017: invalid username/password; logon " + "denied"; boolean isExpectedErrorReceived = testResult.getInvalids().stream() .anyMatch(errorString -> expectedError.equals(errorString.trim())); assertTrue(isExpectedErrorReceived); @@ -62,20 +56,18 @@ public void testDatasourceConnectionTestFailWithInvalidPassword() { @Test public void testDatasourceConnectionTestFailWithInvalidUsername() { DatasourceConfiguration invalidDsConfig = getDefaultDatasourceConfig(oracleDB); - ((DBAuth)invalidDsConfig.getAuthentication()).setUsername("invalid_username"); + ((DBAuth) invalidDsConfig.getAuthentication()).setUsername("invalid_username"); - Mono<DatasourceTestResult> testDsResultMono = - oraclePluginExecutor.testDatasource(invalidDsConfig); + Mono<DatasourceTestResult> testDsResultMono = oraclePluginExecutor.testDatasource(invalidDsConfig); StepVerifier.create(testDsResultMono) .assertNext(testResult -> { assertNotEquals(0, testResult.getInvalids().size()); - String expectedError = "Failed to initialize pool: ORA-01017: invalid username/password; logon " + - "denied"; + String expectedError = + "Failed to initialize pool: ORA-01017: invalid username/password; logon " + "denied"; boolean isExpectedErrorReceived = testResult.getInvalids().stream() .anyMatch(errorString -> expectedError.equals(errorString.trim())); assertTrue(isExpectedErrorReceived); }) .verifyComplete(); } - } diff --git a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginDatasourceValidityErrorsTest.java b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginDatasourceValidityErrorsTest.java index d9201f35edff..26791a2681be 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginDatasourceValidityErrorsTest.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginDatasourceValidityErrorsTest.java @@ -21,18 +21,18 @@ public class OraclePluginDatasourceValidityErrorsTest { @Test public void testErrorOnMissingUsername() { DatasourceConfiguration dsConfigWithMissingUsername = getDefaultDatasourceConfig(null); - ((DBAuth)dsConfigWithMissingUsername.getAuthentication()).setUsername(""); + ((DBAuth) dsConfigWithMissingUsername.getAuthentication()).setUsername(""); Set<String> dsValidateResult = oraclePluginExecutor.validateDatasource(dsConfigWithMissingUsername); boolean isExpectedErrorReceived = dsValidateResult.stream() - .anyMatch(errorString -> DS_MISSING_USERNAME_ERROR_MSG.equals(errorString.trim())); + .anyMatch(errorString -> DS_MISSING_USERNAME_ERROR_MSG.equals(errorString.trim())); assertTrue(isExpectedErrorReceived); } @Test public void testErrorOnMissingPassword() { DatasourceConfiguration dsConfigWithMissingPassword = getDefaultDatasourceConfig(null); - ((DBAuth)dsConfigWithMissingPassword.getAuthentication()).setPassword(""); + ((DBAuth) dsConfigWithMissingPassword.getAuthentication()).setPassword(""); Set<String> dsValidateResult = oraclePluginExecutor.validateDatasource(dsConfigWithMissingPassword); boolean isExpectedErrorReceived = dsValidateResult.stream() diff --git a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginErrorsTest.java b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginErrorsTest.java index ce479766f262..bf75c686706f 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginErrorsTest.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginErrorsTest.java @@ -21,11 +21,18 @@ public class OraclePluginErrorsTest { @Test public void verifyUniquenessOfOraclePluginErrorCode() { - assert (Arrays.stream(OraclePluginError.values()).map(OraclePluginError::getAppErrorCode).distinct().count() == OraclePluginError.values().length); + assert (Arrays.stream(OraclePluginError.values()) + .map(OraclePluginError::getAppErrorCode) + .distinct() + .count() + == OraclePluginError.values().length); - assert (Arrays.stream(OraclePluginError.values()).map(OraclePluginError::getAppErrorCode) - .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-ORC")) - .collect(Collectors.toList()).size() == 0); + assert (Arrays.stream(OraclePluginError.values()) + .map(OraclePluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-ORC")) + .collect(Collectors.toList()) + .size() + == 0); } /** @@ -35,9 +42,9 @@ public void verifyUniquenessOfOraclePluginErrorCode() { */ @Test public void testStaleConnectionErrorHasUpstreamErrorWhenConnectionPoolIsNull() { - Exception exception = assertThrows(StaleConnectionException.class, - () -> oracleDatasourceUtils.checkHikariCPConnectionPoolValidity(null - , "pluginName")); + Exception exception = assertThrows( + StaleConnectionException.class, + () -> oracleDatasourceUtils.checkHikariCPConnectionPoolValidity(null, "pluginName")); String expectedErrorMessage = CONNECTION_POOL_NULL_ERROR_MSG; assertEquals(expectedErrorMessage, exception.getMessage()); } @@ -51,7 +58,8 @@ public void testStaleConnectionErrorHasUpstreamErrorWhenConnectionPoolIsNull() { public void testStaleConnectionErrorHasUpstreamErrorWhenConnectionPoolIsClosed() { HikariDataSource mockConnectionPool = mock(HikariDataSource.class); when(mockConnectionPool.isClosed()).thenReturn(true).thenReturn(true); - Exception exception = assertThrows(StaleConnectionException.class, + Exception exception = assertThrows( + StaleConnectionException.class, () -> oracleDatasourceUtils.checkHikariCPConnectionPoolValidity(mockConnectionPool, "pluginName")); String expectedErrorMessage = CONNECTION_POOL_CLOSED_ERROR_MSG; assertEquals(expectedErrorMessage, exception.getMessage()); @@ -66,7 +74,8 @@ public void testStaleConnectionErrorHasUpstreamErrorWhenConnectionPoolIsClosed() public void testStaleConnectionErrorHasUpstreamErrorWhenConnectionPoolIsRunning() { HikariDataSource mockConnectionPool = mock(HikariDataSource.class); when(mockConnectionPool.isRunning()).thenReturn(false).thenReturn(false); - Exception exception = assertThrows(StaleConnectionException.class, + Exception exception = assertThrows( + StaleConnectionException.class, () -> oracleDatasourceUtils.checkHikariCPConnectionPoolValidity(mockConnectionPool, "pluginName")); String expectedErrorMessage = CONNECTION_POOL_NOT_RUNNING_ERROR_MSG; assertEquals(expectedErrorMessage, exception.getMessage()); @@ -81,7 +90,8 @@ public void testStaleConnectionErrorHasUpstreamErrorWhenConnectionPoolIsRunning( public void testStaleConnectionErrorHasDefaultUpstreamError() { HikariDataSource mockConnectionPool = mock(HikariDataSource.class); when(mockConnectionPool.isRunning()).thenReturn(false).thenReturn(true); - Exception exception = assertThrows(StaleConnectionException.class, + Exception exception = assertThrows( + StaleConnectionException.class, () -> oracleDatasourceUtils.checkHikariCPConnectionPoolValidity(mockConnectionPool, "pluginName")); String expectedErrorMessage = UNKNOWN_CONNECTION_ERROR_MSG; assertEquals(expectedErrorMessage, exception.getMessage()); diff --git a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleTestDBContainerManager.java b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleTestDBContainerManager.java index 7b128702a78e..d0d805e5aded 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleTestDBContainerManager.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OracleTestDBContainerManager.java @@ -35,13 +35,13 @@ public static OracleContainer getOracleDBForTest() { public static DatasourceConfiguration getDefaultDatasourceConfig(OracleContainer oracleDB) { DatasourceConfiguration dsConfig = new DatasourceConfiguration(); dsConfig.setAuthentication(new DBAuth()); - ((DBAuth)dsConfig.getAuthentication()).setUsername(OracleTestDBContainerManager.ORACLE_USERNAME); - ((DBAuth)dsConfig.getAuthentication()).setPassword(OracleTestDBContainerManager.ORACLE_PASSWORD); - ((DBAuth)dsConfig.getAuthentication()).setDatabaseName(OracleTestDBContainerManager.ORACLE_DB_NAME); + ((DBAuth) dsConfig.getAuthentication()).setUsername(OracleTestDBContainerManager.ORACLE_USERNAME); + ((DBAuth) dsConfig.getAuthentication()).setPassword(OracleTestDBContainerManager.ORACLE_PASSWORD); + ((DBAuth) dsConfig.getAuthentication()).setDatabaseName(OracleTestDBContainerManager.ORACLE_DB_NAME); dsConfig.setEndpoints(new ArrayList<>()); String host = oracleDB == null ? "host" : oracleDB.getHost(); - long port = oracleDB == null ? 1521L : (long)oracleDB.getOraclePort(); + long port = oracleDB == null ? 1521L : (long) oracleDB.getOraclePort(); dsConfig.getEndpoints().add(new Endpoint(host, port)); dsConfig.setConnection(new Connection()); @@ -53,8 +53,7 @@ public static DatasourceConfiguration getDefaultDatasourceConfig(OracleContainer static void runSQLQueryOnOracleTestDB(String sqlQuery, HikariDataSource sharedConnectionPool) throws SQLException { java.sql.Connection connectionFromPool = - oracleDatasourceUtils.getConnectionFromHikariConnectionPool(sharedConnectionPool, - ORACLE_PLUGIN_NAME); + oracleDatasourceUtils.getConnectionFromHikariConnectionPool(sharedConnectionPool, ORACLE_PLUGIN_NAME); Statement statement = connectionFromPool.createStatement(); statement.execute(sqlQuery); closeConnectionPostExecution(null, statement, null, connectionFromPool); diff --git a/app/server/appsmith-plugins/pom.xml b/app/server/appsmith-plugins/pom.xml index c76bbf496f8e..66b63c7616d1 100644 --- a/app/server/appsmith-plugins/pom.xml +++ b/app/server/appsmith-plugins/pom.xml @@ -1,17 +1,37 @@ <?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>integrated</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> + <modules> + <module>oraclePlugin</module> + <module>postgresPlugin</module> + <module>restApiPlugin</module> + <module>mongoPlugin</module> + <module>mysqlPlugin</module> + <module>elasticSearchPlugin</module> + <module>dynamoPlugin</module> + <module>redisPlugin</module> + <module>mssqlPlugin</module> + <module>firestorePlugin</module> + <module>redshiftPlugin</module> + <module>amazons3Plugin</module> + <module>googleSheetsPlugin</module> + <module>graphqlPlugin</module> + <module>snowflakePlugin</module> + <module>arangoDBPlugin</module> + <module>jsPlugin</module> + <module>saasPlugin</module> + <module>smtpPlugin</module> + </modules> <properties> <jjwt.version>0.11.5</jjwt.version> @@ -22,13 +42,13 @@ <groupId>org.pf4j</groupId> <artifactId>pf4j-spring</artifactId> <version>0.8.0</version> + <scope>provided</scope> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-reload4j</artifactId> </exclusion> </exclusions> - <scope>provided</scope> </dependency> <dependency> <groupId>com.appsmith</groupId> @@ -108,32 +128,11 @@ <scope>test</scope> <exclusions> <exclusion> - <artifactId>junit</artifactId> <groupId>junit</groupId> + <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> </dependencies> - <modules> - <module>oraclePlugin</module> - <module>postgresPlugin</module> - <module>restApiPlugin</module> - <module>mongoPlugin</module> - <module>mysqlPlugin</module> - <module>elasticSearchPlugin</module> - <module>dynamoPlugin</module> - <module>redisPlugin</module> - <module>mssqlPlugin</module> - <module>firestorePlugin</module> - <module>redshiftPlugin</module> - <module>amazons3Plugin</module> - <module>googleSheetsPlugin</module> - <module>graphqlPlugin</module> - <module>snowflakePlugin</module> - <module>arangoDBPlugin</module> - <module>jsPlugin</module> - <module>saasPlugin</module> - <module>smtpPlugin</module> - </modules> </project> diff --git a/app/server/appsmith-plugins/postgresPlugin/pom.xml b/app/server/appsmith-plugins/postgresPlugin/pom.xml index b8c7187505d7..792df89666b0 100644 --- a/app/server/appsmith-plugins/postgresPlugin/pom.xml +++ b/app/server/appsmith-plugins/postgresPlugin/pom.xml @@ -1,15 +1,14 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>postgresPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -61,10 +60,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java index 594902cd8fac..1a333b2897fd 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java @@ -136,48 +136,46 @@ public PostgresPlugin(PluginWrapper wrapper) { public static class PostgresPluginExecutor implements SmartSubstitutionInterface, PluginExecutor<HikariDataSource> { private final Scheduler scheduler = Schedulers.boundedElastic(); - private static final String TABLES_QUERY = "select a.attname as name,\n" - + - " t1.typname as column_type,\n" + - " case when a.atthasdef then pg_get_expr(d.adbin, d.adrelid) end as default_expr,\n" + - " c.relkind as kind,\n" + - " c.relname as table_name,\n" + - " n.nspname as schema_name\n" + - "from pg_catalog.pg_attribute a\n" + - " left join pg_catalog.pg_type t1 on t1.oid = a.atttypid\n" + - " inner join pg_catalog.pg_class c on a.attrelid = c.oid\n" + - " left join pg_catalog.pg_namespace n on c.relnamespace = n.oid\n" + - " left join pg_catalog.pg_attrdef d on d.adrelid = c.oid and d.adnum = a.attnum\n" + - "where a.attnum > 0\n" + - " and not a.attisdropped\n" + - " and n.nspname not in ('information_schema', 'pg_catalog')\n" + - " and c.relkind in ('r', 'v')\n" + - "order by c.relname, a.attnum;"; - - public static final String KEYS_QUERY = "select c.conname as constraint_name,\n" - + - " c.contype as constraint_type,\n" + - " sch.nspname as self_schema,\n" + - " tbl.relname as self_table,\n" + - " array_agg(col.attname order by u.attposition) as self_columns,\n" + - " f_sch.nspname as foreign_schema,\n" + - " f_tbl.relname as foreign_table,\n" + - " array_agg(f_col.attname order by f_u.attposition) as foreign_columns,\n" + - " pg_get_constraintdef(c.oid) as definition\n" + - "from pg_constraint c\n" + - " left join lateral unnest(c.conkey) with ordinality as u(attnum, attposition) on true\n" + - " left join lateral unnest(c.confkey) with ordinality as f_u(attnum, attposition)\n" + - " on f_u.attposition = u.attposition\n" + - " join pg_class tbl on tbl.oid = c.conrelid\n" + - " join pg_namespace sch on sch.oid = tbl.relnamespace\n" + - " left join pg_attribute col on (col.attrelid = tbl.oid and col.attnum = u.attnum)\n" + - " left join pg_class f_tbl on f_tbl.oid = c.confrelid\n" + - " left join pg_namespace f_sch on f_sch.oid = f_tbl.relnamespace\n" + - " left join pg_attribute f_col on (f_col.attrelid = f_tbl.oid and f_col.attnum = f_u.attnum)\n" - + - "group by constraint_name, constraint_type, self_schema, self_table, definition, foreign_schema, foreign_table\n" - + - "order by self_schema, self_table;"; + private static final String TABLES_QUERY = + "select a.attname as name,\n" + + " t1.typname as column_type,\n" + + " case when a.atthasdef then pg_get_expr(d.adbin, d.adrelid) end as default_expr,\n" + + " c.relkind as kind,\n" + + " c.relname as table_name,\n" + + " n.nspname as schema_name\n" + + "from pg_catalog.pg_attribute a\n" + + " left join pg_catalog.pg_type t1 on t1.oid = a.atttypid\n" + + " inner join pg_catalog.pg_class c on a.attrelid = c.oid\n" + + " left join pg_catalog.pg_namespace n on c.relnamespace = n.oid\n" + + " left join pg_catalog.pg_attrdef d on d.adrelid = c.oid and d.adnum = a.attnum\n" + + "where a.attnum > 0\n" + + " and not a.attisdropped\n" + + " and n.nspname not in ('information_schema', 'pg_catalog')\n" + + " and c.relkind in ('r', 'v')\n" + + "order by c.relname, a.attnum;"; + + public static final String KEYS_QUERY = + "select c.conname as constraint_name,\n" + + " c.contype as constraint_type,\n" + + " sch.nspname as self_schema,\n" + + " tbl.relname as self_table,\n" + + " array_agg(col.attname order by u.attposition) as self_columns,\n" + + " f_sch.nspname as foreign_schema,\n" + + " f_tbl.relname as foreign_table,\n" + + " array_agg(f_col.attname order by f_u.attposition) as foreign_columns,\n" + + " pg_get_constraintdef(c.oid) as definition\n" + + "from pg_constraint c\n" + + " left join lateral unnest(c.conkey) with ordinality as u(attnum, attposition) on true\n" + + " left join lateral unnest(c.confkey) with ordinality as f_u(attnum, attposition)\n" + + " on f_u.attposition = u.attposition\n" + + " join pg_class tbl on tbl.oid = c.conrelid\n" + + " join pg_namespace sch on sch.oid = tbl.relnamespace\n" + + " left join pg_attribute col on (col.attrelid = tbl.oid and col.attnum = u.attnum)\n" + + " left join pg_class f_tbl on f_tbl.oid = c.confrelid\n" + + " left join pg_namespace f_sch on f_sch.oid = f_tbl.relnamespace\n" + + " left join pg_attribute f_col on (f_col.attrelid = f_tbl.oid and f_col.attnum = f_u.attnum)\n" + + "group by constraint_name, constraint_type, self_schema, self_table, definition, foreign_schema, foreign_table\n" + + "order by self_schema, self_table;"; private static final int PREPARED_STATEMENT_INDEX = 0; @@ -212,7 +210,8 @@ public PostgresPluginExecutor(SharedConfig sharedConfig) { * @return */ @Override - public Mono<ActionExecutionResult> executeParameterized(HikariDataSource connection, + public Mono<ActionExecutionResult> executeParameterized( + HikariDataSource connection, ExecuteActionDTO executeActionDTO, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { @@ -221,7 +220,8 @@ public Mono<ActionExecutionResult> executeParameterized(HikariDataSource connect // Check for query parameter before performing the probably expensive fetch // connection from the pool op. if (!StringUtils.hasLength(query)) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, PostgresErrorMessages.MISSING_QUERY_ERROR_MSG)); } @@ -258,11 +258,18 @@ public Mono<ActionExecutionResult> executeParameterized(HikariDataSource connect String updatedQuery = MustacheHelper.replaceMustacheWithQuestionMark(query, mustacheKeysInOrder); List<DataType> explicitCastDataTypes = extractExplicitCasting(updatedQuery); actionConfiguration.setBody(updatedQuery); - return executeCommon(connection, datasourceConfiguration, actionConfiguration, TRUE, - mustacheKeysInOrder, executeActionDTO, explicitCastDataTypes); + return executeCommon( + connection, + datasourceConfiguration, + actionConfiguration, + TRUE, + mustacheKeysInOrder, + executeActionDTO, + explicitCastDataTypes); } - private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, + private Mono<ActionExecutionResult> executeCommon( + HikariDataSource connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration, Boolean preparedStatement, @@ -276,237 +283,255 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, String query = actionConfiguration.getBody(); Map<String, Object> psParams = preparedStatement ? new LinkedHashMap<>() : null; String transformedQuery = preparedStatement ? replaceQuestionMarkWithDollarIndex(query) : query; - List<RequestParamDTO> requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - transformedQuery, null, null, psParams)); + List<RequestParamDTO> requestParams = + List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, transformedQuery, null, null, psParams)); return Mono.fromCallable(() -> { + Connection connectionFromPool; - Connection connectionFromPool; - - try { - connectionFromPool = postgresDatasourceUtils.getConnectionFromHikariConnectionPool(connection, - POSTGRES_PLUGIN_NAME); - } catch (SQLException | StaleConnectionException e) { - // The function can throw either StaleConnectionException or SQLException. The - // underlying hikari - // library throws SQLException in case the pool is closed or there is an issue - // initializing - // the connection pool which can also be translated in our world to - // StaleConnectionException - // and should then trigger the destruction and recreation of the pool. - return Mono.error(e instanceof StaleConnectionException ? e : new StaleConnectionException(e.getMessage())); - } + try { + connectionFromPool = postgresDatasourceUtils.getConnectionFromHikariConnectionPool( + connection, POSTGRES_PLUGIN_NAME); + } catch (SQLException | StaleConnectionException e) { + // The function can throw either StaleConnectionException or SQLException. The + // underlying hikari + // library throws SQLException in case the pool is closed or there is an issue + // initializing + // the connection pool which can also be translated in our world to + // StaleConnectionException + // and should then trigger the destruction and recreation of the pool. + return Mono.error( + e instanceof StaleConnectionException + ? e + : new StaleConnectionException(e.getMessage())); + } - List<Map<String, Object>> rowsList = new ArrayList<>(50); - final List<String> columnsList = new ArrayList<>(); - - Statement statement = null; - ResultSet resultSet = null; - PreparedStatement preparedQuery = null; - boolean isResultSet; - - HikariPoolMXBean poolProxy = connection.getHikariPoolMXBean(); - - int idleConnections = poolProxy.getIdleConnections(); - int activeConnections = poolProxy.getActiveConnections(); - int totalConnections = poolProxy.getTotalConnections(); - int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug( - "Before executing postgres query [{}] Hikari Pool stats : active - {} , idle - {} , awaiting - {} , total - {}", - query, activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); - try { - if (FALSE.equals(preparedStatement)) { - statement = connectionFromPool.createStatement(); - isResultSet = statement.execute(query); - resultSet = statement.getResultSet(); - } else { - preparedQuery = connectionFromPool.prepareStatement(query); - - List<Map.Entry<String, String>> parameters = new ArrayList<>(); - preparedQuery = (PreparedStatement) smartSubstitutionOfBindings(preparedQuery, - mustacheValuesInOrder, - executeActionDTO.getParams(), - parameters, - connectionFromPool, - explicitCastDataTypes); - - IntStream.range(0, parameters.size()) - .forEachOrdered(i -> psParams.put( - getPSParamLabel(i + 1), - new PsParameterDTO(parameters.get(i).getKey(), parameters.get(i).getValue()))); - - requestData.put("ps-parameters", parameters); - isResultSet = preparedQuery.execute(); - resultSet = preparedQuery.getResultSet(); - } + List<Map<String, Object>> rowsList = new ArrayList<>(50); + final List<String> columnsList = new ArrayList<>(); + + Statement statement = null; + ResultSet resultSet = null; + PreparedStatement preparedQuery = null; + boolean isResultSet; + + HikariPoolMXBean poolProxy = connection.getHikariPoolMXBean(); + + int idleConnections = poolProxy.getIdleConnections(); + int activeConnections = poolProxy.getActiveConnections(); + int totalConnections = poolProxy.getTotalConnections(); + int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); + log.debug( + "Before executing postgres query [{}] Hikari Pool stats : active - {} , idle - {} , awaiting - {} , total - {}", + query, + activeConnections, + idleConnections, + threadsAwaitingConnection, + totalConnections); + try { + if (FALSE.equals(preparedStatement)) { + statement = connectionFromPool.createStatement(); + isResultSet = statement.execute(query); + resultSet = statement.getResultSet(); + } else { + preparedQuery = connectionFromPool.prepareStatement(query); + + List<Map.Entry<String, String>> parameters = new ArrayList<>(); + preparedQuery = (PreparedStatement) smartSubstitutionOfBindings( + preparedQuery, + mustacheValuesInOrder, + executeActionDTO.getParams(), + parameters, + connectionFromPool, + explicitCastDataTypes); + + IntStream.range(0, parameters.size()) + .forEachOrdered(i -> psParams.put( + getPSParamLabel(i + 1), + new PsParameterDTO( + parameters.get(i).getKey(), + parameters.get(i).getValue()))); + + requestData.put("ps-parameters", parameters); + isResultSet = preparedQuery.execute(); + resultSet = preparedQuery.getResultSet(); + } - if (!isResultSet) { + if (!isResultSet) { - Object updateCount = FALSE.equals(preparedStatement) - ? ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) - : ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); + Object updateCount = FALSE.equals(preparedStatement) + ? ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) + : ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); - rowsList.add(Map.of("affectedRows", updateCount)); + rowsList.add(Map.of("affectedRows", updateCount)); - } else { + } else { - ResultSetMetaData metaData = resultSet.getMetaData(); - int colCount = metaData.getColumnCount(); - columnsList.addAll(getColumnsListForJdbcPlugin(metaData)); + ResultSetMetaData metaData = resultSet.getMetaData(); + int colCount = metaData.getColumnCount(); + columnsList.addAll(getColumnsListForJdbcPlugin(metaData)); + + int iterator = 0; + while (resultSet.next()) { + + // Only check the data size at low frequency to ensure the performance is not + // impacted heavily + if (iterator % HEAVY_OP_FREQUENCY == 0) { + int objectSize = sizeof(rowsList); + + if (objectSize > MAX_SIZE_SUPPORTED) { + log.debug( + "[PostgresPlugin] Result size greater than maximum supported size of {} bytes. Current size : {}", + MAX_SIZE_SUPPORTED, + objectSize); + return Mono.error(new AppsmithPluginException( + PostgresPluginError.RESPONSE_SIZE_TOO_LARGE, + (float) (MAX_SIZE_SUPPORTED / (1024 * 1024)))); + } + } - int iterator = 0; - while (resultSet.next()) { + // Use `LinkedHashMap` here so that the column ordering is preserved in the + // response. + Map<String, Object> row = new LinkedHashMap<>(colCount); + + for (int i = 1; i <= colCount; i++) { + Object value; + final String typeName = metaData.getColumnTypeName(i); + + if (resultSet.getObject(i) == null) { + value = null; + + } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE.format( + resultSet.getDate(i).toLocalDate()); + + } else if (TIMESTAMP_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.of( + resultSet.getDate(i).toLocalDate(), + resultSet.getTime(i).toLocalTime())) + + "Z"; + + } else if (TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE_TIME.format( + resultSet.getObject(i, OffsetDateTime.class)); + + } else if (TIME_TYPE_NAME.equalsIgnoreCase(typeName) + || TIMETZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = resultSet.getString(i); + + } else if (INTERVAL_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = resultSet.getObject(i).toString(); + + } else if (typeName.startsWith("_")) { + value = resultSet.getArray(i).getArray(); + + } else if (JSON_TYPE_NAME.equalsIgnoreCase(typeName) + || JSONB_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = objectMapper.readTree(resultSet.getString(i)); + } else { + value = resultSet.getObject(i); + + /** + * Any type that JDBC does not understand gets mapped to PGobject. PGobject has + * two attributes: type and value. Hence, when PGobject gets serialized, it gets + * converted into a JSON like {"type":"citext", "value":"someText"}. Since we + * are + * only interested in the value and not the type, it makes sense to extract out + * the value as a string. + * Reference: + * https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/util/PGobject.html + */ + if (value instanceof PGobject) { + value = ((PGobject) value).getValue(); + } + } + + row.put(metaData.getColumnName(i), value); + } - // Only check the data size at low frequency to ensure the performance is not - // impacted heavily - if (iterator % HEAVY_OP_FREQUENCY == 0) { - int objectSize = sizeof(rowsList); + rowsList.add(row); - if (objectSize > MAX_SIZE_SUPPORTED) { - log.debug( - "[PostgresPlugin] Result size greater than maximum supported size of {} bytes. Current size : {}", - MAX_SIZE_SUPPORTED, objectSize); - return Mono.error( - new AppsmithPluginException(PostgresPluginError.RESPONSE_SIZE_TOO_LARGE, - (float) (MAX_SIZE_SUPPORTED / (1024 * 1024)))); + iterator++; } } - // Use `LinkedHashMap` here so that the column ordering is preserved in the - // response. - Map<String, Object> row = new LinkedHashMap<>(colCount); - - for (int i = 1; i <= colCount; i++) { - Object value; - final String typeName = metaData.getColumnTypeName(i); - - if (resultSet.getObject(i) == null) { - value = null; - - } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE.format(resultSet.getDate(i).toLocalDate()); - - } else if (TIMESTAMP_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - LocalDateTime.of( - resultSet.getDate(i).toLocalDate(), - resultSet.getTime(i).toLocalTime())) - + "Z"; - - } else if (TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - resultSet.getObject(i, OffsetDateTime.class)); - - } else if (TIME_TYPE_NAME.equalsIgnoreCase(typeName) - || TIMETZ_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = resultSet.getString(i); - - } else if (INTERVAL_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = resultSet.getObject(i).toString(); - - } else if (typeName.startsWith("_")) { - value = resultSet.getArray(i).getArray(); - - } else if (JSON_TYPE_NAME.equalsIgnoreCase(typeName) - || JSONB_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = objectMapper.readTree(resultSet.getString(i)); - } else { - value = resultSet.getObject(i); - - /** - * Any type that JDBC does not understand gets mapped to PGobject. PGobject has - * two attributes: type and value. Hence, when PGobject gets serialized, it gets - * converted into a JSON like {"type":"citext", "value":"someText"}. Since we - * are - * only interested in the value and not the type, it makes sense to extract out - * the value as a string. - * Reference: - * https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/util/PGobject.html - */ - if (value instanceof PGobject) { - value = ((PGobject) value).getValue(); - } + } catch (SQLException e) { + log.debug("In the PostgresPlugin, got action execution error"); + return Mono.error(new AppsmithPluginException( + PostgresPluginError.QUERY_EXECUTION_FAILED, + PostgresErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage(), + "SQLSTATE: " + e.getSQLState())); + } catch (IOException e) { + // Since postgres json type field can only hold valid json data, this exception + // is not expected + // to occur. + log.debug("In the PostgresPlugin, got action execution error"); + return Mono.error(new AppsmithPluginException( + PostgresPluginError.QUERY_EXECUTION_FAILED, + PostgresErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage())); + } finally { + idleConnections = poolProxy.getIdleConnections(); + activeConnections = poolProxy.getActiveConnections(); + totalConnections = poolProxy.getTotalConnections(); + threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); + log.debug( + "After executing postgres query, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", + activeConnections, + idleConnections, + threadsAwaitingConnection, + totalConnections); + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException e) { + log.debug("Execute Error closing Postgres ResultSet", e); } - - row.put(metaData.getColumnName(i), value); } - rowsList.add(row); - - iterator++; - } - } - - } catch (SQLException e) { - log.debug("In the PostgresPlugin, got action execution error"); - return Mono.error(new AppsmithPluginException(PostgresPluginError.QUERY_EXECUTION_FAILED, - PostgresErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage(), - "SQLSTATE: " + e.getSQLState())); - } catch (IOException e) { - // Since postgres json type field can only hold valid json data, this exception - // is not expected - // to occur. - log.debug("In the PostgresPlugin, got action execution error"); - return Mono.error(new AppsmithPluginException(PostgresPluginError.QUERY_EXECUTION_FAILED, - PostgresErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage())); - } finally { - idleConnections = poolProxy.getIdleConnections(); - activeConnections = poolProxy.getActiveConnections(); - totalConnections = poolProxy.getTotalConnections(); - threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug( - "After executing postgres query, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", - activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); - if (resultSet != null) { - try { - resultSet.close(); - } catch (SQLException e) { - log.debug("Execute Error closing Postgres ResultSet", e); - } - } - - if (statement != null) { - try { - statement.close(); - } catch (SQLException e) { - log.debug("Execute Error closing Postgres Statement", e); - } - } + if (statement != null) { + try { + statement.close(); + } catch (SQLException e) { + log.debug("Execute Error closing Postgres Statement", e); + } + } - if (preparedQuery != null) { - try { - preparedQuery.close(); - } catch (SQLException e) { - log.debug("Execute Error closing Postgres Statement", e); - } - } + if (preparedQuery != null) { + try { + preparedQuery.close(); + } catch (SQLException e) { + log.debug("Execute Error closing Postgres Statement", e); + } + } - if (connectionFromPool != null) { - try { - // Return the connection back to the pool - connectionFromPool.close(); - } catch (SQLException e) { - log.debug("Execute Error returning Postgres connection to pool", e); + if (connectionFromPool != null) { + try { + // Return the connection back to the pool + connectionFromPool.close(); + } catch (SQLException e) { + log.debug("Execute Error returning Postgres connection to pool", e); + } + } } - } - - } - ActionExecutionResult result = new ActionExecutionResult(); - result.setBody(objectMapper.valueToTree(rowsList)); - result.setMessages(populateHintMessages(columnsList)); - result.setIsExecutionSuccess(true); - log.debug("In the PostgresPlugin, got action execution result"); - return Mono.just(result); - }) + ActionExecutionResult result = new ActionExecutionResult(); + result.setBody(objectMapper.valueToTree(rowsList)); + result.setMessages(populateHintMessages(columnsList)); + result.setIsExecutionSuccess(true); + log.debug("In the PostgresPlugin, got action execution result"); + return Mono.just(result); + }) .flatMap(obj -> obj) .map(obj -> (ActionExecutionResult) obj) .onErrorResume(error -> { if (error instanceof StaleConnectionException) { return Mono.error(error); } else if (!(error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(PostgresPluginError.QUERY_EXECUTION_FAILED, - PostgresErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error); + error = new AppsmithPluginException( + PostgresPluginError.QUERY_EXECUTION_FAILED, + PostgresErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error); } ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); @@ -525,7 +550,6 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, }) .timeout(Duration.ofMillis(actionConfiguration.getTimeoutInMillisecond())) .subscribeOn(scheduler); - } private Set<String> populateHintMessages(List<String> columnNames) { @@ -534,17 +558,20 @@ private Set<String> populateHintMessages(List<String> columnNames) { List<String> identicalColumns = getIdenticalColumns(columnNames); if (!CollectionUtils.isEmpty(identicalColumns)) { - messages.add("Your PostgreSQL query result may not have all the columns because duplicate column " + - "names were found for the column(s): " + String.join(", ", identicalColumns) + ". You may use" + - " the SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); + messages.add("Your PostgreSQL query result may not have all the columns because duplicate column " + + "names were found for the column(s): " + + String.join(", ", identicalColumns) + ". You may use" + + " the SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); } return messages; } @Override - public Mono<ActionExecutionResult> execute(HikariDataSource connection, - DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + HikariDataSource connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Unused function return Mono.error( new AppsmithPluginException(PostgresPluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); @@ -555,12 +582,13 @@ public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourc try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { - return Mono.error(new AppsmithPluginException(PostgresPluginError.POSTGRES_PLUGIN_ERROR, - PostgresErrorMessages.POSTGRES_JDBC_DRIVER_LOADING_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + PostgresPluginError.POSTGRES_PLUGIN_ERROR, + PostgresErrorMessages.POSTGRES_JDBC_DRIVER_LOADING_ERROR_MSG, + e.getMessage())); } - return Mono - .fromCallable(() -> { + return Mono.fromCallable(() -> { log.debug("Connecting to Postgres db"); return createConnectionPool(datasourceConfiguration); }) @@ -584,7 +612,8 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur for (final Endpoint endpoint : datasourceConfiguration.getEndpoints()) { if (StringUtils.isEmpty(endpoint.getHost())) { invalids.add(PostgresErrorMessages.DS_MISSING_HOSTNAME_ERROR_MSG); - } else if (endpoint.getHost().contains("/") || endpoint.getHost().contains(":")) { + } else if (endpoint.getHost().contains("/") + || endpoint.getHost().contains(":")) { invalids.add( String.format(PostgresErrorMessages.DS_INVALID_HOSTNAME_ERROR_MSG, endpoint.getHost())); } @@ -608,7 +637,6 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur if (StringUtils.isEmpty(authentication.getDatabaseName())) { invalids.add(PostgresErrorMessages.DS_MISSING_DATABASE_NAME_ERROR_MSG); } - } /* @@ -625,224 +653,258 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur } @Override - public Mono<DatasourceStructure> getStructure(HikariDataSource connection, - DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { final DatasourceStructure structure = new DatasourceStructure(); final Map<String, DatasourceStructure.Table> tablesByName = new LinkedHashMap<>(); return Mono.fromSupplier(() -> { - - Connection connectionFromPool; - try { - connectionFromPool = postgresDatasourceUtils.getConnectionFromHikariConnectionPool(connection, - POSTGRES_PLUGIN_NAME); - } catch (SQLException | StaleConnectionException e) { - // The function can throw either StaleConnectionException or SQLException. The - // underlying hikari - // library throws SQLException in case the pool is closed or there is an issue - // initializing - // the connection pool which can also be translated in our world to - // StaleConnectionException - // and should then trigger the destruction and recreation of the pool. - return Mono.error(e instanceof StaleConnectionException ? e : - new StaleConnectionException(e.getMessage())); - } - - HikariPoolMXBean poolProxy = connection.getHikariPoolMXBean(); - - int idleConnections = poolProxy.getIdleConnections(); - int activeConnections = poolProxy.getActiveConnections(); - int totalConnections = poolProxy.getTotalConnections(); - int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug( - "Before getting postgres db structure Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", - activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); - - // Ref: - // <https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/DatabaseMetaData.html>. - try (Statement statement = connectionFromPool.createStatement()) { - - // Get tables and fill up their columns. - try (ResultSet columnsResultSet = statement.executeQuery(TABLES_QUERY)) { - while (columnsResultSet.next()) { - final char kind = columnsResultSet.getString("kind").charAt(0); - final String schemaName = columnsResultSet.getString("schema_name"); - final String tableName = columnsResultSet.getString("table_name"); - final String fullTableName = schemaName + "." + tableName; - if (!tablesByName.containsKey(fullTableName)) { - tablesByName.put(fullTableName, new DatasourceStructure.Table( - kind == 'r' ? DatasourceStructure.TableType.TABLE - : DatasourceStructure.TableType.VIEW, - schemaName, - fullTableName, - new ArrayList<>(), - new ArrayList<>(), - new ArrayList<>())); - } - final DatasourceStructure.Table table = tablesByName.get(fullTableName); - final String defaultExpr = columnsResultSet.getString("default_expr"); - boolean isAutogenerated = !StringUtils.isEmpty(defaultExpr) - && defaultExpr.toLowerCase().contains("nextval"); - - table.getColumns().add(new DatasourceStructure.Column( - columnsResultSet.getString("name"), - columnsResultSet.getString("column_type"), - defaultExpr, - isAutogenerated)); + Connection connectionFromPool; + try { + connectionFromPool = postgresDatasourceUtils.getConnectionFromHikariConnectionPool( + connection, POSTGRES_PLUGIN_NAME); + } catch (SQLException | StaleConnectionException e) { + // The function can throw either StaleConnectionException or SQLException. The + // underlying hikari + // library throws SQLException in case the pool is closed or there is an issue + // initializing + // the connection pool which can also be translated in our world to + // StaleConnectionException + // and should then trigger the destruction and recreation of the pool. + return Mono.error( + e instanceof StaleConnectionException + ? e + : new StaleConnectionException(e.getMessage())); } - } - // Get tables' constraints and fill those up. - try (ResultSet constraintsResultSet = statement.executeQuery(KEYS_QUERY)) { - while (constraintsResultSet.next()) { - final String constraintName = constraintsResultSet.getString("constraint_name"); - final char constraintType = constraintsResultSet.getString("constraint_type").charAt(0); - final String selfSchema = constraintsResultSet.getString("self_schema"); - final String tableName = constraintsResultSet.getString("self_table"); - final String fullTableName = selfSchema + "." + tableName; - if (!tablesByName.containsKey(fullTableName)) { - continue; + HikariPoolMXBean poolProxy = connection.getHikariPoolMXBean(); + + int idleConnections = poolProxy.getIdleConnections(); + int activeConnections = poolProxy.getActiveConnections(); + int totalConnections = poolProxy.getTotalConnections(); + int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); + log.debug( + "Before getting postgres db structure Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", + activeConnections, + idleConnections, + threadsAwaitingConnection, + totalConnections); + + // Ref: + // <https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/DatabaseMetaData.html>. + try (Statement statement = connectionFromPool.createStatement()) { + + // Get tables and fill up their columns. + try (ResultSet columnsResultSet = statement.executeQuery(TABLES_QUERY)) { + while (columnsResultSet.next()) { + final char kind = + columnsResultSet.getString("kind").charAt(0); + final String schemaName = columnsResultSet.getString("schema_name"); + final String tableName = columnsResultSet.getString("table_name"); + final String fullTableName = schemaName + "." + tableName; + if (!tablesByName.containsKey(fullTableName)) { + tablesByName.put( + fullTableName, + new DatasourceStructure.Table( + kind == 'r' + ? DatasourceStructure.TableType.TABLE + : DatasourceStructure.TableType.VIEW, + schemaName, + fullTableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); + } + final DatasourceStructure.Table table = tablesByName.get(fullTableName); + final String defaultExpr = columnsResultSet.getString("default_expr"); + boolean isAutogenerated = !StringUtils.isEmpty(defaultExpr) + && defaultExpr.toLowerCase().contains("nextval"); + + table.getColumns() + .add(new DatasourceStructure.Column( + columnsResultSet.getString("name"), + columnsResultSet.getString("column_type"), + defaultExpr, + isAutogenerated)); + } } - final DatasourceStructure.Table table = tablesByName.get(fullTableName); + // Get tables' constraints and fill those up. + try (ResultSet constraintsResultSet = statement.executeQuery(KEYS_QUERY)) { + while (constraintsResultSet.next()) { + final String constraintName = constraintsResultSet.getString("constraint_name"); + final char constraintType = constraintsResultSet + .getString("constraint_type") + .charAt(0); + final String selfSchema = constraintsResultSet.getString("self_schema"); + final String tableName = constraintsResultSet.getString("self_table"); + final String fullTableName = selfSchema + "." + tableName; + if (!tablesByName.containsKey(fullTableName)) { + continue; + } - if (constraintType == 'p') { - final DatasourceStructure.PrimaryKey key = new DatasourceStructure.PrimaryKey( - constraintName, - List.of((String[]) constraintsResultSet.getArray("self_columns").getArray())); - table.getKeys().add(key); + final DatasourceStructure.Table table = tablesByName.get(fullTableName); + + if (constraintType == 'p') { + final DatasourceStructure.PrimaryKey key = new DatasourceStructure.PrimaryKey( + constraintName, List.of((String[]) constraintsResultSet + .getArray("self_columns") + .getArray())); + table.getKeys().add(key); + + } else if (constraintType == 'f') { + final String foreignSchema = constraintsResultSet.getString("foreign_schema"); + final String prefix = + (foreignSchema.equalsIgnoreCase(selfSchema) ? "" : foreignSchema + ".") + + constraintsResultSet.getString("foreign_table") + + "."; + + final DatasourceStructure.ForeignKey key = new DatasourceStructure.ForeignKey( + constraintName, + List.of((String[]) constraintsResultSet + .getArray("self_columns") + .getArray()), + Stream.of((String[]) constraintsResultSet + .getArray("foreign_columns") + .getArray()) + .map(name -> prefix + name) + .collect(Collectors.toList())); + + table.getKeys().add(key); + } + } + } - } else if (constraintType == 'f') { - final String foreignSchema = constraintsResultSet.getString("foreign_schema"); - final String prefix = (foreignSchema.equalsIgnoreCase(selfSchema) ? "" - : foreignSchema + ".") - + constraintsResultSet.getString("foreign_table") - + "."; + // Get/compute templates for each table and put those in. + for (DatasourceStructure.Table table : tablesByName.values()) { + final List<DatasourceStructure.Column> columnsWithoutDefault = + table.getColumns().stream() + .filter(column -> column.getDefaultValue() == null) + .collect(Collectors.toList()); + + final List<String> columnNames = new ArrayList<>(); + final List<String> columnValues = new ArrayList<>(); + final StringBuilder setFragments = new StringBuilder(); + + for (DatasourceStructure.Column column : columnsWithoutDefault) { + final String name = column.getName(); + final String type = column.getType(); + String value; + + if (type == null) { + value = "null"; + } else if ("text".equals(type) || "varchar".equals(type)) { + value = "''"; + } else if (type.startsWith("int")) { + value = "1"; + } else if (type.startsWith("float") || type.startsWith("double")) { + value = "1.0"; + } else if ("date".equals(type)) { + value = "'2019-07-01'"; + } else if ("time".equals(type)) { + value = "'18:32:45'"; + } else if ("timetz".equals(type)) { + value = "'04:05:06 PST'"; + } else if ("timestamp".equals(type)) { + value = "TIMESTAMP '2019-07-01 10:00:00'"; + } else if ("timestamptz".equals(type)) { + value = "TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET'"; + } else if (type.startsWith("_int")) { + value = "'{1, 2, 3}'"; + } else if ("_varchar".equals(type)) { + value = "'{\"first\", \"second\"}'"; + } else { + value = "''"; + } - final DatasourceStructure.ForeignKey key = new DatasourceStructure.ForeignKey( - constraintName, - List.of((String[]) constraintsResultSet.getArray("self_columns").getArray()), - Stream.of( - (String[]) constraintsResultSet.getArray("foreign_columns").getArray()) - .map(name -> prefix + name) - .collect(Collectors.toList())); + columnNames.add("\"" + name + "\""); + columnValues.add(value); + setFragments + .append("\n \"") + .append(name) + .append("\" = ") + .append(value) + .append(","); + } - table.getKeys().add(key); + // Delete the last comma + if (setFragments.length() > 0) { + setFragments.deleteCharAt(setFragments.length() - 1); + } + final String quotedTableName = table.getName().replaceFirst("\\.(\\w+)", ".\"$1\""); + table.getTemplates() + .addAll( + List.of( + new DatasourceStructure.Template( + "SELECT", + "SELECT * FROM " + quotedTableName + " LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO " + quotedTableName + + " (" + String.join(", ", columnNames) + ")\n" + + " VALUES (" + String.join(", ", columnValues) + + ");"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE " + quotedTableName + " SET" + + setFragments.toString() + "\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM " + quotedTableName + + "\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"))); } - } - } - // Get/compute templates for each table and put those in. - for (DatasourceStructure.Table table : tablesByName.values()) { - final List<DatasourceStructure.Column> columnsWithoutDefault = table.getColumns() - .stream() - .filter(column -> column.getDefaultValue() == null) - .collect(Collectors.toList()); - - final List<String> columnNames = new ArrayList<>(); - final List<String> columnValues = new ArrayList<>(); - final StringBuilder setFragments = new StringBuilder(); - - for (DatasourceStructure.Column column : columnsWithoutDefault) { - final String name = column.getName(); - final String type = column.getType(); - String value; - - if (type == null) { - value = "null"; - } else if ("text".equals(type) || "varchar".equals(type)) { - value = "''"; - } else if (type.startsWith("int")) { - value = "1"; - } else if (type.startsWith("float") || type.startsWith("double")) { - value = "1.0"; - } else if ("date".equals(type)) { - value = "'2019-07-01'"; - } else if ("time".equals(type)) { - value = "'18:32:45'"; - } else if ("timetz".equals(type)) { - value = "'04:05:06 PST'"; - } else if ("timestamp".equals(type)) { - value = "TIMESTAMP '2019-07-01 10:00:00'"; - } else if ("timestamptz".equals(type)) { - value = "TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET'"; - } else if (type.startsWith("_int")) { - value = "'{1, 2, 3}'"; - } else if ("_varchar".equals(type)) { - value = "'{\"first\", \"second\"}'"; - } else { - value = "''"; + } catch (SQLException throwable) { + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + PostgresErrorMessages.GET_STRUCTURE_ERROR_MSG, + throwable.getMessage(), + "SQLSTATE: " + throwable.getSQLState())); + } finally { + idleConnections = poolProxy.getIdleConnections(); + activeConnections = poolProxy.getActiveConnections(); + totalConnections = poolProxy.getTotalConnections(); + threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); + log.debug( + "After postgres db structure, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", + activeConnections, + idleConnections, + threadsAwaitingConnection, + totalConnections); + + if (connectionFromPool != null) { + try { + // Return the connection back to the pool + connectionFromPool.close(); + } catch (SQLException e) { + log.debug("Error returning Postgres connection to pool during get structure", e); + } } - - columnNames.add("\"" + name + "\""); - columnValues.add(value); - setFragments.append("\n \"").append(name).append("\" = ").append(value).append(","); } - // Delete the last comma - if (setFragments.length() > 0) { - setFragments.deleteCharAt(setFragments.length() - 1); + structure.setTables(new ArrayList<>(tablesByName.values())); + for (DatasourceStructure.Table table : structure.getTables()) { + table.getKeys().sort(Comparator.naturalOrder()); } - - final String quotedTableName = table.getName().replaceFirst("\\.(\\w+)", ".\"$1\""); - table.getTemplates().addAll(List.of( - new DatasourceStructure.Template("SELECT", - "SELECT * FROM " + quotedTableName + " LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO " + quotedTableName - + " (" + String.join(", ", columnNames) + ")\n" - + " VALUES (" + String.join(", ", columnValues) + ");"), - new DatasourceStructure.Template("UPDATE", "UPDATE " + quotedTableName + " SET" - + setFragments.toString() + "\n" - + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM " + quotedTableName - + "\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"))); - } - - } catch (SQLException throwable) { - return Mono.error(new AppsmithPluginException( - AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, - PostgresErrorMessages.GET_STRUCTURE_ERROR_MSG, - throwable.getMessage(), - "SQLSTATE: " + throwable.getSQLState())); - } finally { - idleConnections = poolProxy.getIdleConnections(); - activeConnections = poolProxy.getActiveConnections(); - totalConnections = poolProxy.getTotalConnections(); - threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug( - "After postgres db structure, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", - activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); - - if (connectionFromPool != null) { - try { - // Return the connection back to the pool - connectionFromPool.close(); - } catch (SQLException e) { - log.debug("Error returning Postgres connection to pool during get structure", e); - } - } - } - - structure.setTables(new ArrayList<>(tablesByName.values())); - for (DatasourceStructure.Table table : structure.getTables()) { - table.getKeys().sort(Comparator.naturalOrder()); - } - log.debug("Got the structure of postgres db"); - return structure; - }) + log.debug("Got the structure of postgres db"); + return structure; + }) .map(resultStructure -> (DatasourceStructure) resultStructure) .subscribeOn(scheduler); } @Override - public Object substituteValueInInput(int index, + public Object substituteValueInInput( + int index, String binding, String value, Object input, List<Map.Entry<String, String>> insertedParams, - Object... args) throws AppsmithPluginException { + Object... args) + throws AppsmithPluginException { PreparedStatement preparedStatement = (PreparedStatement) input; HikariProxyConnection connection = (HikariProxyConnection) args[0]; @@ -853,8 +915,8 @@ public Object substituteValueInInput(int index, if (explicitCastDataTypes != null && explicitCastDataTypes.get(index - 1) != null) { valueType = explicitCastDataTypes.get(index - 1); } else { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(param.getClientDataType(), value, - PostgresSpecificDataTypes.pluginSpecificTypes); + AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType( + param.getClientDataType(), value, PostgresSpecificDataTypes.pluginSpecificTypes); valueType = appsmithType.type(); } @@ -940,14 +1002,14 @@ public Object substituteValueInInput(int index, // set in the commented part of // the query. Ignore the exception } else { - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(PostgresErrorMessages.QUERY_PREPARATION_FAILED_ERROR_MSG, value, binding), e.getMessage()); } } return preparedStatement; - } private static String toPostgresqlPrimitiveTypeName(DataType type) { @@ -1007,9 +1069,7 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat // Set up the connection URL StringBuilder urlBuilder = new StringBuilder("jdbc:postgresql://"); - List<String> hosts = datasourceConfiguration - .getEndpoints() - .stream() + List<String> hosts = datasourceConfiguration.getEndpoints().stream() .map(endpoint -> endpoint.getHost() + ":" + ObjectUtils.defaultIfNull(endpoint.getPort(), 5432L)) .collect(Collectors.toList()); @@ -1041,14 +1101,14 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat || datasourceConfiguration.getConnection().getSsl() == null || datasourceConfiguration.getConnection().getSsl().getAuthType() == null) { throw new AppsmithPluginException( - PostgresPluginError.POSTGRES_PLUGIN_ERROR, - PostgresErrorMessages.SSL_CONFIGURATION_ERROR_MSG); + PostgresPluginError.POSTGRES_PLUGIN_ERROR, PostgresErrorMessages.SSL_CONFIGURATION_ERROR_MSG); } /* * - By default, the driver configures SSL in the preferred mode. */ - SSLDetails.AuthType sslAuthType = datasourceConfiguration.getConnection().getSsl().getAuthType(); + SSLDetails.AuthType sslAuthType = + datasourceConfiguration.getConnection().getSsl().getAuthType(); switch (sslAuthType) { case ALLOW: case PREFER: diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/datatypes/PostgresSpecificDataTypes.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/datatypes/PostgresSpecificDataTypes.java index b17627a5fde7..e6adfdae9cec 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/datatypes/PostgresSpecificDataTypes.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/datatypes/PostgresSpecificDataTypes.java @@ -21,33 +21,26 @@ import java.util.Map; public class PostgresSpecificDataTypes { - public final static Map<ClientDataType, List<AppsmithType>> pluginSpecificTypes = new HashMap<>(); + public static final Map<ClientDataType, List<AppsmithType>> pluginSpecificTypes = new HashMap<>(); - static { + static { pluginSpecificTypes.put(ClientDataType.NULL, List.of(new NullType())); pluginSpecificTypes.put(ClientDataType.ARRAY, List.of(new NullArrayType(), new ArrayType())); pluginSpecificTypes.put(ClientDataType.BOOLEAN, List.of(new BooleanType())); - pluginSpecificTypes.put(ClientDataType.NUMBER, List.of( - new IntegerType(), - new LongType(), - new DoubleType(), - new BigDecimalType() - )); + pluginSpecificTypes.put( + ClientDataType.NUMBER, + List.of(new IntegerType(), new LongType(), new DoubleType(), new BigDecimalType())); /* - JsonObjectType is the preferred server-side data type when the client-side data type is of type OBJECT. - Fallback server-side data type for client-side OBJECT type is String. - */ + JsonObjectType is the preferred server-side data type when the client-side data type is of type OBJECT. + Fallback server-side data type for client-side OBJECT type is String. + */ pluginSpecificTypes.put(ClientDataType.OBJECT, List.of(new JsonObjectType())); - pluginSpecificTypes.put(ClientDataType.STRING, List.of( - new TimeType(), - new DateType(), - new TimestampType(), - new StringType() - )); + pluginSpecificTypes.put( + ClientDataType.STRING, List.of(new TimeType(), new DateType(), new TimestampType(), new StringType())); } } diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/exceptions/PostgresErrorMessages.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/exceptions/PostgresErrorMessages.java index 5f3eb6a0af65..06af60d122c3 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/exceptions/PostgresErrorMessages.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/exceptions/PostgresErrorMessages.java @@ -12,28 +12,33 @@ public class PostgresErrorMessages extends BasePluginErrorMessages { public static final String POSTGRES_JDBC_DRIVER_LOADING_ERROR_MSG = "Your PostgreSQL query failed to execute."; - public static final String GET_STRUCTURE_ERROR_MSG = "The Appsmith server has failed to fetch the structure of your schema."; + public static final String GET_STRUCTURE_ERROR_MSG = + "The Appsmith server has failed to fetch the structure of your schema."; - public static final String QUERY_PREPARATION_FAILED_ERROR_MSG = "Query preparation failed while inserting value: %s" - + " for binding: {{%s}}."; + public static final String QUERY_PREPARATION_FAILED_ERROR_MSG = + "Query preparation failed while inserting value: %s" + " for binding: {{%s}}."; - public static final String SSL_CONFIGURATION_ERROR_MSG = "The Appsmith server has failed to fetch SSL configuration from datasource configuration form. "; + public static final String SSL_CONFIGURATION_ERROR_MSG = + "The Appsmith server has failed to fetch SSL configuration from datasource configuration form. "; - public static final String INVALID_SSL_OPTION_ERROR_MSG = "The Appsmith server has found an unexpected SSL option: %s."; + public static final String INVALID_SSL_OPTION_ERROR_MSG = + "The Appsmith server has found an unexpected SSL option: %s."; - public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = "An exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid."; + public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = + "An exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ public static final String DS_MISSING_ENDPOINT_ERROR_MSG = "Missing endpoint."; public static final String DS_MISSING_HOSTNAME_ERROR_MSG = "Missing hostname."; - public static final String DS_INVALID_HOSTNAME_ERROR_MSG = "Host value cannot contain `/` or `:` characters. Found `%s`."; + public static final String DS_INVALID_HOSTNAME_ERROR_MSG = + "Host value cannot contain `/` or `:` characters. Found `%s`."; public static final String DS_MISSING_CONNECTION_MODE_ERROR_MSG = "Missing connection mode."; @@ -42,5 +47,4 @@ public class PostgresErrorMessages extends BasePluginErrorMessages { public static final String DS_MISSING_USERNAME_ERROR_MSG = "Missing username for authentication."; public static final String DS_MISSING_DATABASE_NAME_ERROR_MSG = "Missing database name."; - } diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/exceptions/PostgresPluginError.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/exceptions/PostgresPluginError.java index 991f551cdd62..856178d432f5 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/exceptions/PostgresPluginError.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/exceptions/PostgresPluginError.java @@ -17,8 +17,7 @@ public enum PostgresPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), POSTGRES_PLUGIN_ERROR( 500, "PE-PGS-5001", @@ -27,8 +26,7 @@ public enum PostgresPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), RESPONSE_SIZE_TOO_LARGE( 504, "PE-PGS-5009", @@ -37,8 +35,7 @@ public enum PostgresPluginError implements BasePluginError { "Large Result Set Not Supported", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; private final String appErrorCode; @@ -51,8 +48,15 @@ public enum PostgresPluginError implements BasePluginError { private final String downstreamErrorCode; - PostgresPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + PostgresPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -67,7 +71,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/utils/PostgresDataTypeUtils.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/utils/PostgresDataTypeUtils.java index 0d29ff09301c..77247558f4ca 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/utils/PostgresDataTypeUtils.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/utils/PostgresDataTypeUtils.java @@ -38,6 +38,7 @@ public class PostgresDataTypeUtils { * and ignoring the group "::" from getting captured by using regex "?:" which ignores the subsequent string */ private static String questionWithCast = "\\?(?:::)*([a-zA-Z]+)*"; + private static Pattern questionWithCastPattern = Pattern.compile(questionWithCast); public static DataType dataType = new DataType(); @@ -52,6 +53,7 @@ public static class DataType { * dataTypeMapper which maps the postgres data types to Appsmith data types. */ public static final String INT8 = "int8"; + public static final String INT4 = "int4"; public static final String DECIMAL = "decimal"; public static final String VARCHAR = "varchar"; @@ -106,7 +108,7 @@ private static Map getDataTypeMapper() { dataTypeMapper.put(INT, INTEGER); // Must ensure that all the declared postgres data types have a mapping to appsmith data types - assert(dataTypeMapper.size() == dataType.getDataTypes().size()); + assert (dataTypeMapper.size() == dataType.getDataTypes().size()); } return dataTypeMapper; @@ -122,13 +124,15 @@ public static List<com.appsmith.external.constants.DataType> extractExplicitCast if (prospectiveDataType != null) { String dataTypeFromInput = prospectiveDataType.trim().toLowerCase(); if (dataType.getDataTypes().contains(dataTypeFromInput)) { - com.appsmith.external.constants.DataType appsmithDataType - = (com.appsmith.external.constants.DataType) getDataTypeMapper().get(dataTypeFromInput); + com.appsmith.external.constants.DataType appsmithDataType = + (com.appsmith.external.constants.DataType) + getDataTypeMapper().get(dataTypeFromInput); inputDataTypes.add(appsmithDataType); continue; } } - // Either no external casting exists or unsupported data type is being used. Do not use external casting for this + // Either no external casting exists or unsupported data type is being used. Do not use external casting for + // this // and instead default to implicit type casting (default behaviour) by setting the entry to null. inputDataTypes.add(null); } diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/utils/PostgresDatasourceUtils.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/utils/PostgresDatasourceUtils.java index 31e606b0b1ba..a5e5a1f4af0e 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/utils/PostgresDatasourceUtils.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/utils/PostgresDatasourceUtils.java @@ -13,22 +13,22 @@ import static com.appsmith.external.exceptions.pluginExceptions.BasePluginErrorMessages.UNKNOWN_CONNECTION_ERROR_MSG; public class PostgresDatasourceUtils { - public void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) throws StaleConnectionException { + public void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) + throws StaleConnectionException { if (connectionPool == null || connectionPool.isClosed() || !connectionPool.isRunning()) { - String printMessage = MessageFormat.format(Thread.currentThread().getName() + - ": Encountered stale connection pool in {0} plugin. Reporting back.", pluginName); + String printMessage = MessageFormat.format( + Thread.currentThread().getName() + + ": Encountered stale connection pool in {0} plugin. Reporting back.", + pluginName); System.out.println(printMessage); if (connectionPool == null) { throw new StaleConnectionException(CONNECTION_POOL_NULL_ERROR_MSG); - } - else if (connectionPool.isClosed()) { + } else if (connectionPool.isClosed()) { throw new StaleConnectionException(CONNECTION_POOL_CLOSED_ERROR_MSG); - } - else if (!connectionPool.isRunning()) { + } else if (!connectionPool.isRunning()) { throw new StaleConnectionException(CONNECTION_POOL_NOT_RUNNING_ERROR_MSG); - } - else { + } else { /** * Ideally, code flow is never expected to reach here. However, this section has been added to catch * those cases wherein a developer updates the parent if condition but does not update the nested @@ -39,8 +39,8 @@ else if (!connectionPool.isRunning()) { } } - public Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, - String pluginName) throws SQLException { + public Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, String pluginName) + throws SQLException { checkHikariCPConnectionPoolValidity(connectionPool, pluginName); return connectionPool.getConnection(); } diff --git a/app/server/appsmith-plugins/postgresPlugin/src/test/java/com/external/plugins/PostgresPluginDataTypeTest.java b/app/server/appsmith-plugins/postgresPlugin/src/test/java/com/external/plugins/PostgresPluginDataTypeTest.java index 746554f234fc..7b694e4a4762 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/test/java/com/external/plugins/PostgresPluginDataTypeTest.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/test/java/com/external/plugins/PostgresPluginDataTypeTest.java @@ -27,54 +27,46 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class PostgresPluginDataTypeTest { - public final static Map<ClientDataType, List<AppsmithType>> pluginSpecificTypes = new HashMap<>(); + public static final Map<ClientDataType, List<AppsmithType>> pluginSpecificTypes = new HashMap<>(); - static { + static { pluginSpecificTypes.put(ClientDataType.NULL, List.of(new NullType())); pluginSpecificTypes.put(ClientDataType.ARRAY, List.of(new NullArrayType(), new ArrayType())); pluginSpecificTypes.put(ClientDataType.BOOLEAN, List.of(new BooleanType())); - pluginSpecificTypes.put(ClientDataType.NUMBER, List.of( - new IntegerType(), - new LongType(), - new DoubleType(), - new BigDecimalType() - )); + pluginSpecificTypes.put( + ClientDataType.NUMBER, + List.of(new IntegerType(), new LongType(), new DoubleType(), new BigDecimalType())); /* - JsonObjectType is the preferred server-side data type when the client-side data type is of type OBJECT. - Fallback server-side data type for client-side OBJECT type is String. - */ + JsonObjectType is the preferred server-side data type when the client-side data type is of type OBJECT. + Fallback server-side data type for client-side OBJECT type is String. + */ pluginSpecificTypes.put(ClientDataType.OBJECT, List.of(new JsonObjectType())); - pluginSpecificTypes.put(ClientDataType.STRING, List.of( - new TimeType(), - new DateType(), - new TimestampType(), - new StringType() - )); + pluginSpecificTypes.put( + ClientDataType.STRING, List.of(new TimeType(), new DateType(), new TimestampType(), new StringType())); } @Test public void shouldBeNullType() { String value = "null"; - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.NULL, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.NULL, value, pluginSpecificTypes); assertTrue(appsmithType instanceof NullType); assertEquals(appsmithType.performSmartSubstitution(value), null); } @Test public void shouldBeBooleanType() { - String[] values = { - "true", - "false" - }; + String[] values = {"true", "false"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.BOOLEAN, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.BOOLEAN, value, pluginSpecificTypes); assertTrue(appsmithType instanceof BooleanType); assertEquals(appsmithType.performSmartSubstitution(value), value); } @@ -82,15 +74,11 @@ public void shouldBeBooleanType() { @Test public void shouldBeIntegerType() { - String[] values = { - "0", - "7166", - String.valueOf(Integer.MIN_VALUE), - String.valueOf(Integer.MAX_VALUE) - }; + String[] values = {"0", "7166", String.valueOf(Integer.MIN_VALUE), String.valueOf(Integer.MAX_VALUE)}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); assertTrue(appsmithType instanceof IntegerType); assertEquals(appsmithType.performSmartSubstitution(value), value); } @@ -98,13 +86,11 @@ public void shouldBeIntegerType() { @Test public void shouldBeLongType() { - String[] values = { - "2147483648", - "-2147483649" - }; + String[] values = {"2147483648", "-2147483649"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); assertTrue(appsmithType instanceof LongType); assertEquals(appsmithType.performSmartSubstitution(value), value); } @@ -113,15 +99,16 @@ public void shouldBeLongType() { @Test public void shouldBeDoubleType() { String[] values = { - "323.23", - String.valueOf(Double.MIN_VALUE), - String.valueOf(Double.MAX_VALUE), - String.valueOf(Double.POSITIVE_INFINITY), - String.valueOf(Double.NEGATIVE_INFINITY) + "323.23", + String.valueOf(Double.MIN_VALUE), + String.valueOf(Double.MAX_VALUE), + String.valueOf(Double.POSITIVE_INFINITY), + String.valueOf(Double.NEGATIVE_INFINITY) }; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.NUMBER, value, pluginSpecificTypes); assertTrue(appsmithType instanceof DoubleType); assertEquals(appsmithType.performSmartSubstitution(value), value); } @@ -129,86 +116,71 @@ public void shouldBeDoubleType() { @Test public void shouldBeJsonObjectTypeOrStringType() { - String[] values = { - "{\"a\":97,\"A\":65}", - "{\"a\":97,\"A\":65" - }; + String[] values = {"{\"a\":97,\"A\":65}", "{\"a\":97,\"A\":65"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.OBJECT, value, pluginSpecificTypes); assertTrue(appsmithType instanceof JsonObjectType || appsmithType instanceof FallbackType); } - } @Test public void shouldBeTimeType() { - String[] values = { - "10:15:30", - "10:15" - }; + String[] values = {"10:15:30", "10:15"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); assertTrue(appsmithType instanceof TimeType); } } @Test public void shouldBeDateType() { - String[] values = { - "2011-12-03" - }; + String[] values = {"2011-12-03"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); assertTrue(appsmithType instanceof DateType); } } @Test public void shouldBeTimestampType() { - String[] values = { - "2021-03-24 14:05:34" - }; + String[] values = {"2021-03-24 14:05:34"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); assertTrue(appsmithType instanceof TimestampType); } } @Test public void shouldBeStringType() { - String[] values = { - "Hello, world!", - "123", - "098876", - "2022/09/252", - "", - "10:15:30+06:00", - "2021-03-24 14:05:343" + String[] values = {"Hello, world!", "123", "098876", "2022/09/252", "", "10:15:30+06:00", "2021-03-24 14:05:343" }; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.STRING, value, pluginSpecificTypes); assertTrue(appsmithType instanceof StringType); } } @Test public void shouldNullArrayType() { - String[] values = { - "[]" - }; + String[] values = {"[]"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, value, pluginSpecificTypes); assertTrue(appsmithType instanceof NullArrayType); } } @Test public void shouldArrayType() { - String[] values = { - "[71]" - }; + String[] values = {"[71]"}; for (String value : values) { - AppsmithType appsmithType = DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, value, pluginSpecificTypes); + AppsmithType appsmithType = + DataTypeServiceUtils.getAppsmithType(ClientDataType.ARRAY, value, pluginSpecificTypes); assertTrue(appsmithType instanceof ArrayType); } } diff --git a/app/server/appsmith-plugins/postgresPlugin/src/test/java/com/external/plugins/PostgresPluginTest.java b/app/server/appsmith-plugins/postgresPlugin/src/test/java/com/external/plugins/PostgresPluginTest.java index 365ae641444b..f19e0f425509 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/test/java/com/external/plugins/PostgresPluginTest.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/test/java/com/external/plugins/PostgresPluginTest.java @@ -77,8 +77,8 @@ public String getRemoteExecutionUrl() { } } - - PostgresPlugin.PostgresPluginExecutor pluginExecutor = new PostgresPlugin.PostgresPluginExecutor(new MockSharedConfig()); + PostgresPlugin.PostgresPluginExecutor pluginExecutor = + new PostgresPlugin.PostgresPluginExecutor(new MockSharedConfig()); @SuppressWarnings("rawtypes") // The type parameter for the container type is just itself and is pseudo-optional. @Container @@ -88,11 +88,10 @@ public String getRemoteExecutionUrl() { .withPassword("password"); @Container - public static final PostgreSQLContainer pgsqlContainerNoPwdAuth = - new PostgreSQLContainer<>("postgres:alpine") - .withExposedPorts(5432) - .withUsername("postgres_no_pwd_auth") - .withEnv("POSTGRES_HOST_AUTH_METHOD", "trust"); + public static final PostgreSQLContainer pgsqlContainerNoPwdAuth = new PostgreSQLContainer<>("postgres:alpine") + .withExposedPorts(5432) + .withUsername("postgres_no_pwd_auth") + .withEnv("POSTGRES_HOST_AUTH_METHOD", "trust"); private static String address; private static Integer port; @@ -119,13 +118,10 @@ public static void setUp() { Properties properties = new Properties(); properties.putAll(Map.of( "user", username, - "password", password - )); + "password", password)); - try (Connection connection = DriverManager.getConnection( - "jdbc:postgresql://" + address + ":" + port + "/" + username, - properties - )) { + try (Connection connection = + DriverManager.getConnection("jdbc:postgresql://" + address + ":" + port + "/" + username, properties)) { try (Statement statement = connection.createStatement()) { statement.execute("SET TIME ZONE 'UTC'"); @@ -144,102 +140,91 @@ public static void setUp() { } try (Statement statement = connection.createStatement()) { - statement.execute("CREATE TABLE users (\n" + - " id serial PRIMARY KEY,\n" + - " username VARCHAR (50) UNIQUE,\n" + - " password VARCHAR (50) ,\n" + - " email VARCHAR (355) UNIQUE ,\n" + - " spouse_dob DATE,\n" + - " dob DATE ,\n" + - " time1 TIME ,\n" + - " time_tz TIME WITH TIME ZONE ,\n" + - " created_on TIMESTAMP ,\n" + - " created_on_tz TIMESTAMP WITH TIME ZONE ,\n" + - " interval1 INTERVAL HOUR ,\n" + - " numbers INTEGER[3] ,\n" + - " texts VARCHAR[2] ,\n" + - " rating FLOAT4 \n" + - ")"); - - statement.execute("CREATE TABLE possessions (\n" + - " id serial PRIMARY KEY,\n" + - " title VARCHAR (50) NOT NULL,\n" + - " user_id int NOT NULL,\n" + - " constraint user_fk foreign key (user_id) references users(id)" + - ")"); + statement.execute("CREATE TABLE users (\n" + " id serial PRIMARY KEY,\n" + + " username VARCHAR (50) UNIQUE,\n" + + " password VARCHAR (50) ,\n" + + " email VARCHAR (355) UNIQUE ,\n" + + " spouse_dob DATE,\n" + + " dob DATE ,\n" + + " time1 TIME ,\n" + + " time_tz TIME WITH TIME ZONE ,\n" + + " created_on TIMESTAMP ,\n" + + " created_on_tz TIMESTAMP WITH TIME ZONE ,\n" + + " interval1 INTERVAL HOUR ,\n" + + " numbers INTEGER[3] ,\n" + + " texts VARCHAR[2] ,\n" + + " rating FLOAT4 \n" + + ")"); + + statement.execute("CREATE TABLE possessions (\n" + " id serial PRIMARY KEY,\n" + + " title VARCHAR (50) NOT NULL,\n" + + " user_id int NOT NULL,\n" + + " constraint user_fk foreign key (user_id) references users(id)" + + ")"); // Testing <https://github.com/appsmithorg/appsmith/issues/1758>. - statement.execute("CREATE TABLE campus (\n" + - " id timestamptz default now(),\n" + - " name timestamptz default now()\n" + - ")"); - - statement.execute("CREATE TABLE dataTypeTest (\n" + - " id serial PRIMARY KEY,\n" + - " item json,\n" + - " origin jsonb,\n" + - " citextdata citext" + - ")"); - - statement.execute("CREATE SCHEMA sample_schema " + - " CREATE TABLE sample_table (\n" + - " id serial PRIMARY KEY,\n" + - " username VARCHAR (50) UNIQUE,\n" + - " email VARCHAR (355) UNIQUE ,\n" + - " numbers INTEGER[3] ,\n" + - " texts VARCHAR[2] ,\n" + - " rating FLOAT4 \n" + - ")"); - + statement.execute("CREATE TABLE campus (\n" + " id timestamptz default now(),\n" + + " name timestamptz default now()\n" + + ")"); + + statement.execute("CREATE TABLE dataTypeTest (\n" + " id serial PRIMARY KEY,\n" + + " item json,\n" + + " origin jsonb,\n" + + " citextdata citext" + + ")"); + + statement.execute("CREATE SCHEMA sample_schema " + " CREATE TABLE sample_table (\n" + + " id serial PRIMARY KEY,\n" + + " username VARCHAR (50) UNIQUE,\n" + + " email VARCHAR (355) UNIQUE ,\n" + + " numbers INTEGER[3] ,\n" + + " texts VARCHAR[2] ,\n" + + " rating FLOAT4 \n" + + ")"); } try (Statement statement = connection.createStatement()) { statement.execute( - "INSERT INTO users VALUES (" + - "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31'," + - " '18:32:45', '04:05:06 PST'," + - " TIMESTAMP '2018-11-30 20:45:15', TIMESTAMP WITH TIME ZONE '2018-11-30 20:45:15 CET'," + - " '1.2 years 3 months 2 hours'," + - " '{1, 2, 3}', '{\"a\", \"b\"}', 1.0" + - ")"); + "INSERT INTO users VALUES (" + "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31'," + + " '18:32:45', '04:05:06 PST'," + + " TIMESTAMP '2018-11-30 20:45:15', TIMESTAMP WITH TIME ZONE '2018-11-30 20:45:15 CET'," + + " '1.2 years 3 months 2 hours'," + + " '{1, 2, 3}', '{\"a\", \"b\"}', 1.0" + + ")"); } try (Statement statement = connection.createStatement()) { statement.execute( - "INSERT INTO sample_schema.\"sample_table\" VALUES (" + - "1, 'Jack', '[email protected]', " + - " '{1, 2, 3}', '{\"a\", \"b\"}', 1.0" + - ")"); + "INSERT INTO sample_schema.\"sample_table\" VALUES (" + "1, 'Jack', '[email protected]', " + + " '{1, 2, 3}', '{\"a\", \"b\"}', 1.0" + + ")"); } try (Statement statement = connection.createStatement()) { statement.execute( - "INSERT INTO users VALUES (" + - "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31'," + - " '15:45:30', '04:05:06 PST'," + - " TIMESTAMP '2019-11-30 23:59:59', TIMESTAMP WITH TIME ZONE '2019-11-30 23:59:59 CET'," + - " '2 years'," + - " '{1, 2, 3}', '{\"a\", \"b\"}', 2.0" + - ")"); + "INSERT INTO users VALUES (" + "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31'," + + " '15:45:30', '04:05:06 PST'," + + " TIMESTAMP '2019-11-30 23:59:59', TIMESTAMP WITH TIME ZONE '2019-11-30 23:59:59 CET'," + + " '2 years'," + + " '{1, 2, 3}', '{\"a\", \"b\"}', 2.0" + + ")"); } try (Statement statement = connection.createStatement()) { - statement.execute( - "INSERT INTO users VALUES (" + - "3, 'MiniJackJill', 'jaji', '[email protected]', NULL, '2021-01-31'," + - " '15:45:30', '04:05:06 PST'," + - " TIMESTAMP '2021-01-31 23:59:59', TIMESTAMP WITH TIME ZONE '2021-01-31 23:59:59 CET'," + - " '0 years'," + - " '{1, 2, 3}', '{\"a\", \"b\"}', 3.0" + - ")"); + statement.execute("INSERT INTO users VALUES (" + + "3, 'MiniJackJill', 'jaji', '[email protected]', NULL, '2021-01-31'," + + " '15:45:30', '04:05:06 PST'," + + " TIMESTAMP '2021-01-31 23:59:59', TIMESTAMP WITH TIME ZONE '2021-01-31 23:59:59 CET'," + + " '0 years'," + + " '{1, 2, 3}', '{\"a\", \"b\"}', 3.0" + + ")"); } try (Statement statement = connection.createStatement()) { - statement.execute( - "INSERT INTO dataTypeTest VALUES (" + - "1, '{\"type\":\"racket\", \"manufacturer\":\"butterfly\"}'," + - "'{\"country\":\"japan\", \"city\":\"kyoto\"}', 'A Lincoln'" + - ")"); + statement.execute("INSERT INTO dataTypeTest VALUES (" + + "1, '{\"type\":\"racket\", \"manufacturer\":\"butterfly\"}'," + + "'{\"country\":\"japan\", \"city\":\"kyoto\"}', 'A Lincoln'" + + ")"); } } catch (SQLException throwable) { @@ -318,7 +303,6 @@ public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { assertTrue(datasourceTestResult.getInvalids().isEmpty()); }) .verifyComplete(); - } @Test @@ -327,8 +311,7 @@ public void validateDatasource_withCorrectCredentialsNoPwd_returnsWithoutInvalid final Set<String> datasourceValidationInvalids = pluginExecutor.validateDatasource(dsConfig); - assertTrue(datasourceValidationInvalids.size() == 0); - + assertTrue(datasourceValidationInvalids.isEmpty()); } @Test @@ -337,8 +320,7 @@ public void itShouldValidateDatasourceWithEmptyEndpoints() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.setEndpoints(new ArrayList<>()); - assertEquals(Set.of("Missing endpoint."), - pluginExecutor.validateDatasource(dsConfig)); + assertEquals(Set.of("Missing endpoint."), pluginExecutor.validateDatasource(dsConfig)); } @Test @@ -347,8 +329,7 @@ public void itShouldValidateDatasourceWithEmptyHost() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getEndpoints().get(0).setHost(""); - assertEquals(Set.of("Missing hostname."), - pluginExecutor.validateDatasource(dsConfig)); + assertEquals(Set.of("Missing hostname."), pluginExecutor.validateDatasource(dsConfig)); } @Test @@ -358,7 +339,8 @@ public void itShouldValidateDatasourceWithInvalidHostname() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getEndpoints().get(0).setHost("jdbc://localhost"); - assertEquals(Set.of(String.format(PostgresErrorMessages.DS_INVALID_HOSTNAME_ERROR_MSG, hostname)), + assertEquals( + Set.of(String.format(PostgresErrorMessages.DS_INVALID_HOSTNAME_ERROR_MSG, hostname)), pluginExecutor.validateDatasource(dsConfig)); } @@ -373,21 +355,18 @@ public void testAliasColumnNames() { pluginSpecifiedTemplates.add(new Property("preparedStatement", "false")); actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "user_id" - }, + new String[] {"user_id"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); }) .verifyComplete(); } @@ -398,14 +377,15 @@ public void testApplicationName() { Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("SELECT COUNT(*) FROM pg_stat_activity WHERE application_name='Appsmith JDBC Driver';"); + actionConfiguration.setBody( + "SELECT COUNT(*) FROM pg_stat_activity WHERE application_name='Appsmith JDBC Driver';"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "false")); actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -430,8 +410,8 @@ public void testExecute() { pluginSpecifiedTemplates.add(new Property("preparedStatement", "false")); actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -444,41 +424,43 @@ public void testExecute() { assertEquals("18:32:45", node.get("time1").asText()); assertEquals("04:05:06-08", node.get("time_tz").asText()); assertEquals("2018-11-30T20:45:15Z", node.get("created_on").asText()); - assertEquals("2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); - assertEquals("1 years 5 mons 0 days 2 hours 0 mins 0.0 secs", node.get("interval1").asText()); + assertEquals( + "2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); + assertEquals( + "1 years 5 mons 0 days 2 hours 0 mins 0.0 secs", + node.get("interval1").asText()); assertTrue(node.get("spouse_dob").isNull()); // Check the order of the columns. assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", - "time_tz", - "created_on", - "created_on_tz", - "interval1", - "numbers", - "texts", - "rating" + new String[] { + "id", + "username", + "password", + "email", + "spouse_dob", + "dob", + "time1", + "time_tz", + "created_on", + "created_on_tz", + "interval1", + "numbers", + "texts", + "rating" }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); /* * - RequestParamDTO object only have attributes configProperty and value at this point. * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - actionConfiguration.getBody(), null, null, null)); + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, actionConfiguration.getBody(), null, null, null)); assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -487,7 +469,8 @@ public void testExecute() { @Test public void testStructure() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<DatasourceStructure> structureMono = pluginExecutor.datasourceCreate(dsConfig) + Mono<DatasourceStructure> structureMono = pluginExecutor + .datasourceCreate(dsConfig) .flatMap(connection -> pluginExecutor.getStructure(connection, dsConfig)); StepVerifier.create(structureMono) @@ -495,177 +478,187 @@ public void testStructure() { assertNotNull(structure); assertEquals(5, structure.getTables().size()); - final DatasourceStructure.Table campusTable = structure.getTables().get(0); + final DatasourceStructure.Table campusTable = + structure.getTables().get(0); assertEquals("public.campus", campusTable.getName()); assertEquals(DatasourceStructure.TableType.TABLE, campusTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "timestamptz", "now()", false), - new DatasourceStructure.Column("name", "timestamptz", "now()", false) + new DatasourceStructure.Column[] { + new DatasourceStructure.Column("id", "timestamptz", "now()", false), + new DatasourceStructure.Column("name", "timestamptz", "now()", false) }, - campusTable.getColumns().toArray() - ); + campusTable.getColumns().toArray()); assertEquals(campusTable.getKeys().size(), 0); - final DatasourceStructure.Table dataTypeTestTable = structure.getTables().get(1); + final DatasourceStructure.Table dataTypeTestTable = + structure.getTables().get(1); assertEquals("public.datatypetest", dataTypeTestTable.getName()); assertEquals(DatasourceStructure.TableType.TABLE, campusTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column( - "id", - "int4", - "nextval('datatypetest_id_seq'::regclass)", - true), - new DatasourceStructure.Column("item", "json", null, false), - new DatasourceStructure.Column("origin", "jsonb", null, false), - new DatasourceStructure.Column("citextdata", "citext", null, false) + new DatasourceStructure.Column[] { + new DatasourceStructure.Column( + "id", "int4", "nextval('datatypetest_id_seq'::regclass)", true), + new DatasourceStructure.Column("item", "json", null, false), + new DatasourceStructure.Column("origin", "jsonb", null, false), + new DatasourceStructure.Column("citextdata", "citext", null, false) }, - dataTypeTestTable.getColumns().toArray() - ); + dataTypeTestTable.getColumns().toArray()); assertEquals(dataTypeTestTable.getKeys().size(), 1); - final DatasourceStructure.Table possessionsTable = structure.getTables().get(2); + final DatasourceStructure.Table possessionsTable = + structure.getTables().get(2); assertEquals("public.possessions", possessionsTable.getName()); assertEquals(DatasourceStructure.TableType.TABLE, possessionsTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "int4", "nextval('possessions_id_seq'::regclass)", true), - new DatasourceStructure.Column("title", "varchar", null, false), - new DatasourceStructure.Column("user_id", "int4", null, false), + new DatasourceStructure.Column[] { + new DatasourceStructure.Column( + "id", "int4", "nextval('possessions_id_seq'::regclass)", true), + new DatasourceStructure.Column("title", "varchar", null, false), + new DatasourceStructure.Column("user_id", "int4", null, false), }, - possessionsTable.getColumns().toArray() - ); + possessionsTable.getColumns().toArray()); - final DatasourceStructure.PrimaryKey possessionsPrimaryKey = new DatasourceStructure.PrimaryKey("possessions_pkey", new ArrayList<>()); + final DatasourceStructure.PrimaryKey possessionsPrimaryKey = + new DatasourceStructure.PrimaryKey("possessions_pkey", new ArrayList<>()); possessionsPrimaryKey.getColumnNames().add("id"); - final DatasourceStructure.ForeignKey possessionsUserForeignKey = new DatasourceStructure.ForeignKey( - "user_fk", - List.of("user_id"), - List.of("users.id") - ); + final DatasourceStructure.ForeignKey possessionsUserForeignKey = + new DatasourceStructure.ForeignKey("user_fk", List.of("user_id"), List.of("users.id")); assertArrayEquals( - new DatasourceStructure.Key[]{possessionsPrimaryKey, possessionsUserForeignKey}, - possessionsTable.getKeys().toArray() - ); + new DatasourceStructure.Key[] {possessionsPrimaryKey, possessionsUserForeignKey}, + possessionsTable.getKeys().toArray()); assertArrayEquals( - new DatasourceStructure.Template[]{ - new DatasourceStructure.Template("SELECT", "SELECT * FROM public.\"possessions\" LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO public.\"possessions\" (\"title\", \"user_id\")\n" + - " VALUES ('', 1);"), - new DatasourceStructure.Template("UPDATE", "UPDATE public.\"possessions\" SET\n" + - " \"title\" = '',\n" + - " \"user_id\" = 1\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM public.\"possessions\"\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), + new DatasourceStructure.Template[] { + new DatasourceStructure.Template( + "SELECT", "SELECT * FROM public.\"possessions\" LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO public.\"possessions\" (\"title\", \"user_id\")\n" + + " VALUES ('', 1);"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE public.\"possessions\" SET\n" + " \"title\" = '',\n" + + " \"user_id\" = 1\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM public.\"possessions\"\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), }, - possessionsTable.getTemplates().toArray() - ); + possessionsTable.getTemplates().toArray()); - final DatasourceStructure.Table usersTable = structure.getTables().get(4); + final DatasourceStructure.Table usersTable = + structure.getTables().get(4); assertEquals("public.users", usersTable.getName()); assertEquals(DatasourceStructure.TableType.TABLE, usersTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "int4", "nextval('users_id_seq'::regclass)", true), - new DatasourceStructure.Column("username", "varchar", null, false), - new DatasourceStructure.Column("password", "varchar", null, false), - new DatasourceStructure.Column("email", "varchar", null, false), - new DatasourceStructure.Column("spouse_dob", "date", null, false), - new DatasourceStructure.Column("dob", "date", null, false), - new DatasourceStructure.Column("time1", "time", null, false), - new DatasourceStructure.Column("time_tz", "timetz", null, false), - new DatasourceStructure.Column("created_on", "timestamp", null, false), - new DatasourceStructure.Column("created_on_tz", "timestamptz", null, false), - new DatasourceStructure.Column("interval1", "interval", null, false), - new DatasourceStructure.Column("numbers", "_int4", null, false), - new DatasourceStructure.Column("texts", "_varchar", null, false), - new DatasourceStructure.Column("rating", "float4", null, false), + new DatasourceStructure.Column[] { + new DatasourceStructure.Column("id", "int4", "nextval('users_id_seq'::regclass)", true), + new DatasourceStructure.Column("username", "varchar", null, false), + new DatasourceStructure.Column("password", "varchar", null, false), + new DatasourceStructure.Column("email", "varchar", null, false), + new DatasourceStructure.Column("spouse_dob", "date", null, false), + new DatasourceStructure.Column("dob", "date", null, false), + new DatasourceStructure.Column("time1", "time", null, false), + new DatasourceStructure.Column("time_tz", "timetz", null, false), + new DatasourceStructure.Column("created_on", "timestamp", null, false), + new DatasourceStructure.Column("created_on_tz", "timestamptz", null, false), + new DatasourceStructure.Column("interval1", "interval", null, false), + new DatasourceStructure.Column("numbers", "_int4", null, false), + new DatasourceStructure.Column("texts", "_varchar", null, false), + new DatasourceStructure.Column("rating", "float4", null, false), }, - usersTable.getColumns().toArray() - ); + usersTable.getColumns().toArray()); - final DatasourceStructure.PrimaryKey usersPrimaryKey = new DatasourceStructure.PrimaryKey("users_pkey", new ArrayList<>()); + final DatasourceStructure.PrimaryKey usersPrimaryKey = + new DatasourceStructure.PrimaryKey("users_pkey", new ArrayList<>()); usersPrimaryKey.getColumnNames().add("id"); assertArrayEquals( - new DatasourceStructure.Key[]{usersPrimaryKey}, - usersTable.getKeys().toArray() - ); + new DatasourceStructure.Key[] {usersPrimaryKey}, + usersTable.getKeys().toArray()); assertArrayEquals( - new DatasourceStructure.Template[]{ - new DatasourceStructure.Template("SELECT", "SELECT * FROM public.\"users\" LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO public.\"users\" " + - "(\"username\", \"password\", \"email\", \"spouse_dob\", \"dob\", " + - "\"time1\", \"time_tz\", \"created_on\", \"created_on_tz\", " + - "\"interval1\", \"numbers\", \"texts\", \"rating\")\n " + - "VALUES ('', '', '', '2019-07-01', '2019-07-01', '18:32:45', " + - "'04:05:06 PST', TIMESTAMP '2019-07-01 10:00:00', TIMESTAMP WITH TIME ZONE " + - "'2019-07-01 06:30:00 CET', 1, '{1, 2, 3}', '{\"first\", \"second\"}', 1.0);"), - new DatasourceStructure.Template("UPDATE", "UPDATE public.\"users\" SET\n" + - " \"username\" = '',\n" + - " \"password\" = '',\n" + - " \"email\" = '',\n" + - " \"spouse_dob\" = '2019-07-01',\n" + - " \"dob\" = '2019-07-01',\n" + - " \"time1\" = '18:32:45',\n" + - " \"time_tz\" = '04:05:06 PST',\n" + - " \"created_on\" = TIMESTAMP '2019-07-01 10:00:00',\n" + - " \"created_on_tz\" = TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET',\n" + - " \"interval1\" = 1,\n" + - " \"numbers\" = '{1, 2, 3}',\n" + - " \"texts\" = '{\"first\", \"second\"}',\n" + - " \"rating\" = 1.0\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM public.\"users\"\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), + new DatasourceStructure.Template[] { + new DatasourceStructure.Template("SELECT", "SELECT * FROM public.\"users\" LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO public.\"users\" " + + "(\"username\", \"password\", \"email\", \"spouse_dob\", \"dob\", " + + "\"time1\", \"time_tz\", \"created_on\", \"created_on_tz\", " + + "\"interval1\", \"numbers\", \"texts\", \"rating\")\n " + + "VALUES ('', '', '', '2019-07-01', '2019-07-01', '18:32:45', " + + "'04:05:06 PST', TIMESTAMP '2019-07-01 10:00:00', TIMESTAMP WITH TIME ZONE " + + "'2019-07-01 06:30:00 CET', 1, '{1, 2, 3}', '{\"first\", \"second\"}', 1.0);"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE public.\"users\" SET\n" + " \"username\" = '',\n" + + " \"password\" = '',\n" + + " \"email\" = '',\n" + + " \"spouse_dob\" = '2019-07-01',\n" + + " \"dob\" = '2019-07-01',\n" + + " \"time1\" = '18:32:45',\n" + + " \"time_tz\" = '04:05:06 PST',\n" + + " \"created_on\" = TIMESTAMP '2019-07-01 10:00:00',\n" + + " \"created_on_tz\" = TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET',\n" + + " \"interval1\" = 1,\n" + + " \"numbers\" = '{1, 2, 3}',\n" + + " \"texts\" = '{\"first\", \"second\"}',\n" + + " \"rating\" = 1.0\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM public.\"users\"\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), }, - usersTable.getTemplates().toArray() - ); + usersTable.getTemplates().toArray()); - final DatasourceStructure.Table sampleTable = structure.getTables().get(3); + final DatasourceStructure.Table sampleTable = + structure.getTables().get(3); assertEquals("sample_schema.sample_table", sampleTable.getName()); assertEquals("sample_schema", sampleTable.getSchema()); assertEquals(DatasourceStructure.TableType.TABLE, sampleTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "int4", "nextval('sample_schema.sample_table_id_seq'::regclass)", true), - new DatasourceStructure.Column("username", "varchar", null, false), - new DatasourceStructure.Column("email", "varchar", null, false), - new DatasourceStructure.Column("numbers", "_int4", null, false), - new DatasourceStructure.Column("texts", "_varchar", null, false), - new DatasourceStructure.Column("rating", "float4", null, false), + new DatasourceStructure.Column[] { + new DatasourceStructure.Column( + "id", "int4", "nextval('sample_schema.sample_table_id_seq'::regclass)", true), + new DatasourceStructure.Column("username", "varchar", null, false), + new DatasourceStructure.Column("email", "varchar", null, false), + new DatasourceStructure.Column("numbers", "_int4", null, false), + new DatasourceStructure.Column("texts", "_varchar", null, false), + new DatasourceStructure.Column("rating", "float4", null, false), }, - sampleTable.getColumns().toArray() - ); + sampleTable.getColumns().toArray()); - final DatasourceStructure.PrimaryKey samplePrimaryKey = new DatasourceStructure.PrimaryKey("sample_table_pkey", new ArrayList<>()); + final DatasourceStructure.PrimaryKey samplePrimaryKey = + new DatasourceStructure.PrimaryKey("sample_table_pkey", new ArrayList<>()); samplePrimaryKey.getColumnNames().add("id"); assertArrayEquals( - new DatasourceStructure.Key[]{samplePrimaryKey}, - sampleTable.getKeys().toArray() - ); + new DatasourceStructure.Key[] {samplePrimaryKey}, + sampleTable.getKeys().toArray()); assertArrayEquals( - new DatasourceStructure.Template[]{ - new DatasourceStructure.Template("SELECT", "SELECT * FROM sample_schema.\"sample_table\" LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO sample_schema.\"sample_table\" " + - "(\"username\", \"email\", \"numbers\", \"texts\", \"rating\")\n " + - "VALUES ('', '', '{1, 2, 3}', '{\"first\", \"second\"}', 1.0);"), - new DatasourceStructure.Template("UPDATE", "UPDATE sample_schema.\"sample_table\" SET\n" + - " \"username\" = '',\n" + - " \"email\" = '',\n" + - " \"numbers\" = '{1, 2, 3}',\n" + - " \"texts\" = '{\"first\", \"second\"}',\n" + - " \"rating\" = 1.0\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM sample_schema.\"sample_table\"\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), + new DatasourceStructure.Template[] { + new DatasourceStructure.Template( + "SELECT", "SELECT * FROM sample_schema.\"sample_table\" LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO sample_schema.\"sample_table\" " + + "(\"username\", \"email\", \"numbers\", \"texts\", \"rating\")\n " + + "VALUES ('', '', '{1, 2, 3}', '{\"first\", \"second\"}', 1.0);"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE sample_schema.\"sample_table\" SET\n" + " \"username\" = '',\n" + + " \"email\" = '',\n" + + " \"numbers\" = '{1, 2, 3}',\n" + + " \"texts\" = '{\"first\", \"second\"}',\n" + + " \"rating\" = 1.0\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM sample_schema.\"sample_table\"\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), }, - sampleTable.getTemplates().toArray() - ); + sampleTable.getTemplates().toArray()); }) .verifyComplete(); } @@ -683,11 +676,10 @@ public void testStaleConnectionCheck() { Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> { - pool.close(); - return pluginExecutor.executeParameterized(pool, new ExecuteActionDTO(), dsConfig, actionConfiguration); - }); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap(pool -> { + pool.close(); + return pluginExecutor.executeParameterized(pool, new ExecuteActionDTO(), dsConfig, actionConfiguration); + }); StepVerifier.create(resultMono) .expectErrorMatches(throwable -> throwable instanceof StaleConnectionException) @@ -716,14 +708,14 @@ public void testPreparedStatementWithoutQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { - assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); @@ -731,38 +723,41 @@ public void testPreparedStatementWithoutQuotes() { assertEquals("18:32:45", node.get("time1").asText()); assertEquals("04:05:06-08", node.get("time_tz").asText()); assertEquals("2018-11-30T20:45:15Z", node.get("created_on").asText()); - assertEquals("2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); - assertEquals("1 years 5 mons 0 days 2 hours 0 mins 0.0 secs", node.get("interval1").asText()); + assertEquals( + "2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); + assertEquals( + "1 years 5 mons 0 days 2 hours 0 mins 0.0 secs", + node.get("interval1").asText()); assertTrue(node.get("spouse_dob").isNull()); assertEquals(1.0, node.get("rating").asDouble(), 0.0); // Check the order of the columns. assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", - "time_tz", - "created_on", - "created_on_tz", - "interval1", - "numbers", - "texts", - "rating" + new String[] { + "id", + "username", + "password", + "email", + "spouse_dob", + "dob", + "time1", + "time_tz", + "created_on", + "created_on_tz", + "interval1", + "numbers", + "texts", + "rating" }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); // Assert the debug request parameters are getting set. ActionExecutionRequest request = result.getRequest(); - List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) request.getProperties().get("ps-parameters"); + List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) + request.getProperties().get("ps-parameters"); assertEquals(parameters.size(), 1); Map.Entry<String, String> parameterEntry = parameters.get(0); assertEquals(parameterEntry.getKey(), "1"); @@ -791,14 +786,14 @@ public void testPreparedStatementWithDoubleQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { - assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); @@ -806,33 +801,35 @@ public void testPreparedStatementWithDoubleQuotes() { assertEquals("18:32:45", node.get("time1").asText()); assertEquals("04:05:06-08", node.get("time_tz").asText()); assertEquals("2018-11-30T20:45:15Z", node.get("created_on").asText()); - assertEquals("2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); - assertEquals("1 years 5 mons 0 days 2 hours 0 mins 0.0 secs", node.get("interval1").asText()); + assertEquals( + "2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); + assertEquals( + "1 years 5 mons 0 days 2 hours 0 mins 0.0 secs", + node.get("interval1").asText()); assertTrue(node.get("spouse_dob").isNull()); // Check the order of the columns. assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", - "time_tz", - "created_on", - "created_on_tz", - "interval1", - "numbers", - "texts", - "rating" + new String[] { + "id", + "username", + "password", + "email", + "spouse_dob", + "dob", + "time1", + "time_tz", + "created_on", + "created_on_tz", + "interval1", + "numbers", + "texts", + "rating" }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); /* * - Check if request params are sent back properly. @@ -841,12 +838,15 @@ public void testPreparedStatementWithDoubleQuotes() { */ // check if '?' is replaced by $i. - assertEquals("SELECT * FROM public.\"users\" where id = $1;", + assertEquals( + "SELECT * FROM public.\"users\" where id = $1;", ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getValue()); PsParameterDTO expectedPsParam = new PsParameterDTO("1", "INTEGER"); - PsParameterDTO returnedPsParam = - (PsParameterDTO) ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)).getSubstitutedParams().get("$1"); + PsParameterDTO returnedPsParam = (PsParameterDTO) + ((RequestParamDTO) (((List) result.getRequest().getRequestParams())).get(0)) + .getSubstitutedParams() + .get("$1"); // Check if prepared stmt param value is correctly sent back. assertEquals(expectedPsParam.getValue(), returnedPsParam.getValue()); // check if prepared stmt param type is correctly sent back. @@ -875,14 +875,14 @@ public void testPreparedStatementWithSingleQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { - assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); @@ -890,34 +890,35 @@ public void testPreparedStatementWithSingleQuotes() { assertEquals("18:32:45", node.get("time1").asText()); assertEquals("04:05:06-08", node.get("time_tz").asText()); assertEquals("2018-11-30T20:45:15Z", node.get("created_on").asText()); - assertEquals("2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); - assertEquals("1 years 5 mons 0 days 2 hours 0 mins 0.0 secs", node.get("interval1").asText()); + assertEquals( + "2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); + assertEquals( + "1 years 5 mons 0 days 2 hours 0 mins 0.0 secs", + node.get("interval1").asText()); assertTrue(node.get("spouse_dob").isNull()); // Check the order of the columns. assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", - "time_tz", - "created_on", - "created_on_tz", - "interval1", - "numbers", - "texts", - "rating" + new String[] { + "id", + "username", + "password", + "email", + "spouse_dob", + "dob", + "time1", + "time_tz", + "created_on", + "created_on_tz", + "interval1", + "numbers", + "texts", + "rating" }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); - + .toArray()); }) .verifyComplete(); } @@ -927,20 +928,19 @@ public void testPreparedStatementWithNullStringValue() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("UPDATE public.\"users\" set " + - "username = {{binding1}}, " + - "password = {{binding1}},\n" + - "email = {{binding1}},\n" + - "spouse_dob = {{binding1}},\n" + - "dob = {{binding1}},\n" + - "time1 = {{binding1}},\n" + - "time_tz = {{binding1}},\n" + - "created_on = {{binding1}},\n" + - "created_on_tz = {{binding1}},\n" + - "interval1 = {{binding1}},\n" + - "numbers = {{binding1}},\n" + - "texts = {{binding1}}" + - " where id = 2;"); + actionConfiguration.setBody("UPDATE public.\"users\" set " + "username = {{binding1}}, " + + "password = {{binding1}},\n" + + "email = {{binding1}},\n" + + "spouse_dob = {{binding1}},\n" + + "dob = {{binding1}},\n" + + "time1 = {{binding1}},\n" + + "time_tz = {{binding1}},\n" + + "created_on = {{binding1}},\n" + + "created_on_tz = {{binding1}},\n" + + "interval1 = {{binding1}},\n" + + "numbers = {{binding1}},\n" + + "texts = {{binding1}}" + + " where id = 2;"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -955,10 +955,11 @@ public void testPreparedStatementWithNullStringValue() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -967,8 +968,8 @@ public void testPreparedStatementWithNullStringValue() { .verifyComplete(); actionConfiguration.setBody("SELECT * FROM public.\"users\" where id = 2;"); - resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -992,20 +993,19 @@ public void testPreparedStatementWithNullValue() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("UPDATE public.\"users\" set " + - "username = {{binding1}}, " + - "password = {{binding1}},\n" + - "email = {{binding1}},\n" + - "spouse_dob = {{binding1}},\n" + - "dob = {{binding1}},\n" + - "time1 = {{binding1}},\n" + - "time_tz = {{binding1}},\n" + - "created_on = {{binding1}},\n" + - "created_on_tz = {{binding1}},\n" + - "interval1 = {{binding1}},\n" + - "numbers = {{binding1}},\n" + - "texts = {{binding1}}" + - " where id = 3;"); + actionConfiguration.setBody("UPDATE public.\"users\" set " + "username = {{binding1}}, " + + "password = {{binding1}},\n" + + "email = {{binding1}},\n" + + "spouse_dob = {{binding1}},\n" + + "dob = {{binding1}},\n" + + "time1 = {{binding1}},\n" + + "time_tz = {{binding1}},\n" + + "created_on = {{binding1}},\n" + + "created_on_tz = {{binding1}},\n" + + "interval1 = {{binding1}},\n" + + "numbers = {{binding1}},\n" + + "texts = {{binding1}}" + + " where id = 3;"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -1020,10 +1020,11 @@ public void testPreparedStatementWithNullValue() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1032,8 +1033,8 @@ public void testPreparedStatementWithNullValue() { .verifyComplete(); actionConfiguration.setBody("SELECT * FROM public.\"users\" where id = 3;"); - resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1057,16 +1058,13 @@ public void testSslToggleMissingError() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); datasourceConfiguration.getConnection().getSsl().setAuthType(null); - Mono<Set<String>> invalidsMono = Mono.just(pluginExecutor) - .map(executor -> executor.validateDatasource(datasourceConfiguration)); - + Mono<Set<String>> invalidsMono = + Mono.just(pluginExecutor).map(executor -> executor.validateDatasource(datasourceConfiguration)); StepVerifier.create(invalidsMono) .assertNext(invalids -> { - assertTrue(invalids - .stream() - .anyMatch(error -> PostgresErrorMessages.SSL_CONFIGURATION_ERROR_MSG.equals(error)) - ); + assertTrue(invalids.stream() + .anyMatch(error -> PostgresErrorMessages.SSL_CONFIGURATION_ERROR_MSG.equals(error))); }) .verifyComplete(); } @@ -1079,9 +1077,8 @@ public void testSslDefault() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.DEFAULT); Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { String body = result.getBody().toString(); @@ -1098,9 +1095,8 @@ public void testSslDisable() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.DISABLE); Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { String body = result.getBody().toString(); @@ -1117,17 +1113,17 @@ public void testSslRequire() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.REQUIRE); Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, - actionConfiguration)); - StepVerifier.create(executeMono) - .verifyErrorSatisfies(error -> { - /* - * - This error message indicates that the client was trying to establish an SSL connection but - * could not because the testcontainer server does not have SSL enabled. - */ - assertTrue(((AppsmithPluginException) error).getDownstreamErrorMessage().contains("The server does not support SSL")); - }); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono).verifyErrorSatisfies(error -> { + /* + * - This error message indicates that the client was trying to establish an SSL connection but + * could not because the testcontainer server does not have SSL enabled. + */ + assertTrue(((AppsmithPluginException) error) + .getDownstreamErrorMessage() + .contains("The server does not support SSL")); + }); } @Test @@ -1138,9 +1134,8 @@ public void testSslPrefer() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.PREFER); Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { String body = result.getBody().toString(); @@ -1161,9 +1156,8 @@ public void testSslAllow() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.ALLOW); Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, - actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { String body = result.getBody().toString(); @@ -1188,25 +1182,22 @@ public void testDuplicateColumnNames() { pluginSpecifiedTemplates.add(new Property("preparedStatement", "false")); actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { assertNotEquals(0, result.getMessages().size()); - String expectedMessage = "Your PostgreSQL query result may not have all the columns because " + - "duplicate column names were found for the column(s)"; - assertTrue( - result.getMessages().stream() - .anyMatch(message -> message.contains(expectedMessage)) - ); + String expectedMessage = "Your PostgreSQL query result may not have all the columns because " + + "duplicate column names were found for the column(s)"; + assertTrue(result.getMessages().stream().anyMatch(message -> message.contains(expectedMessage))); /* * - Check if all the duplicate column names are reported. */ - Set<String> expectedColumnNames = Stream.of("id", "password") - .collect(Collectors.toCollection(HashSet::new)); + Set<String> expectedColumnNames = + Stream.of("id", "password").collect(Collectors.toCollection(HashSet::new)); Set<String> foundColumnNames = new HashSet<>(); result.getMessages().stream() .filter(message -> message.contains(expectedMessage)) @@ -1224,9 +1215,7 @@ public void testTimestampPreparedStatement() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("UPDATE public.\"users\" set " + - "created_on = {{binding1}}\n" + - " where id = 3;"); + actionConfiguration.setBody("UPDATE public.\"users\" set " + "created_on = {{binding1}}\n" + " where id = 3;"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -1241,10 +1230,11 @@ public void testTimestampPreparedStatement() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1253,8 +1243,8 @@ public void testTimestampPreparedStatement() { .verifyComplete(); actionConfiguration.setBody("SELECT * FROM public.\"users\" where id = 3;"); - resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1286,10 +1276,11 @@ public void testSettingCommentedBindingPreparedStatement() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1304,8 +1295,8 @@ public void testDataTypes() { actionConfiguration.setBody("SELECT * FROM dataTypeTest"); DatasourceConfiguration dsConfig = createDatasourceConfiguration(); Mono<HikariDataSource> connectionPoolMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> resultMono = connectionPoolMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionPoolMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1315,7 +1306,8 @@ public void testDataTypes() { final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertEquals("racket", node.get("item").get("type").asText()); - assertEquals("butterfly", node.get("item").get("manufacturer").asText()); + assertEquals( + "butterfly", node.get("item").get("manufacturer").asText()); assertEquals("japan", node.get("origin").get("country").asText()); assertEquals("kyoto", node.get("origin").get("city").asText()); assertEquals("A Lincoln", node.get("citextdata").asText()); @@ -1329,7 +1321,8 @@ public void testPreparedStatementWithExplicitTypeCasting() { ActionConfiguration actionConfiguration = new ActionConfiguration(); - String query = "INSERT INTO users (id, username, password, email, dob, rating) VALUES ({{id}}, {{firstName}}::varchar, {{lastName}}, {{email}}, {{date}}::date, {{rating}})"; + String query = + "INSERT INTO users (id, username, password, email, dob, rating) VALUES ({{id}}, {{firstName}}::varchar, {{lastName}}, {{email}}, {{date}}::date, {{rating}})"; actionConfiguration.setBody(query); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); @@ -1364,19 +1357,20 @@ public void testPreparedStatementWithExplicitTypeCasting() { executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { - assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertEquals(node.get("affectedRows").asText(), "1"); - List<RequestParamDTO> requestParams = (List<RequestParamDTO>) result.getRequest().getRequestParams(); + List<RequestParamDTO> requestParams = + (List<RequestParamDTO>) result.getRequest().getRequestParams(); RequestParamDTO requestParamDTO = requestParams.get(0); Map<String, Object> substitutedParams = requestParamDTO.getSubstitutedParams(); for (Map.Entry<String, Object> substitutedParam : substitutedParams.entrySet()) { @@ -1397,13 +1391,14 @@ public void testPreparedStatementWithExplicitTypeCasting() { break; } } - }) .verifyComplete(); actionConfiguration.setBody("SELECT * FROM public.\"users\" WHERE id=10;"); final ActionExecutionResult actionExecutionResult = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)).block(); + .flatMap(pool -> + pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)) + .block(); // Check that precision for decimal value is maintained assert actionExecutionResult != null; @@ -1413,8 +1408,9 @@ public void testPreparedStatementWithExplicitTypeCasting() { // Delete the newly added row to not affect any other test case actionConfiguration.setBody("DELETE FROM users WHERE id = 10"); connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)).block(); - + .flatMap(pool -> + pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)) + .block(); } @Test @@ -1422,9 +1418,8 @@ public void testPreparedStatementWithTimeZoneTimeStamp() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody("UPDATE public.\"users\" set " + - "created_on_tz = {{createdTS}}\n" + - " where id = 3;"); + actionConfiguration.setBody( + "UPDATE public.\"users\" set " + "created_on_tz = {{createdTS}}\n" + " where id = 3;"); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); pluginSpecifiedTemplates.add(new Property("preparedStatement", "true")); @@ -1438,10 +1433,11 @@ public void testPreparedStatementWithTimeZoneTimeStamp() { executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1450,15 +1446,15 @@ public void testPreparedStatementWithTimeZoneTimeStamp() { .verifyComplete(); actionConfiguration.setBody("SELECT * FROM public.\"users\" where id = 3;"); - resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); - assertEquals(node.get("created_on_tz").asText(), "2022-04-11T05:30:00Z"); //UTC time + assertEquals(node.get("created_on_tz").asText(), "2022-04-11T05:30:00Z"); // UTC time }) .verifyComplete(); } @@ -1468,13 +1464,11 @@ public void testReadOnlyMode() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getConnection().setMode(com.appsmith.external.models.Connection.Mode.READ_ONLY); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setBody( - "UPDATE public.\"users\" set created_on = '2021-03-24 14:05:34' where id = 3;" - ); + actionConfiguration.setBody("UPDATE public.\"users\" set created_on = '2021-03-24 14:05:34' where id = 3;"); Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap(conn -> + pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -1492,7 +1486,8 @@ public void testPreparedStatementWithJsonDataType() { ActionConfiguration actionConfiguration = new ActionConfiguration(); - String query = "INSERT INTO dataTypeTest VALUES ({{id}}, {{jsonObject1}}::json, {{jsonObject2}}::json, {{stringValue}})"; + String query = + "INSERT INTO dataTypeTest VALUES ({{id}}, {{jsonObject1}}::json, {{jsonObject2}}::json, {{stringValue}})"; actionConfiguration.setBody(query); List<Property> pluginSpecifiedTemplates = new ArrayList<>(); @@ -1519,19 +1514,20 @@ public void testPreparedStatementWithJsonDataType() { executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { - assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertEquals(node.get("affectedRows").asText(), "1"); - List<RequestParamDTO> requestParams = (List<RequestParamDTO>) result.getRequest().getRequestParams(); + List<RequestParamDTO> requestParams = + (List<RequestParamDTO>) result.getRequest().getRequestParams(); RequestParamDTO requestParamDTO = requestParams.get(0); Map<String, Object> substitutedParams = requestParamDTO.getSubstitutedParams(); for (Map.Entry<String, Object> substitutedParam : substitutedParams.entrySet()) { @@ -1550,15 +1546,15 @@ public void testPreparedStatementWithJsonDataType() { break; } } - }) .verifyComplete(); // Delete the newly added row to not affect any other test case actionConfiguration.setBody("DELETE FROM users dataTypeTest id = 10"); connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)).block(); - + .flatMap(pool -> + pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)) + .block(); } @Test @@ -1581,19 +1577,18 @@ public void testNumericStringHavingLeadingZeroWithPreparedStatement() { params.add(param1); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = + pluginExecutor.datasourceCreate(dsConfig).cache(); - Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = connectionCreateMono.flatMap( + pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); final JsonNode node = ((ArrayNode) result.getBody()).get(0); assertArrayEquals( - new String[]{ - "numeric_string" - }, + new String[] {"numeric_string"}, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() @@ -1602,18 +1597,23 @@ public void testNumericStringHavingLeadingZeroWithPreparedStatement() { // Verify value assertEquals(JsonNodeType.STRING, node.get("numeric_string").getNodeType()); assertEquals(param1.getValue(), node.get("numeric_string").asText()); - }) .verifyComplete(); } @Test public void verifyUniquenessOfPostgresPluginErrorCode() { - assert (Arrays.stream(PostgresPluginError.values()).map(PostgresPluginError::getAppErrorCode).distinct().count() == PostgresPluginError.values().length); - - assert (Arrays.stream(PostgresPluginError.values()).map(PostgresPluginError::getAppErrorCode) - .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-PGS")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(PostgresPluginError.values()) + .map(PostgresPluginError::getAppErrorCode) + .distinct() + .count() + == PostgresPluginError.values().length); + + assert (Arrays.stream(PostgresPluginError.values()) + .map(PostgresPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-PGS")) + .collect(Collectors.toList()) + .size() + == 0); } } diff --git a/app/server/appsmith-plugins/redisPlugin/pom.xml b/app/server/appsmith-plugins/redisPlugin/pom.xml index 94220dea9b91..50f697cccf30 100644 --- a/app/server/appsmith-plugins/redisPlugin/pom.xml +++ b/app/server/appsmith-plugins/redisPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>redisPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -41,10 +40,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java index a0606442ecfa..53691fa1ae01 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java +++ b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java @@ -50,6 +50,7 @@ public class RedisPlugin extends BasePlugin { private static final int CONNECTION_TIMEOUT = 60; private static final String CMD_KEY = "cmd"; private static final String ARGS_KEY = "args"; + public RedisPlugin(PluginWrapper wrapper) { super(wrapper); } @@ -60,34 +61,36 @@ public static class RedisPluginExecutor implements PluginExecutor<JedisPool> { private final Scheduler scheduler = Schedulers.boundedElastic(); @Override - public Mono<ActionExecutionResult> execute(JedisPool jedisPool, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + JedisPool jedisPool, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { String query = actionConfiguration.getBody(); - List<RequestParamDTO> requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null - , null, null)); + List<RequestParamDTO> requestParams = + List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null)); Jedis jedis; try { - jedis = jedisPool.getResource(); + jedis = jedisPool.getResource(); } catch (Exception e) { - return Mono.error(new AppsmithPluginException(RedisPluginError.QUERY_EXECUTION_FAILED, RedisErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + RedisPluginError.QUERY_EXECUTION_FAILED, + RedisErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage())); } return Mono.fromCallable(() -> { if (StringUtils.isNullOrEmpty(query)) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, String.format(RedisErrorMessages.BODY_IS_NULL_OR_EMPTY_ERROR_MSG, query))); } Map cmdAndArgs = getCommandAndArgs(query.trim()); if (!cmdAndArgs.containsKey(CMD_KEY)) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - RedisErrorMessages.QUERY_PARSING_FAILED_ERROR_MSG - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + RedisErrorMessages.QUERY_PARSING_FAILED_ERROR_MSG)); } Protocol.Command command; @@ -95,8 +98,11 @@ public Mono<ActionExecutionResult> execute(JedisPool jedisPool, // Commands are in upper case command = Protocol.Command.valueOf((String) cmdAndArgs.get(CMD_KEY)); } catch (IllegalArgumentException exc) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - String.format(RedisErrorMessages.INVALID_REDIS_COMMAND_ERROR_MSG, cmdAndArgs.get(CMD_KEY)))); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format( + RedisErrorMessages.INVALID_REDIS_COMMAND_ERROR_MSG, + cmdAndArgs.get(CMD_KEY)))); } Object commandOutput; @@ -107,7 +113,8 @@ public Mono<ActionExecutionResult> execute(JedisPool jedisPool, } ActionExecutionResult actionExecutionResult = new ActionExecutionResult(); - actionExecutionResult.setBody(objectMapper.valueToTree(removeQuotes(processCommandOutput(commandOutput)))); + actionExecutionResult.setBody( + objectMapper.valueToTree(removeQuotes(processCommandOutput(commandOutput)))); actionExecutionResult.setIsExecutionSuccess(true); log.debug("In the RedisPlugin, got action execution result"); @@ -119,8 +126,11 @@ public Mono<ActionExecutionResult> execute(JedisPool jedisPool, error.printStackTrace(); ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); - if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(RedisPluginError.QUERY_EXECUTION_FAILED, RedisErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error.getMessage()); + if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + RedisPluginError.QUERY_EXECUTION_FAILED, + RedisErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error.getMessage()); } result.setErrorInfo(error); return Mono.just(result); @@ -159,13 +169,12 @@ private Object removeQuotes(Object result) { if (result instanceof String) { return ((String) result).replaceAll("^\\\"|^'|\\\"$|'$", ""); } else if (result instanceof Collection) { - return ((Collection) result).stream() - .map(this::removeQuotes) - .collect(Collectors.toList()); + return ((Collection) result).stream().map(this::removeQuotes).collect(Collectors.toList()); } else if (result instanceof Map) { - return ((Map<String, Object>) result).entrySet().stream() - .map(item -> Map.entry(item.getKey(), removeQuotes(item.getValue()))) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return ((Map<String, Object>) result) + .entrySet().stream() + .map(item -> Map.entry(item.getKey(), removeQuotes(item.getValue()))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } return result; @@ -243,7 +252,8 @@ private JedisPoolConfig buildPoolConfig() { public Mono<JedisPool> datasourceCreate(DatasourceConfiguration datasourceConfiguration) { return Mono.fromCallable(() -> { final JedisPoolConfig poolConfig = buildPoolConfig(); - int timeout = (int) Duration.ofSeconds(CONNECTION_TIMEOUT).toMillis(); + int timeout = + (int) Duration.ofSeconds(CONNECTION_TIMEOUT).toMillis(); URI uri = RedisURIUtils.getURI(datasourceConfiguration); JedisPool jedisPool = new JedisPool(poolConfig, uri, timeout); return jedisPool; @@ -274,16 +284,12 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur Set<String> invalids = new HashSet<>(); if (isEndpointMissing(datasourceConfiguration.getEndpoints())) { - invalids.add( - RedisErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG - ); + invalids.add(RedisErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG); } DBAuth auth = (DBAuth) datasourceConfiguration.getAuthentication(); if (isAuthenticationMissing(auth)) { - invalids.add( - RedisErrorMessages.DS_MISSING_PASSWORD_ERROR_MSG - ); + invalids.add(RedisErrorMessages.DS_MISSING_PASSWORD_ERROR_MSG); } return invalids; @@ -343,9 +349,8 @@ public Mono<DatasourceTestResult> testDatasource(JedisPool connectionPool) { return Mono.just(connectionPool) .flatMap(c -> verifyPing(connectionPool)) .then(Mono.just(new DatasourceTestResult())) - .onErrorResume(error -> Mono.just(new DatasourceTestResult(error.getCause().getMessage()))); - + .onErrorResume(error -> + Mono.just(new DatasourceTestResult(error.getCause().getMessage()))); } - } } diff --git a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/exceptions/RedisErrorMessages.java b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/exceptions/RedisErrorMessages.java index bd464ff4baaa..f453323f31d4 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/exceptions/RedisErrorMessages.java +++ b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/exceptions/RedisErrorMessages.java @@ -8,23 +8,25 @@ public class RedisErrorMessages extends BasePluginErrorMessages { public static final String BODY_IS_NULL_OR_EMPTY_ERROR_MSG = "Body is null or empty [%s]"; - public static final String QUERY_PARSING_FAILED_ERROR_MSG = "Appsmith server has failed to parse your Redis query. Are you sure it's" + - " been formatted correctly."; + public static final String QUERY_PARSING_FAILED_ERROR_MSG = + "Appsmith server has failed to parse your Redis query. Are you sure it's" + " been formatted correctly."; public static final String INVALID_REDIS_COMMAND_ERROR_MSG = "Not a valid Redis command: %s"; public static final String NO_PONG_RESPONSE_ERROR_MSG = "Expected PONG in response of PING but got %s"; - public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Error occurred while executing Redis query. To know more about the error please check the error details."; + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = + "Error occurred while executing Redis query. To know more about the error please check the error details."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ - public static final String DS_MISSING_HOST_ADDRESS_ERROR_MSG = "Could not find host address. Please edit the 'Host address' field to provide the desired " + - "endpoint."; + public static final String DS_MISSING_HOST_ADDRESS_ERROR_MSG = + "Could not find host address. Please edit the 'Host address' field to provide the desired " + "endpoint."; - public static final String DS_MISSING_PASSWORD_ERROR_MSG = "Could not find password. Please edit the 'Password' field to provide the password."; + public static final String DS_MISSING_PASSWORD_ERROR_MSG = + "Could not find password. Please edit the 'Password' field to provide the password."; } diff --git a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/exceptions/RedisPluginError.java b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/exceptions/RedisPluginError.java index 1b122737c220..1e686f6b380e 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/exceptions/RedisPluginError.java +++ b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/exceptions/RedisPluginError.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum RedisPluginError implements BasePluginError { QUERY_EXECUTION_FAILED( @@ -16,9 +15,7 @@ public enum RedisPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ) - ; + "{2}"); private final Integer httpErrorCode; private final String appErrorCode; @@ -31,8 +28,15 @@ public enum RedisPluginError implements BasePluginError { private final String downstreamErrorCode; - RedisPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + RedisPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -59,5 +63,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java b/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java index aed1208bc6a7..38860c177ede 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java +++ b/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java @@ -37,8 +37,9 @@ @Testcontainers public class RedisPluginTest { @Container - public static final GenericContainer redis = new GenericContainer(DockerImageName.parse("redis:6.2.0-alpine")) - .withExposedPorts(6379); + public static final GenericContainer redis = + new GenericContainer(DockerImageName.parse("redis:6.2.0-alpine")).withExposedPorts(6379); + private static String host; private static Integer port; @@ -66,9 +67,7 @@ public void itShouldCreateDatasource() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); Mono<JedisPool> jedisPoolMono = pluginExecutor.datasourceCreate(datasourceConfiguration); - StepVerifier.create(jedisPoolMono) - .assertNext(Assertions::assertNotNull) - .verifyComplete(); + StepVerifier.create(jedisPoolMono).assertNext(Assertions::assertNotNull).verifyComplete(); pluginExecutor.datasourceDestroy(jedisPoolMono.block()); } @@ -77,7 +76,8 @@ public void itShouldCreateDatasource() { public void itShouldValidateDatasourceWithNoEndpoints() { DatasourceConfiguration invalidDatasourceConfiguration = new DatasourceConfiguration(); - assertEquals(Set.of(RedisErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG), + assertEquals( + Set.of(RedisErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG), pluginExecutor.validateDatasource(invalidDatasourceConfiguration)); } @@ -88,7 +88,8 @@ public void itShouldValidateDatasourceWithInvalidEndpoint() { Endpoint endpoint = new Endpoint(); invalidDatasourceConfiguration.setEndpoints(Collections.singletonList(endpoint)); - assertEquals(Set.of(RedisErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG), + assertEquals( + Set.of(RedisErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG), pluginExecutor.validateDatasource(invalidDatasourceConfiguration)); } @@ -118,9 +119,9 @@ public void itShouldValidateDatasourceWithInvalidAuth() { assertEquals( Set.of(RedisErrorMessages.DS_MISSING_PASSWORD_ERROR_MSG), - pluginExecutor.validateDatasource(invalidDatasourceConfiguration) - ); + pluginExecutor.validateDatasource(invalidDatasourceConfiguration)); } + @Test public void itShouldValidateDatasource() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); @@ -174,6 +175,7 @@ public void itShouldThrowErrorIfHostnameIsInvalid() { }) .verifyComplete(); } + @Test public void itShouldThrowErrorIfEmptyBody() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); @@ -181,8 +183,8 @@ public void itShouldThrowErrorIfEmptyBody() { ActionConfiguration actionConfiguration = new ActionConfiguration(); - Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono - .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono.flatMap( + jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(result -> { @@ -201,8 +203,8 @@ public void itShouldThrowErrorIfInvalidRedisCommand() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("LOL"); - Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono - .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono.flatMap( + jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(result -> { @@ -221,8 +223,8 @@ public void itShouldExecuteCommandWithoutArgs() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("PING"); - Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono - .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono.flatMap( + jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { @@ -230,7 +232,8 @@ public void itShouldExecuteCommandWithoutArgs() { assertNotNull(actionExecutionResult.getBody()); final JsonNode node = ((ArrayNode) actionExecutionResult.getBody()).get(0); assertEquals("PONG", node.get("result").asText()); - }).verifyComplete(); + }) + .verifyComplete(); } @Test @@ -241,9 +244,8 @@ public void itShouldExecuteCommandWithArgs() { // Getting a non-existent key ActionConfiguration getActionConfiguration = new ActionConfiguration(); getActionConfiguration.setBody("GET key"); - Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono - .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, - getActionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono.flatMap( + jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, getActionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { assertNotNull(actionExecutionResult); @@ -251,40 +253,43 @@ public void itShouldExecuteCommandWithArgs() { final JsonNode node = ((ArrayNode) actionExecutionResult.getBody()).get(0); assertEquals("null", node.get("result").asText()); - /* - Adding only in this test as the query editor form for Redis plugin is exactly same for each * query type. Hence, checking with only one query should suffice. * - RequestParamDTO object only have attributes configProperty and value at this point. * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - getActionConfiguration.getBody(), null, null, null)); - assertEquals(actionExecutionResult.getRequest().getRequestParams().toString(), + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, getActionConfiguration.getBody(), null, null, null)); + assertEquals( + actionExecutionResult + .getRequest() + .getRequestParams() + .toString(), expectedRequestParams.toString()); - }).verifyComplete(); + }) + .verifyComplete(); // Set keys ActionConfiguration setActionConfigurationManyKeys = new ActionConfiguration(); - setActionConfigurationManyKeys.setBody("mset key1 value key2 \"value\" key3 \"my value\" key4 'value' key5 'my " + - "value' key6 '{\"a\":\"b\"}'"); - actionExecutionResultMono = jedisPoolMono - .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, - setActionConfigurationManyKeys)); + setActionConfigurationManyKeys.setBody("mset key1 value key2 \"value\" key3 \"my value\" key4 'value' key5 'my " + + "value' key6 '{\"a\":\"b\"}'"); + actionExecutionResultMono = jedisPoolMono.flatMap(jedisPool -> + pluginExecutor.execute(jedisPool, datasourceConfiguration, setActionConfigurationManyKeys)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { assertNotNull(actionExecutionResult); assertNotNull(actionExecutionResult.getBody()); final JsonNode node = ((ArrayNode) actionExecutionResult.getBody()).get(0); assertEquals("OK", node.get("result").asText()); - }).verifyComplete(); + }) + .verifyComplete(); // Verify the keys ActionConfiguration getActionConfigurationManyKeys = new ActionConfiguration(); getActionConfigurationManyKeys.setBody("mget key1 key2 key3 key4 key5 key6"); - actionExecutionResultMono = jedisPoolMono - .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, - getActionConfigurationManyKeys)); + actionExecutionResultMono = jedisPoolMono.flatMap(jedisPool -> + pluginExecutor.execute(jedisPool, datasourceConfiguration, getActionConfigurationManyKeys)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { assertNotNull(actionExecutionResult); @@ -296,7 +301,8 @@ public void itShouldExecuteCommandWithArgs() { assertEquals("value", node.get(3).get("result").asText()); assertEquals("my value", node.get(4).get("result").asText()); assertEquals("{\"a\":\"b\"}", node.get(5).get("result").asText()); - }).verifyComplete(); + }) + .verifyComplete(); } @Test @@ -310,8 +316,8 @@ public void testSelectedDatabase() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("CLIENT INFO"); - Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono - .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono.flatMap( + jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { @@ -319,7 +325,8 @@ public void testSelectedDatabase() { assertNotNull(actionExecutionResult.getBody()); final JsonNode node = ((ArrayNode) actionExecutionResult.getBody()).get(0); assertTrue(node.get("result").asText().contains("db=7")); - }).verifyComplete(); + }) + .verifyComplete(); } @Test @@ -332,8 +339,8 @@ public void testDefaultDatabase() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("CLIENT INFO"); - Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono - .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); + Mono<ActionExecutionResult> actionExecutionResultMono = jedisPoolMono.flatMap( + jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, actionConfiguration)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { @@ -341,16 +348,23 @@ public void testDefaultDatabase() { assertNotNull(actionExecutionResult.getBody()); final JsonNode node = ((ArrayNode) actionExecutionResult.getBody()).get(0); assertTrue(node.get("result").asText().contains("db=0")); - }).verifyComplete(); + }) + .verifyComplete(); } @Test public void verifyUniquenessOfRedisPluginErrorCode() { - assert (Arrays.stream(RedisPluginError.values()).map(RedisPluginError::getAppErrorCode).distinct().count() == RedisPluginError.values().length); - - assert (Arrays.stream(RedisPluginError.values()).map(RedisPluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-RDS")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(RedisPluginError.values()) + .map(RedisPluginError::getAppErrorCode) + .distinct() + .count() + == RedisPluginError.values().length); + + assert (Arrays.stream(RedisPluginError.values()) + .map(RedisPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-RDS")) + .collect(Collectors.toList()) + .size() + == 0); } } diff --git a/app/server/appsmith-plugins/redshiftPlugin/pom.xml b/app/server/appsmith-plugins/redshiftPlugin/pom.xml index 88a7b439b1c1..45fa9867f098 100644 --- a/app/server/appsmith-plugins/redshiftPlugin/pom.xml +++ b/app/server/appsmith-plugins/redshiftPlugin/pom.xml @@ -1,27 +1,19 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>redshiftPlugin</artifactId> <version>1.0-SNAPSHOT</version> <name>redshiftPlugin</name> - <repositories> - <repository> - <id>redshift</id> - <url>http://redshift-maven-repository.s3-website-us-east-1.amazonaws.com/release</url> - </repository> - </repositories> - <dependencies> <dependency> @@ -41,7 +33,6 @@ </exclusions> </dependency> - <!-- ******************* Test Dependencies ******************* --> <dependency> @@ -52,6 +43,13 @@ </dependency> </dependencies> + <repositories> + <repository> + <id>redshift</id> + <url>http://redshift-maven-repository.s3-website-us-east-1.amazonaws.com/release</url> + </repository> + </repositories> + <build> <plugins> <plugin> @@ -62,10 +60,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java index 98a83b590569..0c9bbfe81b19 100644 --- a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java +++ b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java @@ -70,70 +70,68 @@ public static class RedshiftPluginExecutor implements PluginExecutor<HikariDataS private final Scheduler scheduler = Schedulers.boundedElastic(); private static final String TABLES_QUERY = - "select a.attname as name,\n" + - " t1.typname as column_type,\n" + - " case when a.atthasdef then pg_get_expr(d.adbin, d.adrelid) end as default_expr,\n" + - " c.relkind as kind,\n" + - " c.relname as table_name,\n" + - " n.nspname as schema_name\n" + - "from pg_catalog.pg_attribute a\n" + - " left join pg_catalog.pg_type t1 on t1.oid = a.atttypid\n" + - " inner join pg_catalog.pg_class c on a.attrelid = c.oid\n" + - " left join pg_catalog.pg_namespace n on c.relnamespace = n.oid\n" + - " left join pg_catalog.pg_attrdef d on d.adrelid = c.oid and d.adnum = a.attnum\n" + - "where a.attnum > 0\n" + - " and not a.attisdropped\n" + - " and n.nspname not in ('information_schema', 'pg_catalog')\n" + - " and c.relkind in ('r', 'v')\n" + - " and pg_catalog.pg_table_is_visible(a.attrelid)\n" + - "order by c.relname, a.attnum;"; - - private static final String KEYS_QUERY_PRIMARY_KEY = "select tco.constraint_schema as self_schema,\n" + - " tco.constraint_name,\n" + - " kcu.column_name as self_column,\n" + - " kcu.table_name as self_table,\n" + - " 'p' as constraint_type\n" + - "from information_schema.table_constraints tco\n" + - "join information_schema.key_column_usage kcu \n" + - " on kcu.constraint_name = tco.constraint_name\n" + - " and kcu.constraint_schema = tco.constraint_schema\n" + - " and kcu.constraint_name = tco.constraint_name\n" + - "where tco.constraint_type = 'PRIMARY KEY'\n" + - "order by tco.constraint_schema,\n" + - " tco.constraint_name,\n" + - " kcu.ordinal_position;"; - - private static final String KEYS_QUERY_FOREIGN_KEY = "select kcu.table_schema as self_schema,\n" + - "\t kcu.table_name as self_table,\n" + - " rel_kcu.table_schema as foreign_schema,\n" + - " rel_kcu.table_name as foreign_table,\n" + - " kcu.column_name as self_column,\n" + - " rel_kcu.column_name as foreign_column,\n" + - " kcu.constraint_name,\n" + - " 'f' as constraint_type\n" + - "from information_schema.table_constraints tco\n" + - "left join information_schema.key_column_usage kcu\n" + - " on tco.constraint_schema = kcu.constraint_schema\n" + - " and tco.constraint_name = kcu.constraint_name\n" + - "left join information_schema.referential_constraints rco\n" + - " on tco.constraint_schema = rco.constraint_schema\n" + - " and tco.constraint_name = rco.constraint_name\n" + - "left join information_schema.key_column_usage rel_kcu\n" + - " on rco.unique_constraint_schema = rel_kcu.constraint_schema\n" + - " and rco.unique_constraint_name = rel_kcu.constraint_name\n" + - " and kcu.ordinal_position = rel_kcu.ordinal_position\n" + - "where tco.constraint_type = 'FOREIGN KEY'\n" + - "order by kcu.table_schema,\n" + - " kcu.table_name,\n" + - " kcu.ordinal_position;\n"; + "select a.attname as name,\n" + + " t1.typname as column_type,\n" + + " case when a.atthasdef then pg_get_expr(d.adbin, d.adrelid) end as default_expr,\n" + + " c.relkind as kind,\n" + + " c.relname as table_name,\n" + + " n.nspname as schema_name\n" + + "from pg_catalog.pg_attribute a\n" + + " left join pg_catalog.pg_type t1 on t1.oid = a.atttypid\n" + + " inner join pg_catalog.pg_class c on a.attrelid = c.oid\n" + + " left join pg_catalog.pg_namespace n on c.relnamespace = n.oid\n" + + " left join pg_catalog.pg_attrdef d on d.adrelid = c.oid and d.adnum = a.attnum\n" + + "where a.attnum > 0\n" + + " and not a.attisdropped\n" + + " and n.nspname not in ('information_schema', 'pg_catalog')\n" + + " and c.relkind in ('r', 'v')\n" + + " and pg_catalog.pg_table_is_visible(a.attrelid)\n" + + "order by c.relname, a.attnum;"; + + private static final String KEYS_QUERY_PRIMARY_KEY = + "select tco.constraint_schema as self_schema,\n" + " tco.constraint_name,\n" + + " kcu.column_name as self_column,\n" + + " kcu.table_name as self_table,\n" + + " 'p' as constraint_type\n" + + "from information_schema.table_constraints tco\n" + + "join information_schema.key_column_usage kcu \n" + + " on kcu.constraint_name = tco.constraint_name\n" + + " and kcu.constraint_schema = tco.constraint_schema\n" + + " and kcu.constraint_name = tco.constraint_name\n" + + "where tco.constraint_type = 'PRIMARY KEY'\n" + + "order by tco.constraint_schema,\n" + + " tco.constraint_name,\n" + + " kcu.ordinal_position;"; + + private static final String KEYS_QUERY_FOREIGN_KEY = + "select kcu.table_schema as self_schema,\n" + "\t kcu.table_name as self_table,\n" + + " rel_kcu.table_schema as foreign_schema,\n" + + " rel_kcu.table_name as foreign_table,\n" + + " kcu.column_name as self_column,\n" + + " rel_kcu.column_name as foreign_column,\n" + + " kcu.constraint_name,\n" + + " 'f' as constraint_type\n" + + "from information_schema.table_constraints tco\n" + + "left join information_schema.key_column_usage kcu\n" + + " on tco.constraint_schema = kcu.constraint_schema\n" + + " and tco.constraint_name = kcu.constraint_name\n" + + "left join information_schema.referential_constraints rco\n" + + " on tco.constraint_schema = rco.constraint_schema\n" + + " and tco.constraint_name = rco.constraint_name\n" + + "left join information_schema.key_column_usage rel_kcu\n" + + " on rco.unique_constraint_schema = rel_kcu.constraint_schema\n" + + " and rco.unique_constraint_name = rel_kcu.constraint_name\n" + + " and kcu.ordinal_position = rel_kcu.ordinal_position\n" + + "where tco.constraint_type = 'FOREIGN KEY'\n" + + "order by kcu.table_schema,\n" + + " kcu.table_name,\n" + + " kcu.ordinal_position;\n"; private void checkResultSetValidity(ResultSet resultSet) throws AppsmithPluginException { if (resultSet == null) { log.debug("Redshift plugin: getRow: driver failed to fetch result: resultSet is null."); throw new AppsmithPluginException( - RedshiftPluginError.QUERY_EXECUTION_FAILED, - RedshiftErrorMessages.NULL_RESULTSET_ERROR_MSG - ); + RedshiftPluginError.QUERY_EXECUTION_FAILED, RedshiftErrorMessages.NULL_RESULTSET_ERROR_MSG); } } @@ -147,13 +145,11 @@ private Map<String, Object> getRow(ResultSet resultSet) throws SQLException, App * ResultSetMetaData. */ if (metaData == null) { - log.debug("Redshift plugin: getRow: metaData is null. Ideally this is never supposed to " + - "happen as the Redshift JDBC driver does a null check before passing this object. This means " + - "that something has gone wrong while processing the query result."); + log.debug("Redshift plugin: getRow: metaData is null. Ideally this is never supposed to " + + "happen as the Redshift JDBC driver does a null check before passing this object. This means " + + "that something has gone wrong while processing the query result."); throw new AppsmithPluginException( - RedshiftPluginError.QUERY_EXECUTION_FAILED, - RedshiftErrorMessages.NULL_METADATA_ERROR_MSG - ); + RedshiftPluginError.QUERY_EXECUTION_FAILED, RedshiftErrorMessages.NULL_METADATA_ERROR_MSG); } int colCount = metaData.getColumnCount(); @@ -168,20 +164,17 @@ private Map<String, Object> getRow(ResultSet resultSet) throws SQLException, App value = null; } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE.format(resultSet.getDate(i).toLocalDate()); + value = DateTimeFormatter.ISO_DATE.format( + resultSet.getDate(i).toLocalDate()); } else if ("timestamp".equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - LocalDateTime.of( + value = DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.of( resultSet.getDate(i).toLocalDate(), - resultSet.getTime(i).toLocalTime() - ) - ) + "Z"; + resultSet.getTime(i).toLocalTime())) + + "Z"; } else if ("timestamptz".equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - resultSet.getObject(i, OffsetDateTime.class) - ); + value = DateTimeFormatter.ISO_DATE_TIME.format(resultSet.getObject(i, OffsetDateTime.class)); } else if ("time".equalsIgnoreCase(typeName) || "timetz".equalsIgnoreCase(typeName)) { value = resultSet.getString(i); } else { @@ -195,27 +188,26 @@ private Map<String, Object> getRow(ResultSet resultSet) throws SQLException, App } @Override - public Mono<ActionExecutionResult> execute(HikariDataSource connectionPool, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + HikariDataSource connectionPool, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { String query = actionConfiguration.getBody(); - List<RequestParamDTO> requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null - , null, null)); - - if (! StringUtils.hasLength(query)) { - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - RedshiftErrorMessages.QUERY_PARAMETER_MISSING_ERROR_MSG - ) - ); + List<RequestParamDTO> requestParams = + List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null)); + + if (!StringUtils.hasLength(query)) { + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + RedshiftErrorMessages.QUERY_PARAMETER_MISSING_ERROR_MSG)); } return Mono.fromCallable(() -> { Connection connection = null; try { - connection = redshiftDatasourceUtils.getConnectionFromHikariConnectionPool(connectionPool, REDSHIFT_PLUGIN_NAME); + connection = redshiftDatasourceUtils.getConnectionFromHikariConnectionPool( + connectionPool, REDSHIFT_PLUGIN_NAME); } catch (SQLException | StaleConnectionException e) { e.printStackTrace(); @@ -229,14 +221,14 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connectionPool, return Mono.error(e); } - // The function can throw either StaleConnectionException or SQLException. The underlying hikari + // The function can throw either StaleConnectionException or SQLException. The underlying + // hikari // library throws SQLException in case the pool is closed or there is an issue initializing // the connection pool which can also be translated in our world to StaleConnectionException // and should then trigger the destruction and recreation of the pool. return Mono.error(new StaleConnectionException(e.getMessage())); } - /** * Keeping this print statement post call to getConnectionFromHikariConnectionPool because it * checks for stale connection pool. @@ -263,14 +255,15 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connectionPool, } } else { rowsList.add(Map.of( - "affectedRows", - ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0)) - ); - + "affectedRows", ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0))); } } catch (SQLException e) { e.printStackTrace(); - return Mono.error(new AppsmithPluginException(RedshiftPluginError.QUERY_EXECUTION_FAILED, RedshiftErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage(), "SQLSTATE: " + e.getSQLState())); + return Mono.error(new AppsmithPluginException( + RedshiftPluginError.QUERY_EXECUTION_FAILED, + RedshiftErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage(), + "SQLSTATE: " + e.getSQLState())); } finally { if (resultSet != null) { try { @@ -293,7 +286,6 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connectionPool, } catch (SQLException e) { log.error("Error closing Redshift Connection", e); } - } ActionExecutionResult result = new ActionExecutionResult(); @@ -309,8 +301,11 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connectionPool, error.printStackTrace(); if (error instanceof StaleConnectionException) { return Mono.error(error); - } else if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(RedshiftPluginError.QUERY_EXECUTION_FAILED, RedshiftErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, error); + } else if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + RedshiftPluginError.QUERY_EXECUTION_FAILED, + RedshiftErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + error); } ActionExecutionResult result = new ActionExecutionResult(); result.setIsExecutionSuccess(false); @@ -335,12 +330,15 @@ public void printConnectionPoolStatus(HikariDataSource connectionPool, boolean i int activeConnections = poolProxy.getActiveConnections(); int totalConnections = poolProxy.getTotalConnections(); int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug(Thread.currentThread().getName() + (isFetchingStructure ? "Before fetching Redshift db" + - " structure." : "Before executing Redshift query.") + " Hikari Pool stats : " + - " active - " + activeConnections + - ", idle - " + idleConnections + - ", awaiting - " + threadsAwaitingConnection + - ", total - " + totalConnections); + log.debug(Thread.currentThread().getName() + + (isFetchingStructure + ? "Before fetching Redshift db" + " structure." + : "Before executing Redshift query.") + + " Hikari Pool stats : " + " active - " + + activeConnections + ", idle - " + + idleConnections + ", awaiting - " + + threadsAwaitingConnection + ", total - " + + totalConnections); } private Set<String> populateHintMessages(List<String> columnNames) { @@ -349,9 +347,10 @@ private Set<String> populateHintMessages(List<String> columnNames) { List<String> identicalColumns = getIdenticalColumns(columnNames); if (!CollectionUtils.isEmpty(identicalColumns)) { - messages.add("Your Redshift query result may not have all the columns because duplicate column names " + - "were found for the column(s): " + String.join(", ", identicalColumns) + ". You may use the " + - "SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); + messages.add("Your Redshift query result may not have all the columns because duplicate column names " + + "were found for the column(s): " + + String.join(", ", identicalColumns) + ". You may use the " + + "SQL keyword 'as' to rename the duplicate column name(s) and resolve this issue."); } return messages; @@ -362,11 +361,13 @@ public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourc try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, JDBC_DRIVER_LOADING_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + JDBC_DRIVER_LOADING_ERROR_MSG, + e.getMessage())); } - return Mono - .fromCallable(() -> { + return Mono.fromCallable(() -> { log.debug(Thread.currentThread().getName() + ": Connecting to Redshift db"); return createConnectionPool(datasourceConfiguration); }) @@ -390,8 +391,10 @@ public Set<String> validateDatasource(@NonNull DatasourceConfiguration datasourc for (final Endpoint endpoint : datasourceConfiguration.getEndpoints()) { if (StringUtils.isEmpty(endpoint.getHost())) { invalids.add("Missing hostname."); - } else if (endpoint.getHost().contains("/") || endpoint.getHost().contains(":")) { - invalids.add("Host value cannot contain `/` or `:` characters. Found `" + endpoint.getHost() + "`."); + } else if (endpoint.getHost().contains("/") + || endpoint.getHost().contains(":")) { + invalids.add( + "Host value cannot contain `/` or `:` characters. Found `" + endpoint.getHost() + "`."); } } } @@ -432,34 +435,42 @@ private void getTablesInfo(ResultSet columnsResultSet, Map<String, DatasourceStr final String tableName = columnsResultSet.getString("table_name"); final String fullTableName = schemaName + "." + tableName; final String defaultExpr = columnsResultSet.getString("default_expr"); - boolean isAutogenerated = !StringUtils.isEmpty(defaultExpr) && defaultExpr.toLowerCase().contains("identity"); + boolean isAutogenerated = !StringUtils.isEmpty(defaultExpr) + && defaultExpr.toLowerCase().contains("identity"); if (!tablesByName.containsKey(fullTableName)) { - tablesByName.put(fullTableName, new DatasourceStructure.Table( - kind == 'r' ? DatasourceStructure.TableType.TABLE : DatasourceStructure.TableType.VIEW, - schemaName, + tablesByName.put( fullTableName, - new ArrayList<>(), - new ArrayList<>(), - new ArrayList<>() - )); + new DatasourceStructure.Table( + kind == 'r' + ? DatasourceStructure.TableType.TABLE + : DatasourceStructure.TableType.VIEW, + schemaName, + fullTableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); } final DatasourceStructure.Table table = tablesByName.get(fullTableName); - table.getColumns().add(new DatasourceStructure.Column( - columnsResultSet.getString("name"), - columnsResultSet.getString("column_type"), - defaultExpr, - isAutogenerated - )); + table.getColumns() + .add(new DatasourceStructure.Column( + columnsResultSet.getString("name"), + columnsResultSet.getString("column_type"), + defaultExpr, + isAutogenerated)); } } - private void getKeysInfo(ResultSet constraintsResultSet, Map<String, DatasourceStructure.Table> tablesByName, - Map<String, DatasourceStructure.Key> keyRegistry) throws SQLException, AppsmithPluginException { + private void getKeysInfo( + ResultSet constraintsResultSet, + Map<String, DatasourceStructure.Table> tablesByName, + Map<String, DatasourceStructure.Key> keyRegistry) + throws SQLException, AppsmithPluginException { checkResultSetValidity(constraintsResultSet); while (constraintsResultSet.next()) { final String constraintName = constraintsResultSet.getString("constraint_name"); - final char constraintType = constraintsResultSet.getString("constraint_type").charAt(0); + final char constraintType = + constraintsResultSet.getString("constraint_type").charAt(0); final String selfSchema = constraintsResultSet.getString("self_schema"); final String tableName = constraintsResultSet.getString("self_table"); final String fullTableName = selfSchema + "." + tableName; @@ -474,14 +485,13 @@ private void getKeysInfo(ResultSet constraintsResultSet, Map<String, DatasourceS if (constraintType == 'p') { if (!keyRegistry.containsKey(keyFullName)) { - final DatasourceStructure.PrimaryKey key = new DatasourceStructure.PrimaryKey( - constraintName, - new ArrayList<>() - ); + final DatasourceStructure.PrimaryKey key = + new DatasourceStructure.PrimaryKey(constraintName, new ArrayList<>()); keyRegistry.put(keyFullName, key); table.getKeys().add(key); } - ((DatasourceStructure.PrimaryKey) keyRegistry.get(keyFullName)).getColumnNames() + ((DatasourceStructure.PrimaryKey) keyRegistry.get(keyFullName)) + .getColumnNames() .add(constraintsResultSet.getString("self_column")); } else if (constraintType == 'f') { final String foreignSchema = constraintsResultSet.getString("foreign_schema"); @@ -490,17 +500,16 @@ private void getKeysInfo(ResultSet constraintsResultSet, Map<String, DatasourceS if (!keyRegistry.containsKey(keyFullName)) { final DatasourceStructure.ForeignKey key = new DatasourceStructure.ForeignKey( - constraintName, - new ArrayList<>(), - new ArrayList<>() - ); + constraintName, new ArrayList<>(), new ArrayList<>()); keyRegistry.put(keyFullName, key); table.getKeys().add(key); } - ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)).getFromColumns() + ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)) + .getFromColumns() .add(constraintsResultSet.getString("self_column")); - ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)).getToColumns() + ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)) + .getToColumns() .add(prefix + constraintsResultSet.getString("foreign_column")); } } @@ -508,8 +517,7 @@ private void getKeysInfo(ResultSet constraintsResultSet, Map<String, DatasourceS private void getTemplates(Map<String, DatasourceStructure.Table> tablesByName) { for (DatasourceStructure.Table table : tablesByName.values()) { - final List<DatasourceStructure.Column> columnsWithoutDefault = table.getColumns() - .stream() + final List<DatasourceStructure.Column> columnsWithoutDefault = table.getColumns().stream() .filter(column -> column.getDefaultValue() == null) .collect(Collectors.toList()); @@ -548,23 +556,31 @@ private void getTemplates(Map<String, DatasourceStructure.Table> tablesByName) { } final String quotedTableName = table.getName().replaceFirst("\\.(\\w+)", ".\"$1\""); - table.getTemplates().addAll(List.of( - new DatasourceStructure.Template("SELECT", "SELECT * FROM " + quotedTableName + " LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO " + quotedTableName - + " (" + String.join(", ", columnNames) + ")\n" - + " VALUES (" + String.join(", ", columnValues) + ");"), - new DatasourceStructure.Template("UPDATE", "UPDATE " + quotedTableName + " SET" - + setFragments.toString() + "\n" - + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM " + quotedTableName - + "\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!") - )); + table.getTemplates() + .addAll( + List.of( + new DatasourceStructure.Template( + "SELECT", "SELECT * FROM " + quotedTableName + " LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO " + quotedTableName + + " (" + String.join(", ", columnNames) + ")\n" + + " VALUES (" + String.join(", ", columnValues) + ");"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE " + quotedTableName + " SET" + + setFragments.toString() + "\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM " + quotedTableName + + "\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"))); } } @Override - public Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, - DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + HikariDataSource connectionPool, DatasourceConfiguration datasourceConfiguration) { final DatasourceStructure structure = new DatasourceStructure(); final Map<String, DatasourceStructure.Table> tablesByName = new LinkedHashMap<>(); final Map<String, DatasourceStructure.Key> keyRegistry = new HashMap<>(); @@ -572,8 +588,8 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, return Mono.fromSupplier(() -> { Connection connection = null; try { - connection = redshiftDatasourceUtils.getConnectionFromHikariConnectionPool(connectionPool - , REDSHIFT_PLUGIN_NAME); + connection = redshiftDatasourceUtils.getConnectionFromHikariConnectionPool( + connectionPool, REDSHIFT_PLUGIN_NAME); } catch (SQLException | StaleConnectionException e) { e.printStackTrace(); @@ -587,7 +603,8 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, return Mono.error(e); } - // The function can throw either StaleConnectionException or SQLException. The underlying hikari + // The function can throw either StaleConnectionException or SQLException. The underlying + // hikari // library throws SQLException in case the pool is closed or there is an issue initializing // the connection pool which can also be translated in our world to StaleConnectionException // and should then trigger the destruction and recreation of the pool. @@ -600,7 +617,8 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, */ printConnectionPoolStatus(connectionPool, true); - // Ref: <https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/DatabaseMetaData.html>. + // Ref: + // <https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/DatabaseMetaData.html>. log.debug(Thread.currentThread().getName() + ": Getting Redshift Db structure"); try (Statement statement = connection.createStatement()) { @@ -620,14 +638,11 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, getTemplates(tablesByName); } catch (SQLException e) { e.printStackTrace(); - return Mono.error( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, - RedshiftErrorMessages.GET_STRUCTURE_ERROR_MSG, - e.getMessage(), - "SQLSTATE: " + e.getSQLState() - ) - ); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + RedshiftErrorMessages.GET_STRUCTURE_ERROR_MSG, + e.getMessage(), + "SQLSTATE: " + e.getSQLState())); } catch (AppsmithPluginException e) { e.printStackTrace(); return Mono.error(e); @@ -638,7 +653,6 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, } catch (SQLException e) { log.error("Error closing Redshift Connection", e); } - } structure.setTables(new ArrayList<>(tablesByName.values())); @@ -655,7 +669,10 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, return e; } - return new AppsmithPluginException(AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, RedshiftErrorMessages.GET_STRUCTURE_ERROR_MSG, e.getMessage()); + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + RedshiftErrorMessages.GET_STRUCTURE_ERROR_MSG, + e.getMessage()); }) .subscribeOn(scheduler); } diff --git a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/exceptions/RedshiftErrorMessages.java b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/exceptions/RedshiftErrorMessages.java index 13d02be5e6c8..9fc589ebfee1 100644 --- a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/exceptions/RedshiftErrorMessages.java +++ b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/exceptions/RedshiftErrorMessages.java @@ -10,14 +10,18 @@ public class RedshiftErrorMessages extends BasePluginErrorMessages { public static final String NULL_RESULTSET_ERROR_MSG = "Redshift driver failed to fetch result: resultSet is null."; - public static final String NULL_METADATA_ERROR_MSG = "metaData is null. Ideally this is never supposed to happen as the Redshift JDBC driver " + - "does a null check before passing this object. This means that something has gone wrong " + - "while processing the query result"; + public static final String NULL_METADATA_ERROR_MSG = + "metaData is null. Ideally this is never supposed to happen as the Redshift JDBC driver " + + "does a null check before passing this object. This means that something has gone wrong " + + "while processing the query result"; - public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Error occurred while executing Redshift query. To know more please check the error details."; + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = + "Error occurred while executing Redshift query. To know more please check the error details."; - public static final String GET_STRUCTURE_ERROR_MSG = "Appsmith server has failed to fetch the structure of the database. " - + "Please check if the database credentials are valid and/or you have the required permissions."; + public static final String GET_STRUCTURE_ERROR_MSG = + "Appsmith server has failed to fetch the structure of the database. " + + "Please check if the database credentials are valid and/or you have the required permissions."; - public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = "Exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid. Please check your datasource configuration."; + public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = + "Exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid. Please check your datasource configuration."; } diff --git a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/exceptions/RedshiftPluginError.java b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/exceptions/RedshiftPluginError.java index 00e39e0a0d61..5c9a06cfca31 100644 --- a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/exceptions/RedshiftPluginError.java +++ b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/exceptions/RedshiftPluginError.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum RedshiftPluginError implements BasePluginError { QUERY_EXECUTION_FAILED( @@ -16,9 +15,7 @@ public enum RedshiftPluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ) - ; + "{2}"); private final Integer httpErrorCode; private final String appErrorCode; @@ -31,8 +28,15 @@ public enum RedshiftPluginError implements BasePluginError { private final String downstreamErrorCode; - RedshiftPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + RedshiftPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -59,5 +63,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/utils/RedshiftDatasourceUtils.java b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/utils/RedshiftDatasourceUtils.java index a1a0203344bc..12f15f06b06d 100644 --- a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/utils/RedshiftDatasourceUtils.java +++ b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/utils/RedshiftDatasourceUtils.java @@ -31,8 +31,8 @@ public class RedshiftDatasourceUtils { private static final long LEAK_DETECTION_TIME_MS = 60 * 1000; private static final String JDBC_PROTOCOL = "jdbc:redshift://"; - - public static HikariDataSource createConnectionPool(DatasourceConfiguration datasourceConfiguration) throws AppsmithPluginException { + public static HikariDataSource createConnectionPool(DatasourceConfiguration datasourceConfiguration) + throws AppsmithPluginException { HikariConfig config = new HikariConfig(); config.setDriverClassName(JDBC_DRIVER); @@ -51,9 +51,7 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data // Set up the connection URL StringBuilder urlBuilder = new StringBuilder(JDBC_PROTOCOL); - List<String> hosts = datasourceConfiguration - .getEndpoints() - .stream() + List<String> hosts = datasourceConfiguration.getEndpoints().stream() .map(endpoint -> endpoint.getHost() + ":" + ObjectUtils.defaultIfNull(endpoint.getPort(), 5439L)) .collect(Collectors.toList()); @@ -93,29 +91,28 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data throw new AppsmithPluginException( AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, RedshiftErrorMessages.CONNECTION_POOL_CREATION_FAILED_ERROR_MSG, - e.getMessage() - ); + e.getMessage()); } return datasource; } - public void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) throws StaleConnectionException { + public void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) + throws StaleConnectionException { if (connectionPool == null || connectionPool.isClosed() || !connectionPool.isRunning()) { - String printMessage = MessageFormat.format(Thread.currentThread().getName() + - ": Encountered stale connection pool in {0} plugin. Reporting back.", pluginName); + String printMessage = MessageFormat.format( + Thread.currentThread().getName() + + ": Encountered stale connection pool in {0} plugin. Reporting back.", + pluginName); System.out.println(printMessage); if (connectionPool == null) { throw new StaleConnectionException(CONNECTION_POOL_NULL_ERROR_MSG); - } - else if (connectionPool.isClosed()) { + } else if (connectionPool.isClosed()) { throw new StaleConnectionException(CONNECTION_POOL_CLOSED_ERROR_MSG); - } - else if (!connectionPool.isRunning()) { + } else if (!connectionPool.isRunning()) { throw new StaleConnectionException(CONNECTION_POOL_NOT_RUNNING_ERROR_MSG); - } - else { + } else { /** * Ideally, code flow is never expected to reach here. However, this section has been added to catch * those cases wherein a developer updates the parent if condition but does not update the nested @@ -126,8 +123,8 @@ else if (!connectionPool.isRunning()) { } } - public Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, - String pluginName) throws SQLException { + public Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, String pluginName) + throws SQLException { checkHikariCPConnectionPoolValidity(connectionPool, pluginName); return connectionPool.getConnection(); } diff --git a/app/server/appsmith-plugins/redshiftPlugin/src/test/java/com/external/plugins/RedshiftPluginTest.java b/app/server/appsmith-plugins/redshiftPlugin/src/test/java/com/external/plugins/RedshiftPluginTest.java index b48f2747e5d7..5e2dade36990 100644 --- a/app/server/appsmith-plugins/redshiftPlugin/src/test/java/com/external/plugins/RedshiftPluginTest.java +++ b/app/server/appsmith-plugins/redshiftPlugin/src/test/java/com/external/plugins/RedshiftPluginTest.java @@ -1,6 +1,5 @@ package com.external.plugins; -import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; import com.appsmith.external.models.ActionConfiguration; @@ -102,12 +101,10 @@ public void testDatasourceCreateConnectionFailure() { Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); StepVerifier.create(dsConnectionMono) - .expectErrorMatches(throwable -> - throwable instanceof AppsmithPluginException && - ((AppsmithPluginException) throwable).getDownstreamErrorMessage().equals( - "Failed to initialize pool: The connection attempt failed." - ) - ) + .expectErrorMatches(throwable -> throwable instanceof AppsmithPluginException + && ((AppsmithPluginException) throwable) + .getDownstreamErrorMessage() + .equals("Failed to initialize pool: The connection attempt failed.")) .verify(); } @@ -137,8 +134,7 @@ public void itShouldValidateDatasourceWithEmptyEndpoints() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.setEndpoints(new ArrayList<>()); - assertEquals(Set.of("Missing endpoint."), - pluginExecutor.validateDatasource(dsConfig)); + assertEquals(Set.of("Missing endpoint."), pluginExecutor.validateDatasource(dsConfig)); } @Test @@ -146,8 +142,7 @@ public void itShouldValidateDatasourceWithEmptyHost() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getEndpoints().get(0).setHost(""); - assertEquals(Set.of("Missing hostname."), - pluginExecutor.validateDatasource(dsConfig)); + assertEquals(Set.of("Missing hostname."), pluginExecutor.validateDatasource(dsConfig)); } @Test @@ -156,7 +151,8 @@ public void itShouldValidateDatasourceWithInvalidHostname() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); dsConfig.getEndpoints().get(0).setHost("jdbc://localhost"); - assertEquals(Set.of("Host value cannot contain `/` or `:` characters. Found `" + hostname + "`."), + assertEquals( + Set.of("Host value cannot contain `/` or `:` characters. Found `" + hostname + "`."), pluginExecutor.validateDatasource(dsConfig)); } @@ -221,13 +217,14 @@ public void testExecute() throws SQLException { */ ResultSet mockResultSet = mock(ResultSet.class); when(mockStatement.getResultSet()).thenReturn(mockResultSet); - when(mockResultSet.getObject(Mockito.anyInt())).thenReturn("", 1, "", "Jack", "", "jill", "", "[email protected]" - , null, "", "", "", "", ""); - when(mockResultSet.getDate(Mockito.anyInt())).thenReturn(Date.valueOf("2018-12-31"), Date.valueOf("2018-11-30")); + when(mockResultSet.getObject(Mockito.anyInt())) + .thenReturn("", 1, "", "Jack", "", "jill", "", "[email protected]", null, "", "", "", "", ""); + when(mockResultSet.getDate(Mockito.anyInt())) + .thenReturn(Date.valueOf("2018-12-31"), Date.valueOf("2018-11-30")); when(mockResultSet.getString(Mockito.anyInt())).thenReturn("18:32:45", "12:05:06+00"); when(mockResultSet.getTime(Mockito.anyInt())).thenReturn(Time.valueOf("20:45:15")); - when(mockResultSet.getObject(Mockito.anyInt(), any(Class.class))).thenReturn(OffsetDateTime.parse( - "2018-11-30T19:45:15+00")); + when(mockResultSet.getObject(Mockito.anyInt(), any(Class.class))) + .thenReturn(OffsetDateTime.parse("2018-11-30T19:45:15+00")); when(mockResultSet.next()).thenReturn(true).thenReturn(false); doNothing().when(mockResultSet).close(); @@ -239,10 +236,30 @@ public void testExecute() throws SQLException { ResultSetMetaData mockResultSetMetaData = mock(ResultSetMetaData.class); when(mockResultSet.getMetaData()).thenReturn(mockResultSetMetaData); when(mockResultSetMetaData.getColumnCount()).thenReturn(0).thenReturn(10); - when(mockResultSetMetaData.getColumnTypeName(Mockito.anyInt())).thenReturn("int4", "varchar", "varchar", - "varchar", "date", "date", "time", "timetz", "timestamp", "timestamptz"); - when(mockResultSetMetaData.getColumnName(Mockito.anyInt())).thenReturn("id", "username", "password", "email", - "spouse_dob", "dob", "time1", "time_tz", "created_on", "created_on_tz"); + when(mockResultSetMetaData.getColumnTypeName(Mockito.anyInt())) + .thenReturn( + "int4", + "varchar", + "varchar", + "varchar", + "date", + "date", + "time", + "timetz", + "timestamp", + "timestamptz"); + when(mockResultSetMetaData.getColumnName(Mockito.anyInt())) + .thenReturn( + "id", + "username", + "password", + "email", + "spouse_dob", + "dob", + "time1", + "time_tz", + "created_on", + "created_on_tz"); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users WHERE id = 1"); @@ -252,8 +269,8 @@ public void testExecute() throws SQLException { RedshiftPlugin.RedshiftPluginExecutor spyPluginExecutor = spy(new RedshiftPlugin.RedshiftPluginExecutor()); doNothing().when(spyPluginExecutor).printConnectionPoolStatus(mockConnectionPool, false); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(connPool -> spyPluginExecutor.execute(connPool, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + connPool -> spyPluginExecutor.execute(connPool, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -266,34 +283,34 @@ public void testExecute() throws SQLException { assertEquals("18:32:45", node.get("time1").asText()); assertEquals("12:05:06+00", node.get("time_tz").asText()); assertEquals("2018-11-30T20:45:15Z", node.get("created_on").asText()); - assertEquals("2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); + assertEquals( + "2018-11-30T19:45:15Z", node.get("created_on_tz").asText()); assertTrue(node.get("spouse_dob").isNull()); assertArrayEquals( - new String[]{ - "id", - "username", - "password", - "email", - "spouse_dob", - "dob", - "time1", - "time_tz", - "created_on", - "created_on_tz", + new String[] { + "id", + "username", + "password", + "email", + "spouse_dob", + "dob", + "time1", + "time_tz", + "created_on", + "created_on_tz", }, new ObjectMapper() .convertValue(node, LinkedHashMap.class) .keySet() - .toArray() - ); + .toArray()); /* * - RequestParamDTO object only have attributes configProperty and value at this point. * - The other two RequestParamDTO attributes - label and type are null at this point. */ List<RequestParamDTO> expectedRequestParams = new ArrayList<>(); - expectedRequestParams.add(new RequestParamDTO(ACTION_CONFIGURATION_BODY, - actionConfiguration.getBody(), null, null, null)); + expectedRequestParams.add(new RequestParamDTO( + ACTION_CONFIGURATION_BODY, actionConfiguration.getBody(), null, null, null)); assertEquals(result.getRequest().getRequestParams().toString(), expectedRequestParams.toString()); }) .verifyComplete(); @@ -356,38 +373,63 @@ public void testStructure() throws SQLException { ResultSet mockResultSet = mock(ResultSet.class); when(mockStatement.executeQuery(Mockito.anyString())).thenReturn(mockResultSet, mockResultSet, mockResultSet); when(mockResultSet.next()) - .thenReturn(true, true, true, true, true, true, true, true, false) // TABLES_QUERY - .thenReturn(true, true, false) // KEYS_QUERY_PRIMARY_KEY - .thenReturn(true, false); // KEYS_QUERY_FOREIGN_KEY - when(mockResultSet.getString("kind")).thenReturn("r", "r", "r", "r", "r", "r", "r", "r");// TABLES_QUERY - when(mockResultSet.getString("schema_name")).thenReturn("public", "public", "public", "public", "public", - "public", "public", "public"); // TABLES_QUERY - when(mockResultSet.getString("table_name")).thenReturn("campus", "campus", "possessions", "possessions", - "possessions", "users", "users", "users"); // TABLES_QUERY - when(mockResultSet.getString("name")).thenReturn("id", "name", "id", "title", "user_id", "id", "username", - "password"); // TABLES_QUERY - when(mockResultSet.getString("column_type")).thenReturn("timestamptz", "timestamptz", "int4", "varchar", - "int4", "int4", "varchar", "varchar"); // TABLES_QUERY - when(mockResultSet.getString("default_expr")).thenReturn("now()", "now()", null, null, null, "\"identity\"" + - "(101507, 0, '1,1'::text)", null, null); // TABLES_QUERY + .thenReturn(true, true, true, true, true, true, true, true, false) // TABLES_QUERY + .thenReturn(true, true, false) // KEYS_QUERY_PRIMARY_KEY + .thenReturn(true, false); // KEYS_QUERY_FOREIGN_KEY + when(mockResultSet.getString("kind")).thenReturn("r", "r", "r", "r", "r", "r", "r", "r"); // TABLES_QUERY + when(mockResultSet.getString("schema_name")) + .thenReturn( + "public", "public", "public", "public", "public", "public", "public", "public"); // TABLES_QUERY + when(mockResultSet.getString("table_name")) + .thenReturn( + "campus", + "campus", + "possessions", + "possessions", + "possessions", + "users", + "users", + "users"); // TABLES_QUERY + when(mockResultSet.getString("name")) + .thenReturn("id", "name", "id", "title", "user_id", "id", "username", "password"); // TABLES_QUERY + when(mockResultSet.getString("column_type")) + .thenReturn( + "timestamptz", + "timestamptz", + "int4", + "varchar", + "int4", + "int4", + "varchar", + "varchar"); // TABLES_QUERY + when(mockResultSet.getString("default_expr")) + .thenReturn( + "now()", + "now()", + null, + null, + null, + "\"identity\"" + "(101507, 0, '1,1'::text)", + null, + null); // TABLES_QUERY when(mockResultSet.getString("constraint_name")) - .thenReturn("possessions_pkey", "users_pkey") // KEYS_QUERY_PRIMARY_KEY - .thenReturn("user_fk"); // KEYS_QUERY_FOREIGN_KEY + .thenReturn("possessions_pkey", "users_pkey") // KEYS_QUERY_PRIMARY_KEY + .thenReturn("user_fk"); // KEYS_QUERY_FOREIGN_KEY when(mockResultSet.getString("constraint_type")) - .thenReturn("p", "p") // KEYS_QUERY_PRIMARY_KEY - .thenReturn("f"); // KEYS_QUERY_FOREIGN_KEY + .thenReturn("p", "p") // KEYS_QUERY_PRIMARY_KEY + .thenReturn("f"); // KEYS_QUERY_FOREIGN_KEY when(mockResultSet.getString("self_schema")) - .thenReturn("public", "public") // KEYS_QUERY_PRIMARY_KEY - .thenReturn("public"); // KEYS_QUERY_FOREIGN_KEY + .thenReturn("public", "public") // KEYS_QUERY_PRIMARY_KEY + .thenReturn("public"); // KEYS_QUERY_FOREIGN_KEY when(mockResultSet.getString("self_table")) - .thenReturn("possessions", "users") // KEYS_QUERY_PRIMARY_KEY - .thenReturn("possessions"); // KEYS_QUERY_FOREIGN_KEY + .thenReturn("possessions", "users") // KEYS_QUERY_PRIMARY_KEY + .thenReturn("possessions"); // KEYS_QUERY_FOREIGN_KEY when(mockResultSet.getString("self_column")) - .thenReturn("id", "id") // KEYS_QUERY_PRIMARY_KEY - .thenReturn("user_id"); // KEYS_QUERY_FOREIGN_KEY + .thenReturn("id", "id") // KEYS_QUERY_PRIMARY_KEY + .thenReturn("user_id"); // KEYS_QUERY_FOREIGN_KEY when(mockResultSet.getString("foreign_schema")).thenReturn("public"); // KEYS_QUERY_FOREIGN_KEY - when(mockResultSet.getString("foreign_table")).thenReturn("users"); // KEYS_QUERY_FOREIGN_KEY - when(mockResultSet.getString("foreign_column")).thenReturn("id"); // KEYS_QUERY_FOREIGN_KEY + when(mockResultSet.getString("foreign_table")).thenReturn("users"); // KEYS_QUERY_FOREIGN_KEY + when(mockResultSet.getString("foreign_column")).thenReturn("id"); // KEYS_QUERY_FOREIGN_KEY doNothing().when(mockResultSet).close(); RedshiftPlugin.RedshiftPluginExecutor spyPluginExecutor = spy(new RedshiftPlugin.RedshiftPluginExecutor()); @@ -395,100 +437,106 @@ public void testStructure() throws SQLException { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); Mono<HikariDataSource> dsConnectionMono = Mono.just(mockConnectionPool); - Mono<DatasourceStructure> structureMono = dsConnectionMono - .flatMap(connectionPool -> spyPluginExecutor.getStructure(connectionPool, dsConfig)); + Mono<DatasourceStructure> structureMono = + dsConnectionMono.flatMap(connectionPool -> spyPluginExecutor.getStructure(connectionPool, dsConfig)); StepVerifier.create(structureMono) .assertNext(structure -> { assertNotNull(structure); assertEquals(3, structure.getTables().size()); - final DatasourceStructure.Table campusTable = structure.getTables().get(0); + final DatasourceStructure.Table campusTable = + structure.getTables().get(0); assertEquals("public.campus", campusTable.getName()); assertEquals(DatasourceStructure.TableType.TABLE, campusTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "timestamptz", "now()", false), - new DatasourceStructure.Column("name", "timestamptz", "now()", false) + new DatasourceStructure.Column[] { + new DatasourceStructure.Column("id", "timestamptz", "now()", false), + new DatasourceStructure.Column("name", "timestamptz", "now()", false) }, - campusTable.getColumns().toArray() - ); + campusTable.getColumns().toArray()); assertEquals(campusTable.getKeys().size(), 0); - final DatasourceStructure.Table possessionsTable = structure.getTables().get(1); + final DatasourceStructure.Table possessionsTable = + structure.getTables().get(1); assertEquals("public.possessions", possessionsTable.getName()); assertEquals(DatasourceStructure.TableType.TABLE, possessionsTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "int4", null, false), - new DatasourceStructure.Column("title", "varchar", null, false), - new DatasourceStructure.Column("user_id", "int4", null, false) + new DatasourceStructure.Column[] { + new DatasourceStructure.Column("id", "int4", null, false), + new DatasourceStructure.Column("title", "varchar", null, false), + new DatasourceStructure.Column("user_id", "int4", null, false) }, - possessionsTable.getColumns().toArray() - ); + possessionsTable.getColumns().toArray()); - final DatasourceStructure.PrimaryKey possessionsPrimaryKey = new DatasourceStructure.PrimaryKey("possessions_pkey", new ArrayList<>()); + final DatasourceStructure.PrimaryKey possessionsPrimaryKey = + new DatasourceStructure.PrimaryKey("possessions_pkey", new ArrayList<>()); possessionsPrimaryKey.getColumnNames().add("id"); - final DatasourceStructure.ForeignKey possessionsUserForeignKey = new DatasourceStructure.ForeignKey( - "user_fk", - List.of("user_id"), - List.of("users.id") - ); + final DatasourceStructure.ForeignKey possessionsUserForeignKey = + new DatasourceStructure.ForeignKey("user_fk", List.of("user_id"), List.of("users.id")); assertArrayEquals( - new DatasourceStructure.Key[]{possessionsPrimaryKey, possessionsUserForeignKey}, - possessionsTable.getKeys().toArray() - ); + new DatasourceStructure.Key[] {possessionsPrimaryKey, possessionsUserForeignKey}, + possessionsTable.getKeys().toArray()); assertArrayEquals( - new DatasourceStructure.Template[]{ - new DatasourceStructure.Template("SELECT", "SELECT * FROM public.\"possessions\" LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO public.\"possessions\" " + - "(\"id\", \"title\", \"user_id\")\n VALUES (1, '', 1);"), - new DatasourceStructure.Template("UPDATE", "UPDATE public.\"possessions\" SET\n" + - " \"id\" = 1\n" + - " \"title\" = ''\n" + - " \"user_id\" = 1\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM public.\"possessions\"\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), + new DatasourceStructure.Template[] { + new DatasourceStructure.Template( + "SELECT", "SELECT * FROM public.\"possessions\" LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO public.\"possessions\" " + + "(\"id\", \"title\", \"user_id\")\n VALUES (1, '', 1);"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE public.\"possessions\" SET\n" + " \"id\" = 1\n" + + " \"title\" = ''\n" + + " \"user_id\" = 1\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM public.\"possessions\"\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), }, - possessionsTable.getTemplates().toArray() - ); + possessionsTable.getTemplates().toArray()); - final DatasourceStructure.Table usersTable = structure.getTables().get(2); + final DatasourceStructure.Table usersTable = + structure.getTables().get(2); assertEquals("public.users", usersTable.getName()); assertEquals(DatasourceStructure.TableType.TABLE, usersTable.getType()); assertArrayEquals( - new DatasourceStructure.Column[]{ - new DatasourceStructure.Column("id", "int4", "\"identity\"(101507, " + - "0, '1,1'::text)", true), - new DatasourceStructure.Column("username", "varchar", null, false), - new DatasourceStructure.Column("password", "varchar", null, false) + new DatasourceStructure.Column[] { + new DatasourceStructure.Column( + "id", "int4", "\"identity\"(101507, " + "0, '1,1'::text)", true), + new DatasourceStructure.Column("username", "varchar", null, false), + new DatasourceStructure.Column("password", "varchar", null, false) }, - usersTable.getColumns().toArray() - ); + usersTable.getColumns().toArray()); - final DatasourceStructure.PrimaryKey usersPrimaryKey = new DatasourceStructure.PrimaryKey("users_pkey", new ArrayList<>()); + final DatasourceStructure.PrimaryKey usersPrimaryKey = + new DatasourceStructure.PrimaryKey("users_pkey", new ArrayList<>()); usersPrimaryKey.getColumnNames().add("id"); assertArrayEquals( - new DatasourceStructure.Key[]{usersPrimaryKey}, - usersTable.getKeys().toArray() - ); + new DatasourceStructure.Key[] {usersPrimaryKey}, + usersTable.getKeys().toArray()); assertArrayEquals( - new DatasourceStructure.Template[]{ - new DatasourceStructure.Template("SELECT", "SELECT * FROM public.\"users\" LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO public.\"users\" (\"username\", \"password\")\n" + - " VALUES ('', '');"), - new DatasourceStructure.Template("UPDATE", "UPDATE public.\"users\" SET\n" + - " \"username\" = ''\n" + - " \"password\" = ''\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM public.\"users\"\n" + - " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), + new DatasourceStructure.Template[] { + new DatasourceStructure.Template("SELECT", "SELECT * FROM public.\"users\" LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO public.\"users\" (\"username\", \"password\")\n" + + " VALUES ('', '');"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE public.\"users\" SET\n" + " \"username\" = ''\n" + + " \"password\" = ''\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM public.\"users\"\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"), }, - usersTable.getTemplates().toArray() - ); + usersTable.getTemplates().toArray()); }) .verifyComplete(); } @@ -536,8 +584,8 @@ public void testDuplicateColumnNames() throws SQLException { ResultSetMetaData mockResultSetMetaData = mock(ResultSetMetaData.class); when(mockResultSet.getMetaData()).thenReturn(mockResultSetMetaData); when(mockResultSetMetaData.getColumnCount()).thenReturn(4); - when(mockResultSetMetaData.getColumnTypeName(Mockito.anyInt())).thenReturn("int4", "int4", "varchar", - "varchar"); + when(mockResultSetMetaData.getColumnTypeName(Mockito.anyInt())) + .thenReturn("int4", "int4", "varchar", "varchar"); when(mockResultSetMetaData.getColumnName(Mockito.anyInt())).thenReturn("id", "id", "username", "username"); ActionConfiguration actionConfiguration = new ActionConfiguration(); @@ -548,8 +596,8 @@ public void testDuplicateColumnNames() throws SQLException { RedshiftPlugin.RedshiftPluginExecutor spyPluginExecutor = spy(new RedshiftPlugin.RedshiftPluginExecutor()); doNothing().when(spyPluginExecutor).printConnectionPoolStatus(mockConnectionPool, false); - Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(connPool -> spyPluginExecutor.execute(connPool, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> executeMono = dsConnectionMono.flatMap( + connPool -> spyPluginExecutor.execute(connPool, dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -557,18 +605,15 @@ public void testDuplicateColumnNames() throws SQLException { assertTrue(result.getIsExecutionSuccess()); assertNotEquals(0, result.getMessages().size()); - String expectedMessage = "Your Redshift query result may not have all the columns because " + - "duplicate column names were found for the column(s)"; - assertTrue( - result.getMessages().stream() - .anyMatch(message -> message.contains(expectedMessage)) - ); + String expectedMessage = "Your Redshift query result may not have all the columns because " + + "duplicate column names were found for the column(s)"; + assertTrue(result.getMessages().stream().anyMatch(message -> message.contains(expectedMessage))); /* * - Check if all of the duplicate column names are reported. */ - Set<String> expectedColumnNames = Stream.of("id", "username") - .collect(Collectors.toCollection(HashSet::new)); + Set<String> expectedColumnNames = + Stream.of("id", "username").collect(Collectors.toCollection(HashSet::new)); Set<String> foundColumnNames = new HashSet<>(); result.getMessages().stream() .filter(message -> message.contains(expectedMessage)) diff --git a/app/server/appsmith-plugins/restApiPlugin/pom.xml b/app/server/appsmith-plugins/restApiPlugin/pom.xml index a5f481f6d17d..775003d9ea5d 100644 --- a/app/server/appsmith-plugins/restApiPlugin/pom.xml +++ b/app/server/appsmith-plugins/restApiPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>restApiPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -80,7 +79,8 @@ </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> - <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --> + <artifactId>jjwt-jackson</artifactId> + <!-- or jjwt-gson if Gson is preferred --> <version>${jjwt.version}</version> </dependency> @@ -110,10 +110,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy</goal> </goals> + <phase>package</phase> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <artifactItems> diff --git a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java index 575cc120344c..51645d7705a3 100644 --- a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java +++ b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java @@ -66,10 +66,11 @@ public RestApiPluginExecutor(SharedConfig sharedConfig) { * @return */ @Override - public Mono<ActionExecutionResult> executeParameterized(APIConnection connection, - ExecuteActionDTO executeActionDTO, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> executeParameterized( + APIConnection connection, + ExecuteActionDTO executeActionDTO, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { final List<Property> properties = actionConfiguration.getPluginSpecifiedTemplates(); List<Map.Entry<String, String>> parameters = new ArrayList<>(); @@ -81,15 +82,15 @@ public Mono<ActionExecutionResult> executeParameterized(APIConnection connection if (actionConfiguration.getBody() != null) { // First extract all the bindings in order - List<MustacheBindingToken> mustacheKeysInOrder = MustacheHelper.extractMustacheKeysInOrder(actionConfiguration.getBody()); + List<MustacheBindingToken> mustacheKeysInOrder = + MustacheHelper.extractMustacheKeysInOrder(actionConfiguration.getBody()); // Replace all the bindings with a ? as expected in a prepared statement. - String updatedBody = MustacheHelper.replaceMustacheWithPlaceholder(actionConfiguration.getBody(), mustacheKeysInOrder); + String updatedBody = MustacheHelper.replaceMustacheWithPlaceholder( + actionConfiguration.getBody(), mustacheKeysInOrder); try { - updatedBody = (String) smartSubstitutionOfBindings(updatedBody, - mustacheKeysInOrder, - executeActionDTO.getParams(), - parameters); + updatedBody = (String) smartSubstitutionOfBindings( + updatedBody, mustacheKeysInOrder, executeActionDTO.getParams(), parameters); } catch (AppsmithPluginException e) { ActionExecutionResult errorResult = new ActionExecutionResult(); errorResult.setIsExecutionSuccess(false); @@ -104,12 +105,17 @@ public Mono<ActionExecutionResult> executeParameterized(APIConnection connection prepareConfigurationsForExecution(executeActionDTO, actionConfiguration, datasourceConfiguration); // If the action is paginated, update the configurations to update the correct URL. - if (actionConfiguration.getPaginationType() != null && - PaginationType.URL.equals(actionConfiguration.getPaginationType()) && - executeActionDTO.getPaginationField() != null) { + if (actionConfiguration.getPaginationType() != null + && PaginationType.URL.equals(actionConfiguration.getPaginationType()) + && executeActionDTO.getPaginationField() != null) { List<Property> paginationQueryParamsList = new ArrayList<>(); - updateDatasourceConfigurationForPagination(actionConfiguration, datasourceConfiguration, paginationQueryParamsList,executeActionDTO.getPaginationField()); - updateActionConfigurationForPagination(actionConfiguration, paginationQueryParamsList,executeActionDTO.getPaginationField()); + updateDatasourceConfigurationForPagination( + actionConfiguration, + datasourceConfiguration, + paginationQueryParamsList, + executeActionDTO.getPaginationField()); + updateActionConfigurationForPagination( + actionConfiguration, paginationQueryParamsList, executeActionDTO.getPaginationField()); } // Filter out any empty headers @@ -119,10 +125,11 @@ public Mono<ActionExecutionResult> executeParameterized(APIConnection connection return this.executeCommon(connection, datasourceConfiguration, actionConfiguration, parameters); } - public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, - DatasourceConfiguration datasourceConfiguration, - ActionConfiguration actionConfiguration, - List<Map.Entry<String, String>> insertedParams) { + public Mono<ActionExecutionResult> executeCommon( + APIConnection apiConnection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration, + List<Map.Entry<String, String>> insertedParams) { // Initializing object for error condition ActionExecutionResult errorResult = new ActionExecutionResult(); @@ -138,13 +145,16 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, URI uri; try { - uri = uriUtils.createUriWithQueryParams(actionConfiguration, datasourceConfiguration, url, - encodeParamsToggle); + uri = uriUtils.createUriWithQueryParams( + actionConfiguration, datasourceConfiguration, url, encodeParamsToggle); } catch (Exception e) { - ActionExecutionRequest actionExecutionRequest = - RequestCaptureFilter.populateRequestFields(actionConfiguration, null, insertedParams, objectMapper); + ActionExecutionRequest actionExecutionRequest = RequestCaptureFilter.populateRequestFields( + actionConfiguration, null, insertedParams, objectMapper); actionExecutionRequest.setUrl(url); - errorResult.setErrorInfo(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, RestApiErrorMessages.URI_SYNTAX_WRONG_ERROR_MSG, e.getMessage())); + errorResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + RestApiErrorMessages.URI_SYNTAX_WRONG_ERROR_MSG, + e.getMessage())); errorResult.setRequest(actionExecutionRequest); return Mono.just(errorResult); } @@ -152,51 +162,67 @@ public Mono<ActionExecutionResult> executeCommon(APIConnection apiConnection, ActionExecutionRequest actionExecutionRequest = RequestCaptureFilter.populateRequestFields(actionConfiguration, uri, insertedParams, objectMapper); - WebClient.Builder webClientBuilder = restAPIActivateUtils.getWebClientBuilder(actionConfiguration, - datasourceConfiguration); + WebClient.Builder webClientBuilder = + restAPIActivateUtils.getWebClientBuilder(actionConfiguration, datasourceConfiguration); String reqContentType = headerUtils.getRequestContentType(actionConfiguration, datasourceConfiguration); /* Check for content type */ final String contentTypeError = headerUtils.verifyContentType(actionConfiguration.getHeaders()); if (contentTypeError != null) { - errorResult.setErrorInfo(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, RestApiErrorMessages.INVALID_CONTENT_TYPE_ERROR_MSG)); + errorResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + RestApiErrorMessages.INVALID_CONTENT_TYPE_ERROR_MSG)); errorResult.setRequest(actionExecutionRequest); return Mono.just(errorResult); } HttpMethod httpMethod = actionConfiguration.getHttpMethod(); if (httpMethod == null) { - errorResult.setErrorInfo(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, RestApiErrorMessages.NO_HTTP_METHOD_ERROR_MSG)); + errorResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + RestApiErrorMessages.NO_HTTP_METHOD_ERROR_MSG)); errorResult.setRequest(actionExecutionRequest); return Mono.just(errorResult); } final RequestCaptureFilter requestCaptureFilter = new RequestCaptureFilter(objectMapper); - Object requestBodyObj = dataUtils.getRequestBodyObject(actionConfiguration, reqContentType, - encodeParamsToggle, httpMethod); - WebClient client = restAPIActivateUtils.getWebClient(webClientBuilder, apiConnection, reqContentType, - EXCHANGE_STRATEGIES, requestCaptureFilter); + Object requestBodyObj = + dataUtils.getRequestBodyObject(actionConfiguration, reqContentType, encodeParamsToggle, httpMethod); + WebClient client = restAPIActivateUtils.getWebClient( + webClientBuilder, apiConnection, reqContentType, EXCHANGE_STRATEGIES, requestCaptureFilter); /* Triggering the actual REST API call */ - return restAPIActivateUtils.triggerApiCall( - client, httpMethod, uri, requestBodyObj, actionExecutionRequest, - objectMapper, hintMessages, errorResult, requestCaptureFilter - ) + return restAPIActivateUtils + .triggerApiCall( + client, + httpMethod, + uri, + requestBodyObj, + actionExecutionRequest, + objectMapper, + hintMessages, + errorResult, + requestCaptureFilter) .onErrorResume(error -> { boolean isBodySentWithApiRequest = requestBodyObj == null ? false : true; - errorResult.setRequest(requestCaptureFilter.populateRequestFields(actionExecutionRequest, isBodySentWithApiRequest)); + errorResult.setRequest(requestCaptureFilter.populateRequestFields( + actionExecutionRequest, isBodySentWithApiRequest)); errorResult.setIsExecutionSuccess(false); - if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(RestApiPluginError.API_EXECUTION_FAILED, RestApiErrorMessages.API_EXECUTION_FAILED_ERROR_MSG, error); + if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + RestApiPluginError.API_EXECUTION_FAILED, + RestApiErrorMessages.API_EXECUTION_FAILED_ERROR_MSG, + error); } errorResult.setErrorInfo(error); return Mono.just(errorResult); }); } - private ActionConfiguration updateActionConfigurationForPagination(ActionConfiguration actionConfiguration, - List<Property> queryParamsList, - PaginationField paginationField) { + private ActionConfiguration updateActionConfigurationForPagination( + ActionConfiguration actionConfiguration, + List<Property> queryParamsList, + PaginationField paginationField) { if (PaginationField.NEXT.equals(paginationField) || PaginationField.PREV.equals(paginationField)) { actionConfiguration.setPath(""); actionConfiguration.setQueryParameters(queryParamsList); @@ -204,27 +230,31 @@ private ActionConfiguration updateActionConfigurationForPagination(ActionConfigu return actionConfiguration; } - private DatasourceConfiguration updateDatasourceConfigurationForPagination(ActionConfiguration actionConfiguration, - DatasourceConfiguration datasourceConfiguration, - List<Property> paginationQueryParamsList, - PaginationField paginationField) { + private DatasourceConfiguration updateDatasourceConfigurationForPagination( + ActionConfiguration actionConfiguration, + DatasourceConfiguration datasourceConfiguration, + List<Property> paginationQueryParamsList, + PaginationField paginationField) { if (PaginationField.NEXT.equals(paginationField)) { if (actionConfiguration.getNext() == null) { datasourceConfiguration.setUrl(null); } else { - paginationQueryParamsList.addAll(decodeUrlAndGetAllQueryParams(datasourceConfiguration,actionConfiguration.getNext())); + paginationQueryParamsList.addAll( + decodeUrlAndGetAllQueryParams(datasourceConfiguration, actionConfiguration.getNext())); } } else if (PaginationField.PREV.equals(paginationField)) { - paginationQueryParamsList.addAll(decodeUrlAndGetAllQueryParams(datasourceConfiguration,actionConfiguration.getPrev())); + paginationQueryParamsList.addAll( + decodeUrlAndGetAllQueryParams(datasourceConfiguration, actionConfiguration.getPrev())); } return datasourceConfiguration; } - private List<Property> decodeUrlAndGetAllQueryParams(DatasourceConfiguration datasourceConfiguration, String inputUrl) { + private List<Property> decodeUrlAndGetAllQueryParams( + DatasourceConfiguration datasourceConfiguration, String inputUrl) { - String decodedUrl = URLDecoder.decode(inputUrl,StandardCharsets.UTF_8); + String decodedUrl = URLDecoder.decode(inputUrl, StandardCharsets.UTF_8); String[] urlParts = decodedUrl.split("\\?"); datasourceConfiguration.setUrl(urlParts[0]); @@ -248,7 +278,7 @@ private List<Property> decodeUrlAndGetAllQueryParams(DatasourceConfiguration dat return new ArrayList<>(); } - private List<Property> getQueryParamListFromUrlSuffix(String queryParams) { + private List<Property> getQueryParamListFromUrlSuffix(String queryParams) { String[] queryParamArray = queryParams.split("&"); @@ -260,11 +290,11 @@ private List<Property> getQueryParamListFromUrlSuffix(String queryParams) { String key = keyValue.length > 0 ? keyValue[0] : ""; String value = keyValue.length > 1 ? keyValue[1] : ""; - if (key.length() == 0) { + if (key.isEmpty()) { continue; } - Property property = new Property(key,value); + Property property = new Property(key, value); queryParamList.add(property); } @@ -272,15 +302,17 @@ private List<Property> getQueryParamListFromUrlSuffix(String queryParams) { } @Override - public Object substituteValueInInput(int index, - String binding, - String value, - Object input, - List<Map.Entry<String, String>> insertedParams, - Object... args) { + public Object substituteValueInInput( + int index, + String binding, + String value, + Object input, + List<Map.Entry<String, String>> insertedParams, + Object... args) { String jsonBody = (String) input; Param param = (Param) args[0]; - return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue(jsonBody, value, null, insertedParams, null, param); + return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue( + jsonBody, value, null, insertedParams, null, param); } } } diff --git a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/exceptions/RestApiPluginError.java b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/exceptions/RestApiPluginError.java index ba8a2481956d..2a93577ad915 100644 --- a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/exceptions/RestApiPluginError.java +++ b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/exceptions/RestApiPluginError.java @@ -17,8 +17,7 @@ public enum RestApiPluginError implements BasePluginError { "API execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; private final String appErrorCode; @@ -31,8 +30,15 @@ public enum RestApiPluginError implements BasePluginError { private final String downstreamErrorCode; - RestApiPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + RestApiPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -47,7 +53,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java b/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java index cc48ef48b597..12d4d27e7dde 100644 --- a/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java +++ b/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java @@ -98,7 +98,8 @@ public String getRemoteExecutionUrl() { } } - RestApiPlugin.RestApiPluginExecutor pluginExecutor = new RestApiPlugin.RestApiPluginExecutor(new MockSharedConfig()); + RestApiPlugin.RestApiPluginExecutor pluginExecutor = + new RestApiPlugin.RestApiPluginExecutor(new MockSharedConfig()); @BeforeEach public void setUp() throws IOException { @@ -111,7 +112,7 @@ public void setUp() throws IOException { public void tearDown() throws IOException { mockEndpoint.shutdown(); } - + @Test public void testValidJsonApiExecution() { DatasourceConfiguration dsConfig = new DatasourceConfiguration(); @@ -119,11 +120,7 @@ public void testValidJsonApiExecution() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); - + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); final List<Property> headers = List.of(new Property("content-type", "application/json")); @@ -132,7 +129,8 @@ public void testValidJsonApiExecution() { String requestBody = "{\"key\":\"value\"}"; actionConfig.setBody(requestBody); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -152,15 +150,16 @@ public void testValidJsonApiExecution() { assert false : e.getMessage(); } - final ActionExecutionRequest request = result.getRequest(); assertEquals(baseUrl, request.getUrl()); assertEquals(HttpMethod.POST, request.getHttpMethod()); assertEquals(requestBody, request.getBody().toString()); - final Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) result.getRequest().getHeaders()).fields(); + final Iterator<Map.Entry<String, JsonNode>> fields = + ((ObjectNode) result.getRequest().getHeaders()).fields(); fields.forEachRemaining(field -> { if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(field.getKey())) { - assertEquals("application/json", field.getValue().get(0).asText()); + assertEquals( + "application/json", field.getValue().get(0).asText()); } }); }) @@ -172,13 +171,10 @@ public void testValidApiExecutionWithWhitespacesInUrl() { DatasourceConfiguration dsConfig = new DatasourceConfiguration(); String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); - //added whitespaces in url to validate successful execution of the same + // added whitespaces in url to validate successful execution of the same dsConfig.setUrl(" " + baseUrl + " "); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); final List<Property> headers = List.of(new Property("content-type", "application/json")); @@ -187,7 +183,8 @@ public void testValidApiExecutionWithWhitespacesInUrl() { String requestBody = "{\"key\":\"value\"}"; actionConfig.setBody(requestBody); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -217,10 +214,7 @@ public void testExecuteApiWithPaginationForPreviousUrl() throws IOException { final List<Property> headers = List.of(); final List<Property> queryParameters = List.of( - new Property("mock_filter", "abc 11"), - new Property("pageSize", "1"), - new Property("page", "3") - ); + new Property("mock_filter", "abc 11"), new Property("pageSize", "1"), new Property("page", "3")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(headers); @@ -241,7 +235,8 @@ public void testExecuteApiWithPaginationForPreviousUrl() throws IOException { actionConfig.setFormData(Collections.singletonMap("apiContentType", "none")); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -266,8 +261,8 @@ public void testExecuteApiWithPaginationForPreviousEncodedUrl() throws IOExcepti HttpUrl mockHttpUrl = mockEndpoint.url("/mock"); - String previousUrl = URLEncoder.encode(mockHttpUrl + "?pageSize=1&page=2&mock_filter=abc 11", - StandardCharsets.UTF_8); + String previousUrl = + URLEncoder.encode(mockHttpUrl + "?pageSize=1&page=2&mock_filter=abc 11", StandardCharsets.UTF_8); String nextUrl = mockHttpUrl + "?pageSize=1&page=4&mock_filter=abc 11"; ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); @@ -280,10 +275,7 @@ public void testExecuteApiWithPaginationForPreviousEncodedUrl() throws IOExcepti final List<Property> headers = List.of(); final List<Property> queryParameters = List.of( - new Property("mock_filter", "abc 11"), - new Property("pageSize", "1"), - new Property("page", "3") - ); + new Property("mock_filter", "abc 11"), new Property("pageSize", "1"), new Property("page", "3")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(headers); @@ -304,7 +296,8 @@ public void testExecuteApiWithPaginationForPreviousEncodedUrl() throws IOExcepti actionConfig.setFormData(Collections.singletonMap("apiContentType", "none")); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -342,10 +335,7 @@ public void testExecuteApiWithPaginationForNextUrl() throws IOException { final List<Property> headers = List.of(); final List<Property> queryParameters = List.of( - new Property("mock_filter", "abc 11"), - new Property("pageSize", "1"), - new Property("page", "3") - ); + new Property("mock_filter", "abc 11"), new Property("pageSize", "1"), new Property("page", "3")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(headers); @@ -366,7 +356,8 @@ public void testExecuteApiWithPaginationForNextUrl() throws IOException { actionConfig.setFormData(Collections.singletonMap("apiContentType", "none")); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -392,7 +383,8 @@ public void testExecuteApiWithPaginationForNextEncodedUrl() throws IOException { HttpUrl mockHttpUrl = mockEndpoint.url("/mock"); String previousUrl = mockHttpUrl + "?pageSize=1&page=2&mock_filter=abc 11"; - String nextUrl = URLEncoder.encode(mockHttpUrl + "?pageSize=1&page=4&mock_filter=abc 11", StandardCharsets.UTF_8); + String nextUrl = + URLEncoder.encode(mockHttpUrl + "?pageSize=1&page=4&mock_filter=abc 11", StandardCharsets.UTF_8); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setPaginationField(PaginationField.NEXT); @@ -404,10 +396,7 @@ public void testExecuteApiWithPaginationForNextEncodedUrl() throws IOException { final List<Property> headers = List.of(); final List<Property> queryParameters = List.of( - new Property("mock_filter", "abc 11"), - new Property("pageSize", "1"), - new Property("page", "3") - ); + new Property("mock_filter", "abc 11"), new Property("pageSize", "1"), new Property("page", "3")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(headers); @@ -428,7 +417,8 @@ public void testExecuteApiWithPaginationForNextEncodedUrl() throws IOException { actionConfig.setFormData(Collections.singletonMap("apiContentType", "none")); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -451,21 +441,15 @@ public void testValidFormApiExecution() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); - + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/x-www-form-urlencoded"))); actionConfig.setHttpMethod(HttpMethod.POST); actionConfig.setBodyFormData(List.of( - new Property("key", "value"), - new Property("key1", "value1"), - new Property(null, "irrelevantValue") - )); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + new Property("key", "value"), new Property("key1", "value1"), new Property(null, "irrelevantValue"))); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -498,11 +482,7 @@ public void testValidRawApiExecution() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); - + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "text/plain;charset=UTF-8"))); @@ -510,7 +490,8 @@ public void testValidRawApiExecution() { String requestBody = "{\"key\":\"value\"}"; actionConfig.setBody(requestBody); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -541,21 +522,16 @@ public void testValidSignature() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); - + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); final String secretKey = "a-random-key-that-should-be-32-chars-long-at-least"; - dsConfig.setProperties(List.of( - new Property("isSendSessionEnabled", "Y"), - new Property("sessionSignatureKey", secretKey) - )); + dsConfig.setProperties( + List.of(new Property("isSendSessionEnabled", "Y"), new Property("sessionSignatureKey", secretKey))); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -575,7 +551,8 @@ public void testValidSignature() { .getBody() .getIssuer(); assertEquals("Appsmith", issuer); - final Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) result.getRequest().getHeaders()).fields(); + final Iterator<Map.Entry<String, JsonNode>> fields = + ((ObjectNode) result.getRequest().getHeaders()).fields(); fields.forEachRemaining(field -> { if ("X-Appsmith-Signature".equalsIgnoreCase(field.getKey())) { assertEquals(token, field.getValue().get(0).asText()); @@ -585,7 +562,6 @@ public void testValidSignature() { } catch (InterruptedException e) { assert false : e.getMessage(); } - }) .verifyComplete(); } @@ -611,8 +587,7 @@ public void testHttpGetRequestRawBody() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setUrl("https://postman-echo.com/get"); - final List<Property> headers = List.of( - new Property("content-type", MediaType.TEXT_PLAIN_VALUE)); + final List<Property> headers = List.of(new Property("content-type", MediaType.TEXT_PLAIN_VALUE)); final List<Property> queryParameters = List.of(); @@ -638,7 +613,8 @@ public void testHttpGetRequestRawBody() { for (int requestBodyIndex = 0; requestBodyIndex < requestBodyList.length; requestBodyIndex++) { actionConfiguration.setBody(requestBodyList[requestBodyIndex]); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, datasourceConfiguration, actionConfiguration); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized( + null, executeActionDTO, datasourceConfiguration, actionConfiguration); int currentIndex = requestBodyIndex; StepVerifier.create(resultMono) @@ -668,20 +644,16 @@ public void testInvalidSignature() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); final String secretKey = "a-random-key-that-should-be-32-chars-long-at-least"; - dsConfig.setProperties(List.of( - new Property("isSendSessionEnabled", "Y"), - new Property("sessionSignatureKey", secretKey) - )); + dsConfig.setProperties( + List.of(new Property("isSendSessionEnabled", "Y"), new Property("sessionSignatureKey", secretKey))); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -694,13 +666,13 @@ public void testInvalidSignature() { String token = recordedRequest.getHeaders().get("X-Appsmith-Signature"); final SecretKey key = Keys.hmacShaKeyFor((secretKey + "-abc").getBytes(StandardCharsets.UTF_8)); - final JwtParser parser = Jwts.parserBuilder().setSigningKey(key).build(); + final JwtParser parser = + Jwts.parserBuilder().setSigningKey(key).build(); assertThrows(SignatureException.class, () -> parser.parseClaimsJws(token)); } catch (InterruptedException e) { assert false : e.getMessage(); } - }) .verifyComplete(); } @@ -712,10 +684,7 @@ public void testEncodeParamsToggleOn() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); @@ -728,7 +697,8 @@ public void testEncodeParamsToggleOn() { actionConfig.setQueryParameters(queryParams); actionConfig.setEncodeParamsToggle(true); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -762,10 +732,7 @@ public void testEncodeParamsToggleNull() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); @@ -778,7 +745,8 @@ public void testEncodeParamsToggleNull() { actionConfig.setQueryParameters(queryParams); actionConfig.setEncodeParamsToggle(null); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -812,10 +780,7 @@ public void testEncodeParamsToggleOff() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); @@ -829,12 +794,13 @@ public void testEncodeParamsToggleOff() { actionConfig.setEncodeParamsToggle(false); Mono<RestApiPlugin.RestApiPluginExecutor> pluginExecutorMono = Mono.just(pluginExecutor); - Mono<ActionExecutionResult> resultMono = pluginExecutorMono.flatMap(executor -> executor.executeParameterized(null, - new ExecuteActionDTO(), - dsConfig, - actionConfig)); + Mono<ActionExecutionResult> resultMono = pluginExecutorMono.flatMap( + executor -> executor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig)); StepVerifier.create(resultMono) - .assertNext(actionExecutionResult -> assertTrue(actionExecutionResult.getPluginErrorDetails().getDownstreamErrorMessage().contains("Invalid character ' ' for QUERY_PARAM in \"query val\""))) + .assertNext(actionExecutionResult -> assertTrue(actionExecutionResult + .getPluginErrorDetails() + .getDownstreamErrorMessage() + .contains("Invalid character ' ' for QUERY_PARAM in \"query val\""))) .verifyComplete(); } @@ -846,11 +812,12 @@ public void testValidateDatasource_invalidAuthentication() { datasourceConfiguration.setAuthentication(oAuth2); Mono<RestApiPlugin.RestApiPluginExecutor> pluginExecutorMono = Mono.just(pluginExecutor); - Mono<Set<String>> invalidsMono = pluginExecutorMono.map(executor -> executor.validateDatasource(datasourceConfiguration)); + Mono<Set<String>> invalidsMono = + pluginExecutorMono.map(executor -> executor.validateDatasource(datasourceConfiguration)); - StepVerifier - .create(invalidsMono) - .assertNext(invalids -> assertIterableEquals(Set.of("Missing Client ID", "Missing client secret", "Missing access token URL"), invalids)); + StepVerifier.create(invalidsMono) + .assertNext(invalids -> assertIterableEquals( + Set.of("Missing Client ID", "Missing client secret", "Missing access token URL"), invalids)); } @Test @@ -859,15 +826,13 @@ public void testSmartSubstitutionJSONBody() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); actionConfig.setHttpMethod(HttpMethod.POST); - String requestBody = """ + String requestBody = + """ { \t"name" : {{Input1.text}}, \t"email" : {{Input2.text}}, @@ -911,22 +876,26 @@ public void testSmartSubstitutionJSONBody() { params.add(param6); Param param7 = new Param(); param7.setKey("Table1.selectedRow"); - param7.setValue("{ \"id\": 2381224, \"email\": \"[email protected]\", \"userName\": \"Michael Lawson\", \"productName\": \"Chicken Sandwich\", \"orderAmount\": 4.99}"); + param7.setValue( + "{ \"id\": 2381224, \"email\": \"[email protected]\", \"userName\": \"Michael Lawson\", \"productName\": \"Chicken Sandwich\", \"orderAmount\": 4.99}"); param7.setClientDataType(ClientDataType.OBJECT); params.add(param7); Param param8 = new Param(); param8.setKey("Table1.tableData"); - param8.setValue("[ { \"id\": 2381224, \"email\": \"[email protected]\", \"userName\": \"Michael Lawson\", \"productName\": \"Chicken Sandwich\", \"orderAmount\": 4.99 }, { \"id\": 2736212, \"email\": \"[email protected]\", \"userName\": \"Lindsay Ferguson\", \"productName\": \"Tuna Salad\", \"orderAmount\": 9.99 }, { \"id\": 6788734, \"email\": \"[email protected]\", \"userName\": \"Tobias Funke\", \"productName\": \"Beef steak\", \"orderAmount\": 19.99 }]"); + param8.setValue( + "[ { \"id\": 2381224, \"email\": \"[email protected]\", \"userName\": \"Michael Lawson\", \"productName\": \"Chicken Sandwich\", \"orderAmount\": 4.99 }, { \"id\": 2736212, \"email\": \"[email protected]\", \"userName\": \"Lindsay Ferguson\", \"productName\": \"Tuna Salad\", \"orderAmount\": 9.99 }, { \"id\": 6788734, \"email\": \"[email protected]\", \"userName\": \"Tobias Funke\", \"productName\": \"Beef steak\", \"orderAmount\": 19.99 }]"); param8.setClientDataType(ClientDataType.ARRAY); params.add(param8); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - String resultBody = "{\"password\":\"12/01/2018\",\"name\":\"this is a string! Yay :D\",\"newField\":null,\"tableRow\":{\"orderAmount\":4.99,\"id\":2381224,\"userName\":\"Michael Lawson\",\"email\":\"[email protected]\",\"productName\":\"Chicken Sandwich\"},\"email\":true,\"table\":[{\"orderAmount\":4.99,\"id\":2381224,\"userName\":\"Michael Lawson\",\"email\":\"[email protected]\",\"productName\":\"Chicken Sandwich\"},{\"orderAmount\":9.99,\"id\":2736212,\"userName\":\"Lindsay Ferguson\",\"email\":\"[email protected]\",\"productName\":\"Tuna Salad\"},{\"orderAmount\":19.99,\"id\":6788734,\"userName\":\"Tobias Funke\",\"email\":\"[email protected]\",\"productName\":\"Beef steak\"}],\"username\":0}"; + String resultBody = + "{\"password\":\"12/01/2018\",\"name\":\"this is a string! Yay :D\",\"newField\":null,\"tableRow\":{\"orderAmount\":4.99,\"id\":2381224,\"userName\":\"Michael Lawson\",\"email\":\"[email protected]\",\"productName\":\"Chicken Sandwich\"},\"email\":true,\"table\":[{\"orderAmount\":4.99,\"id\":2381224,\"userName\":\"Michael Lawson\",\"email\":\"[email protected]\",\"productName\":\"Chicken Sandwich\"},{\"orderAmount\":9.99,\"id\":2736212,\"userName\":\"Lindsay Ferguson\",\"email\":\"[email protected]\",\"productName\":\"Tuna Salad\"},{\"orderAmount\":19.99,\"id\":6788734,\"userName\":\"Tobias Funke\",\"email\":\"[email protected]\",\"productName\":\"Beef steak\"}],\"username\":0}"; try { final RecordedRequest recordedRequest = mockEndpoint.takeRequest(30, TimeUnit.SECONDS); @@ -944,8 +913,8 @@ public void testSmartSubstitutionJSONBody() { // Assert the debug request parameters are getting set. ActionExecutionRequest request = result.getRequest(); - List<Map.Entry<String, String>> parameters = - (List<Map.Entry<String, String>>) request.getProperties().get("smart-substitution-parameters"); + List<Map.Entry<String, String>> parameters = (List<Map.Entry<String, String>>) + request.getProperties().get("smart-substitution-parameters"); assertEquals(7, parameters.size()); Map.Entry<String, String> parameterEntry = parameters.get(0); @@ -977,30 +946,31 @@ public void testMultipartFormData() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setAutoGeneratedHeaders(List.of(new Property("content-type", "multipart/form-data"))); actionConfig.setHttpMethod(HttpMethod.POST); final Property key1 = new Property("key1", "onlyValue"); - final Property key2 = new Property("key2", "{\"name\":\"fileName\", \"type\":\"application/json\", \"data\":{\"key\":\"value\"}}"); - final Property key3 = new Property("key3", "[{\"name\":\"fileName2\", \"type\":\"application/json\", \"data\":{\"key2\":\"value2\"}}]"); + final Property key2 = new Property( + "key2", "{\"name\":\"fileName\", \"type\":\"application/json\", \"data\":{\"key\":\"value\"}}"); + final Property key3 = new Property( + "key3", "[{\"name\":\"fileName2\", \"type\":\"application/json\", \"data\":{\"key2\":\"value2\"}}]"); final Property key4 = new Property(null, "irrelevantValue"); key2.setType("FILE"); key3.setType("FILE"); List<Property> formData = List.of(key1, key2, key3, key4); actionConfig.setBodyFormData(formData); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getBody()); - assertEquals(Map.of( + assertEquals( + Map.of( "key1", "onlyValue", "key2", "<file>", "key3", "<file>"), @@ -1017,20 +987,26 @@ public void testMultipartFormData() { String bodyString = new String(bodyBytes); - assertTrue(bodyString.contains(""" + assertTrue( + bodyString.contains( + """ Content-Disposition: form-data; name="key1"\r Content-Type: text/plain;charset=UTF-8\r Content-Length: 9\r \r onlyValue""")); - assertTrue(bodyString.contains(""" + assertTrue( + bodyString.contains( + """ Content-Disposition: form-data; name="key2"; filename="fileName"\r Content-Type: application/json\r \r {key=value}""")); - assertTrue(bodyString.contains(""" + assertTrue( + bodyString.contains( + """ Content-Disposition: form-data; name="key3"; filename="fileName2"\r Content-Type: application/json\r \r @@ -1048,16 +1024,15 @@ public void testParsingBodyWithInvalidJSONHeader() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("invalid json text") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue( + new MockResponse().setBody("invalid json text").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); actionConfig.setHttpMethod(HttpMethod.POST); - String requestBody = """ + String requestBody = + """ { "headers": { "Content-Type": "application/json", @@ -1067,7 +1042,8 @@ public void testParsingBodyWithInvalidJSONHeader() { }"""; actionConfig.setBody(requestBody); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -1082,7 +1058,8 @@ public void testParsingBodyWithInvalidJSONHeader() { recordedRequestBody.readFully(bodyBytes); recordedRequestBody.close(); - assertEquals("{\"headers\":{\"X-RANDOM-HEADER\":\"random-value\",\"Content-Type\":\"application/json\"},\"body\":\"invalid json text\"}", + assertEquals( + "{\"headers\":{\"X-RANDOM-HEADER\":\"random-value\",\"Content-Type\":\"application/json\"},\"body\":\"invalid json text\"}", new String(bodyBytes)); String contentType = recordedRequest.getHeaders().get("Content-Type"); @@ -1093,11 +1070,11 @@ public void testParsingBodyWithInvalidJSONHeader() { assertEquals("invalid json text", result.getBody()); assertEquals(1, result.getMessages().size()); - String expectedMessage = "The response returned by this API is not a valid JSON. Please " + - "be careful when using the API response anywhere a valid JSON is required" + - ". You may resolve this issue either by modifying the 'Content-Type' " + - "Header to indicate a non-JSON response or by modifying the API response " + - "to return a valid JSON."; + String expectedMessage = "The response returned by this API is not a valid JSON. Please " + + "be careful when using the API response anywhere a valid JSON is required" + + ". You may resolve this issue either by modifying the 'Content-Type' " + + "Header to indicate a non-JSON response or by modifying the API response " + + "to return a valid JSON."; assertEquals(expectedMessage, result.getMessages().toArray()[0]); }) .verifyComplete(); @@ -1109,10 +1086,7 @@ public void testRequestWithApiKeyHeader() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); AuthenticationDTO authenticationDTO = new ApiKeyAuth(ApiKeyAuth.Type.HEADER, "api_key", "Token", "test"); dsConfig.setAuthentication(authenticationDTO); @@ -1120,24 +1094,27 @@ public void testRequestWithApiKeyHeader() { ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of( new Property("content-type", "application/json"), - new Property(HttpHeaders.AUTHORIZATION, "auth-value") - )); + new Property(HttpHeaders.AUTHORIZATION, "auth-value"))); actionConfig.setAutoGeneratedHeaders(List.of(new Property("content-type", "application/json"))); actionConfig.setHttpMethod(HttpMethod.POST); String requestBody = "{\"key\":\"value\"}"; actionConfig.setBody(requestBody); - final APIConnection apiConnection = pluginExecutor.datasourceCreate(dsConfig).block(); + final APIConnection apiConnection = + pluginExecutor.datasourceCreate(dsConfig).block(); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(apiConnection, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(apiConnection, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); assertNotNull(result.getRequest().getBody()); - final Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) result.getRequest().getHeaders()).fields(); + final Iterator<Map.Entry<String, JsonNode>> fields = + ((ObjectNode) result.getRequest().getHeaders()).fields(); fields.forEachRemaining(field -> { - if ("api_key".equalsIgnoreCase(field.getKey()) || HttpHeaders.AUTHORIZATION.equalsIgnoreCase(field.getKey())) { + if ("api_key".equalsIgnoreCase(field.getKey()) + || HttpHeaders.AUTHORIZATION.equalsIgnoreCase(field.getKey())) { assertEquals("****", field.getValue().get(0).asText()); } }); @@ -1151,15 +1128,13 @@ public void testSmartSubstitutionEvaluatedValueContainingQuestionMark() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); actionConfig.setHttpMethod(HttpMethod.POST); - String requestBody = """ + String requestBody = + """ { \t"name" : {{Input1.text}}, \t"email" : {{Input2.text}}, @@ -1183,7 +1158,8 @@ public void testSmartSubstitutionEvaluatedValueContainingQuestionMark() { params.add(param2); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -1237,7 +1213,7 @@ public void testGetDuplicateHeadersAndParams() { actionHeaders.add(new Property("myHeader4", "myVal")); actionHeaders.add(new Property("myHeader4", "myVal")); // duplicate actionHeaders.add(new Property("myHeader5", "myVal")); - actionHeaders.add(new Property("apiKey", "myVal")); // duplicate - because also inherited from authentication + actionHeaders.add(new Property("apiKey", "myVal")); // duplicate - because also inherited from authentication actionConfig.setHeaders(actionHeaders); // Add params to API query editor page. @@ -1260,8 +1236,7 @@ public void testGetDuplicateHeadersAndParams() { /* Test duplicate query params in datasource configuration only */ Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> duplicateParamsWithDsConfigOnly = - hintMessageUtils.getAllDuplicateParams(null, - dsConfig); + hintMessageUtils.getAllDuplicateParams(null, dsConfig); // Query param duplicates Set<String> expectedDuplicateParams = new HashSet<>(); @@ -1293,8 +1268,7 @@ public void testGetDuplicateHeadersAndParams() { /* Test duplicate query params in action + datasource config */ Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> allDuplicateParams = - hintMessageUtils.getAllDuplicateParams(actionConfig, - dsConfig); + hintMessageUtils.getAllDuplicateParams(actionConfig, dsConfig); // Query param duplicates in datasource config only expectedDuplicateParams = new HashSet<>(); @@ -1326,7 +1300,7 @@ public void testGetDuplicateHeadersWithOAuth() { // Add headers to API query editor page. ArrayList<Property> actionHeaders = new ArrayList<>(); actionHeaders.add(new Property("myHeader1", "myVal")); - actionHeaders.add(new Property("Authorization", "myVal")); // duplicate - because also inherited from dsConfig + actionHeaders.add(new Property("Authorization", "myVal")); // duplicate - because also inherited from dsConfig ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(actionHeaders); @@ -1366,8 +1340,7 @@ public void testGetDuplicateParamsWithOAuth() { /* Test duplicate params in datasource + action configuration */ Map<DUPLICATE_ATTRIBUTE_LOCATION, Set<String>> allDuplicateParams = - hintMessageUtils.getAllDuplicateParams(actionConfig, - dsConfig); + hintMessageUtils.getAllDuplicateParams(actionConfig, dsConfig); // Param duplicates in ds config only assertTrue(allDuplicateParams.get(DATASOURCE_CONFIG_ONLY).isEmpty()); @@ -1407,26 +1380,26 @@ public void testHintMessageForDuplicateHeadersAndParamsWithDatasourceConfigOnly( .assertNext(tuple -> { Set<String> datasourceHintMessages = tuple.getT1(); Set<String> expectedDatasourceHintMessages = new HashSet<>(); - expectedDatasourceHintMessages.add("API queries linked to this datasource may not run as expected" + - " because this datasource has duplicate definition(s) for param(s): [myParam1]. Please " + - "remove the duplicate definition(s) to resolve this warning. Please note that some of the" + - " authentication mechanisms also implicitly define a param."); - - expectedDatasourceHintMessages.add("API queries linked to this datasource may not run as expected" + - " because this datasource has duplicate definition(s) for header(s): [myHeader1]. Please " + - "remove the duplicate definition(s) to resolve this warning. Please note that some of the" + - " authentication mechanisms also implicitly define a header."); + expectedDatasourceHintMessages.add("API queries linked to this datasource may not run as expected" + + " because this datasource has duplicate definition(s) for param(s): [myParam1]. Please " + + "remove the duplicate definition(s) to resolve this warning. Please note that some of the" + + " authentication mechanisms also implicitly define a param."); + + expectedDatasourceHintMessages.add("API queries linked to this datasource may not run as expected" + + " because this datasource has duplicate definition(s) for header(s): [myHeader1]. Please " + + "remove the duplicate definition(s) to resolve this warning. Please note that some of the" + + " authentication mechanisms also implicitly define a header."); assertEquals(expectedDatasourceHintMessages, datasourceHintMessages); Set<String> actionHintMessages = tuple.getT2(); Set<String> expectedActionHintMessages = new HashSet<>(); - expectedActionHintMessages.add("Your API query may not run as expected because its datasource has" + - " duplicate definition(s) for param(s): [myParam1]. Please remove the duplicate " + - "definition(s) from the datasource to resolve this warning."); + expectedActionHintMessages.add("Your API query may not run as expected because its datasource has" + + " duplicate definition(s) for param(s): [myParam1]. Please remove the duplicate " + + "definition(s) from the datasource to resolve this warning."); - expectedActionHintMessages.add("Your API query may not run as expected because its datasource has" + - " duplicate definition(s) for header(s): [myHeader1]. Please remove the duplicate " + - "definition(s) from the datasource to resolve this warning."); + expectedActionHintMessages.add("Your API query may not run as expected because its datasource has" + + " duplicate definition(s) for header(s): [myHeader1]. Please remove the duplicate " + + "definition(s) from the datasource to resolve this warning."); assertEquals(expectedActionHintMessages, actionHintMessages); }) .verifyComplete(); @@ -1454,7 +1427,8 @@ public void testHintMessageForDuplicateHeadersAndParamsWithActionConfigOnly() { actionConfig.setQueryParameters(params); DatasourceConfiguration dsConfig = new DatasourceConfiguration(); - Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = pluginExecutor.getHintMessages(actionConfig, dsConfig); + Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = + pluginExecutor.getHintMessages(actionConfig, dsConfig); StepVerifier.create(hintMessagesMono) .assertNext(tuple -> { Set<String> datasourceHintMessages = tuple.getT1(); @@ -1462,13 +1436,13 @@ public void testHintMessageForDuplicateHeadersAndParamsWithActionConfigOnly() { Set<String> actionHintMessages = tuple.getT2(); Set<String> expectedActionHintMessages = new HashSet<>(); - expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + - "definition(s) for header(s): [myHeader1]. Please remove the duplicate definition(s) from" + - " the 'Headers' tab to resolve this warning."); + expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + + "definition(s) for header(s): [myHeader1]. Please remove the duplicate definition(s) from" + + " the 'Headers' tab to resolve this warning."); - expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + - "definition(s) for param(s): [myParam1]. Please remove the duplicate definition(s) from " + - "the 'Params' tab to resolve this warning."); + expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + + "definition(s) for param(s): [myParam1]. Please remove the duplicate definition(s) from " + + "the 'Params' tab to resolve this warning."); assertEquals(expectedActionHintMessages, actionHintMessages); }) .verifyComplete(); @@ -1487,14 +1461,14 @@ public void testHintMessageForDuplicateHeaderWithOneInstanceEachInActionAndDsCon headers.add(new Property("myHeader1", "myVal")); actionConfig.setHeaders(headers); - // This authentication mechanism will add `myHeader1` as header implicitly. AuthenticationDTO authenticationDTO = new ApiKeyAuth(ApiKeyAuth.Type.HEADER, "myHeader1", "Token", "test"); authenticationDTO.setAuthenticationType(API_KEY); DatasourceConfiguration dsConfig = new DatasourceConfiguration(); dsConfig.setAuthentication(authenticationDTO); - Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = pluginExecutor.getHintMessages(actionConfig, dsConfig); + Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = + pluginExecutor.getHintMessages(actionConfig, dsConfig); StepVerifier.create(hintMessagesMono) .assertNext(tuple -> { Set<String> datasourceHintMessages = tuple.getT1(); @@ -1502,10 +1476,10 @@ public void testHintMessageForDuplicateHeaderWithOneInstanceEachInActionAndDsCon Set<String> actionHintMessages = tuple.getT2(); Set<String> expectedActionHintMessages = new HashSet<>(); - expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + - "definition(s) for header(s): [myHeader1]. Please remove the duplicate definition(s) from" + - " the 'Headers' section of either the API query or the datasource. Please note that some " + - "of the authentication mechanisms also implicitly define a header."); + expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + + "definition(s) for header(s): [myHeader1]. Please remove the duplicate definition(s) from" + + " the 'Headers' section of either the API query or the datasource. Please note that some " + + "of the authentication mechanisms also implicitly define a header."); assertEquals(expectedActionHintMessages, actionHintMessages); }) @@ -1525,14 +1499,14 @@ public void testHintMessageForDuplicateParamWithOneInstanceEachInActionAndDsConf params.add(new Property("myParam1", "myVal")); actionConfig.setQueryParameters(params); - // This authentication mechanism will add `myHeader1` as query param implicitly. AuthenticationDTO authenticationDTO = new ApiKeyAuth(ApiKeyAuth.Type.QUERY_PARAMS, "myParam1", "Token", "test"); authenticationDTO.setAuthenticationType(API_KEY); DatasourceConfiguration dsConfig = new DatasourceConfiguration(); dsConfig.setAuthentication(authenticationDTO); - Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = pluginExecutor.getHintMessages(actionConfig, dsConfig); + Mono<Tuple2<Set<String>, Set<String>>> hintMessagesMono = + pluginExecutor.getHintMessages(actionConfig, dsConfig); StepVerifier.create(hintMessagesMono) .assertNext(tuple -> { Set<String> datasourceHintMessages = tuple.getT1(); @@ -1540,10 +1514,10 @@ public void testHintMessageForDuplicateParamWithOneInstanceEachInActionAndDsConf Set<String> actionHintMessages = tuple.getT2(); Set<String> expectedActionHintMessages = new HashSet<>(); - expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + - "definition(s) for param(s): [myParam1]. Please remove the duplicate definition(s) from" + - " the 'Params' section of either the API query or the datasource. Please note that some " + - "of the authentication mechanisms also implicitly define a param."); + expectedActionHintMessages.add("Your API query may not run as expected because it has duplicate " + + "definition(s) for param(s): [myParam1]. Please remove the duplicate definition(s) from" + + " the 'Params' section of either the API query or the datasource. Please note that some " + + "of the authentication mechanisms also implicitly define a param."); assertEquals(expectedActionHintMessages, actionHintMessages); }) @@ -1556,10 +1530,7 @@ public void testQueryParamsInDatasource() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); @@ -1572,7 +1543,8 @@ public void testQueryParamsInDatasource() { queryParams.add(new Property("query_key", "query val")); /* encoding changes 'query val' to 'query+val' */ dsConfig.setQueryParameters(queryParams); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { @@ -1608,14 +1580,16 @@ public void testDenyInstanceMetadataAws() { ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); assertTrue( - result.getPluginErrorDetails().getDownstreamErrorMessage().contains("Host not allowed."), - "Unexpected error message. Did this fail for a different reason?" - ); + result.getPluginErrorDetails() + .getDownstreamErrorMessage() + .contains("Host not allowed."), + "Unexpected error message. Did this fail for a different reason?"); }) .verifyComplete(); } @@ -1628,11 +1602,14 @@ public void testDenyInstanceMetadataAwsViaCname() { ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); - assertTrue(result.getPluginErrorDetails().getDownstreamErrorMessage().contains("Host not allowed.")); + assertTrue(result.getPluginErrorDetails() + .getDownstreamErrorMessage() + .contains("Host not allowed.")); }) .verifyComplete(); } @@ -1645,7 +1622,8 @@ public void testDenyInstanceMetadataGcp() { ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> assertFalse(result.getIsExecutionSuccess())) .verifyComplete(); @@ -1668,11 +1646,14 @@ public void testDenyInstanceMetadataAwsWithRedirect() throws IOException { ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); - assertTrue(result.getPluginErrorDetails().getDownstreamErrorMessage().contains("Host not allowed.")); + assertTrue(result.getPluginErrorDetails() + .getDownstreamErrorMessage() + .contains("Host not allowed.")); }) .verifyComplete(); } @@ -1683,9 +1664,7 @@ public void testGetApiWithBody() { dsConfig.setUrl("https://postman-echo.com/get"); ActionConfiguration actionConfig = new ActionConfiguration(); - actionConfig.setHeaders(List.of( - new Property("content-type", "application/json") - )); + actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); actionConfig.setHttpMethod(HttpMethod.GET); actionConfig.setFormData(new HashMap<>()); PluginUtils.setValueSafelyInFormData(actionConfig.getFormData(), "apiContentType", "application/json"); @@ -1693,9 +1672,11 @@ public void testGetApiWithBody() { String requestBody = "{\"key\":\"value\"}"; actionConfig.setBody(requestBody); - final APIConnection apiConnection = pluginExecutor.datasourceCreate(dsConfig).block(); + final APIConnection apiConnection = + pluginExecutor.datasourceCreate(dsConfig).block(); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(apiConnection, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(apiConnection, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -1728,18 +1709,16 @@ public void testAPIResponseEncodedInGzipFormat() { String body = "GzippedBody"; try (Buffer buffer = new Buffer()) { - mockEndpoint - .enqueue(new MockResponse() - .setBody(buffer.write(compressor.apply(body))) - .addHeader("Content-Encoding", "gzip")); + mockEndpoint.enqueue(new MockResponse() + .setBody(buffer.write(compressor.apply(body))) + .addHeader("Content-Encoding", "gzip")); } ActionConfiguration actionConfig = new ActionConfiguration(); - actionConfig.setHeaders(List.of( - new Property("content-type", "application/json") - )); + actionConfig.setHeaders(List.of(new Property("content-type", "application/json"))); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -1756,10 +1735,7 @@ public void testNumericStringHavingLeadingZero() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); final List<Property> headers = List.of(new Property("content-type", "application/json")); @@ -1776,7 +1752,8 @@ public void testNumericStringHavingLeadingZero() { params.add(param); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -1791,7 +1768,8 @@ public void testNumericStringHavingLeadingZero() { recordedRequestBody.readFully(bodyBytes); recordedRequestBody.close(); - assertEquals(requestBody.replace("{{phoneNumber.text}}", param.getValue()), new String(bodyBytes)); + assertEquals( + requestBody.replace("{{phoneNumber.text}}", param.getValue()), new String(bodyBytes)); } catch (EOFException | InterruptedException e) { assert false : e.getMessage(); } @@ -1799,10 +1777,12 @@ public void testNumericStringHavingLeadingZero() { final ActionExecutionRequest request = result.getRequest(); assertEquals(baseUrl, request.getUrl()); assertEquals(HttpMethod.POST, request.getHttpMethod()); - final Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) result.getRequest().getHeaders()).fields(); + final Iterator<Map.Entry<String, JsonNode>> fields = + ((ObjectNode) result.getRequest().getHeaders()).fields(); fields.forEachRemaining(field -> { if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(field.getKey())) { - assertEquals("application/json", field.getValue().get(0).asText()); + assertEquals( + "application/json", field.getValue().get(0).asText()); } }); }) @@ -1815,10 +1795,7 @@ public void whenBindingFoundWithoutValue_doNotReplaceWithNull() { String baseUrl = String.format("http://%s:%s", mockEndpoint.getHostName(), mockEndpoint.getPort()); dsConfig.setUrl(baseUrl); - mockEndpoint - .enqueue(new MockResponse() - .setBody("{}") - .addHeader("Content-Type", "application/json")); + mockEndpoint.enqueue(new MockResponse().setBody("{}").addHeader("Content-Type", "application/json")); ActionConfiguration actionConfig = new ActionConfiguration(); final List<Property> headers = List.of(new Property("content-type", "application/json")); @@ -1829,13 +1806,15 @@ public void whenBindingFoundWithoutValue_doNotReplaceWithNull() { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); Param param = new Param(); param.setKey("Input1.text"); - param.setValue("This TC is for this {{bug11688}}. HL7 Result: CODE 5 - CRITICAL VALUE - {{institution}} {{accessionNumber}}"); + param.setValue( + "This TC is for this {{bug11688}}. HL7 Result: CODE 5 - CRITICAL VALUE - {{institution}} {{accessionNumber}}"); param.setClientDataType(ClientDataType.STRING); List<Param> params = new ArrayList<>(); params.add(param); executeActionDTO.setParams(params); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, executeActionDTO, dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -1858,10 +1837,12 @@ public void whenBindingFoundWithoutValue_doNotReplaceWithNull() { final ActionExecutionRequest request = result.getRequest(); assertEquals(baseUrl, request.getUrl()); assertEquals(HttpMethod.POST, request.getHttpMethod()); - final Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) result.getRequest().getHeaders()).fields(); + final Iterator<Map.Entry<String, JsonNode>> fields = + ((ObjectNode) result.getRequest().getHeaders()).fields(); fields.forEachRemaining(field -> { if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(field.getKey())) { - assertEquals("application/json", field.getValue().get(0).asText()); + assertEquals( + "application/json", field.getValue().get(0).asText()); } }); }) @@ -1870,11 +1851,19 @@ public void whenBindingFoundWithoutValue_doNotReplaceWithNull() { @Test public void verifyUniquenessOfRestApiPluginErrorCode() { - assertEquals(RestApiPluginError.values().length, Arrays.stream(RestApiPluginError.values()).map(RestApiPluginError::getAppErrorCode).distinct().count()); - - assertEquals(0, Arrays.stream(RestApiPluginError.values()).map(RestApiPluginError::getAppErrorCode) - .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-RST")).count()); - + assertEquals( + RestApiPluginError.values().length, + Arrays.stream(RestApiPluginError.values()) + .map(RestApiPluginError::getAppErrorCode) + .distinct() + .count()); + + assertEquals( + 0, + Arrays.stream(RestApiPluginError.values()) + .map(RestApiPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-RST")) + .count()); } @Test @@ -1896,7 +1885,8 @@ public void whenAPIReturnsNon200_doNotStringifyResponseBody() throws IOException ActionConfiguration actionConfig = new ActionConfiguration(); actionConfig.setHttpMethod(HttpMethod.GET); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(null, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertFalse(result.getIsExecutionSuccess()); @@ -1905,7 +1895,6 @@ public void whenAPIReturnsNon200_doNotStringifyResponseBody() throws IOException .verifyComplete(); } - /** * Please note that this test also serves to test the GraphQL plugin flow as the API handling part for both is * handled via a common flow, hence not adding a duplicate test for the GraphQL plugin. @@ -1919,8 +1908,10 @@ public void testGetApiWithoutBody() { actionConfig.setHttpMethod(HttpMethod.GET); actionConfig.setFormData(new HashMap<>()); - final APIConnection apiConnection = pluginExecutor.datasourceCreate(dsConfig).block(); - Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(apiConnection, new ExecuteActionDTO(), dsConfig, actionConfig); + final APIConnection apiConnection = + pluginExecutor.datasourceCreate(dsConfig).block(); + Mono<ActionExecutionResult> resultMono = + pluginExecutor.executeParameterized(apiConnection, new ExecuteActionDTO(), dsConfig, actionConfig); StepVerifier.create(resultMono) .assertNext(result -> { assertTrue(result.getIsExecutionSuccess()); @@ -1928,6 +1919,4 @@ public void testGetApiWithoutBody() { }) .verifyComplete(); } - } - diff --git a/app/server/appsmith-plugins/saasPlugin/pom.xml b/app/server/appsmith-plugins/saasPlugin/pom.xml index d459cc13ffed..b13abe70fa70 100644 --- a/app/server/appsmith-plugins/saasPlugin/pom.xml +++ b/app/server/appsmith-plugins/saasPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>saasPlugin</artifactId> <version>1.0-SNAPSHOT</version> diff --git a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/helpers/BodyReceiver.java b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/helpers/BodyReceiver.java index e12c900a8fac..e74801a16fa7 100644 --- a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/helpers/BodyReceiver.java +++ b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/helpers/BodyReceiver.java @@ -54,9 +54,7 @@ private void demandValueFrom(BodyInserter<?, ? extends ReactiveHttpOutputMessage (BodyInserter<Object, MinimalHttpOutputMessage>) bodyInserter; inserter.insert( - MinimalHttpOutputMessage.INSTANCE, - new SingleWriterContext(new WriteToConsumer<>(reference::set)) - ); + MinimalHttpOutputMessage.INSTANCE, new SingleWriterContext(new WriteToConsumer<>(reference::set))); } private Object receivedValue() { @@ -67,8 +65,7 @@ private Object receivedValue() { if (value == DUMMY) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_ERROR, - "Value was not received, check if your inserter worked properly"); + AppsmithPluginError.PLUGIN_ERROR, "Value was not received, check if your inserter worked properly"); } else { validatedValue = value; } @@ -102,8 +99,7 @@ public Mono<Void> write( ResolvableType elementType, MediaType mediaType, ReactiveHttpOutputMessage message, - Map<String, Object> hints - ) { + Map<String, Object> hints) { inputStream.subscribe(new OneValueConsumption<>(consumer)); return Mono.empty(); } @@ -113,8 +109,7 @@ static class MinimalHttpOutputMessage implements ClientHttpRequest { public static final MinimalHttpOutputMessage INSTANCE = new MinimalHttpOutputMessage(); - private MinimalHttpOutputMessage() { - } + private MinimalHttpOutputMessage() {} @Override public HttpHeaders getHeaders() { @@ -127,8 +122,7 @@ public DataBufferFactory bufferFactory() { } @Override - public void beforeCommit(Supplier<? extends Mono<Void>> action) { - } + public void beforeCommit(Supplier<? extends Mono<Void>> action) {} @Override public boolean isCommitted() { diff --git a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/helpers/RequestCaptureFilter.java b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/helpers/RequestCaptureFilter.java index c0c2b35beadc..84bd00006ff3 100644 --- a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/helpers/RequestCaptureFilter.java +++ b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/helpers/RequestCaptureFilter.java @@ -45,8 +45,7 @@ public RequestCaptureFilter(ObjectMapper objectMapper) { } @Override - @NonNull - public Mono<ClientResponse> filter(@NonNull ClientRequest request, ExchangeFunction next) { + @NonNull public Mono<ClientResponse> filter(@NonNull ClientRequest request, ExchangeFunction next) { this.request = request; return next.exchange(request); } @@ -56,7 +55,8 @@ public ActionExecutionRequest populateRequestFields(ActionExecutionRequest exist final ActionExecutionRequest actionExecutionRequest = new ActionExecutionRequest(); actionExecutionRequest.setUrl(request.url().toString()); actionExecutionRequest.setHttpMethod(request.method()); - MultiValueMap<String, String> headers = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); + MultiValueMap<String, String> headers = + CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); AtomicBoolean isMultipart = new AtomicBoolean(false); request.headers().forEach((header, value) -> { if (HttpHeaders.AUTHORIZATION.equalsIgnoreCase(header) || "api_key".equalsIgnoreCase(header)) { @@ -64,7 +64,8 @@ public ActionExecutionRequest populateRequestFields(ActionExecutionRequest exist } else { headers.addAll(header, value); } - if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(header) && MULTIPART_FORM_DATA_VALUE.equalsIgnoreCase(value.get(0))) { + if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(header) + && MULTIPART_FORM_DATA_VALUE.equalsIgnoreCase(value.get(0))) { isMultipart.set(true); } }); @@ -84,10 +85,11 @@ public ActionExecutionRequest populateRequestFields(ActionExecutionRequest exist return actionExecutionRequest; } - public static ActionExecutionRequest populateRequestFields(ActionConfiguration actionConfiguration, - URI uri, - List<Map.Entry<String, String>> insertedParams, - ObjectMapper objectMapper) { + public static ActionExecutionRequest populateRequestFields( + ActionConfiguration actionConfiguration, + URI uri, + List<Map.Entry<String, String>> insertedParams, + ObjectMapper objectMapper) { ActionExecutionRequest actionExecutionRequest = new ActionExecutionRequest(); @@ -100,15 +102,15 @@ public static ActionExecutionRequest populateRequestFields(ActionConfiguration a AtomicReference<String> reqContentType = new AtomicReference<>(); if (actionConfiguration.getHeaders() != null) { - MultiValueMap<String, String> reqMultiMap = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); - - actionConfiguration.getHeaders() - .forEach(header -> { - if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(header.getKey())) { - reqContentType.set((String) header.getValue()); - } - reqMultiMap.put(header.getKey(), Arrays.asList((String) header.getValue())); - }); + MultiValueMap<String, String> reqMultiMap = + CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); + + actionConfiguration.getHeaders().forEach(header -> { + if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(header.getKey())) { + reqContentType.set((String) header.getValue()); + } + reqMultiMap.put(header.getKey(), Arrays.asList((String) header.getValue())); + }); actionExecutionRequest.setHeaders(objectMapper.valueToTree(reqMultiMap)); } diff --git a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java index 14e3e4dab6a1..28737bc5e820 100644 --- a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java +++ b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java @@ -67,28 +67,39 @@ public SaasPluginExecutor(SharedConfig sharedConfig) { saasObjectMapper.disable(MapperFeature.USE_ANNOTATIONS); saasObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); saasObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - this.EXCHANGE_STRATEGIES = ExchangeStrategies - .builder() + this.EXCHANGE_STRATEGIES = ExchangeStrategies.builder() .codecs(clientDefaultCodecsConfigurer -> { - clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(saasObjectMapper, MediaType.APPLICATION_JSON)); + clientDefaultCodecsConfigurer + .defaultCodecs() + .jackson2JsonEncoder( + new Jackson2JsonEncoder(saasObjectMapper, MediaType.APPLICATION_JSON)); clientDefaultCodecsConfigurer.defaultCodecs().maxInMemorySize(sharedConfig.getCodecSize()); }) .build(); } @Override - public Mono<ActionExecutionResult> execute(ExecutePluginDTO connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + ExecutePluginDTO connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { // Initializing object for error condition ActionExecutionResult errorResult = new ActionExecutionResult(); - final String datasourceConfigurationCommand = datasourceConfiguration.getAuthentication().getAuthenticationType(); + final String datasourceConfigurationCommand = + datasourceConfiguration.getAuthentication().getAuthenticationType(); if (datasourceConfigurationCommand == null || datasourceConfigurationCommand.isEmpty()) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, SaaSErrorMessages.MISSING_DATASOURCE_TEMPLATE_NAME_ERROR_MSG)); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + SaaSErrorMessages.MISSING_DATASOURCE_TEMPLATE_NAME_ERROR_MSG)); } - final String actionConfigurationCommand = (String) actionConfiguration.getFormData().get("command"); + final String actionConfigurationCommand = + (String) actionConfiguration.getFormData().get("command"); if (actionConfigurationCommand == null || actionConfigurationCommand.isEmpty()) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, SaaSErrorMessages.MISSING_ACTION_TEMPLATE_NAME_ERROR_MSG)); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + SaaSErrorMessages.MISSING_ACTION_TEMPLATE_NAME_ERROR_MSG)); } connection.setActionConfiguration(actionConfiguration); @@ -98,7 +109,10 @@ public Mono<ActionExecutionResult> execute(ExecutePluginDTO connection, Datasour UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance(); URI uri = null; try { - uri = uriBuilder.uri(new URI(sharedConfig.getRemoteExecutionUrl())).build(true).toUri(); + uri = uriBuilder + .uri(new URI(sharedConfig.getRemoteExecutionUrl())) + .build(true) + .toUri(); } catch (URISyntaxException e) { e.printStackTrace(); } @@ -106,14 +120,14 @@ public Mono<ActionExecutionResult> execute(ExecutePluginDTO connection, Datasour ActionExecutionRequest actionExecutionRequest = RequestCaptureFilter.populateRequestFields(actionConfiguration, uri, List.of(), objectMapper); - // Initializing webClient to be used for http call WebClient.Builder webClientBuilder = WebClientUtils.builder(); webClientBuilder.defaultHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE); final RequestCaptureFilter requestCaptureFilter = new RequestCaptureFilter(objectMapper); webClientBuilder.filter(requestCaptureFilter); - WebClient client = webClientBuilder.exchangeStrategies(EXCHANGE_STRATEGIES).build(); + WebClient client = + webClientBuilder.exchangeStrategies(EXCHANGE_STRATEGIES).build(); String valueAsString = ""; try { @@ -132,43 +146,41 @@ public Mono<ActionExecutionResult> execute(ExecutePluginDTO connection, Datasour try { return saasObjectMapper.readValue(body, ActionExecutionResult.class); } catch (IOException e) { - throw Exceptions.propagate( - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, - body, - e.getMessage() - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, body, e.getMessage())); } } else { - throw Exceptions.propagate( - new AppsmithPluginException( - SaaSPluginError.API_EXECUTION_FAILED, - SaaSErrorMessages.API_EXECUTION_FAILED_ERROR_MSG, - body - ) - ); + throw Exceptions.propagate(new AppsmithPluginException( + SaaSPluginError.API_EXECUTION_FAILED, + SaaSErrorMessages.API_EXECUTION_FAILED_ERROR_MSG, + body)); } }) .onErrorResume(error -> { errorResult.setRequest(requestCaptureFilter.populateRequestFields(actionExecutionRequest)); errorResult.setIsExecutionSuccess(false); - if (! (error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(SaaSPluginError.API_EXECUTION_FAILED, SaaSErrorMessages.API_EXECUTION_FAILED_ERROR_MSG, error.getMessage()); + if (!(error instanceof AppsmithPluginException)) { + error = new AppsmithPluginException( + SaaSPluginError.API_EXECUTION_FAILED, + SaaSErrorMessages.API_EXECUTION_FAILED_ERROR_MSG, + error.getMessage()); } errorResult.setErrorInfo(error); return Mono.just(errorResult); }); - } - private Mono<ResponseEntity<byte[]>> httpCall(WebClient webClient, HttpMethod httpMethod, URI uri, Object requestBody, - int iteration, String contentType) { + private Mono<ResponseEntity<byte[]>> httpCall( + WebClient webClient, + HttpMethod httpMethod, + URI uri, + Object requestBody, + int iteration, + String contentType) { if (iteration == MAX_REDIRECTS) { return Mono.error(new AppsmithPluginException( SaaSPluginError.API_EXECUTION_FAILED, - String.format(SaaSErrorMessages.MAX_REDIRECT_LIMIT_REACHED_ERROR_MSG, MAX_REDIRECTS) - )); + String.format(SaaSErrorMessages.MAX_REDIRECT_LIMIT_REACHED_ERROR_MSG, MAX_REDIRECTS))); } assert requestBody instanceof BodyInserter<?, ?>; @@ -180,10 +192,12 @@ private Mono<ResponseEntity<byte[]>> httpCall(WebClient webClient, HttpMethod ht .body((BodyInserter<?, ? super ClientHttpRequest>) finalRequestBody) .retrieve() .toEntity(byte[].class) - .doOnError(e -> Mono.error(new AppsmithPluginException(SaaSPluginError.API_EXECUTION_FAILED, SaaSErrorMessages.API_EXECUTION_FAILED_ERROR_MSG, e))) + .doOnError(e -> Mono.error(new AppsmithPluginException( + SaaSPluginError.API_EXECUTION_FAILED, SaaSErrorMessages.API_EXECUTION_FAILED_ERROR_MSG, e))) .flatMap(response -> { if (response.getStatusCode().is3xxRedirection()) { - String redirectUrl = response.getHeaders().getLocation().toString(); + String redirectUrl = + response.getHeaders().getLocation().toString(); /** * TODO * In case the redirected URL is not absolute (complete), create the new URL using the relative path @@ -195,10 +209,13 @@ private Mono<ResponseEntity<byte[]>> httpCall(WebClient webClient, HttpMethod ht try { redirectUri = new URI(redirectUrl); } catch (URISyntaxException e) { - return Mono.error(new AppsmithPluginException(SaaSPluginError.API_EXECUTION_FAILED, SaaSErrorMessages.URI_SYNTAX_WRONG_ERROR_MSG, e)); + return Mono.error(new AppsmithPluginException( + SaaSPluginError.API_EXECUTION_FAILED, + SaaSErrorMessages.URI_SYNTAX_WRONG_ERROR_MSG, + e)); } - return httpCall(webClient, httpMethod, redirectUri, finalRequestBody, iteration + 1, - contentType); + return httpCall( + webClient, httpMethod, redirectUri, finalRequestBody, iteration + 1, contentType); } return Mono.just(response); }); @@ -210,8 +227,7 @@ public Mono<ExecutePluginDTO> datasourceCreate(DatasourceConfiguration datasourc } @Override - public void datasourceDestroy(ExecutePluginDTO connection) { - } + public void datasourceDestroy(ExecutePluginDTO connection) {} @Override public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) { diff --git a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/exceptions/SaaSErrorMessages.java b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/exceptions/SaaSErrorMessages.java index 05bc7028eac7..c28feedcfc9b 100644 --- a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/exceptions/SaaSErrorMessages.java +++ b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/exceptions/SaaSErrorMessages.java @@ -10,7 +10,8 @@ public class SaaSErrorMessages extends BasePluginErrorMessages { public static final String MISSING_ACTION_TEMPLATE_NAME_ERROR_MSG = "Missing template name for action"; - public static final String API_EXECUTION_FAILED_ERROR_MSG = "Error occurred while invoking API. To know more please check the error details."; + public static final String API_EXECUTION_FAILED_ERROR_MSG = + "Error occurred while invoking API. To know more please check the error details."; public static final String MAX_REDIRECT_LIMIT_REACHED_ERROR_MSG = "Exceeded the HTTP redirect limits of %s"; diff --git a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/exceptions/SaaSPluginError.java b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/exceptions/SaaSPluginError.java index 21f08299815b..83a5ed9e841f 100644 --- a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/exceptions/SaaSPluginError.java +++ b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/exceptions/SaaSPluginError.java @@ -1,12 +1,10 @@ package com.external.plugins.exceptions; import com.appsmith.external.exceptions.AppsmithErrorAction; -import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginErrorCode; import com.appsmith.external.exceptions.pluginExceptions.BasePluginError; import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum SaaSPluginError implements BasePluginError { API_EXECUTION_FAILED( @@ -17,8 +15,7 @@ public enum SaaSPluginError implements BasePluginError { "API execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), UNSUPPORTED_PLUGIN_OPERATION( 500, "PE-SAS-5001", @@ -27,8 +24,7 @@ public enum SaaSPluginError implements BasePluginError { "Unsupported operation", ErrorType.INTERNAL_ERROR, "{0}", - "{1}" - ), + "{1}"), ; private final Integer httpErrorCode; @@ -42,8 +38,15 @@ public enum SaaSPluginError implements BasePluginError { private final String downstreamErrorCode; - SaaSPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + SaaSPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -70,5 +73,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/smtpPlugin/pom.xml b/app/server/appsmith-plugins/smtpPlugin/pom.xml index 4ddf298f6a11..77f7deb6e9ab 100644 --- a/app/server/appsmith-plugins/smtpPlugin/pom.xml +++ b/app/server/appsmith-plugins/smtpPlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>smtpPlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -33,10 +32,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> + <phase>package</phase> <configuration> <includeScope>runtime</includeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> diff --git a/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/SmtpPlugin.java b/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/SmtpPlugin.java index 71f55fb1d542..2821b608aece 100644 --- a/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/SmtpPlugin.java +++ b/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/SmtpPlugin.java @@ -14,6 +14,8 @@ import com.appsmith.external.plugins.PluginExecutor; import com.external.plugins.exceptions.SMTPErrorMessages; import com.external.plugins.exceptions.SMTPPluginError; +import jakarta.activation.DataHandler; +import jakarta.activation.DataSource; import jakarta.mail.AuthenticationFailedException; import jakarta.mail.Authenticator; import jakarta.mail.Message; @@ -37,9 +39,6 @@ import org.springframework.util.StringUtils; import reactor.core.publisher.Mono; -import jakarta.activation.DataHandler; -import jakarta.activation.DataSource; - import java.io.IOException; import java.util.Base64; import java.util.HashMap; @@ -62,27 +61,41 @@ public static class SmtpPluginExecutor implements PluginExecutor<Session> { private static final String ENCODING = "UTF-8"; @Override - public Mono<ActionExecutionResult> execute(Session connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + Session connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { MimeMessage message = getMimeMessage(connection); ActionExecutionResult result = new ActionExecutionResult(); try { - String fromAddress = (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.from"); - String toAddress = (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.to"); - String ccAddress = (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.cc"); - String bccAddress = (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.bcc"); - String subject = (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.subject"); - String bodyType = (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.bodyType"); - Boolean isReplyTo = (Boolean) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.isReplyTo"); - String replyTo = Boolean.TRUE.equals(isReplyTo) ? - (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.replyTo") : null; + String fromAddress = + (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.from"); + String toAddress = + (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.to"); + String ccAddress = + (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.cc"); + String bccAddress = + (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.bcc"); + String subject = (String) + PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.subject"); + String bodyType = (String) + PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.bodyType"); + Boolean isReplyTo = (Boolean) + PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.isReplyTo"); + String replyTo = Boolean.TRUE.equals(isReplyTo) + ? (String) PluginUtils.getValueSafelyFromFormData( + actionConfiguration.getFormData(), "send.replyTo") + : null; if (!StringUtils.hasText(toAddress)) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, SMTPErrorMessages.RECIPIENT_ADDRESS_NOT_FOUND_ERROR_MSG)); } if (!StringUtils.hasText(fromAddress)) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, SMTPErrorMessages.SENDER_ADDRESS_NOT_FOUND_ERROR_MSG)); } message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress, false)); @@ -112,25 +125,27 @@ public Mono<ActionExecutionResult> execute(Session connection, DatasourceConfigu message.setContent(multipart); // Look for any attachments that need to be sent along with this email - String attachmentsStr = (String) PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.attachments"); + String attachmentsStr = (String) + PluginUtils.getValueSafelyFromFormData(actionConfiguration.getFormData(), "send.attachments"); if (StringUtils.hasText(attachmentsStr)) { - MultipartFormDataDTO[] attachmentData = objectMapper.readValue( - attachmentsStr, - MultipartFormDataDTO[].class - ); + MultipartFormDataDTO[] attachmentData = + objectMapper.readValue(attachmentsStr, MultipartFormDataDTO[].class); // Iterate over each attachment and add it to the main multipart body of the email for (MultipartFormDataDTO attachment : attachmentData) { MimeBodyPart attachBodyPart = getMimeBodyPart(); - // Decode the base64 data received in the input by first removing the sequence data:image/png;base64, + // Decode the base64 data received in the input by first removing the sequence + // data:image/png;base64, // from the start of the string. Base64.Decoder decoder = Base64.getDecoder(); String attachmentStr = String.valueOf(attachment.getData()); if (!attachmentStr.contains(BASE64_DELIMITER)) { - return Mono.error(new AppsmithPluginException(SMTPPluginError.MAIL_SENDING_FAILED, - String.format(SMTPErrorMessages.INVALID_ATTACHMENT_ERROR_MSG, attachment.getName()))); + return Mono.error(new AppsmithPluginException( + SMTPPluginError.MAIL_SENDING_FAILED, + String.format( + SMTPErrorMessages.INVALID_ATTACHMENT_ERROR_MSG, attachment.getName()))); } byte[] bytes = decoder.decode(attachmentStr.split(BASE64_DELIMITER)[1]); DataSource emailDatasource = new ByteArrayDataSource(bytes, attachment.getType()); @@ -154,18 +169,21 @@ public Mono<ActionExecutionResult> execute(Session connection, DatasourceConfigu log.debug("Sent the email successfully"); } catch (MessagingException e) { - return Mono.error(new AppsmithPluginException(SMTPPluginError.MAIL_SENDING_FAILED, - SMTPErrorMessages.MAIL_SENDING_FAILED_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + SMTPPluginError.MAIL_SENDING_FAILED, + SMTPErrorMessages.MAIL_SENDING_FAILED_ERROR_MSG, + e.getMessage())); } catch (IOException e) { - return Mono.error(new AppsmithPluginException(SMTPPluginError.MAIL_SENDING_FAILED, - SMTPErrorMessages.UNPARSABLE_EMAIL_BODY_OR_ATTACHMENT_ERROR_MSG, e.getMessage())); + return Mono.error(new AppsmithPluginException( + SMTPPluginError.MAIL_SENDING_FAILED, + SMTPErrorMessages.UNPARSABLE_EMAIL_BODY_OR_ATTACHMENT_ERROR_MSG, + e.getMessage())); } return Mono.just(result); } - @NotNull - MimeBodyPart getMimeBodyPart() { + @NotNull MimeBodyPart getMimeBodyPart() { return new MimeBodyPart(); } @@ -226,9 +244,9 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur } DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); - if (authentication == null || !StringUtils.hasText(authentication.getUsername()) || - !StringUtils.hasText(authentication.getPassword()) - ) { + if (authentication == null + || !StringUtils.hasText(authentication.getUsername()) + || !StringUtils.hasText(authentication.getPassword())) { invalids.add(new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR).getMessage()); } @@ -258,6 +276,5 @@ public Mono<DatasourceTestResult> testDatasource(Session connection) { }) .map(DatasourceTestResult::new); } - } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/exceptions/SMTPErrorMessages.java b/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/exceptions/SMTPErrorMessages.java index 82030e18af53..282ed1b76ecc 100644 --- a/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/exceptions/SMTPErrorMessages.java +++ b/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/exceptions/SMTPErrorMessages.java @@ -5,26 +5,35 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) // To prevent instantiation public class SMTPErrorMessages { - public static final String RECIPIENT_ADDRESS_NOT_FOUND_ERROR_MSG = "Couldn't find a valid recipient address. Please check your action configuration."; + public static final String RECIPIENT_ADDRESS_NOT_FOUND_ERROR_MSG = + "Couldn't find a valid recipient address. Please check your action configuration."; - public static final String SENDER_ADDRESS_NOT_FOUND_ERROR_MSG = "Couldn't find a valid sender address. Please check your action configuration."; + public static final String SENDER_ADDRESS_NOT_FOUND_ERROR_MSG = + "Couldn't find a valid sender address. Please check your action configuration."; - public static final String INVALID_ATTACHMENT_ERROR_MSG = "Attachment `%s` contains invalid data. Unable to send email."; + public static final String INVALID_ATTACHMENT_ERROR_MSG = + "Attachment `%s` contains invalid data. Unable to send email."; - public static final String MAIL_SENDING_FAILED_ERROR_MSG = "Error occurred while sending mail. To know more about the error please check the error details."; + public static final String MAIL_SENDING_FAILED_ERROR_MSG = + "Error occurred while sending mail. To know more about the error please check the error details."; - public static final String UNPARSABLE_EMAIL_BODY_OR_ATTACHMENT_ERROR_MSG = "Unable to parse the email body/attachments because it was an invalid object."; + public static final String UNPARSABLE_EMAIL_BODY_OR_ATTACHMENT_ERROR_MSG = + "Unable to parse the email body/attachments because it was an invalid object."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ - public static final String DS_MISSING_HOST_ADDRESS_ERROR_MSG = "Could not find host address. Please edit the 'Hostname' field to provide the desired endpoint."; + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ + public static final String DS_MISSING_HOST_ADDRESS_ERROR_MSG = + "Could not find host address. Please edit the 'Hostname' field to provide the desired endpoint."; - public static final String DS_NO_SUCH_PROVIDER_ERROR_MSG = "Unable to create underlying SMTP protocol. Please contact support"; + public static final String DS_NO_SUCH_PROVIDER_ERROR_MSG = + "Unable to create underlying SMTP protocol. Please contact support"; - public static final String DS_AUTHENTICATION_FAILED_ERROR_MSG = "Authentication failed with the SMTP server. Please check your username/password settings."; + public static final String DS_AUTHENTICATION_FAILED_ERROR_MSG = + "Authentication failed with the SMTP server. Please check your username/password settings."; - public static final String DS_CONNECTION_FAILED_TO_SMTP_SERVER_ERROR_MSG = "Unable to connect to SMTP server. Please check your host/port settings."; + public static final String DS_CONNECTION_FAILED_TO_SMTP_SERVER_ERROR_MSG = + "Unable to connect to SMTP server. Please check your host/port settings."; } diff --git a/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/exceptions/SMTPPluginError.java b/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/exceptions/SMTPPluginError.java index 54be1df94209..a1707fd3259b 100644 --- a/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/exceptions/SMTPPluginError.java +++ b/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/exceptions/SMTPPluginError.java @@ -5,7 +5,6 @@ import com.appsmith.external.models.ErrorType; import lombok.Getter; - @Getter public enum SMTPPluginError implements BasePluginError { MAIL_SENDING_FAILED( @@ -16,9 +15,7 @@ public enum SMTPPluginError implements BasePluginError { "Mail sending error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ) - ; + "{2}"); private final Integer httpErrorCode; private final String appErrorCode; @@ -31,8 +28,15 @@ public enum SMTPPluginError implements BasePluginError { private final String downstreamErrorCode; - SMTPPluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + SMTPPluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -59,5 +63,7 @@ public String getDownstreamErrorCode(Object... args) { } @Override - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } } diff --git a/app/server/appsmith-plugins/smtpPlugin/src/test/java/com/external/plugins/SmtpPluginTest.java b/app/server/appsmith-plugins/smtpPlugin/src/test/java/com/external/plugins/SmtpPluginTest.java index f35b28543957..114a74cccda8 100644 --- a/app/server/appsmith-plugins/smtpPlugin/src/test/java/com/external/plugins/SmtpPluginTest.java +++ b/app/server/appsmith-plugins/smtpPlugin/src/test/java/com/external/plugins/SmtpPluginTest.java @@ -9,13 +9,13 @@ import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceTestResult; import com.appsmith.external.models.Endpoint; +import com.external.plugins.exceptions.SMTPErrorMessages; +import com.external.plugins.exceptions.SMTPPluginError; +import jakarta.mail.MessagingException; import jakarta.mail.Session; import jakarta.mail.Transport; -import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeBodyPart; import jakarta.mail.internet.MimeMessage; -import com.external.plugins.exceptions.SMTPErrorMessages; -import com.external.plugins.exceptions.SMTPPluginError; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; @@ -28,38 +28,38 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Arrays; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @Testcontainers public class SmtpPluginTest { - final static String username = "smtpUser"; - final static String password = "smtpPass"; + static final String username = "smtpUser"; + static final String password = "smtpPass"; private static String host = "localhost"; private static Long port = 25L; @Container public static final GenericContainer smtp = new GenericContainer(DockerImageName.parse("maildev/maildev")) .withExposedPorts(25) - .withCommand("bin/maildev --base-pathname /maildev --incoming-user " + username + " --incoming-pass " + password + " -s 25"); + .withCommand("bin/maildev --base-pathname /maildev --incoming-user " + username + " --incoming-pass " + + password + " -s 25"); private final SmtpPlugin.SmtpPluginExecutor pluginExecutor = new SmtpPlugin.SmtpPluginExecutor(); - @BeforeAll public static void setup() { host = smtp.getContainerIpAddress(); @@ -79,30 +79,21 @@ private DatasourceConfiguration createDatasourceConfiguration() { private ActionConfiguration createActionConfiguration() { return createActionConfiguration( - "[email protected]", - "[email protected]", - "[email protected]", - "[email protected]", - "[email protected]", - "text/html"); + "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "text/html"); } private ActionConfiguration createActionConfiguration(String bodyType) { return createActionConfiguration( - "[email protected]", - "[email protected]", - "[email protected]", - "[email protected]", - "[email protected]", - bodyType); + "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", bodyType); } - private ActionConfiguration createActionConfiguration(String fromAddress, - String toAddress, - String ccAddress, - String bccAddress, - String replyTo, - String bodyType) { + private ActionConfiguration createActionConfiguration( + String fromAddress, + String toAddress, + String ccAddress, + String bccAddress, + String replyTo, + String bodyType) { ActionConfiguration actionConfiguration = new ActionConfiguration(); Map<String, Object> formData = new HashMap<>(); PluginUtils.setValueSafelyInFormData(formData, "send.from", fromAddress); @@ -124,7 +115,8 @@ public void testInvalidHostname() { DatasourceConfiguration invalidDatasourceConfiguration = createDatasourceConfiguration(); invalidDatasourceConfiguration.setEndpoints(List.of(new Endpoint("", 25L))); - assertEquals(Set.of(SMTPErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG), + assertEquals( + Set.of(SMTPErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG), pluginExecutor.validateDatasource(invalidDatasourceConfiguration)); } @@ -141,7 +133,8 @@ public void testNullAuthentication() { DatasourceConfiguration invalidDatasourceConfiguration = createDatasourceConfiguration(); invalidDatasourceConfiguration.setAuthentication(null); - assertEquals(Set.of(new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR).getMessage()), + assertEquals( + Set.of(new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR).getMessage()), pluginExecutor.validateDatasource(invalidDatasourceConfiguration)); } @@ -158,7 +151,6 @@ public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { assertTrue(datasourceTestResult.getInvalids().isEmpty()); }) .verifyComplete(); - } @Test @@ -171,12 +163,16 @@ public void testInvalidAuthentication() { ActionConfiguration actionConfiguration = createActionConfiguration(); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(invalidDatasourceConfiguration) - .flatMap(session -> pluginExecutor.execute(session, invalidDatasourceConfiguration, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(invalidDatasourceConfiguration) + .flatMap(session -> + pluginExecutor.execute(session, invalidDatasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) - .expectErrorMatches(e -> e instanceof AppsmithPluginException && - ((AppsmithPluginException) e).getDownstreamErrorMessage().contains("535 Invalid username or password")) + .expectErrorMatches(e -> e instanceof AppsmithPluginException + && ((AppsmithPluginException) e) + .getDownstreamErrorMessage() + .contains("535 Invalid username or password")) .verify(); } @@ -185,15 +181,14 @@ public void testBlankFromAddress() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = createActionConfiguration(); - PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), - "send.from", " "); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.from", " "); + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) - .expectErrorMatches(e -> - e instanceof AppsmithPluginException && - e.getMessage().equals(SMTPErrorMessages.SENDER_ADDRESS_NOT_FOUND_ERROR_MSG)) + .expectErrorMatches(e -> e instanceof AppsmithPluginException + && e.getMessage().equals(SMTPErrorMessages.SENDER_ADDRESS_NOT_FOUND_ERROR_MSG)) .verify(); } @@ -202,16 +197,14 @@ public void testBlankToAddress() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = createActionConfiguration(); - PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), - "send.to", " "); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.to", " "); + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) - .expectErrorMatches(e -> - e instanceof AppsmithPluginException && - e.getMessage().equals(SMTPErrorMessages.RECIPIENT_ADDRESS_NOT_FOUND_ERROR_MSG) - ) + .expectErrorMatches(e -> e instanceof AppsmithPluginException + && e.getMessage().equals(SMTPErrorMessages.RECIPIENT_ADDRESS_NOT_FOUND_ERROR_MSG)) .verify(); } @@ -220,9 +213,9 @@ public void testInvalidFromAddress() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = createActionConfiguration(); - PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), - "send.from", "invalid"); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.from", "invalid"); + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) @@ -235,9 +228,9 @@ public void testInvalidToAddress() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = createActionConfiguration(); - PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), - "send.to", "invalidEmail"); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.to", "invalidEmail"); + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) @@ -250,9 +243,9 @@ public void testNullSubject() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = createActionConfiguration(); - PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), - "subject", null); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "subject", null); + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) @@ -267,7 +260,8 @@ public void testBlankBody() { ActionConfiguration actionConfiguration = createActionConfiguration(); actionConfiguration.setBody(null); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) @@ -285,7 +279,8 @@ public void testEmptyAttachments() { ActionConfiguration actionConfiguration = createActionConfiguration(); PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.attachments", ""); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) @@ -300,7 +295,8 @@ public void testNullAttachment() { ActionConfiguration actionConfiguration = createActionConfiguration(); PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.attachments", null); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) @@ -315,7 +311,8 @@ public void testInvalidAttachmentJSON() { ActionConfiguration actionConfiguration = createActionConfiguration(); PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.attachments", "randomValue"); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) @@ -328,20 +325,23 @@ public void testInvalidAttachmentFileData() { DatasourceConfiguration datasourceConfiguration = createDatasourceConfiguration(); ActionConfiguration actionConfiguration = createActionConfiguration(); - String attachmentJson = "[{\n" + - " \"type\": \"image/png\",\n" + - " \"id\": \"uppy-smtp/icon/png-1d-1e-image/png-2854-1635400419555\",\n" + - " \"data\": \"data:image/png;randomValueHere\",\n" + - " \"name\": \"test-icon-file.png\",\n" + - " \"size\": 2854\n" + - " }]"; + String attachmentJson = "[{\n" + " \"type\": \"image/png\",\n" + + " \"id\": \"uppy-smtp/icon/png-1d-1e-image/png-2854-1635400419555\",\n" + + " \"data\": \"data:image/png;randomValueHere\",\n" + + " \"name\": \"test-icon-file.png\",\n" + + " \"size\": 2854\n" + + " }]"; PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.attachments", attachmentJson); - Mono<ActionExecutionResult> resultMono = pluginExecutor.datasourceCreate(datasourceConfiguration) + Mono<ActionExecutionResult> resultMono = pluginExecutor + .datasourceCreate(datasourceConfiguration) .flatMap(session -> pluginExecutor.execute(session, datasourceConfiguration, actionConfiguration)); StepVerifier.create(resultMono) - .expectErrorMatches(e -> e instanceof AppsmithPluginException && e.getMessage().equals(String.format(SMTPErrorMessages.INVALID_ATTACHMENT_ERROR_MSG, "test-icon-file.png"))) + .expectErrorMatches(e -> e instanceof AppsmithPluginException + && e.getMessage() + .equals(String.format( + SMTPErrorMessages.INVALID_ATTACHMENT_ERROR_MSG, "test-icon-file.png"))) .verify(); } @@ -354,7 +354,8 @@ public void testSendEmailValidWithAttachment() { ActionConfiguration actionConfiguration = createActionConfiguration(); PluginUtils.setValueSafelyInFormData(actionConfiguration.getFormData(), "send.attachments", ""); - Mono<ActionExecutionResult> resultMono = sessionMono.flatMap(session -> pluginExecutor.execute(session, dsConfig, actionConfiguration)); + Mono<ActionExecutionResult> resultMono = + sessionMono.flatMap(session -> pluginExecutor.execute(session, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> assertTrue(result.getIsExecutionSuccess())) @@ -373,8 +374,10 @@ public void testSendMultipleEmailsConcurrently() { ActionConfiguration actionConfiguration2 = createActionConfiguration(); PluginUtils.setValueSafelyInFormData(actionConfiguration2.getFormData(), "send.from", "[email protected]"); - Mono<ActionExecutionResult> email1Mono = sessionMono.flatMap(session -> pluginExecutor.execute(session, dsConfig, actionConfiguration1)); - Mono<ActionExecutionResult> email2Mono = sessionMono.flatMap(session -> pluginExecutor.execute(session, dsConfig, actionConfiguration2)); + Mono<ActionExecutionResult> email1Mono = + sessionMono.flatMap(session -> pluginExecutor.execute(session, dsConfig, actionConfiguration1)); + Mono<ActionExecutionResult> email2Mono = + sessionMono.flatMap(session -> pluginExecutor.execute(session, dsConfig, actionConfiguration2)); StepVerifier.create(Mono.zip(email1Mono, email2Mono)) .assertNext(tuple -> { @@ -384,7 +387,6 @@ public void testSendMultipleEmailsConcurrently() { assertTrue(result2.getIsExecutionSuccess()); }) .verifyComplete(); - } @Test @@ -399,14 +401,15 @@ public void testExecuteWithUTFEncoding() throws MessagingException { SmtpPlugin.SmtpPluginExecutor spySmtp = spy(pluginExecutor); try (MockedStatic<Transport> transportMock = Mockito.mockStatic(Transport.class)) { - Session session = pluginExecutor.datasourceCreate(datasourceConfiguration).block(); + Session session = + pluginExecutor.datasourceCreate(datasourceConfiguration).block(); when(spySmtp.getMimeMessage(session)).thenReturn(mockMimeMessage); when(spySmtp.getMimeBodyPart()).thenReturn(mockMimeBodyPart); transportMock.when(() -> Transport.send(mockMimeMessage)).thenAnswer((Answer<Void>) invocation -> null); - spySmtp.execute(session, datasourceConfiguration, actionConfiguration);// test method call + spySmtp.execute(session, datasourceConfiguration, actionConfiguration); // test method call String ENCODING = "UTF-8"; verify(mockMimeMessage).setSubject("This is a test subject", ENCODING); @@ -426,14 +429,15 @@ public void testExecuteWithBodyTypePlainText() throws MessagingException { SmtpPlugin.SmtpPluginExecutor spySmtp = spy(pluginExecutor); try (MockedStatic<Transport> transportMock = Mockito.mockStatic(Transport.class)) { - Session session = pluginExecutor.datasourceCreate(datasourceConfiguration).block(); + Session session = + pluginExecutor.datasourceCreate(datasourceConfiguration).block(); when(spySmtp.getMimeMessage(session)).thenReturn(mockMimeMessage); when(spySmtp.getMimeBodyPart()).thenReturn(mockMimeBodyPart); transportMock.when(() -> Transport.send(mockMimeMessage)).thenAnswer((Answer<Void>) invocation -> null); - spySmtp.execute(session, datasourceConfiguration, actionConfiguration);// test method call + spySmtp.execute(session, datasourceConfiguration, actionConfiguration); // test method call String ENCODING = "UTF-8"; verify(mockMimeMessage).setSubject("This is a test subject", ENCODING); @@ -443,11 +447,17 @@ public void testExecuteWithBodyTypePlainText() throws MessagingException { @Test public void verifyUniquenessOfSMTPPluginErrorCode() { - assert (Arrays.stream(SMTPPluginError.values()).map(SMTPPluginError::getAppErrorCode).distinct().count() == SMTPPluginError.values().length); - - assert (Arrays.stream(SMTPPluginError.values()).map(SMTPPluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-SMT")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(SMTPPluginError.values()) + .map(SMTPPluginError::getAppErrorCode) + .distinct() + .count() + == SMTPPluginError.values().length); + + assert (Arrays.stream(SMTPPluginError.values()) + .map(SMTPPluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-SMT")) + .collect(Collectors.toList()) + .size() + == 0); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/snowflakePlugin/pom.xml b/app/server/appsmith-plugins/snowflakePlugin/pom.xml index c16f3615759c..c545d22dd8c0 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/pom.xml +++ b/app/server/appsmith-plugins/snowflakePlugin/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>appsmith-plugins</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.external.plugins</groupId> <artifactId>snowflakePlugin</artifactId> <version>1.0-SNAPSHOT</version> @@ -65,7 +64,8 @@ </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> - <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --> + <artifactId>jjwt-jackson</artifactId> + <!-- or jjwt-gson if Gson is preferred --> <version>${jjwt.version}</version> </dependency> @@ -95,10 +95,10 @@ <executions> <execution> <id>copy-dependencies</id> - <phase>package</phase> <goals> <goal>copy</goal> </goals> + <phase>package</phase> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <artifactItems> @@ -132,11 +132,9 @@ <artifactId>maven-surefire-plugin</artifactId> <configuration> <!-- Allow JUnit to access the test classes --> - <argLine> - --add-opens java.base/java.lang=ALL-UNNAMED + <argLine>--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.time=ALL-UNNAMED - --add-opens java.base/java.util=ALL-UNNAMED - </argLine> + --add-opens java.base/java.util=ALL-UNNAMED</argLine> </configuration> </plugin> </plugins> diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/SnowflakePlugin.java b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/SnowflakePlugin.java index 8337d5ec5b0c..25081633c4e9 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/SnowflakePlugin.java +++ b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/SnowflakePlugin.java @@ -68,18 +68,20 @@ public static class SnowflakePluginExecutor implements PluginExecutor<HikariData private final Scheduler scheduler = Schedulers.boundedElastic(); @Override - public Mono<ActionExecutionResult> execute(HikariDataSource connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + HikariDataSource connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { String query = actionConfiguration.getBody(); - if (! StringUtils.hasLength(query)) { + if (!StringUtils.hasLength(query)) { return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, SnowflakeErrorMessages.MISSING_QUERY_ERROR_MSG)); } return Mono.fromCallable(() -> { - Connection connectionFromPool; try { @@ -89,8 +91,7 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connection, Datasour * the method definition to understand more. */ connectionFromPool = - getConnectionFromHikariConnectionPool(connection, - SNOWFLAKE_PLUGIN_NAME); + getConnectionFromHikariConnectionPool(connection, SNOWFLAKE_PLUGIN_NAME); } catch (SQLException | StaleConnectionException e) { if (e instanceof StaleConnectionException) { throw e; @@ -105,8 +106,13 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connection, Datasour int activeConnections = poolProxy.getActiveConnections(); int totalConnections = poolProxy.getTotalConnections(); int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug("Before executing snowflake query [{}] Hikari Pool stats : active - {} , idle - {} , awaiting - {} , total - {}", - query, activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); + log.debug( + "Before executing snowflake query [{}] Hikari Pool stats : active - {} , idle - {} , awaiting - {} , total - {}", + query, + activeConnections, + idleConnections, + threadsAwaitingConnection, + totalConnections); try { // Connection staleness is checked as part of this method call. @@ -119,8 +125,12 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connection, Datasour activeConnections = poolProxy.getActiveConnections(); totalConnections = poolProxy.getTotalConnections(); threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug("After executing snowflake query, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", - activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); + log.debug( + "After executing snowflake query, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", + activeConnections, + idleConnections, + threadsAwaitingConnection, + totalConnections); if (connectionFromPool != null) { try { @@ -131,7 +141,6 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connection, Datasour } } } - }) .map(rowsList -> { ActionExecutionResult result = new ActionExecutionResult(); @@ -146,55 +155,61 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connection, Datasour } @Override - public Mono<HikariDataSource> createConnectionClient(DatasourceConfiguration datasourceConfiguration, Properties properties) { + public Mono<HikariDataSource> createConnectionClient( + DatasourceConfiguration datasourceConfiguration, Properties properties) { return Mono.fromCallable(() -> { - HikariConfig config = new HikariConfig(); + HikariConfig config = new HikariConfig(); - config.setDriverClassName(properties.getProperty("driver_name")); + config.setDriverClassName(properties.getProperty("driver_name")); - config.setMinimumIdle(Integer.parseInt(properties.get("minimumIdle").toString())); - config.setMaximumPoolSize(Integer.parseInt(properties.get("maximunPoolSize").toString())); + config.setMinimumIdle( + Integer.parseInt(properties.get("minimumIdle").toString())); + config.setMaximumPoolSize(Integer.parseInt( + properties.get("maximunPoolSize").toString())); - config.setInitializationFailTimeout(Long.parseLong(properties.get("initializationFailTimeout").toString())); - config.setConnectionTimeout(Long.parseLong(properties.get("connectionTimeoutMillis").toString())); + config.setInitializationFailTimeout(Long.parseLong( + properties.get("initializationFailTimeout").toString())); + config.setConnectionTimeout(Long.parseLong( + properties.get("connectionTimeoutMillis").toString())); - // Set authentication properties - DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); - if (authentication.getUsername() != null) { - config.setUsername(authentication.getUsername()); - } - if (authentication.getPassword() != null) { - config.setPassword(authentication.getPassword()); - } + // Set authentication properties + DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); + if (authentication.getUsername() != null) { + config.setUsername(authentication.getUsername()); + } + if (authentication.getPassword() != null) { + config.setPassword(authentication.getPassword()); + } - // Set up the connection URL - StringBuilder urlBuilder = new StringBuilder("jdbc:snowflake://" + - datasourceConfiguration.getUrl() + ".snowflakecomputing.com?"); - config.setJdbcUrl(urlBuilder.toString()); - - config.setDataSourceProperties(properties); - - // Now create the connection pool from the configuration - HikariDataSource datasource = null; - try { - datasource = new HikariDataSource(config); - } catch (HikariPool.PoolInitializationException e) { - throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - e.getMessage() - ); - } + // Set up the connection URL + StringBuilder urlBuilder = new StringBuilder( + "jdbc:snowflake://" + datasourceConfiguration.getUrl() + ".snowflakecomputing.com?"); + config.setJdbcUrl(urlBuilder.toString()); + + config.setDataSourceProperties(properties); - return datasource; - }).subscribeOn(scheduler); + // Now create the connection pool from the configuration + HikariDataSource datasource = null; + try { + datasource = new HikariDataSource(config); + } catch (HikariPool.PoolInitializationException e) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, e.getMessage()); + } + + return datasource; + }) + .subscribeOn(scheduler); } @Override - public Properties addPluginSpecificProperties(DatasourceConfiguration datasourceConfiguration, Properties properties) { + public Properties addPluginSpecificProperties( + DatasourceConfiguration datasourceConfiguration, Properties properties) { properties.setProperty("driver_name", JDBC_DRIVER); properties.setProperty("minimumIdle", String.valueOf(MINIMUM_POOL_SIZE)); properties.setProperty("maximunPoolSize", String.valueOf(MAXIMUM_POOL_SIZE)); - properties.setProperty(SNOWFLAKE_DB_LOGIN_TIMEOUT_PROPERTY_KEY, String.valueOf(SNOWFLAKE_DB_LOGIN_TIMEOUT_VALUE_SEC)); + properties.setProperty( + SNOWFLAKE_DB_LOGIN_TIMEOUT_PROPERTY_KEY, String.valueOf(SNOWFLAKE_DB_LOGIN_TIMEOUT_VALUE_SEC)); /** * Setting the value for setInitializationFailTimeout to -1 to * bypass any connection attempt and validation during startup @@ -206,14 +221,27 @@ public Properties addPluginSpecificProperties(DatasourceConfiguration datasource } @Override - public Properties addAuthParamsToConnectionConfig(DatasourceConfiguration datasourceConfiguration, Properties properties) { + public Properties addAuthParamsToConnectionConfig( + DatasourceConfiguration datasourceConfiguration, Properties properties) { DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); properties.setProperty("user", authentication.getUsername()); properties.setProperty("password", authentication.getPassword()); - properties.setProperty("warehouse", String.valueOf(datasourceConfiguration.getProperties().get(0).getValue())); - properties.setProperty("db", String.valueOf(datasourceConfiguration.getProperties().get(1).getValue())); - properties.setProperty("schema", String.valueOf(datasourceConfiguration.getProperties().get(2).getValue())); - properties.setProperty("role", String.valueOf(datasourceConfiguration.getProperties().get(3).getValue())); + properties.setProperty( + "warehouse", + String.valueOf( + datasourceConfiguration.getProperties().get(0).getValue())); + properties.setProperty( + "db", + String.valueOf( + datasourceConfiguration.getProperties().get(1).getValue())); + properties.setProperty( + "schema", + String.valueOf( + datasourceConfiguration.getProperties().get(2).getValue())); + properties.setProperty( + "role", + String.valueOf( + datasourceConfiguration.getProperties().get(3).getValue())); /* Ref: https://github.com/appsmithorg/appsmith/issues/19784 */ properties.setProperty("jdbc_query_result_format", "json"); return properties; @@ -236,25 +264,34 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur if (datasourceConfiguration.getProperties() != null && (datasourceConfiguration.getProperties().size() < 1 - || datasourceConfiguration.getProperties().get(0) == null - || datasourceConfiguration.getProperties().get(0).getValue() == null - || StringUtils.isEmpty(String.valueOf(datasourceConfiguration.getProperties().get(0).getValue())))) { + || datasourceConfiguration.getProperties().get(0) == null + || datasourceConfiguration.getProperties().get(0).getValue() == null + || StringUtils.isEmpty(String.valueOf(datasourceConfiguration + .getProperties() + .get(0) + .getValue())))) { invalids.add(SnowflakeErrorMessages.DS_MISSING_WAREHOUSE_NAME_ERROR_MSG); } if (datasourceConfiguration.getProperties() != null && (datasourceConfiguration.getProperties().size() < 2 - || datasourceConfiguration.getProperties().get(1) == null - || datasourceConfiguration.getProperties().get(1).getValue() == null - || StringUtils.isEmpty(String.valueOf(datasourceConfiguration.getProperties().get(1).getValue())))) { + || datasourceConfiguration.getProperties().get(1) == null + || datasourceConfiguration.getProperties().get(1).getValue() == null + || StringUtils.isEmpty(String.valueOf(datasourceConfiguration + .getProperties() + .get(1) + .getValue())))) { invalids.add(SnowflakeErrorMessages.DS_MISSING_DATABASE_NAME_ERROR_MSG); } if (datasourceConfiguration.getProperties() != null && (datasourceConfiguration.getProperties().size() < 3 - || datasourceConfiguration.getProperties().get(2) == null - || datasourceConfiguration.getProperties().get(2).getValue() == null - || StringUtils.isEmpty(String.valueOf(datasourceConfiguration.getProperties().get(2).getValue())))) { + || datasourceConfiguration.getProperties().get(2) == null + || datasourceConfiguration.getProperties().get(2).getValue() == null + || StringUtils.isEmpty(String.valueOf(datasourceConfiguration + .getProperties() + .get(2) + .getValue())))) { invalids.add(SnowflakeErrorMessages.DS_MISSING_SCHEMA_NAME_ERROR_MSG); } @@ -279,7 +316,6 @@ public Mono<DatasourceTestResult> testDatasource(HikariDataSource connection) { return Mono.just(connection) .flatMap(connectionPool -> { - Connection connectionFromPool; try { /** @@ -288,11 +324,11 @@ public Mono<DatasourceTestResult> testDatasource(HikariDataSource connection) { * the method definition to understand more. */ connectionFromPool = - getConnectionFromHikariConnectionPool(connectionPool, - SNOWFLAKE_PLUGIN_NAME); + getConnectionFromHikariConnectionPool(connectionPool, SNOWFLAKE_PLUGIN_NAME); return Mono.just(validateWarehouseDatabaseSchema(connectionFromPool)); } catch (SQLException e) { - // The function can throw either StaleConnectionException or SQLException. The underlying hikari + // The function can throw either StaleConnectionException or SQLException. The underlying + // hikari // library throws SQLException in case the pool is closed or there is an issue initializing // the connection pool which can also be translated in our world to StaleConnectionException // and should then trigger the destruction and recreation of the pool. @@ -302,11 +338,11 @@ public Mono<DatasourceTestResult> testDatasource(HikariDataSource connection) { SnowflakeErrorMessages.UNABLE_TO_CREATE_CONNECTION_ERROR_MSG)); } catch (StaleConnectionException e) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.STALE_CONNECTION_ERROR, - e.getMessage())); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.STALE_CONNECTION_ERROR, e.getMessage())); } }) - .map(errorSet ->{ + .map(errorSet -> { if (!errorSet.isEmpty()) { return new DatasourceTestResult(errorSet); } @@ -317,14 +353,13 @@ public Mono<DatasourceTestResult> testDatasource(HikariDataSource connection) { } @Override - public Mono<DatasourceStructure> getStructure(HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { + public Mono<DatasourceStructure> getStructure( + HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { final DatasourceStructure structure = new DatasourceStructure(); final Map<String, DatasourceStructure.Table> tablesByName = new LinkedHashMap<>(); final Map<String, DatasourceStructure.Key> keyRegistry = new HashMap<>(); - return Mono - .fromSupplier(() -> { - + return Mono.fromSupplier(() -> { Connection connectionFromPool; try { /** @@ -335,7 +370,8 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connection, Datas connectionFromPool = getConnectionFromHikariConnectionPool(connection, SNOWFLAKE_PLUGIN_NAME); } catch (SQLException | StaleConnectionException e) { - // The function can throw either StaleConnectionException or SQLException. The underlying hikari + // The function can throw either StaleConnectionException or SQLException. The underlying + // hikari // library throws SQLException in case the pool is closed or there is an issue initializing // the connection pool which can also be translated in our world to StaleConnectionException // and should then trigger the destruction and recreation of the pool. @@ -348,22 +384,26 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connection, Datas int activeConnections = poolProxy.getActiveConnections(); int totalConnections = poolProxy.getTotalConnections(); int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug("Before getting snowflake structure Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", - activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); - + log.debug( + "Before getting snowflake structure Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", + activeConnections, + idleConnections, + threadsAwaitingConnection, + totalConnections); try { // Connection staleness is checked as part of this method call. Set<String> invalids = validateWarehouseDatabaseSchema(connectionFromPool); if (!invalids.isEmpty()) { throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - invalids.toArray()[0] - ); + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, invalids.toArray()[0]); } Statement statement = connectionFromPool.createStatement(); final String columnsQuery = SqlUtils.COLUMNS_QUERY + "'" - + datasourceConfiguration.getProperties().get(2).getValue() + "'"; + + datasourceConfiguration + .getProperties() + .get(2) + .getValue() + "'"; ResultSet resultSet = statement.executeQuery(columnsQuery); while (resultSet.next()) { @@ -387,16 +427,26 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connection, Datas table.getKeys().sort(Comparator.naturalOrder()); } } catch (SQLException throwable) { - log.error("Exception caught while fetching structure of Snowflake datasource. Cause: ", throwable); - throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, SnowflakeErrorMessages.GET_STRUCTURE_ERROR_MSG, throwable.getMessage(), "SQLSTATE: " + throwable.getSQLState()); + log.error( + "Exception caught while fetching structure of Snowflake datasource. Cause: ", + throwable); + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + SnowflakeErrorMessages.GET_STRUCTURE_ERROR_MSG, + throwable.getMessage(), + "SQLSTATE: " + throwable.getSQLState()); } finally { idleConnections = poolProxy.getIdleConnections(); activeConnections = poolProxy.getActiveConnections(); totalConnections = poolProxy.getTotalConnections(); threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug("After snowflake structure, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", - activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); + log.debug( + "After snowflake structure, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ", + activeConnections, + idleConnections, + threadsAwaitingConnection, + totalConnections); if (connectionFromPool != null) { try { @@ -412,4 +462,4 @@ public Mono<DatasourceStructure> getStructure(HikariDataSource connection, Datas .subscribeOn(scheduler); } } -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/exceptions/SnowflakeErrorMessages.java b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/exceptions/SnowflakeErrorMessages.java index 68516db8fb94..96a2f71e8e4b 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/exceptions/SnowflakeErrorMessages.java +++ b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/exceptions/SnowflakeErrorMessages.java @@ -8,18 +8,19 @@ public class SnowflakeErrorMessages extends BasePluginErrorMessages { public static final String MISSING_QUERY_ERROR_MSG = "Missing required parameter: Query."; - public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Your query failed to execute. Please check more information in the error details."; + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = + "Your query failed to execute. Please check more information in the error details."; public static final String UNABLE_TO_CREATE_CONNECTION_ERROR_MSG = "Unable to create connection to Snowflake URL"; - public static final String GET_STRUCTURE_ERROR_MSG = "Appsmith server has failed to fetch the structure of your schema. Please check more information in the error details."; - + public static final String GET_STRUCTURE_ERROR_MSG = + "Appsmith server has failed to fetch the structure of your schema. Please check more information in the error details."; /* - ************************************************************************************************************************************************ - Error messages related to validation of datasource. - ************************************************************************************************************************************************ - */ + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ public static final String DS_MISSING_ENDPOINT_ERROR_MSG = "Missing Snowflake URL."; public static final String DS_MISSING_WAREHOUSE_NAME_ERROR_MSG = "Missing warehouse name."; diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/exceptions/SnowflakePluginError.java b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/exceptions/SnowflakePluginError.java index d50a8c7adbc2..f7896fed50c4 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/exceptions/SnowflakePluginError.java +++ b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/exceptions/SnowflakePluginError.java @@ -17,8 +17,7 @@ public enum SnowflakePluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), SNOWFLAKE_PLUGIN_ERROR( 500, "PE-SNW-5001", @@ -27,8 +26,7 @@ public enum SnowflakePluginError implements BasePluginError { "Query execution error", ErrorType.INTERNAL_ERROR, "{1}", - "{2}" - ), + "{2}"), ; private final Integer httpErrorCode; private final String appErrorCode; @@ -41,8 +39,15 @@ public enum SnowflakePluginError implements BasePluginError { private final String downstreamErrorCode; - SnowflakePluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, - String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + SnowflakePluginError( + Integer httpErrorCode, + String appErrorCode, + String message, + AppsmithErrorAction errorAction, + String title, + ErrorType errorType, + String downstreamErrorMessage, + String downstreamErrorCode) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; @@ -57,7 +62,9 @@ public String getMessage(Object... args) { return new MessageFormat(this.message).format(args); } - public String getErrorType() { return this.errorType.toString(); } + public String getErrorType() { + return this.errorType.toString(); + } public String getDownstreamErrorMessage(Object... args) { return replacePlaceholderWithValue(this.downstreamErrorMessage, args); diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/ExecutionUtils.java b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/ExecutionUtils.java index 3a9bafb1298a..2d0ae7c396f3 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/ExecutionUtils.java +++ b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/ExecutionUtils.java @@ -30,8 +30,8 @@ public class ExecutionUtils { * @throws AppsmithPluginException * @throws StaleConnectionException */ - public static List<Map<String, Object>> getRowsFromQueryResult(Connection connection, String query) throws - AppsmithPluginException, StaleConnectionException { + public static List<Map<String, Object>> getRowsFromQueryResult(Connection connection, String query) + throws AppsmithPluginException, StaleConnectionException { List<Map<String, Object>> rowsList = new ArrayList<>(); ResultSet resultSet = null; Statement statement = null; @@ -63,7 +63,11 @@ public static List<Map<String, Object>> getRowsFromQueryResult(Connection connec throw new StaleConnectionException(e.getMessage()); } log.error("Exception caught when executing Snowflake query. Cause: ", e); - throw new AppsmithPluginException(SnowflakePluginError.QUERY_EXECUTION_FAILED, SnowflakeErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage(), "SQLSTATE: " + e.getSQLState() ); + throw new AppsmithPluginException( + SnowflakePluginError.QUERY_EXECUTION_FAILED, + SnowflakeErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, + e.getMessage(), + "SQLSTATE: " + e.getSQLState()); } finally { if (resultSet != null) { diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/SnowflakeDatasourceUtils.java b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/SnowflakeDatasourceUtils.java index f3e5f940543e..d71f795dd5a1 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/SnowflakeDatasourceUtils.java +++ b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/SnowflakeDatasourceUtils.java @@ -13,22 +13,22 @@ import static com.appsmith.external.exceptions.pluginExceptions.BasePluginErrorMessages.UNKNOWN_CONNECTION_ERROR_MSG; public class SnowflakeDatasourceUtils { - public static void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) throws StaleConnectionException { + public static void checkHikariCPConnectionPoolValidity(HikariDataSource connectionPool, String pluginName) + throws StaleConnectionException { if (connectionPool == null || connectionPool.isClosed() || !connectionPool.isRunning()) { - String printMessage = MessageFormat.format(Thread.currentThread().getName() + - ": Encountered stale connection pool in {0} plugin. Reporting back.", pluginName); + String printMessage = MessageFormat.format( + Thread.currentThread().getName() + + ": Encountered stale connection pool in {0} plugin. Reporting back.", + pluginName); System.out.println(printMessage); if (connectionPool == null) { throw new StaleConnectionException(CONNECTION_POOL_NULL_ERROR_MSG); - } - else if (connectionPool.isClosed()) { + } else if (connectionPool.isClosed()) { throw new StaleConnectionException(CONNECTION_POOL_CLOSED_ERROR_MSG); - } - else if (!connectionPool.isRunning()) { + } else if (!connectionPool.isRunning()) { throw new StaleConnectionException(CONNECTION_POOL_NOT_RUNNING_ERROR_MSG); - } - else { + } else { /** * Ideally, code flow is never expected to reach here. However, this section has been added to catch * those cases wherein a developer updates the parent if condition but does not update the nested @@ -39,8 +39,8 @@ else if (!connectionPool.isRunning()) { } } - public static Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, - String pluginName) throws SQLException { + public static Connection getConnectionFromHikariConnectionPool(HikariDataSource connectionPool, String pluginName) + throws SQLException { checkHikariCPConnectionPoolValidity(connectionPool, pluginName); return connectionPool.getConnection(); } diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/SqlUtils.java b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/SqlUtils.java index 1a13af669018..df0879e39a2c 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/SqlUtils.java +++ b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/SqlUtils.java @@ -26,20 +26,18 @@ public class SqlUtils { * | test_schema | test | 4 | lastname | varchar | 1 | | NO | * +--------------+------------+-----------+-------------+-------------+-------------+----------------+-------------+ */ - public static final String COLUMNS_QUERY = - "SELECT " + - "cols.table_schema as table_schema, " + - "cols.table_name as table_name, " + - "cols.ordinal_position as column_id, " + - "cols.column_name as column_name, " + - "cols.data_type as column_type, " + - "cols.is_nullable = 'YES' as is_nullable, " + - "cols.column_default as column_default, " + - "cols.is_identity as is_identity " + - "FROM " + - "information_schema.columns cols " + - "WHERE " + - "cols.table_schema = "; + public static final String COLUMNS_QUERY = "SELECT " + "cols.table_schema as table_schema, " + + "cols.table_name as table_name, " + + "cols.ordinal_position as column_id, " + + "cols.column_name as column_name, " + + "cols.data_type as column_type, " + + "cols.is_nullable = 'YES' as is_nullable, " + + "cols.column_default as column_default, " + + "cols.is_identity as is_identity " + + "FROM " + + "information_schema.columns cols " + + "WHERE " + + "cols.table_schema = "; /** * Example output for PRIMARY_KEYS_QUERY: @@ -100,15 +98,13 @@ public static String getDefaultValueByDataType(String datatype) { case "ARRAY": return "array_construct(1, 2, 3)"; case "VARIANT": - return - "parse_json(' { \"key1\": \"value1\", \"key2\": \"value2\" } ')"; + return "parse_json(' { \"key1\": \"value1\", \"key2\": \"value2\" } ')"; case "OBJECT": - return - "parse_json(' { \"outer_key1\": { \"inner_key1A\": \"1a\", \"inner_key1B\": NULL }, '\n" + - " ||\n" + - " ' \"outer_key2\": { \"inner_key2\": 2 } '\n" + - " ||\n" + - " ' } ')"; + return "parse_json(' { \"outer_key1\": { \"inner_key1A\": \"1a\", \"inner_key1B\": NULL }, '\n" + + " ||\n" + + " ' \"outer_key2\": { \"inner_key2\": 2 } '\n" + + " ||\n" + + " ' } ')"; case "GEOGRAPHY": return "'POINT(-122.35 37.55)'"; case "VARCHAR": @@ -126,8 +122,7 @@ public static String getDefaultValueByDataType(String datatype) { */ public static void getTemplates(Map<String, DatasourceStructure.Table> tablesByName) { for (DatasourceStructure.Table table : tablesByName.values()) { - final List<DatasourceStructure.Column> columnsWithoutDefault = table.getColumns() - .stream() + final List<DatasourceStructure.Column> columnsWithoutDefault = table.getColumns().stream() .filter(column -> column.getDefaultValue() == null) .collect(Collectors.toList()); @@ -142,7 +137,12 @@ public static void getTemplates(Map<String, DatasourceStructure.Table> tablesByN columnNames.add(name); columnValues.add(value); - setFragments.append("\n ").append(name).append(" = ").append(value).append(","); + setFragments + .append("\n ") + .append(name) + .append(" = ") + .append(value) + .append(","); } // Delete the last comma @@ -151,21 +151,33 @@ public static void getTemplates(Map<String, DatasourceStructure.Table> tablesByN } final String tableName = table.getSchema() + "." + table.getName(); - table.getTemplates().addAll(List.of( - new DatasourceStructure.Template("SELECT", "SELECT * FROM " + tableName + " LIMIT 10;"), - new DatasourceStructure.Template("INSERT", "INSERT INTO " + tableName - + " (" + String.join(", ", columnNames) + ")\n" - + " VALUES (" + String.join(", ", columnValues) + ");"), - new DatasourceStructure.Template("UPDATE", "UPDATE " + tableName + " SET" - + setFragments.toString() + "\n" - + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), - new DatasourceStructure.Template("DELETE", "DELETE FROM " + tableName - + "\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!") - )); + table.getTemplates() + .addAll( + List.of( + new DatasourceStructure.Template( + "SELECT", "SELECT * FROM " + tableName + " LIMIT 10;"), + new DatasourceStructure.Template( + "INSERT", + "INSERT INTO " + tableName + + " (" + String.join(", ", columnNames) + ")\n" + + " VALUES (" + String.join(", ", columnValues) + ");"), + new DatasourceStructure.Template( + "UPDATE", + "UPDATE " + tableName + " SET" + + setFragments.toString() + "\n" + + " WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"), + new DatasourceStructure.Template( + "DELETE", + "DELETE FROM " + tableName + + "\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"))); } } - public static void getForeignKeyInfo(ResultSet row, Map<String, DatasourceStructure.Table> tablesByName, Map<String, DatasourceStructure.Key> keyRegistry) throws SQLException { + public static void getForeignKeyInfo( + ResultSet row, + Map<String, DatasourceStructure.Table> tablesByName, + Map<String, DatasourceStructure.Key> keyRegistry) + throws SQLException { final String constraintName = row.getString("fk_name"); final String selfSchema = row.getString("pk_schema_name"); final String fkTableName = row.getString("fk_table_name"); @@ -180,26 +192,29 @@ public static void getForeignKeyInfo(ResultSet row, Map<String, DatasourceStruct final String keyFullName = tableName + "." + constraintName; final String foreignSchema = row.getString("fk_schema_name"); - final String prefix = (foreignSchema.equalsIgnoreCase(selfSchema) ? "" : foreignSchema + ".") - + fkTableName + "."; + final String prefix = + (foreignSchema.equalsIgnoreCase(selfSchema) ? "" : foreignSchema + ".") + fkTableName + "."; if (!keyRegistry.containsKey(keyFullName)) { - final DatasourceStructure.ForeignKey key = new DatasourceStructure.ForeignKey( - constraintName, - new ArrayList<>(), - new ArrayList<>() - ); + final DatasourceStructure.ForeignKey key = + new DatasourceStructure.ForeignKey(constraintName, new ArrayList<>(), new ArrayList<>()); keyRegistry.put(keyFullName, key); table.getKeys().add(key); } - ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)).getFromColumns() + ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)) + .getFromColumns() .add(row.getString("pk_column_name")); - ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)).getToColumns() + ((DatasourceStructure.ForeignKey) keyRegistry.get(keyFullName)) + .getToColumns() .add(prefix + row.getString("fk_column_name")); } - public static void getPrimaryKeyInfo(ResultSet row, Map<String, DatasourceStructure.Table> tablesByName, Map<String, DatasourceStructure.Key> keyRegistry) throws SQLException { + public static void getPrimaryKeyInfo( + ResultSet row, + Map<String, DatasourceStructure.Table> tablesByName, + Map<String, DatasourceStructure.Key> keyRegistry) + throws SQLException { final String constraintName = row.getString("constraint_name"); final String tableName = row.getString("table_name"); @@ -212,43 +227,42 @@ public static void getPrimaryKeyInfo(ResultSet row, Map<String, DatasourceStruct final String keyFullName = tableName + "." + constraintName; if (!keyRegistry.containsKey(keyFullName)) { - final DatasourceStructure.PrimaryKey key = new DatasourceStructure.PrimaryKey( - constraintName, - new ArrayList<>() - ); + final DatasourceStructure.PrimaryKey key = + new DatasourceStructure.PrimaryKey(constraintName, new ArrayList<>()); keyRegistry.put(keyFullName, key); table.getKeys().add(key); } - ((DatasourceStructure.PrimaryKey) keyRegistry.get(keyFullName)).getColumnNames() + ((DatasourceStructure.PrimaryKey) keyRegistry.get(keyFullName)) + .getColumnNames() .add(row.getString("column_name")); } - public static void getTableInfo(ResultSet row, Map<String, DatasourceStructure.Table> tablesByName) throws SQLException { + public static void getTableInfo(ResultSet row, Map<String, DatasourceStructure.Table> tablesByName) + throws SQLException { final String tableSchema = row.getString("TABLE_SCHEMA"); final String tableName = row.getString("TABLE_NAME"); if (!tablesByName.containsKey(tableName)) { - tablesByName.put(tableName, new DatasourceStructure.Table( - DatasourceStructure.TableType.TABLE, - tableSchema, + tablesByName.put( tableName, - new ArrayList<>(), - new ArrayList<>(), - new ArrayList<>() - )); + new DatasourceStructure.Table( + DatasourceStructure.TableType.TABLE, + tableSchema, + tableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); } final DatasourceStructure.Table table = tablesByName.get(tableName); String defaultValue = row.getString("COLUMN_DEFAULT"); // AUTOINCREMENT and IDENTITY are synonymous. If either is specified for a column, Snowflake utilizes a sequence // to generate the values for the column. For more information about sequences, see Using Sequences boolean isAutogenerated = "YES".equalsIgnoreCase(row.getString("IS_IDENTITY")) - || (!StringUtils.isEmpty(defaultValue) && defaultValue.toLowerCase().contains("nextval")); - - table.getColumns().add(new DatasourceStructure.Column( - row.getString("COLUMN_NAME"), - row.getString("COLUMN_TYPE"), - defaultValue, - isAutogenerated - )); + || (!StringUtils.isEmpty(defaultValue) + && defaultValue.toLowerCase().contains("nextval")); + + table.getColumns() + .add(new DatasourceStructure.Column( + row.getString("COLUMN_NAME"), row.getString("COLUMN_TYPE"), defaultValue, isAutogenerated)); } } diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/ValidationUtils.java b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/ValidationUtils.java index 12609261b9a3..79de10ec0b6b 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/ValidationUtils.java +++ b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/utils/ValidationUtils.java @@ -29,8 +29,8 @@ public class ValidationUtils { * @param connection - Connection object to execute query * @return A set of error statements in case the query result contains any null / empty value. */ - public static Set<String> validateWarehouseDatabaseSchema(Connection connection) throws StaleConnectionException, - AppsmithPluginException { + public static Set<String> validateWarehouseDatabaseSchema(Connection connection) + throws StaleConnectionException, AppsmithPluginException { Set<String> invalids = new HashSet<>(); // Check database validity. @@ -60,8 +60,9 @@ public static Set<String> validateWarehouseDatabaseSchema(Connection connection) // Construct error message string. private static String getWarehouseDatabaseSchemaErrorMessage(String key) { String fieldName = StringUtils.capitalize(key.toLowerCase()); - return "Appsmith could not find any valid " + key.toLowerCase() + " configured for this datasource. " + - "Please provide a valid " + key.toLowerCase() + " by editing the " + fieldName + " field in the " + - "datasource configuration page."; + return "Appsmith could not find any valid " + key.toLowerCase() + " configured for this datasource. " + + "Please provide a valid " + + key.toLowerCase() + " by editing the " + fieldName + " field in the " + + "datasource configuration page."; } } diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/test/java/com/external/plugins/SnowflakePluginTest.java b/app/server/appsmith-plugins/snowflakePlugin/src/test/java/com/external/plugins/SnowflakePluginTest.java index fb9d91352ce9..e0d58493fce9 100644 --- a/app/server/appsmith-plugins/snowflakePlugin/src/test/java/com/external/plugins/SnowflakePluginTest.java +++ b/app/server/appsmith-plugins/snowflakePlugin/src/test/java/com/external/plugins/SnowflakePluginTest.java @@ -1,11 +1,11 @@ package com.external.plugins; import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; -import com.appsmith.external.models.DatasourceTestResult; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionResult; import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.DatasourceTestResult; import com.appsmith.external.models.Property; import com.external.plugins.exceptions.SnowflakeErrorMessages; import com.external.plugins.exceptions.SnowflakePluginError; @@ -32,9 +32,8 @@ import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; - -import java.util.Arrays; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -85,56 +84,44 @@ public void testDatasourceWithInvalidUrl() { auth.setPassword("test"); datasourceConfiguration.setAuthentication(auth); List<Property> properties = new ArrayList<>(); - properties.add(new Property("warehouse","warehouse")); - properties.add(new Property("db","dbName")); - properties.add(new Property("schema","schemaName")); - properties.add(new Property("role","userRole")); + properties.add(new Property("warehouse", "warehouse")); + properties.add(new Property("db", "dbName")); + properties.add(new Property("schema", "schemaName")); + properties.add(new Property("role", "userRole")); datasourceConfiguration.setUrl("invalid.host.name"); datasourceConfiguration.setProperties(properties); Mono<DatasourceTestResult> output = pluginExecutor.testDatasource(datasourceConfiguration); StepVerifier.create(pluginExecutor.testDatasource(datasourceConfiguration)) .assertNext(datasourceTestResult -> { assertNotNull(datasourceTestResult); - assertTrue(datasourceTestResult.getInvalids().contains(SnowflakeErrorMessages. - UNABLE_TO_CREATE_CONNECTION_ERROR_MSG)); - }).verifyComplete(); + assertTrue(datasourceTestResult + .getInvalids() + .contains(SnowflakeErrorMessages.UNABLE_TO_CREATE_CONNECTION_ERROR_MSG)); + }) + .verifyComplete(); } @Test public void testExecute_authenticationTimeout_returnsStaleConnectionException() throws SQLException { final String testQuery = "testQuery"; final Connection connection = mock(Connection.class); - when(connection.isValid(30)) - .thenReturn(true); + when(connection.isValid(30)).thenReturn(true); final Statement statement = mock(Statement.class); - when(connection.createStatement()) - .thenReturn(statement); + when(connection.createStatement()).thenReturn(statement); when(statement.executeQuery(testQuery)) - .thenThrow(new SnowflakeReauthenticationRequest( - "1", - "Authentication token expired", - "", - 0)); + .thenThrow(new SnowflakeReauthenticationRequest("1", "Authentication token expired", "", 0)); final HikariPoolMXBean hikariPoolMXBean = mock(HikariPoolMXBean.class); - when(hikariPoolMXBean.getActiveConnections()) - .thenReturn(1); - when(hikariPoolMXBean.getIdleConnections()) - .thenReturn(4); - when(hikariPoolMXBean.getTotalConnections()) - .thenReturn(5); - when(hikariPoolMXBean.getThreadsAwaitingConnection()) - .thenReturn(0); + when(hikariPoolMXBean.getActiveConnections()).thenReturn(1); + when(hikariPoolMXBean.getIdleConnections()).thenReturn(4); + when(hikariPoolMXBean.getTotalConnections()).thenReturn(5); + when(hikariPoolMXBean.getThreadsAwaitingConnection()).thenReturn(0); final HikariDataSource hikariDataSource = mock(HikariDataSource.class); - when(hikariDataSource.getConnection()) - .thenReturn(connection); - when(hikariDataSource.isClosed()) - .thenReturn(false); - when(hikariDataSource.isRunning()) - .thenReturn(true); - when(hikariDataSource.getHikariPoolMXBean()) - .thenReturn(hikariPoolMXBean); + when(hikariDataSource.getConnection()).thenReturn(connection); + when(hikariDataSource.isClosed()).thenReturn(false); + when(hikariDataSource.isRunning()).thenReturn(true); + when(hikariDataSource.getHikariPoolMXBean()).thenReturn(hikariPoolMXBean); final ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody(testQuery); @@ -165,7 +152,9 @@ public void testValidationUtils_withBadDatabaseName() { Set<String> invalids; try (MockedStatic<ExecutionUtils> executionUtilsMockedStatic = mockStatic(ExecutionUtils.class)) { - executionUtilsMockedStatic.when(() -> ExecutionUtils.getRowsFromQueryResult(any(), anyString())).thenAnswer((Answer<List>) invocation -> rowList); + executionUtilsMockedStatic + .when(() -> ExecutionUtils.getRowsFromQueryResult(any(), anyString())) + .thenAnswer((Answer<List>) invocation -> rowList); invalids = ValidationUtils.validateWarehouseDatabaseSchema(mockConnection); } @@ -175,20 +164,26 @@ public void testValidationUtils_withBadDatabaseName() { // Match error statement. Set<String> expectedInvalids = new HashSet<>(); - expectedInvalids.add("Appsmith could not find any valid database configured for this datasource" + - ". Please provide a valid database by editing the Database field in the datasource " + - "configuration page."); + expectedInvalids.add("Appsmith could not find any valid database configured for this datasource" + + ". Please provide a valid database by editing the Database field in the datasource " + + "configuration page."); assertEquals(expectedInvalids, invalids); } @Test public void verifyUniquenessOfSnowflakePluginErrorCode() { - assert (Arrays.stream(SnowflakePluginError.values()).map(SnowflakePluginError::getAppErrorCode).distinct().count() == SnowflakePluginError.values().length); - - assert (Arrays.stream(SnowflakePluginError.values()).map(SnowflakePluginError::getAppErrorCode) - .filter(appErrorCode-> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-SNW")) - .collect(Collectors.toList()).size() == 0); - + assert (Arrays.stream(SnowflakePluginError.values()) + .map(SnowflakePluginError::getAppErrorCode) + .distinct() + .count() + == SnowflakePluginError.values().length); + + assert (Arrays.stream(SnowflakePluginError.values()) + .map(SnowflakePluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-SNW")) + .collect(Collectors.toList()) + .size() + == 0); } @Test @@ -204,20 +199,21 @@ public void verifyTemplatesHasQuotesAroundMustacheSubstitutions() throws IOExcep MapType type; factory = TypeFactory.defaultInstance(); - type = factory.constructMapType(HashMap.class, String.class, List.class); - mapper = new ObjectMapper(); - result = mapper.readValue(meta, type); + type = factory.constructMapType(HashMap.class, String.class, List.class); + mapper = new ObjectMapper(); + result = mapper.readValue(meta, type); List<String> templates = new ArrayList<>(); // parsing each template file and putting to a string to process for mustache templates result.get("templates").forEach(entry -> { for (Map.Entry<String, String> mapEntry : entry.entrySet()) { - try(InputStream template = new ClassPathResource("templates/" + mapEntry.getValue()).getInputStream()) { + try (InputStream template = + new ClassPathResource("templates/" + mapEntry.getValue()).getInputStream()) { BufferedReader templateReader = new BufferedReader(new InputStreamReader(template)); String file = templateReader.lines().collect(Collectors.joining(System.lineSeparator())); templates.add(file); - } catch (IOException e){ + } catch (IOException e) { throw new RuntimeException(e); } } @@ -230,7 +226,7 @@ public void verifyTemplatesHasQuotesAroundMustacheSubstitutions() throws IOExcep Pattern enclosedMustachePattern = Pattern.compile(enclosedMustache); // processing each template file in loop - for(String template : templates) { + for (String template : templates) { Matcher mustacheMatcher = mustachePattern.matcher(template); Matcher enclosedMustacheMatcher = enclosedMustachePattern.matcher(template); @@ -239,18 +235,20 @@ public void verifyTemplatesHasQuotesAroundMustacheSubstitutions() throws IOExcep int enclosedMustacheMatchCount = 0; // finding count of mustache substitution expressions - while( mustacheMatcher.find() ) { + while (mustacheMatcher.find()) { mustacheMatchCount++; } // finding count of mustache substitution expressions enclosed in single quotes - while( enclosedMustacheMatcher.find() ) { + while (enclosedMustacheMatcher.find()) { enclosedMustacheMatchCount++; } // count of mustache substitution expression and enclosed expressions should be same in hint text - // current test is based on rationale that all fields in hint are text fields hence should be enclosed in quotes in an sql query. - // moving forward this condition can be deemed incompatible with introduction of numeric fields hence this test case can then be adjusted accordingly. + // current test is based on rationale that all fields in hint are text fields hence should be enclosed in + // quotes in an sql query. + // moving forward this condition can be deemed incompatible with introduction of numeric fields hence this + // test case can then be adjusted accordingly. assertEquals(mustacheMatchCount, enclosedMustacheMatchCount); } } diff --git a/app/server/appsmith-server/pom.xml b/app/server/appsmith-server/pom.xml index bd0c0081b3f1..1da66de8b5b1 100644 --- a/app/server/appsmith-server/pom.xml +++ b/app/server/appsmith-server/pom.xml @@ -17,28 +17,21 @@ <properties> <ff4j.version>2.0.0</ff4j.version> - <org.modelmapper.version>2.4.4</org.modelmapper.version> <jmh.version>1.35</jmh.version> + <org.modelmapper.version>2.4.4</org.modelmapper.version> </properties> - <repositories> - <repository> - <id>spring-milestones</id> - <name>Spring Milestones</name> - <url>https://repo.spring.io/milestone</url> - <snapshots> - <enabled>false</enabled> - </snapshots> - </repository> - <repository> - <id>jboss-maven2-release-repository</id> - <name>JBoss Spring Repository</name> - <url>https://repository.jboss.org/nexus/content/repositories/public/</url> - <snapshots> - <enabled>false</enabled> - </snapshots> - </repository> - </repositories> + <dependencyManagement> + <dependencies> + <dependency> + <groupId>io.mongock</groupId> + <artifactId>mongock-bom</artifactId> + <version>5.1.7</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement> <dependencies> @@ -58,20 +51,20 @@ <artifactId>slf4j-api</artifactId> </exclusion> <exclusion> - <artifactId>reactor-core</artifactId> <groupId>io.projectreactor</groupId> + <artifactId>reactor-core</artifactId> </exclusion> <exclusion> - <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> + <artifactId>spring-core</artifactId> </exclusion> <exclusion> - <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> + <artifactId>spring-web</artifactId> </exclusion> <exclusion> - <artifactId>reactive-streams</artifactId> <groupId>org.reactivestreams</groupId> + <artifactId>reactive-streams</artifactId> </exclusion> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> @@ -406,8 +399,8 @@ <scope>test</scope> <exclusions> <exclusion> - <artifactId>junit</artifactId> <groupId>junit</groupId> + <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> @@ -420,6 +413,25 @@ </dependency> </dependencies> + <repositories> + <repository> + <snapshots> + <enabled>false</enabled> + </snapshots> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + </repository> + <repository> + <snapshots> + <enabled>false</enabled> + </snapshots> + <id>jboss-maven2-release-repository</id> + <name>JBoss Spring Repository</name> + <url>https://repository.jboss.org/nexus/content/repositories/public/</url> + </repository> + </repositories> + <build> <plugins> <plugin> @@ -438,9 +450,7 @@ </goals> <configuration> <outputDirectory>target/generated-sources/java</outputDirectory> - <processor> - org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor - </processor> + <processor>org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor</processor> <options> <querydsl.listAccessors>true</querydsl.listAccessors> </options> @@ -451,16 +461,4 @@ </plugins> </build> - <dependencyManagement> - <dependencies> - <dependency> - <groupId>io.mongock</groupId> - <artifactId>mongock-bom</artifactId> - <version>5.1.7</version> - <type>pom</type> - <scope>import</scope> - </dependency> - </dependencies> - </dependencyManagement> - </project> diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/ServerApplication.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/ServerApplication.java index 1f9982262320..9874bc5debec 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/ServerApplication.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/ServerApplication.java @@ -14,5 +14,4 @@ public static void main(String[] args) { .bannerMode(Banner.Mode.OFF) .run(args); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclConstants.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclConstants.java index 85b386f5e659..19fa8d37e96d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclConstants.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclConstants.java @@ -10,12 +10,5 @@ public interface AclConstants { String DEFAULT_ORG_ID = "default-org"; Set<String> PERMISSIONS_GROUP_ORG_ADMIN = Set.of( - "create:organizations", - "read:organizations", - "create:groups", - "read:groups", - "create:users", - "read:users" - ); + "create:organizations", "read:organizations", "create:groups", "read:groups", "create:users", "read:users"); } - diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclPermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclPermission.java index 371e24b12ac4..c35697188851 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclPermission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclPermission.java @@ -32,7 +32,7 @@ public enum AclPermission { // Does the user have manage workspace permission @Deprecated USER_MANAGE_WORKSPACES("manage:userWorkspace", User.class), - //Does the user have read workspace permissions + // Does the user have read workspace permissions @Deprecated USER_READ_WORKSPACES("read:userWorkspace", User.class), @@ -120,7 +120,6 @@ public enum AclPermission { MANAGE_TENANT("manage:tenants", Tenant.class), ; - private final String value; private final Class<? extends BaseDomain> entity; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AppsmithRole.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AppsmithRole.java index 46e8574e681e..f05d1d782778 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AppsmithRole.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AppsmithRole.java @@ -30,18 +30,40 @@ @Getter public enum AppsmithRole { - ORGANIZATION_ADMIN(ADMINISTRATOR, WORKSPACE_ADMINISTRATOR_DESCRIPTION, - Set.of(MANAGE_WORKSPACES, WORKSPACE_INVITE_USERS, WORKSPACE_EXPORT_APPLICATIONS, WORKSPACE_CREATE_APPLICATION, WORKSPACE_CREATE_DATASOURCE, - WORKSPACE_DELETE_DATASOURCES, WORKSPACE_DELETE_APPLICATIONS, DELETE_WORKSPACES)), - ORGANIZATION_DEVELOPER(DEVELOPER, WORKSPACE_DEVELOPER_DESCRIPTION, - Set.of(READ_WORKSPACES, WORKSPACE_MANAGE_APPLICATIONS, WORKSPACE_MANAGE_DATASOURCES, WORKSPACE_READ_APPLICATIONS, - WORKSPACE_PUBLISH_APPLICATIONS, WORKSPACE_INVITE_USERS, WORKSPACE_CREATE_APPLICATION, WORKSPACE_CREATE_DATASOURCE, - WORKSPACE_DELETE_DATASOURCES, WORKSPACE_DELETE_APPLICATIONS)), + ORGANIZATION_ADMIN( + ADMINISTRATOR, + WORKSPACE_ADMINISTRATOR_DESCRIPTION, + Set.of( + MANAGE_WORKSPACES, + WORKSPACE_INVITE_USERS, + WORKSPACE_EXPORT_APPLICATIONS, + WORKSPACE_CREATE_APPLICATION, + WORKSPACE_CREATE_DATASOURCE, + WORKSPACE_DELETE_DATASOURCES, + WORKSPACE_DELETE_APPLICATIONS, + DELETE_WORKSPACES)), + ORGANIZATION_DEVELOPER( + DEVELOPER, + WORKSPACE_DEVELOPER_DESCRIPTION, + Set.of( + READ_WORKSPACES, + WORKSPACE_MANAGE_APPLICATIONS, + WORKSPACE_MANAGE_DATASOURCES, + WORKSPACE_READ_APPLICATIONS, + WORKSPACE_PUBLISH_APPLICATIONS, + WORKSPACE_INVITE_USERS, + WORKSPACE_CREATE_APPLICATION, + WORKSPACE_CREATE_DATASOURCE, + WORKSPACE_DELETE_DATASOURCES, + WORKSPACE_DELETE_APPLICATIONS)), ORGANIZATION_VIEWER( VIEWER, WORKSPACE_VIEWER_DESCRIPTION, - Set.of(READ_WORKSPACES, WORKSPACE_READ_APPLICATIONS, WORKSPACE_INVITE_USERS, WORKSPACE_EXECUTE_DATASOURCES) - ), + Set.of( + READ_WORKSPACES, + WORKSPACE_READ_APPLICATIONS, + WORKSPACE_INVITE_USERS, + WORKSPACE_EXECUTE_DATASOURCES)), TENANT_ADMIN("", "", Set.of(MANAGE_TENANT)), ; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/PolicyGenerator.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/PolicyGenerator.java index 0426dc52b3ba..693ed551654d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/PolicyGenerator.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/PolicyGenerator.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class PolicyGenerator extends PolicyGeneratorCE { - -} +public class PolicyGenerator extends PolicyGeneratorCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/RoleGraph.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/RoleGraph.java index d60f07bc2d7e..35883a376c73 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/RoleGraph.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/RoleGraph.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class RoleGraph extends RoleGraphCE { - -} +public class RoleGraph extends RoleGraphCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/ce/PolicyGeneratorCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/ce/PolicyGeneratorCE.java index aac84a91f473..e9c4ea973703 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/ce/PolicyGeneratorCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/ce/PolicyGeneratorCE.java @@ -64,7 +64,6 @@ import static com.appsmith.server.acl.AclPermission.WORKSPACE_READ_APPLICATIONS; import static com.appsmith.server.acl.AclPermission.WORKSPACE_READ_DATASOURCES; - @Getter @Setter @Slf4j @@ -90,16 +89,14 @@ public void createPolicyGraph() { createPolicyGraphForEachType(); addLateralEdgesForAllIndirectRelationships(); - } protected void addVertices() { // Initialization of the hierarchical and lateral graphs by adding all the vertices - EnumSet.allOf(AclPermission.class) - .forEach(permission -> { - hierarchyGraph.addVertex(permission); - lateralGraph.addVertex(permission); - }); + EnumSet.allOf(AclPermission.class).forEach(permission -> { + hierarchyGraph.addVertex(permission); + lateralGraph.addVertex(permission); + }); } protected void createPolicyGraphForEachType() { @@ -241,19 +238,22 @@ protected void createPermissionGroupPolicyGraph() { lateralGraph.addEdge(AclPermission.ASSIGN_PERMISSION_GROUPS, AclPermission.READ_PERMISSION_GROUP_MEMBERS); } - public Set<Policy> getLateralPolicies(AclPermission permission, Set<String> permissionGroups, Class<? extends BaseDomain> destinationEntity) { + public Set<Policy> getLateralPolicies( + AclPermission permission, Set<String> permissionGroups, Class<? extends BaseDomain> destinationEntity) { Set<DefaultEdge> lateralEdges = lateralGraph.outgoingEdgesOf(permission); return lateralEdges.stream() .map(edge -> lateralGraph.getEdgeTarget(edge)) .filter(lateralPermission -> { - if (destinationEntity == null || - lateralPermission.getEntity().equals(destinationEntity)) { + if (destinationEntity == null + || lateralPermission.getEntity().equals(destinationEntity)) { return true; } return false; }) - .map(lateralPermission -> Policy.builder().permission(lateralPermission.getValue()) - .permissionGroups(permissionGroups).build()) + .map(lateralPermission -> Policy.builder() + .permission(lateralPermission.getValue()) + .permissionGroups(permissionGroups) + .build()) .collect(Collectors.toSet()); } @@ -267,9 +267,11 @@ public Set<Policy> getLateralPolicies(AclPermission permission, Set<String> perm * @param destinationEntity * @return */ - public Set<Policy> getChildPolicies(Policy policy, AclPermission aclPermission, Class<? extends BaseDomain> destinationEntity) { + public Set<Policy> getChildPolicies( + Policy policy, AclPermission aclPermission, Class<? extends BaseDomain> destinationEntity) { - // In case the calling function could not translate the string value to AclPermission, return an empty set to handle + // In case the calling function could not translate the string value to AclPermission, return an empty set to + // handle // erroneous cases if (aclPermission == null) { return Collections.emptySet(); @@ -286,8 +288,10 @@ public Set<Policy> getChildPolicies(Policy policy, AclPermission aclPermission, AclPermission childPermission = hierarchyGraph.getEdgeTarget(edge); if (childPermission.getEntity().equals(destinationEntity)) { - childPolicySet.add(Policy.builder().permission(childPermission.getValue()) - .permissionGroups(policy.getPermissionGroups()).build()); + childPolicySet.add(Policy.builder() + .permission(childPermission.getValue()) + .permissionGroups(policy.getPermissionGroups()) + .build()); } // Check the lateral graph to derive the child permissions that must be given to this document @@ -297,14 +301,18 @@ public Set<Policy> getChildPolicies(Policy policy, AclPermission aclPermission, return childPolicySet; } - public Set<Policy> getAllChildPolicies(Set<Policy> policySet, Class<? extends BaseDomain> sourceEntity, Class<? extends BaseDomain> destinationEntity) { + public Set<Policy> getAllChildPolicies( + Set<Policy> policySet, + Class<? extends BaseDomain> sourceEntity, + Class<? extends BaseDomain> destinationEntity) { Set<Policy> policies = policySet.stream() .map(policy -> { - AclPermission aclPermission = AclPermission - .getPermissionByValue(policy.getPermission(), sourceEntity); + AclPermission aclPermission = + AclPermission.getPermissionByValue(policy.getPermission(), sourceEntity); // Get all the child policies for the given policy and aclPermission return getChildPolicies(policy, aclPermission, destinationEntity); - }).flatMap(Collection::stream) + }) + .flatMap(Collection::stream) .collect(Collectors.toSet()); Map<String, Policy> policyMap = new LinkedHashMap<>(); @@ -313,7 +321,8 @@ public Set<Policy> getAllChildPolicies(Set<Policy> policySet, Class<? extends Ba if (policyMap.containsKey(policy.getPermission())) { Policy mergedPolicy = policyMap.get(policy.getPermission()); - mergedPolicy.setPermissionGroups(Sets.union(mergedPolicy.getPermissionGroups(), policy.getPermissionGroups())); + mergedPolicy.setPermissionGroups( + Sets.union(mergedPolicy.getPermissionGroups(), policy.getPermissionGroups())); policyMap.put(policy.getPermission(), mergedPolicy); } else { @@ -324,23 +333,27 @@ public Set<Policy> getAllChildPolicies(Set<Policy> policySet, Class<? extends Ba return new HashSet<>(policyMap.values()); } - public Set<AclPermission> getChildPermissions(AclPermission aclPermission, Class<? extends BaseDomain> destinationEntity) { + public Set<AclPermission> getChildPermissions( + AclPermission aclPermission, Class<? extends BaseDomain> destinationEntity) { Set<AclPermission> childPermissionSet = new HashSet<>(); - Set<AclPermission> lateralPermissions = lateralGraph.outgoingEdgesOf(aclPermission) - .stream().map(defaultEdge -> lateralGraph.getEdgeTarget(defaultEdge)) - .filter(permission -> destinationEntity == null || permission.getEntity().equals(destinationEntity)) + Set<AclPermission> lateralPermissions = lateralGraph.outgoingEdgesOf(aclPermission).stream() + .map(defaultEdge -> lateralGraph.getEdgeTarget(defaultEdge)) + .filter(permission -> + destinationEntity == null || permission.getEntity().equals(destinationEntity)) .collect(Collectors.toSet()); childPermissionSet.addAll(lateralPermissions); - Set<AclPermission> directChildPermissions = hierarchyGraph.outgoingEdgesOf(aclPermission) - .stream().map(defaultEdge -> hierarchyGraph.getEdgeTarget(defaultEdge)) - .filter(permission -> destinationEntity == null || permission.getEntity().equals(destinationEntity)) + Set<AclPermission> directChildPermissions = hierarchyGraph.outgoingEdgesOf(aclPermission).stream() + .map(defaultEdge -> hierarchyGraph.getEdgeTarget(defaultEdge)) + .filter(permission -> + destinationEntity == null || permission.getEntity().equals(destinationEntity)) .collect(Collectors.toSet()); childPermissionSet.addAll(directChildPermissions); childPermissionSet.addAll(getAllChildPermissions(directChildPermissions, destinationEntity)); return childPermissionSet; } - public Set<AclPermission> getAllChildPermissions(Collection<AclPermission> aclPermissions, Class<? extends BaseDomain> destinationEntity) { + public Set<AclPermission> getAllChildPermissions( + Collection<AclPermission> aclPermissions, Class<? extends BaseDomain> destinationEntity) { return aclPermissions.stream() .map(permission -> getChildPermissions(permission, destinationEntity)) .flatMap(Set::stream) diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/ce/RoleGraphCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/ce/RoleGraphCE.java index f4058ad5783c..4cba472ea1d3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/ce/RoleGraphCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/ce/RoleGraphCE.java @@ -27,10 +27,9 @@ public class RoleGraphCE { public void createPolicyGraph() { // Initialization of the hierarchical and lateral graphs by adding all the vertices - EnumSet.allOf(AppsmithRole.class) - .forEach(role -> { - hierarchyGraph.addVertex(role); - }); + EnumSet.allOf(AppsmithRole.class).forEach(role -> { + hierarchyGraph.addVertex(role); + }); hierarchyGraph.addEdge(ORGANIZATION_ADMIN, ORGANIZATION_DEVELOPER); hierarchyGraph.addEdge(ORGANIZATION_DEVELOPER, ORGANIZATION_VIEWER); @@ -41,7 +40,8 @@ public Set<AppsmithRole> generateHierarchicalRoles(String roleName) { Set<AppsmithRole> childrenRoles = new LinkedHashSet<>(); childrenRoles.add(role); - BreadthFirstIterator<AppsmithRole, DefaultEdge> breadthFirstIterator = new BreadthFirstIterator<>(hierarchyGraph, role); + BreadthFirstIterator<AppsmithRole, DefaultEdge> breadthFirstIterator = + new BreadthFirstIterator<>(hierarchyGraph, role); while (breadthFirstIterator.hasNext()) { childrenRoles.add(breadthFirstIterator.next()); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AccessDeniedHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AccessDeniedHandler.java index 02f601c7ca2b..b6d891bb380e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AccessDeniedHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AccessDeniedHandler.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class AccessDeniedHandler extends AccessDeniedHandlerCE { - -} +public class AccessDeniedHandler extends AccessDeniedHandlerCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationEntryPoint.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationEntryPoint.java index 9672f59e7889..9eb6c14b5e67 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationEntryPoint.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationEntryPoint.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class AuthenticationEntryPoint extends AuthenticationEntryPointCE { - -} +public class AuthenticationEntryPoint extends AuthenticationEntryPointCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationFailureHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationFailureHandler.java index 0ba216e0dfae..b5003afdc364 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationFailureHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationFailureHandler.java @@ -6,6 +6,4 @@ @Component @RequiredArgsConstructor -public class AuthenticationFailureHandler extends AuthenticationFailureHandlerCE { - -} +public class AuthenticationFailureHandler extends AuthenticationFailureHandlerCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationSuccessHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationSuccessHandler.java index 0e4ee671130b..9861ff27fc21 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationSuccessHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationSuccessHandler.java @@ -22,23 +22,36 @@ @Component public class AuthenticationSuccessHandler extends AuthenticationSuccessHandlerCE { - public AuthenticationSuccessHandler(ForkExamplesWorkspace examplesWorkspaceCloner, - RedirectHelper redirectHelper, - SessionUserService sessionUserService, - AnalyticsService analyticsService, - UserDataService userDataService, - UserRepository userRepository, - WorkspaceService workspaceService, - WorkspaceRepository workspaceRepository, - ApplicationPageService applicationPageService, - WorkspacePermission workspacePermission, - ConfigService configService, - FeatureFlagService featureFlagService, - CommonConfig commonConfig, - UserIdentifierService userIdentifierService) { + public AuthenticationSuccessHandler( + ForkExamplesWorkspace examplesWorkspaceCloner, + RedirectHelper redirectHelper, + SessionUserService sessionUserService, + AnalyticsService analyticsService, + UserDataService userDataService, + UserRepository userRepository, + WorkspaceService workspaceService, + WorkspaceRepository workspaceRepository, + ApplicationPageService applicationPageService, + WorkspacePermission workspacePermission, + ConfigService configService, + FeatureFlagService featureFlagService, + CommonConfig commonConfig, + UserIdentifierService userIdentifierService) { - super(examplesWorkspaceCloner, redirectHelper, sessionUserService, analyticsService, userDataService, - userRepository, workspaceRepository, workspaceService, applicationPageService, workspacePermission, - configService, featureFlagService, commonConfig, userIdentifierService); + super( + examplesWorkspaceCloner, + redirectHelper, + sessionUserService, + analyticsService, + userDataService, + userRepository, + workspaceRepository, + workspaceService, + applicationPageService, + workspacePermission, + configService, + featureFlagService, + commonConfig, + userIdentifierService); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/CustomServerOAuth2AuthorizationRequestResolver.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/CustomServerOAuth2AuthorizationRequestResolver.java index a37894042495..532819bec599 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/CustomServerOAuth2AuthorizationRequestResolver.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/CustomServerOAuth2AuthorizationRequestResolver.java @@ -26,11 +26,15 @@ public class CustomServerOAuth2AuthorizationRequestResolver extends CustomServer * @param commonConfig * @param redirectHelper */ - public CustomServerOAuth2AuthorizationRequestResolver(ReactiveClientRegistrationRepository clientRegistrationRepository, - CommonConfig commonConfig, - RedirectHelper redirectHelper) { - this(clientRegistrationRepository, new PathPatternParserServerWebExchangeMatcher( - DEFAULT_AUTHORIZATION_REQUEST_PATTERN), commonConfig, redirectHelper); + public CustomServerOAuth2AuthorizationRequestResolver( + ReactiveClientRegistrationRepository clientRegistrationRepository, + CommonConfig commonConfig, + RedirectHelper redirectHelper) { + this( + clientRegistrationRepository, + new PathPatternParserServerWebExchangeMatcher(DEFAULT_AUTHORIZATION_REQUEST_PATTERN), + commonConfig, + redirectHelper); } /** @@ -41,10 +45,11 @@ public CustomServerOAuth2AuthorizationRequestResolver(ReactiveClientRegistration * {@link #DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME} from the path variables. * @param redirectHelper */ - public CustomServerOAuth2AuthorizationRequestResolver(ReactiveClientRegistrationRepository clientRegistrationRepository, - ServerWebExchangeMatcher authorizationRequestMatcher, - CommonConfig commonConfig, - RedirectHelper redirectHelper) { + public CustomServerOAuth2AuthorizationRequestResolver( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerWebExchangeMatcher authorizationRequestMatcher, + CommonConfig commonConfig, + RedirectHelper redirectHelper) { super(clientRegistrationRepository, authorizationRequestMatcher, commonConfig, redirectHelper); this.redirectHelper = redirectHelper; Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/LogoutSuccessHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/LogoutSuccessHandler.java index 32ecc9e24f64..2bfc350dd915 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/LogoutSuccessHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/LogoutSuccessHandler.java @@ -11,5 +11,4 @@ public class LogoutSuccessHandler extends LogoutSuccessHandlerCE { public LogoutSuccessHandler(ObjectMapper objectMapper, AnalyticsService analyticsService) { super(objectMapper, analyticsService); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationFailureHandlerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationFailureHandlerCE.java index b8eab1dc1a89..99ac2d34996a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationFailureHandlerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationFailureHandlerCE.java @@ -46,7 +46,9 @@ public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, A String[] stateArray = state.split(","); for (int i = 0; i < stateArray.length; i++) { String stateVar = stateArray[i]; - if (stateVar != null && stateVar.startsWith(Security.STATE_PARAMETER_ORIGIN) && stateVar.contains("=")) { + if (stateVar != null + && stateVar.startsWith(Security.STATE_PARAMETER_ORIGIN) + && stateVar.contains("=")) { // This is the origin of the request that we want to redirect to originHeader = stateVar.split("=")[1]; } @@ -76,11 +78,17 @@ public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, A URI defaultRedirectLocation; String url = ""; if (exception instanceof OAuth2AuthenticationException - && AppsmithError.SIGNUP_DISABLED.getAppErrorCode().toString().equals(((OAuth2AuthenticationException) exception).getError().getErrorCode())) { + && AppsmithError.SIGNUP_DISABLED + .getAppErrorCode() + .toString() + .equals(((OAuth2AuthenticationException) exception) + .getError() + .getErrorCode())) { url = "/user/signup?error=" + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8); } else { if (exception instanceof InternalAuthenticationServiceException) { - url = originHeader + "/user/login?error=true&message=" + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8); + url = originHeader + "/user/login?error=true&message=" + + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8); } else { url = originHeader + "/user/login?error=true"; } @@ -91,5 +99,4 @@ public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, A defaultRedirectLocation = URI.create(url); return this.redirectStrategy.sendRedirect(exchange, defaultRedirectLocation); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationSuccessHandlerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationSuccessHandlerCE.java index 8bb0a2a56fff..8b14269f2ee6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationSuccessHandlerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationSuccessHandlerCE.java @@ -25,7 +25,6 @@ import com.appsmith.server.solutions.WorkspacePermission; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.codec.digest.DigestUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.security.core.Authentication; @@ -75,10 +74,7 @@ public class AuthenticationSuccessHandlerCE implements ServerAuthenticationSucce * @return Publishes empty, that completes after handler tasks are finished. */ @Override - public Mono<Void> onAuthenticationSuccess( - WebFilterExchange webFilterExchange, - Authentication authentication - ) { + public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) { return onAuthenticationSuccess(webFilterExchange, authentication, false, false, null); } @@ -87,8 +83,7 @@ public Mono<Void> onAuthenticationSuccess( Authentication authentication, boolean createDefaultApplication, boolean isFromSignup, - String defaultWorkspaceId - ) { + String defaultWorkspaceId) { log.debug("Login succeeded for user: {}", authentication.getPrincipal()); Mono<Void> redirectionMono; User user = (User) authentication.getPrincipal(); @@ -105,18 +100,23 @@ public Mono<Void> onAuthenticationSuccess( // verification this can be eliminated safely if (user.getPassword() != null) { user.setPassword(null); - user.setSource( - LoginSource.fromString(((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId()) - ); + user.setSource(LoginSource.fromString( + ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId())); // Update the user in separate thread - userRepository.save(user).subscribeOn(Schedulers.boundedElastic()).subscribe(); + userRepository + .save(user) + .subscribeOn(Schedulers.boundedElastic()) + .subscribe(); } if (isFromSignup) { boolean finalIsFromSignup = isFromSignup; - redirectionMono = workspaceService.isCreateWorkspaceAllowed(Boolean.TRUE) + redirectionMono = workspaceService + .isCreateWorkspaceAllowed(Boolean.TRUE) .elapsed() .map(pair -> { - log.debug("AuthenticationSuccessHandlerCE::Time taken to check if workspace creation allowed: {} ms", pair.getT1()); + log.debug( + "AuthenticationSuccessHandlerCE::Time taken to check if workspace creation allowed: {} ms", + pair.getT1()); return pair.getT2(); }) .flatMap(isCreateWorkspaceAllowed -> { @@ -124,11 +124,13 @@ public Mono<Void> onAuthenticationSuccess( return createDefaultApplication(defaultWorkspaceId, authentication) .elapsed() .map(pair -> { - log.debug("AuthenticationSuccessHandlerCE::Time taken to create default application: {} ms", pair.getT1()); + log.debug( + "AuthenticationSuccessHandlerCE::Time taken to create default application: {} ms", + pair.getT1()); return pair.getT2(); }) - .flatMap(defaultApplication -> - handleOAuth2Redirect(webFilterExchange, defaultApplication, finalIsFromSignup)); + .flatMap(defaultApplication -> handleOAuth2Redirect( + webFilterExchange, defaultApplication, finalIsFromSignup)); } return handleOAuth2Redirect(webFilterExchange, null, finalIsFromSignup); }); @@ -141,18 +143,21 @@ public Mono<Void> onAuthenticationSuccess( redirectionMono = createDefaultApplication(defaultWorkspaceId, authentication) .elapsed() .map(pair -> { - log.debug("AuthenticationSuccessHandlerCE::Time taken to create default application: {} ms", pair.getT1()); + log.debug( + "AuthenticationSuccessHandlerCE::Time taken to create default application: {} ms", + pair.getT1()); return pair.getT2(); }) - .flatMap(defaultApplication -> redirectHelper.handleRedirect(webFilterExchange, defaultApplication, true) - ); + .flatMap(defaultApplication -> + redirectHelper.handleRedirect(webFilterExchange, defaultApplication, true)); } else { redirectionMono = redirectHelper.handleRedirect(webFilterExchange, null, finalIsFromSignup); } } final boolean isFromSignupFinal = isFromSignup; - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .flatMap(currentUser -> { List<Mono<?>> monos = new ArrayList<>(); monos.add(userDataService.ensureViewedCurrentVersionReleaseNotes(currentUser)); @@ -162,8 +167,8 @@ public Mono<Void> onAuthenticationSuccess( modeOfLogin = ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(); } /* - Adding default traits to flagsmith for the logged-in user - */ + Adding default traits to flagsmith for the logged-in user + */ monos.add(addDefaultUserTraits(user)); if (isFromSignupFinal) { @@ -171,32 +176,30 @@ public Mono<Void> onAuthenticationSuccess( final boolean isFromInvite = inviteToken != null; // This should hold the role of the user, e.g., `App Viewer`, `Developer`, etc. - final String invitedAs = inviteToken == null ? "" : inviteToken.split(":", 2)[0]; + final String invitedAs = + inviteToken == null ? "" : inviteToken.split(":", 2)[0]; modeOfLogin = "FormSignUp"; if (authentication instanceof OAuth2AuthenticationToken) { - modeOfLogin = ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(); + modeOfLogin = + ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(); } monos.add(analyticsService.sendObjectEvent( AnalyticsEvents.FIRST_LOGIN, currentUser, Map.of( - "isFromInvite", isFromInvite, - "invitedAs", invitedAs, - FieldName.MODE_OF_LOGIN, modeOfLogin - ) - )); + "isFromInvite", + isFromInvite, + "invitedAs", + invitedAs, + FieldName.MODE_OF_LOGIN, + modeOfLogin))); monos.add(examplesWorkspaceCloner.forkExamplesWorkspace()); } monos.add(analyticsService.sendObjectEvent( - AnalyticsEvents.LOGIN, - currentUser, - Map.of( - FieldName.MODE_OF_LOGIN, modeOfLogin - ) - )); + AnalyticsEvents.LOGIN, currentUser, Map.of(FieldName.MODE_OF_LOGIN, modeOfLogin))); return Mono.whenDelayError(monos); }) @@ -212,14 +215,14 @@ private Mono<Void> addDefaultUserTraits(User user) { } else { emailTrait = user.getEmail(); } - return configService.getInstanceId() - .flatMap(instanceId -> { - featureFlagTraits.add(addTraitKeyValueToTraitObject(identifier, "email", emailTrait)); - featureFlagTraits.add(addTraitKeyValueToTraitObject(identifier, "instanceId", instanceId)); - featureFlagTraits.add(addTraitKeyValueToTraitObject(identifier, "tenantId", user.getTenantId())); - featureFlagTraits.add(addTraitKeyValueToTraitObject(identifier, "is_telemetry_on", String.valueOf(!commonConfig.isTelemetryDisabled()))); - return featureFlagService.remoteSetUserTraits(featureFlagTraits); - }); + return configService.getInstanceId().flatMap(instanceId -> { + featureFlagTraits.add(addTraitKeyValueToTraitObject(identifier, "email", emailTrait)); + featureFlagTraits.add(addTraitKeyValueToTraitObject(identifier, "instanceId", instanceId)); + featureFlagTraits.add(addTraitKeyValueToTraitObject(identifier, "tenantId", user.getTenantId())); + featureFlagTraits.add(addTraitKeyValueToTraitObject( + identifier, "is_telemetry_on", String.valueOf(!commonConfig.isTelemetryDisabled()))); + return featureFlagService.remoteSetUserTraits(featureFlagTraits); + }); } private FeatureFlagTrait addTraitKeyValueToTraitObject(String identifier, String traitKey, String traitValue) { @@ -239,7 +242,8 @@ protected Mono<Application> createDefaultApplication(String defaultWorkspaceId, Mono<Application> applicationMono = Mono.just(application); if (defaultWorkspaceId == null) { - applicationMono = workspaceRepository.findAll(workspacePermission.getEditPermission()) + applicationMono = workspaceRepository + .findAll(workspacePermission.getEditPermission()) .take(1, true) .collectList() .flatMap(workspaces -> { @@ -254,18 +258,17 @@ protected Mono<Application> createDefaultApplication(String defaultWorkspaceId, // In case no workspaces are found for the user, create a new default workspace String email = ((User) authentication.getPrincipal()).getEmail(); - return userRepository.findByEmail(email) + return userRepository + .findByEmail(email) .flatMap(user -> workspaceService.createDefault(new Workspace(), user)) .map(workspace -> { application.setWorkspaceId(workspace.getId()); return application; }); - }); } - return applicationMono - .flatMap(application1 -> applicationPageService.createApplication(application1)); + return applicationMono.flatMap(application1 -> applicationPageService.createApplication(application1)); } /** @@ -281,9 +284,9 @@ protected Mono<Application> createDefaultApplication(String defaultWorkspaceId, */ @SuppressWarnings( // Disabling this because although the reference in the Javadoc is to a private method, it is still useful. - "JavadocReference" - ) - private Mono<Void> handleOAuth2Redirect(WebFilterExchange webFilterExchange, Application defaultApplication, boolean isFromSignup) { + "JavadocReference") + private Mono<Void> handleOAuth2Redirect( + WebFilterExchange webFilterExchange, Application defaultApplication, boolean isFromSignup) { ServerWebExchange exchange = webFilterExchange.getExchange(); String state = exchange.getRequest().getQueryParams().getFirst(Security.QUERY_PARAMETER_STATE); String redirectUrl = RedirectHelper.DEFAULT_REDIRECT_URL; @@ -309,6 +312,4 @@ private Mono<Void> handleOAuth2Redirect(WebFilterExchange webFilterExchange, App return redirectStrategy.sendRedirect(exchange, URI.create(redirectUrl)); } - - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomFormLoginServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomFormLoginServiceCEImpl.java index 380656750020..c05999fe0012 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomFormLoginServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomFormLoginServiceCEImpl.java @@ -31,7 +31,8 @@ public CustomFormLoginServiceCEImpl(UserRepository repository) { */ @Override public Mono<UserDetails> findByUsername(String username) { - return repository.findByEmail(username) + return repository + .findByEmail(username) .switchIfEmpty(repository.findByCaseInsensitiveEmail(username)) .switchIfEmpty(Mono.error(new UsernameNotFoundException("Unable to find username: " + username))) .onErrorMap(error -> { @@ -47,11 +48,8 @@ public Mono<UserDetails> findByUsername(String username) { if (user.getPassword() == null && !LoginSource.FORM.equals(user.getSource())) { // We can have a implementation to give which login method user should use but this will // expose the sign-in source for external world and in turn to spammers - throw new InternalAuthenticationServiceException( - AppsmithError.INVALID_LOGIN_METHOD.getMessage( - WordUtils.capitalize(user.getSource().toString().toLowerCase()) - ) - ); + throw new InternalAuthenticationServiceException(AppsmithError.INVALID_LOGIN_METHOD.getMessage( + WordUtils.capitalize(user.getSource().toString().toLowerCase()))); } return user; }); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomOAuth2UserServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomOAuth2UserServiceCEImpl.java index ef04f73556be..cdaf770ef696 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomOAuth2UserServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomOAuth2UserServiceCEImpl.java @@ -44,13 +44,15 @@ private Mono<User> checkAndCreateUser(OAuth2User oAuth2User, OAuth2UserRequest u String username = oAuth2User.getName(); - return repository.findByEmail(username) + return repository + .findByEmail(username) .switchIfEmpty(repository.findByCaseInsensitiveEmail(username)) .switchIfEmpty(Mono.defer(() -> { User newUser = new User(); newUser.setName(oAuth2User.getName()); newUser.setEmail(username); - LoginSource loginSource = LoginSource.fromString(userRequest.getClientRegistration().getRegistrationId()); + LoginSource loginSource = LoginSource.fromString( + userRequest.getClientRegistration().getRegistrationId()); newUser.setSource(loginSource); newUser.setState(UserState.ACTIVATED); newUser.setIsEnabled(true); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomOidcUserServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomOidcUserServiceCEImpl.java index a7c74b17484d..d2e46aa47cb9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomOidcUserServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomOidcUserServiceCEImpl.java @@ -22,7 +22,6 @@ * We transform the {@link OAuth2User} object to {@link User} object via the {@link #loadUser(OidcUserRequest)} * We also create the user if it doesn't exist we create it via {@link #checkAndCreateUser(OidcUser, OidcUserRequest)} */ - @Slf4j public class CustomOidcUserServiceCEImpl extends OidcReactiveOAuth2UserService { @@ -49,7 +48,8 @@ public Mono<User> checkAndCreateUser(OidcUser oidcUser, OidcUserRequest userRequ String username = (!StringUtils.isEmpty(oidcUser.getEmail())) ? oidcUser.getEmail() : oidcUser.getName(); - return repository.findByEmail(username) + return repository + .findByEmail(username) .switchIfEmpty(repository.findByCaseInsensitiveEmail(username)) .switchIfEmpty(Mono.defer(() -> { User newUser = new User(); @@ -59,7 +59,8 @@ public Mono<User> checkAndCreateUser(OidcUser oidcUser, OidcUserRequest userRequ newUser.setName(oidcUser.getName()); } newUser.setEmail(username); - LoginSource loginSource = LoginSource.fromString(userRequest.getClientRegistration().getRegistrationId()); + LoginSource loginSource = LoginSource.fromString( + userRequest.getClientRegistration().getRegistrationId()); newUser.setSource(loginSource); newUser.setState(UserState.ACTIVATED); newUser.setIsEnabled(true); @@ -76,8 +77,6 @@ public Mono<User> checkAndCreateUser(OidcUser oidcUser, OidcUserRequest userRequ .onErrorMap( AppsmithException.class, error -> new OAuth2AuthenticationException( - new OAuth2Error(error.getAppErrorCode().toString(), error.getMessage(), "") - ) - ); + new OAuth2Error(error.getAppErrorCode().toString(), error.getMessage(), ""))); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomServerOAuth2AuthorizationRequestResolverCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomServerOAuth2AuthorizationRequestResolverCE.java index 0eba59ce0a80..006a39781769 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomServerOAuth2AuthorizationRequestResolverCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/CustomServerOAuth2AuthorizationRequestResolverCE.java @@ -56,7 +56,8 @@ public class CustomServerOAuth2AuthorizationRequestResolverCE implements ServerO /** * The default pattern used to resolve the {@link ClientRegistration#getRegistrationId()} */ - public static final String DEFAULT_AUTHORIZATION_REQUEST_PATTERN = "/oauth2/authorization/{" + DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME + "}"; + public static final String DEFAULT_AUTHORIZATION_REQUEST_PATTERN = + "/oauth2/authorization/{" + DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME + "}"; private static final char PATH_DELIMITER = '/'; @@ -64,9 +65,11 @@ public class CustomServerOAuth2AuthorizationRequestResolverCE implements ServerO private final ReactiveClientRegistrationRepository clientRegistrationRepository; - private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding()); + private final StringKeyGenerator stateGenerator = + new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding()); - private final StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96); + private final StringKeyGenerator secureKeyGenerator = + new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96); private static final String MISSING_VALUE_SENTINEL = "missing_value_sentinel"; @@ -81,11 +84,15 @@ public class CustomServerOAuth2AuthorizationRequestResolverCE implements ServerO * @param commonConfig * @param redirectHelper */ - public CustomServerOAuth2AuthorizationRequestResolverCE(ReactiveClientRegistrationRepository clientRegistrationRepository, - CommonConfig commonConfig, - RedirectHelper redirectHelper) { - this(clientRegistrationRepository, new PathPatternParserServerWebExchangeMatcher( - DEFAULT_AUTHORIZATION_REQUEST_PATTERN), commonConfig, redirectHelper); + public CustomServerOAuth2AuthorizationRequestResolverCE( + ReactiveClientRegistrationRepository clientRegistrationRepository, + CommonConfig commonConfig, + RedirectHelper redirectHelper) { + this( + clientRegistrationRepository, + new PathPatternParserServerWebExchangeMatcher(DEFAULT_AUTHORIZATION_REQUEST_PATTERN), + commonConfig, + redirectHelper); } /** @@ -96,10 +103,11 @@ public CustomServerOAuth2AuthorizationRequestResolverCE(ReactiveClientRegistrati * {@link #DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME} from the path variables. * @param redirectHelper */ - public CustomServerOAuth2AuthorizationRequestResolverCE(ReactiveClientRegistrationRepository clientRegistrationRepository, - ServerWebExchangeMatcher authorizationRequestMatcher, - CommonConfig commonConfig, - RedirectHelper redirectHelper) { + public CustomServerOAuth2AuthorizationRequestResolverCE( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerWebExchangeMatcher authorizationRequestMatcher, + CommonConfig commonConfig, + RedirectHelper redirectHelper) { this.redirectHelper = redirectHelper; Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); Assert.notNull(authorizationRequestMatcher, "authorizationRequestMatcher cannot be null"); @@ -110,7 +118,8 @@ public CustomServerOAuth2AuthorizationRequestResolverCE(ReactiveClientRegistrati @Override public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange) { - return this.authorizationRequestMatcher.matches(exchange) + return this.authorizationRequestMatcher + .matches(exchange) .filter(ServerWebExchangeMatcher.MatchResult::isMatch) .map(ServerWebExchangeMatcher.MatchResult::getVariables) .map(variables -> variables.get(DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME)) @@ -119,25 +128,25 @@ public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange) { } @Override - public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange, - String clientRegistrationId) { - return this.findByRegistrationId(clientRegistrationId) - .flatMap(clientRegistration -> { - if (MISSING_VALUE_SENTINEL.equals(clientRegistration.getClientId())) { - return Mono.error(new AppsmithException(AppsmithError.OAUTH_NOT_AVAILABLE, clientRegistrationId)); - } else { - return authorizationRequest(exchange, clientRegistration); - } - }); + public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange, String clientRegistrationId) { + return this.findByRegistrationId(clientRegistrationId).flatMap(clientRegistration -> { + if (MISSING_VALUE_SENTINEL.equals(clientRegistration.getClientId())) { + return Mono.error(new AppsmithException(AppsmithError.OAUTH_NOT_AVAILABLE, clientRegistrationId)); + } else { + return authorizationRequest(exchange, clientRegistration); + } + }); } private Mono<ClientRegistration> findByRegistrationId(String clientRegistration) { - return this.clientRegistrationRepository.findByRegistrationId(clientRegistration) - .switchIfEmpty(Mono.error(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid client registration id"))); + return this.clientRegistrationRepository + .findByRegistrationId(clientRegistration) + .switchIfEmpty(Mono.error( + () -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid client registration id"))); } - private Mono<OAuth2AuthorizationRequest> authorizationRequest(ServerWebExchange exchange, - ClientRegistration clientRegistration) { + private Mono<OAuth2AuthorizationRequest> authorizationRequest( + ServerWebExchange exchange, ClientRegistration clientRegistration) { String redirectUriStr = expandRedirectUri(exchange.getRequest(), clientRegistration); Map<String, Object> attributes = new HashMap<>(); @@ -147,9 +156,10 @@ private Mono<OAuth2AuthorizationRequest> authorizationRequest(ServerWebExchange if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) { builder = OAuth2AuthorizationRequest.authorizationCode(); Map<String, Object> additionalParameters = new HashMap<>(); - if (!CollectionUtils.isEmpty(clientRegistration.getScopes()) && - clientRegistration.getScopes().contains(OidcScopes.OPENID)) { - // Section 3.1.2.1 Authentication Request - https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest + if (!CollectionUtils.isEmpty(clientRegistration.getScopes()) + && clientRegistration.getScopes().contains(OidcScopes.OPENID)) { + // Section 3.1.2.1 Authentication Request - + // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest // scope // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value. addNonceParameters(attributes, additionalParameters); @@ -159,9 +169,11 @@ private Mono<OAuth2AuthorizationRequest> authorizationRequest(ServerWebExchange } if (!commonConfig.getOauthAllowedDomains().isEmpty()) { if (commonConfig.getOauthAllowedDomains().size() == 1) { - // Incase there's only 1 domain, we can do a further optimization to let the user select a specific one + // Incase there's only 1 domain, we can do a further optimization to let the user select a specific + // one // from the list - additionalParameters.put("hd", commonConfig.getOauthAllowedDomains().get(0)); + additionalParameters.put( + "hd", commonConfig.getOauthAllowedDomains().get(0)); } else { // Add multiple domains to the list of allowed domains additionalParameters.put("hd", commonConfig.getOauthAllowedDomains()); @@ -169,22 +181,22 @@ private Mono<OAuth2AuthorizationRequest> authorizationRequest(ServerWebExchange } builder.additionalParameters(additionalParameters); -// } else if (AuthorizationGrantType.IMPLICIT.equals(clientRegistration.getAuthorizationGrantType())) { -// builder = OAuth2AuthorizationRequest.implicit(); + // } else if (AuthorizationGrantType.IMPLICIT.equals(clientRegistration.getAuthorizationGrantType())) + // { + // builder = OAuth2AuthorizationRequest.implicit(); } else { - throw new IllegalArgumentException( - "Invalid Authorization Grant type (" + clientRegistration.getAuthorizationGrantType().getValue() - + ") for Client Registration with Id: " + clientRegistration.getRegistrationId()); + throw new IllegalArgumentException("Invalid Authorization Grant type (" + + clientRegistration.getAuthorizationGrantType().getValue() + ") for Client Registration with Id: " + + clientRegistration.getRegistrationId()); } - return generateKey(exchange.getRequest()) - .map(key -> builder - .clientId(clientRegistration.getClientId()) - .authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()) - .redirectUri(redirectUriStr).scopes(clientRegistration.getScopes()) - .state(key) - .attributes(attributes) - .build()); + return generateKey(exchange.getRequest()).map(key -> builder.clientId(clientRegistration.getClientId()) + .authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()) + .redirectUri(redirectUriStr) + .scopes(clientRegistration.getScopes()) + .state(key) + .attributes(attributes) + .build()); } /** @@ -197,12 +209,11 @@ private Mono<OAuth2AuthorizationRequest> authorizationRequest(ServerWebExchange * @return Publishes a single String, that is the generated key. */ private Mono<String> generateKey(ServerHttpRequest request) { - return redirectHelper.getRedirectUrl(request) - .map(redirectUrl -> { - String stateKey = this.stateGenerator.generateKey(); - stateKey = stateKey + "@" + Security.STATE_PARAMETER_ORIGIN + redirectUrl; - return stateKey; - }); + return redirectHelper.getRedirectUrl(request).map(redirectUrl -> { + String stateKey = this.stateGenerator.generateKey(); + stateKey = stateKey + "@" + Security.STATE_PARAMETER_ORIGIN + redirectUrl; + return stateKey; + }); } /** diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/LogoutSuccessHandlerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/LogoutSuccessHandlerCE.java index 2d356397e9dd..b1c36eb10114 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/LogoutSuccessHandlerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/LogoutSuccessHandlerCE.java @@ -40,19 +40,18 @@ public Mono<Void> onLogoutSuccess(WebFilterExchange webFilterExchange, Authentic try { ResponseDTO<Boolean> responseBody = new ResponseDTO<>(HttpStatus.OK.value(), true, null); String responseStr = objectMapper.writeValueAsString(responseBody); - DataBuffer buffer = exchange.getResponse().bufferFactory().allocateBuffer().write(responseStr.getBytes()); - return analyticsService.sendObjectEvent( - AnalyticsEvents.LOGOUT, - (User) authentication.getPrincipal() - ) + DataBuffer buffer = + exchange.getResponse().bufferFactory().allocateBuffer().write(responseStr.getBytes()); + return analyticsService + .sendObjectEvent(AnalyticsEvents.LOGOUT, (User) authentication.getPrincipal()) .then(response.writeWith(Mono.just(buffer))); } catch (JsonProcessingException e) { log.error("Unable to write to response json. Cause: ", e); // Returning a hard-coded failure json String responseStr = "{\"responseMeta\":{\"status\":500,\"success\":false},\"data\":false}"; - DataBuffer buffer = exchange.getResponse().bufferFactory().allocateBuffer().write(responseStr.getBytes()); + DataBuffer buffer = + exchange.getResponse().bufferFactory().allocateBuffer().write(responseStr.getBytes()); return response.writeWith(Mono.just(buffer)); } } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ClientUserRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ClientUserRepository.java index 9f41a29662e0..efd0c311edfa 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ClientUserRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ClientUserRepository.java @@ -18,7 +18,6 @@ import java.util.HashMap; import java.util.Map; - /** * This code has been copied from {@link WebSessionServerOAuth2AuthorizedClientRepository} * which also implements ServerOAuth2AuthorizedClientRepository. This was done to make changes @@ -58,8 +57,8 @@ public ClientUserRepository(UserService userService, CommonConfig commonConfig) @Override @SuppressWarnings("unchecked") - public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId, Authentication principal, - ServerWebExchange exchange) { + public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient( + String clientRegistrationId, Authentication principal, ServerWebExchange exchange) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.notNull(exchange, "exchange cannot be null"); return exchange.getSession() @@ -68,18 +67,21 @@ public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String cl } @Override - public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, - ServerWebExchange exchange) { + public Mono<Void> saveAuthorizedClient( + OAuth2AuthorizedClient authorizedClient, Authentication principal, ServerWebExchange exchange) { Assert.notNull(authorizedClient, "authorizedClient cannot be null"); Assert.notNull(exchange, "exchange cannot be null"); Assert.notNull(principal, "authentication object cannot be null"); // Check if the list of configured custom domains match the authenticated principal. // This is to provide more control over which accounts can be used to access the application. - // TODO: This is not a good way to do this. Ideally, we should pass "hd=example.com" to OAuth2 provider to list relevant accounts only + // TODO: This is not a good way to do this. Ideally, we should pass "hd=example.com" to OAuth2 provider to list + // relevant accounts only if (!commonConfig.getOauthAllowedDomains().isEmpty()) { String domain = null; - log.debug("Got the principal class as: {}", principal.getPrincipal().getClass().getName()); + log.debug( + "Got the principal class as: {}", + principal.getPrincipal().getClass().getName()); if (principal.getPrincipal() instanceof DefaultOidcUser) { DefaultOidcUser userPrincipal = (DefaultOidcUser) principal.getPrincipal(); domain = (String) userPrincipal.getAttributes().getOrDefault("hd", ""); @@ -92,7 +94,8 @@ public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, return exchange.getSession() .doOnSuccess(session -> { Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session); - authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient); + authorizedClients.put( + authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient); session.getAttributes().put(this.sessionAttributeName, authorizedClients); }) /* @@ -105,8 +108,8 @@ public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, } @Override - public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal, - ServerWebExchange exchange) { + public Mono<Void> removeAuthorizedClient( + String clientRegistrationId, Authentication principal, ServerWebExchange exchange) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.notNull(exchange, "exchange cannot be null"); return exchange.getSession() @@ -124,8 +127,9 @@ public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentica @SuppressWarnings("unchecked") private Map<String, OAuth2AuthorizedClient> getAuthorizedClients(WebSession session) { - Map<String, OAuth2AuthorizedClient> authorizedClients = session == null ? null : - (Map<String, OAuth2AuthorizedClient>) session.getAttribute(this.sessionAttributeName); + Map<String, OAuth2AuthorizedClient> authorizedClients = session == null + ? null + : (Map<String, OAuth2AuthorizedClient>) session.getAttribute(this.sessionAttributeName); if (authorizedClients == null) { authorizedClients = new HashMap<>(); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CustomAccessTokenResponseClient.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CustomAccessTokenResponseClient.java index e9a2c1ca76ff..9567f15ca0bc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CustomAccessTokenResponseClient.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CustomAccessTokenResponseClient.java @@ -18,5 +18,4 @@ public Mono<OAuth2AccessTokenResponse> getTokenResponse(OAuth2AuthorizationCodeG setWebClient(webClient); return super.getTokenResponse(grantRequest); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/EmailConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/EmailConfig.java index 6caaa1fd7636..f5440901af0c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/EmailConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/EmailConfig.java @@ -53,5 +53,4 @@ public void setMailFrom(@Value("${mail.from}") String value) { } } } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/FeatureFlagConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/FeatureFlagConfig.java index bf7f6083faf3..c1208dce2e95 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/FeatureFlagConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/FeatureFlagConfig.java @@ -10,8 +10,6 @@ public class FeatureFlagConfig { @Bean public FF4j ff4j() { - return new FF4j(new XmlParser(), "features/init-flags.xml") - .audit(true) - .autoCreate(true); + return new FF4j(new XmlParser(), "features/init-flags.xml").audit(true).autoCreate(true); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/GoogleRecaptchaConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/GoogleRecaptchaConfig.java index f2554e980182..4f64eb6a94fe 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/GoogleRecaptchaConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/GoogleRecaptchaConfig.java @@ -15,5 +15,4 @@ public class GoogleRecaptchaConfig { @Value("${google.recaptcha.key.secret}") private String secretKey; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/InstanceConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/InstanceConfig.java index b4fdc0ee23a2..a26c9cc316d4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/InstanceConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/InstanceConfig.java @@ -23,11 +23,11 @@ public class InstanceConfig implements ApplicationListener<ApplicationReadyEvent private final InstanceConfigHelper instanceConfigHelper; - @Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { - Mono<Void> registrationAndRtsCheckMono = configService.getByName(Appsmith.APPSMITH_REGISTERED) + Mono<Void> registrationAndRtsCheckMono = configService + .getByName(Appsmith.APPSMITH_REGISTERED) .filter(config -> Boolean.TRUE.equals(config.getConfig().get("value"))) .switchIfEmpty(instanceConfigHelper.registerInstance()) .onErrorResume(errorSignal -> { @@ -37,7 +37,8 @@ public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { .then(instanceConfigHelper.performRtsHealthCheck()) .doFinally(ignored -> instanceConfigHelper.printReady()); - Mono<?> startupProcess = instanceConfigHelper.checkInstanceSchemaVersion() + Mono<?> startupProcess = instanceConfigHelper + .checkInstanceSchemaVersion() .flatMap(signal -> registrationAndRtsCheckMono) // Prefill the server cache with anonymous user permission group ids. .then(cacheableRepositoryHelper.preFillAnonymousUserPermissionGroupIdsCache()) @@ -55,5 +56,4 @@ public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { public boolean getIsRtsAccessible() { return instanceConfigHelper.getIsRtsAccessible(); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MDCConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MDCConfig.java index b0f170c7284d..4d3621355574 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MDCConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MDCConfig.java @@ -21,7 +21,8 @@ public class MDCConfig { @PostConstruct void contextOperatorHook() { - Hooks.onEachOperator(MDC_CONTEXT_REACTOR_KEY, Operators.lift((sc, subscriber) -> new MdcContextLifter<>(subscriber))); + Hooks.onEachOperator( + MDC_CONTEXT_REACTOR_KEY, Operators.lift((sc, subscriber) -> new MdcContextLifter<>(subscriber))); } @PreDestroy @@ -29,7 +30,6 @@ void cleanupHook() { Hooks.resetOnEachOperator(MDC_CONTEXT_REACTOR_KEY); } - /** * Helper that copies the state of Reactor [Context] to MDC on the #onNext function. */ diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ModelMapperConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ModelMapperConfig.java index 85102ebd3a88..8ef16d88487b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ModelMapperConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ModelMapperConfig.java @@ -11,5 +11,4 @@ public class ModelMapperConfig { ModelMapper modelMapper() { return new ModelMapper(); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MongoConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MongoConfig.java index 050f13f918da..4c2f8c28b315 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MongoConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MongoConfig.java @@ -50,10 +50,10 @@ @Slf4j @Configuration @EnableReactiveMongoAuditing -@EnableReactiveMongoRepositories(repositoryFactoryBeanClass = SoftDeleteMongoRepositoryFactoryBean.class, +@EnableReactiveMongoRepositories( + repositoryFactoryBeanClass = SoftDeleteMongoRepositoryFactoryBean.class, basePackages = "com.appsmith.server.repositories", - repositoryBaseClass = BaseRepositoryImpl.class -) + repositoryBaseClass = BaseRepositoryImpl.class) public class MongoConfig { /* @@ -63,7 +63,8 @@ public class MongoConfig { Link to documentation: https://docs.mongock.io/v5/runner/springboot/index.html */ @Bean - public MongockInitializingBeanRunner mongockInitializingBeanRunner(ApplicationContext springContext, MongoTemplate mongoTemplate) { + public MongockInitializingBeanRunner mongockInitializingBeanRunner( + ApplicationContext springContext, MongoTemplate mongoTemplate) { SpringDataMongoV4Driver mongoDriver = SpringDataMongoV4Driver.withDefaultLock(mongoTemplate); mongoDriver.setWriteConcern(WriteConcern.JOURNALED.withJournal(false)); mongoDriver.setReadConcern(ReadConcern.LOCAL); @@ -78,7 +79,8 @@ public MongockInitializingBeanRunner mongockInitializingBeanRunner(ApplicationCo } @Bean - public ReactiveMongoTemplate reactiveMongoTemplate(ReactiveMongoDatabaseFactory mongoDbFactory, MappingMongoConverter mappingMongoConverter) { + public ReactiveMongoTemplate reactiveMongoTemplate( + ReactiveMongoDatabaseFactory mongoDbFactory, MappingMongoConverter mappingMongoConverter) { ReactiveMongoTemplate mongoTemplate = new ReactiveMongoTemplate(mongoDbFactory, mappingMongoConverter); MappingMongoConverter conv = (MappingMongoConverter) mongoTemplate.getConverter(); // tell mongodb to use the custom converters @@ -88,7 +90,8 @@ public ReactiveMongoTemplate reactiveMongoTemplate(ReactiveMongoDatabaseFactory } @Bean - public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDbFactory, MappingMongoConverter mappingMongoConverter) { + public MongoTemplate mongoTemplate( + MongoDatabaseFactory mongoDbFactory, MappingMongoConverter mappingMongoConverter) { MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, mappingMongoConverter); MappingMongoConverter conv = (MappingMongoConverter) mongoTemplate.getConverter(); // tell mongodb to use the custom converters @@ -97,16 +100,19 @@ public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDbFactory, MappingM return mongoTemplate; } - // Custom type mapper here includes our annotation based mapper that is meant to ensure correct mapping for sub-classes + // Custom type mapper here includes our annotation based mapper that is meant to ensure correct mapping for + // sub-classes // We have currently only included the package which contains the DTOs that need this mapping @Bean public DefaultTypeMapper<Bson> typeMapper() { - TypeInformationMapper typeInformationMapper = new DocumentTypeMapper - .Builder() - .withBasePackages(new String[]{AuthenticationDTO.class.getPackageName()}) + TypeInformationMapper typeInformationMapper = new DocumentTypeMapper.Builder() + .withBasePackages(new String[] {AuthenticationDTO.class.getPackageName()}) .build(); - // This is a hack to include the default mapper as a fallback, because Spring seems to override its list instead of appending mappers - return new DefaultMongoTypeMapper(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Arrays.asList(typeInformationMapper, new SimpleTypeInformationMapper())); + // This is a hack to include the default mapper as a fallback, because Spring seems to override its list instead + // of appending mappers + return new DefaultMongoTypeMapper( + DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, + Arrays.asList(typeInformationMapper, new SimpleTypeInformationMapper())); } @Bean @@ -115,7 +121,8 @@ public MongoCustomConversions mongoCustomConversions() { } @Bean - public MappingMongoConverter mappingMongoConverter(DefaultTypeMapper<Bson> typeMapper, MongoMappingContext context) { + public MappingMongoConverter mappingMongoConverter( + DefaultTypeMapper<Bson> typeMapper, MongoMappingContext context) { MappingMongoConverter converter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, context); converter.setTypeMapper((MongoTypeMapper) typeMapper); converter.setCustomConversions(mongoCustomConversions()); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/PasswordEncoderConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/PasswordEncoderConfig.java index 5d5cc5b0bd45..47a13ea19de2 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/PasswordEncoderConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/PasswordEncoderConfig.java @@ -12,5 +12,4 @@ public class PasswordEncoderConfig { public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/PluginConfiguration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/PluginConfiguration.java index 405f9463bb4f..ff49c00afeb2 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/PluginConfiguration.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/PluginConfiguration.java @@ -21,5 +21,4 @@ public CustomPluginManager() { : new PropertiesPluginDescriptorFinder(); } } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ProjectProperties.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ProjectProperties.java index c9a758a235bb..e6468f34c648 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ProjectProperties.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ProjectProperties.java @@ -20,5 +20,4 @@ public class ProjectProperties { @Value("${version:UNKNOWN}") private String version; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java index a5366908bb19..6935a2c13c67 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java @@ -15,7 +15,6 @@ import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.data.redis.connection.RedisClusterConfiguration; import org.springframework.data.redis.connection.RedisNode; -import org.springframework.data.redis.connection.RedisSentinelConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration; @@ -39,7 +38,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import java.util.Set; @Configuration @Slf4j @@ -74,9 +72,8 @@ public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() { case "redis-cluster" -> { // For ElastiCache Redis with cluster mode enabled, with the configuration endpoint. - final LettuceClientConfiguration config = LettucePoolingClientConfiguration - .builder() - .build(); + final LettuceClientConfiguration config = + LettucePoolingClientConfiguration.builder().build(); final RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(); clusterConfig.addClusterNode(new RedisNode(redisUri.getHost(), redisUri.getPort())); return new LettuceConnectionFactory(clusterConfig, config); @@ -106,7 +103,8 @@ ReactiveRedisOperations<String, String> reactiveRedisOperations(ReactiveRedisCon RedisSerializationContext.RedisSerializationContextBuilder<String, String> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer()); - RedisSerializationContext<String, String> context = builder.value(serializer).build(); + RedisSerializationContext<String, String> context = + builder.value(serializer).build(); return new ReactiveRedisTemplate<>(factory, context); } @@ -114,12 +112,14 @@ ReactiveRedisOperations<String, String> reactiveRedisOperations(ReactiveRedisCon // Lifted from below and turned it into a bean. Wish Spring provided it as a bean. // RedisWebSessionConfiguration.createReactiveRedisTemplate @Bean - ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory, - RedisSerializer<Object> serializer) { + ReactiveRedisTemplate<String, Object> reactiveRedisTemplate( + ReactiveRedisConnectionFactory factory, RedisSerializer<Object> serializer) { RedisSerializer<String> keySerializer = new StringRedisSerializer(); - RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext - .<String, Object>newSerializationContext(serializer).key(keySerializer).hashKey(keySerializer) - .build(); + RedisSerializationContext<String, Object> serializationContext = + RedisSerializationContext.<String, Object>newSerializationContext(serializer) + .key(keySerializer) + .hashKey(keySerializer) + .build(); return new ReactiveRedisTemplate<>(factory, serializationContext); } @@ -131,7 +131,8 @@ private static class JSONSessionRedisSerializer implements RedisSerializer<Objec private final JdkSerializationRedisSerializer fallback = new JdkSerializationRedisSerializer(); - private final GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(new JsonMapper()); + private final GenericJackson2JsonRedisSerializer jsonSerializer = + new GenericJackson2JsonRedisSerializer(new JsonMapper()); @Override public byte[] serialize(Object t) { @@ -154,7 +155,6 @@ public byte[] serialize(Object t) { final byte[] bytes = serializeOAuthClientMap(data); return bytes == null ? null : ByteUtils.concat(OAUTH_CLIENT_PREFIX, bytes); } - } return fallback.serialize(t); @@ -175,7 +175,10 @@ private byte[] serializeOAuthClientMap(Map<?, ?> data) { } dataMap.put(key, dto); } else { - log.warn("Unknown data type found in session data. Key: {}, Value: {}", entry.getKey(), entry.getValue()); + log.warn( + "Unknown data type found in session data. Key: {}, Value: {}", + entry.getKey(), + entry.getValue()); } } return jsonSerializer.serialize(dataMap); @@ -203,13 +206,12 @@ public Object deserialize(byte[] bytes) { final Map<String, OAuth2AuthorizedClient> sessionData = new HashMap<>(); for (final Map.Entry<String, Map<?, ?>> entry : clientData.entrySet()) { - final OAuth2AuthorizedClientDTO dto = new ObjectMapper() - .convertValue(entry.getValue(), OAuth2AuthorizedClientDTO.class); + final OAuth2AuthorizedClientDTO dto = + new ObjectMapper().convertValue(entry.getValue(), OAuth2AuthorizedClientDTO.class); sessionData.put(entry.getKey(), dto.makeOAuth2AuthorizedClient()); } return sessionData; - } return fallback.deserialize(bytes); @@ -221,5 +223,4 @@ public InvalidRedisURIException(String message) { super(message); } } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisListenerConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisListenerConfig.java index b61d9da9c137..abd3958e94e2 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisListenerConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisListenerConfig.java @@ -48,7 +48,8 @@ public ReactiveRedisMessageListenerContainer container(ReactiveRedisConnectionFa .map(p -> p.getMessage()) .map(msg -> { try { - InstallPluginRedisDTO installPluginRedisDTO = objectMapper.readValue(msg, InstallPluginRedisDTO.class); + InstallPluginRedisDTO installPluginRedisDTO = + objectMapper.readValue(msg, InstallPluginRedisDTO.class); return installPluginRedisDTO; } catch (Exception e) { log.error("", e); @@ -57,7 +58,8 @@ public ReactiveRedisMessageListenerContainer container(ReactiveRedisConnectionFa }) // Actual processing of the message. .map(redisPluginObj -> pluginService.redisInstallPlugin((InstallPluginRedisDTO) redisPluginObj)) - // Handle this error because it prevents the Redis connection from shutting down when the server is shut down + // Handle this error because it prevents the Redis connection from shutting down when the server is shut + // down // TODO: Verify if this is invoked in normal redis pubsub execution as well .doOnError(throwable -> { if (!(throwable instanceof CancellationException)) { @@ -70,5 +72,4 @@ public ReactiveRedisMessageListenerContainer container(ReactiveRedisConnectionFa .subscribe(); return container; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/SecurityConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/SecurityConfig.java index 1e858a77533d..8be937f99282 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/SecurityConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/SecurityConfig.java @@ -1,6 +1,5 @@ package com.appsmith.server.configurations; - import com.appsmith.server.authentication.handlers.AccessDeniedHandler; import com.appsmith.server.authentication.handlers.CustomServerOAuth2AuthorizationRequestResolver; import com.appsmith.server.authentication.handlers.LogoutSuccessHandler; @@ -16,7 +15,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; @@ -112,8 +110,7 @@ public class SecurityConfig { */ @Bean public RouterFunction<ServerResponse> publicRouter() { - return RouterFunctions - .resources("/public/**", new ClassPathResource("public/")); + return RouterFunctions.resources("/public/**", new ClassPathResource("public/")); } @Bean @@ -125,43 +122,47 @@ public ForwardedHeaderTransformer forwardedHeaderTransformer() { @Bean @ConditionalOnExpression(value = "'${appsmith.internal.password}'.length() > 0") public SecurityWebFilterChain internalWebFilterChain(ServerHttpSecurity http) { - return http - .securityMatcher(new PathPatternParserServerWebExchangeMatcher("/actuator/**")) - .authorizeExchange(authorizeExchangeSpec -> authorizeExchangeSpec.anyExchange().authenticated()) - .httpBasic(httpBasicSpec -> httpBasicSpec - .authenticationManager(authentication -> { - if (isAuthorizedToAccessInternal(authentication.getCredentials().toString())) { - return Mono.just(UsernamePasswordAuthenticationToken.authenticated( - authentication.getPrincipal(), - authentication.getCredentials(), - authentication.getAuthorities())); - } else { - return Mono.just(UsernamePasswordAuthenticationToken.unauthenticated( - authentication.getPrincipal(), - authentication.getCredentials())); - } - })) + return http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/actuator/**")) + .authorizeExchange(authorizeExchangeSpec -> + authorizeExchangeSpec.anyExchange().authenticated()) + .httpBasic(httpBasicSpec -> httpBasicSpec.authenticationManager(authentication -> { + if (isAuthorizedToAccessInternal( + authentication.getCredentials().toString())) { + return Mono.just(UsernamePasswordAuthenticationToken.authenticated( + authentication.getPrincipal(), + authentication.getCredentials(), + authentication.getAuthorities())); + } else { + return Mono.just(UsernamePasswordAuthenticationToken.unauthenticated( + authentication.getPrincipal(), authentication.getCredentials())); + } + })) .build(); } @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { - ServerAuthenticationEntryPointFailureHandler failureHandler = new ServerAuthenticationEntryPointFailureHandler(authenticationEntryPoint); + ServerAuthenticationEntryPointFailureHandler failureHandler = + new ServerAuthenticationEntryPointFailureHandler(authenticationEntryPoint); return http // The native CSRF solution doesn't work with WebFlux, yet, but only for WebMVC. So we make our own. - .csrf().disable() + .csrf() + .disable() .addFilterAt(new CSRFFilter(), SecurityWebFiltersOrder.CSRF) - .anonymous().principal(createAnonymousUser()) + .anonymous() + .principal(createAnonymousUser()) .and() - // This returns 401 unauthorized for all requests that are not authenticated but authentication is required + // This returns 401 unauthorized for all requests that are not authenticated but authentication is + // required // The client will redirect to the login page if we return 401 as Http status response .exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint) .accessDeniedHandler(accessDeniedHandler) .and() .authorizeExchange() - .matchers(ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, Url.LOGIN_URL), + .matchers( + ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, Url.LOGIN_URL), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, Url.HEALTH_CHECK), ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, USER_URL), ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, USER_URL + "/super"), @@ -181,29 +182,32 @@ public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, ACTION_URL + "/execute"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, TENANT_URL + "/current"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, USAGE_PULSE_URL), - ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, CUSTOM_JS_LIB_URL + "/*/view") - ) + ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, CUSTOM_JS_LIB_URL + "/*/view")) + .permitAll() + .pathMatchers("/public/**", "/oauth2/**", "/actuator/**") .permitAll() - .pathMatchers("/public/**", "/oauth2/**", "/actuator/**").permitAll() .anyExchange() .authenticated() .and() .httpBasic(httpBasicSpec -> httpBasicSpec.authenticationFailureHandler(failureHandler)) - .formLogin(formLoginSpec -> formLoginSpec.authenticationFailureHandler(failureHandler) + .formLogin(formLoginSpec -> formLoginSpec + .authenticationFailureHandler(failureHandler) .loginPage(Url.LOGIN_URL) .authenticationEntryPoint(authenticationEntryPoint) - .requiresAuthenticationMatcher(ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, Url.LOGIN_URL)) + .requiresAuthenticationMatcher( + ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, Url.LOGIN_URL)) .authenticationSuccessHandler(authenticationSuccessHandler) .authenticationFailureHandler(authenticationFailureHandler)) // For Github SSO Login, check transformation class: CustomOAuth2UserServiceImpl // For Google SSO Login, check transformation class: CustomOAuth2UserServiceImpl - .oauth2Login(oAuth2LoginSpec -> oAuth2LoginSpec.authenticationFailureHandler(failureHandler) - .authorizationRequestResolver(new CustomServerOAuth2AuthorizationRequestResolver(reactiveClientRegistrationRepository, commonConfig, redirectHelper)) + .oauth2Login(oAuth2LoginSpec -> oAuth2LoginSpec + .authenticationFailureHandler(failureHandler) + .authorizationRequestResolver(new CustomServerOAuth2AuthorizationRequestResolver( + reactiveClientRegistrationRepository, commonConfig, redirectHelper)) .authenticationSuccessHandler(authenticationSuccessHandler) .authenticationFailureHandler(authenticationFailureHandler) .authorizedClientRepository(new ClientUserRepository(userService, commonConfig))) - .logout() .logoutUrl(Url.LOGOUT_URL) .logoutSuccessHandler(new LogoutSuccessHandler(objectMapper, analyticsService)) diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/SegmentConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/SegmentConfig.java index b1528000a24f..d1663a30c098 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/SegmentConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/SegmentConfig.java @@ -49,22 +49,24 @@ public Analytics analyticsRunner() { final LogProcessor logProcessor = new LogProcessor(); - Analytics analyticsOnAnalytics = Analytics.builder(analyticsWriteKey).log(logProcessor).build(); + Analytics analyticsOnAnalytics = + Analytics.builder(analyticsWriteKey).log(logProcessor).build(); // We use a different analytics instance for sending events about the analytics system itself so we don't end up // in a recursive state. final LogProcessor logProcessorWithErrorHandler = new LogProcessor(); - final Analytics analytics = Analytics.builder(analyticsWriteKey).log(logProcessorWithErrorHandler).build(); + final Analytics analytics = Analytics.builder(analyticsWriteKey) + .log(logProcessorWithErrorHandler) + .build(); logProcessorWithErrorHandler.onError(logData -> { final Throwable error = logData.getError(); - analyticsOnAnalytics.enqueue(TrackMessage.builder("segment_error").userId("segmentError") + analyticsOnAnalytics.enqueue(TrackMessage.builder("segment_error") + .userId("segmentError") .properties(Map.of( "message", logData.getMessage(), "error", error == null ? "" : error.getMessage(), "args", ObjectUtils.defaultIfNull(logData.getArgs(), Collections.emptyList()), - "stackTrace", ExceptionUtils.getStackTrace(error) - )) - ); + "stackTrace", ExceptionUtils.getStackTrace(error)))); }); return analytics; @@ -109,5 +111,4 @@ private static class LogData { final String message; final Object[] args; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/WebConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/WebConfig.java index 1c54183abed5..406626211884 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/WebConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/WebConfig.java @@ -13,16 +13,14 @@ public class WebConfig implements WebFluxConfigurer { @Override public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { - configurer - .defaultCodecs() - .configureDefaultCodec(codec -> { - if (codec instanceof MultipartHttpMessageReader) { - HttpMessageReader<Part> partReader = ((MultipartHttpMessageReader) codec).getPartReader(); - if (partReader instanceof DefaultPartHttpMessageReader) { - // Set max file part header size to 128kB - ((DefaultPartHttpMessageReader) partReader).setMaxHeadersSize(128 * 1024); - } - } - }); + configurer.defaultCodecs().configureDefaultCodec(codec -> { + if (codec instanceof MultipartHttpMessageReader) { + HttpMessageReader<Part> partReader = ((MultipartHttpMessageReader) codec).getPartReader(); + if (partReader instanceof DefaultPartHttpMessageReader) { + // Set max file part header size to 128kB + ((DefaultPartHttpMessageReader) partReader).setMaxHeadersSize(128 * 1024); + } + } + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/CanSeeSoftDeletedRecords.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/CanSeeSoftDeletedRecords.java index 607abbbc784b..44d8f31d4d1f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/CanSeeSoftDeletedRecords.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/CanSeeSoftDeletedRecords.java @@ -11,5 +11,4 @@ */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) -public @interface CanSeeSoftDeletedRecords { -} \ No newline at end of file +public @interface CanSeeSoftDeletedRecords {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeleteMongoQueryLookupStrategy.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeleteMongoQueryLookupStrategy.java index 72ee7a675c42..6088bce2a895 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeleteMongoQueryLookupStrategy.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeleteMongoQueryLookupStrategy.java @@ -28,18 +28,18 @@ public class SoftDeleteMongoQueryLookupStrategy implements QueryLookupStrategy { private final QueryLookupStrategy strategy; private final ReactiveMongoOperations mongoOperations; private static final SpelExpressionParser EXPRESSION_PARSER = new SpelExpressionParser(); - ReactiveQueryMethodEvaluationContextProvider evaluationContextProvider = ReactiveQueryMethodEvaluationContextProvider.DEFAULT.DEFAULT; + ReactiveQueryMethodEvaluationContextProvider evaluationContextProvider = + ReactiveQueryMethodEvaluationContextProvider.DEFAULT.DEFAULT; private ExpressionParser expressionParser = new SpelExpressionParser(); - public SoftDeleteMongoQueryLookupStrategy(QueryLookupStrategy strategy, - ReactiveMongoOperations mongoOperations) { + public SoftDeleteMongoQueryLookupStrategy(QueryLookupStrategy strategy, ReactiveMongoOperations mongoOperations) { this.strategy = strategy; this.mongoOperations = mongoOperations; } @Override - public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory, - NamedQueries namedQueries) { + public RepositoryQuery resolveQuery( + Method method, RepositoryMetadata metadata, ProjectionFactory factory, NamedQueries namedQueries) { RepositoryQuery repositoryQuery = strategy.resolveQuery(method, metadata, factory, namedQueries); // revert to the standard behavior if requested @@ -52,7 +52,7 @@ public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, } ReactivePartTreeMongoQuery partTreeQuery = (ReactivePartTreeMongoQuery) repositoryQuery; - return new SoftDeletePartTreeMongoQuery(method, partTreeQuery, this.mongoOperations, EXPRESSION_PARSER, evaluationContextProvider); + return new SoftDeletePartTreeMongoQuery( + method, partTreeQuery, this.mongoOperations, EXPRESSION_PARSER, evaluationContextProvider); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeleteMongoRepositoryFactory.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeleteMongoRepositoryFactory.java index 34670460ce67..5c592c21b7b3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeleteMongoRepositoryFactory.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeleteMongoRepositoryFactory.java @@ -19,14 +19,13 @@ public SoftDeleteMongoRepositoryFactory(ReactiveMongoOperations mongoOperations) } @Override - protected Optional<QueryLookupStrategy> getQueryLookupStrategy(QueryLookupStrategy.Key key, - QueryMethodEvaluationContextProvider evaluationContextProvider) { - Optional<QueryLookupStrategy> optStrategy = super.getQueryLookupStrategy(key, - evaluationContextProvider); + protected Optional<QueryLookupStrategy> getQueryLookupStrategy( + QueryLookupStrategy.Key key, QueryMethodEvaluationContextProvider evaluationContextProvider) { + Optional<QueryLookupStrategy> optStrategy = super.getQueryLookupStrategy(key, evaluationContextProvider); return optStrategy.map(this::createSoftDeleteQueryLookupStrategy); } private SoftDeleteMongoQueryLookupStrategy createSoftDeleteQueryLookupStrategy(QueryLookupStrategy strategy) { return new SoftDeleteMongoQueryLookupStrategy(strategy, mongoOperations); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeletePartTreeMongoQuery.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeletePartTreeMongoQuery.java index 17521fa3dac1..ac5ced38b90f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeletePartTreeMongoQuery.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/mongo/SoftDeletePartTreeMongoQuery.java @@ -20,12 +20,17 @@ public class SoftDeletePartTreeMongoQuery extends ReactivePartTreeMongoQuery { private ReactivePartTreeMongoQuery reactivePartTreeQuery; private Method method; - SoftDeletePartTreeMongoQuery(Method method, ReactivePartTreeMongoQuery reactivePartTreeMongoQuery, - ReactiveMongoOperations mongoOperations, - SpelExpressionParser expressionParser, - ReactiveQueryMethodEvaluationContextProvider evaluationContextProvider) { - super((ReactiveMongoQueryMethod) reactivePartTreeMongoQuery.getQueryMethod(), - mongoOperations, expressionParser, evaluationContextProvider); + SoftDeletePartTreeMongoQuery( + Method method, + ReactivePartTreeMongoQuery reactivePartTreeMongoQuery, + ReactiveMongoOperations mongoOperations, + SpelExpressionParser expressionParser, + ReactiveQueryMethodEvaluationContextProvider evaluationContextProvider) { + super( + (ReactiveMongoQueryMethod) reactivePartTreeMongoQuery.getQueryMethod(), + mongoOperations, + expressionParser, + evaluationContextProvider); this.reactivePartTreeQuery = reactivePartTreeMongoQuery; this.method = method; } @@ -50,9 +55,7 @@ private Mono<Query> withNotDeleted(Mono<Query> queryMono) { } private Criteria notDeleted() { - return new Criteria().orOperator( - where("deleted").exists(false), - where("deleted").is(false) - ); + return new Criteria() + .orOperator(where("deleted").exists(false), where("deleted").is(false)); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/AnalyticsConstants.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/AnalyticsConstants.java index 50db924e60db..b9a60bd3a07e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/AnalyticsConstants.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/AnalyticsConstants.java @@ -5,5 +5,4 @@ /** * Class to store instrumentation constants only */ -public class AnalyticsConstants extends AnalyticsConstantsCE { -} +public class AnalyticsConstants extends AnalyticsConstantsCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ApplicationConstants.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ApplicationConstants.java index a962d3c50027..0a7b2d2a0aed 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ApplicationConstants.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ApplicationConstants.java @@ -2,7 +2,7 @@ public class ApplicationConstants { public static final String[] APP_CARD_COLORS = { - "#FFDEDE", "#FFEFDB", "#F3F1C7", "#F4FFDE", "#C7F3F0", "#D9E7FF", "#E3DEFF", "#F1DEFF", - "#C7F3E3", "#F5D1D1", "#ECECEC", "#FBF4ED", "#D6D1F2", "#FFEBFB", "#EAEDFB" + "#FFDEDE", "#FFEFDB", "#F3F1C7", "#F4FFDE", "#C7F3F0", "#D9E7FF", "#E3DEFF", "#F1DEFF", "#C7F3E3", "#F5D1D1", + "#ECECEC", "#FBF4ED", "#D6D1F2", "#FFEBFB", "#EAEDFB" }; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Appsmith.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Appsmith.java index 1efb2c503279..08464341efd0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Appsmith.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Appsmith.java @@ -1,10 +1,9 @@ package com.appsmith.server.constants; public class Appsmith { - public final static String APPSMITH_REGISTERED = "appsmith_registered"; - public final static String INSTANCE_SCHEMA_VERSION = "schemaVersion"; + public static final String APPSMITH_REGISTERED = "appsmith_registered"; + public static final String INSTANCE_SCHEMA_VERSION = "schemaVersion"; // We default the origin header to the production deployment of the client's URL public static final String DEFAULT_ORIGIN_HEADER = "https://app.appsmith.com"; public static final String DEFAULT_INSTANCE_NAME = "Appsmith"; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Assets.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Assets.java index b12ffce88d8e..29db6fd94f65 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Assets.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Assets.java @@ -2,7 +2,9 @@ public class Assets { - public static final String GENERATE_CRUD_PAGE_SUCCESS_URL_TABULAR = "https://assets.appsmith.com/crud/workflow_sql.svg"; + public static final String GENERATE_CRUD_PAGE_SUCCESS_URL_TABULAR = + "https://assets.appsmith.com/crud/workflow_sql.svg"; public static final String GENERATE_CRUD_PAGE_SUCCESS_URL_S3 = "https://assets.appsmith.com/crud/workflow_s3.svg"; - public final static String GIT_DEPLOY_KEY_DOC_URL = "https://docs.appsmith.com/core-concepts/version-control-with-git/connecting-to-git-repository#generating-a-deploy-key"; + public static final String GIT_DEPLOY_KEY_DOC_URL = + "https://docs.appsmith.com/core-concepts/version-control-with-git/connecting-to-git-repository#generating-a-deploy-key"; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/CommonConstants.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/CommonConstants.java index 9184c433f9c5..53a85bf4794b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/CommonConstants.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/CommonConstants.java @@ -2,6 +2,4 @@ import com.appsmith.server.constants.ce.CommonConstantsCE; -public class CommonConstants extends CommonConstantsCE { - -} +public class CommonConstants extends CommonConstantsCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ConfigNames.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ConfigNames.java index b48bc0216c4c..af03f0de894d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ConfigNames.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ConfigNames.java @@ -6,6 +6,5 @@ public class ConfigNames { // Disallow instantiation of this class. - private ConfigNames() { - } + private ConfigNames() {} } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/FieldName.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/FieldName.java index e46694a9be34..09450dbe4d95 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/FieldName.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/FieldName.java @@ -2,5 +2,4 @@ import com.appsmith.server.constants.ce.FieldNameCE; -public class FieldName extends FieldNameCE { -} +public class FieldName extends FieldNameCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/LicensePlan.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/LicensePlan.java index 20fdc8d15e7d..524ca651643b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/LicensePlan.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/LicensePlan.java @@ -2,4 +2,4 @@ public enum LicensePlan { FREE -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/PatternConstants.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/PatternConstants.java index cd92fc534e80..76e0f28fdea9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/PatternConstants.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/PatternConstants.java @@ -21,7 +21,7 @@ public class PatternConstants { * - www * - www. */ - public final static String WEBSITE_PATTERN = "^(http://|https://)?(www.)?(([a-z0-9\\-]+)\\.)+([a-z]+)(/)?$"; + public static final String WEBSITE_PATTERN = "^(http://|https://)?(www.)?(([a-z0-9\\-]+)\\.)+([a-z]+)(/)?$"; /** * Valid Email Patterns: * - [email protected] @@ -31,6 +31,6 @@ public class PatternConstants { * - [email protected] * - @invalid.com */ - public final static String EMAIL_PATTERN = "^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@" + public static final String EMAIL_PATTERN = "^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@" + "[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$"; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ResourceModes.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ResourceModes.java index 384c5f593432..b3cb0e88c50c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ResourceModes.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ResourceModes.java @@ -1,5 +1,6 @@ package com.appsmith.server.constants; public enum ResourceModes { - EDIT, VIEW + EDIT, + VIEW } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Url.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Url.java index 7ee04d3934ec..a58baf8c8032 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Url.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Url.java @@ -2,6 +2,4 @@ import com.appsmith.server.constants.ce.UrlCE; -public class Url extends UrlCE { - -} +public class Url extends UrlCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/CommonConstantsCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/CommonConstantsCE.java index d475ad7ff7fb..370fe1e1a7b0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/CommonConstantsCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/CommonConstantsCE.java @@ -6,4 +6,4 @@ public class CommonConstantsCE { public static String FOR = DELIMETER_SPACE + "for" + DELIMETER_SPACE; public static String IN = DELIMETER_SPACE + "in" + DELIMETER_SPACE; public static String DEFAULT = "default"; -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java index 0e5e1406767a..adf585a12893 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java @@ -3,8 +3,10 @@ public class FieldNameCE { public static final String EMAIL = "email"; public static final String PASSWORD = "password"; + @Deprecated public static final String ORGANIZATION_ID = "organizationId"; + public static final String WORKSPACE_ID = "workspaceId"; public static final String DATASOURCE_ID = "datasourceId"; public static final String DELETED = "deleted"; @@ -44,28 +46,27 @@ public class FieldNameCE { public static String SIZE = "size"; public static String ROLE = "role"; public static String DEFAULT_WIDGET_NAME = "MainContainer"; - public static String DEFAULT_PAGE_LAYOUT = "{\n" + - " \"widgetName\": \"MainContainer\",\n" + - " \"backgroundColor\": \"none\",\n" + - " \"rightColumn\": 1224,\n" + - " \"snapColumns\": 16,\n" + - " \"detachFromLayout\": true,\n" + - " \"widgetId\": \"0\",\n" + - " \"topRow\": 0,\n" + - " \"bottomRow\": 1250,\n" + - " \"containerStyle\": \"none\",\n" + - " \"snapRows\": 33,\n" + - " \"parentRowSpace\": 1,\n" + - " \"type\": \"CANVAS_WIDGET\",\n" + - " \"canExtend\": true,\n" + - " \"dynamicBindingPathList\": [],\n" + - " \"dynamicTriggerPathList\": [],\n" + - " \"version\": 4,\n" + - " \"minHeight\": 1292,\n" + - " \"parentColumnSpace\": 1,\n" + - " \"leftColumn\": 0,\n" + - " \"children\": []\n" + - "}"; + public static String DEFAULT_PAGE_LAYOUT = "{\n" + " \"widgetName\": \"MainContainer\",\n" + + " \"backgroundColor\": \"none\",\n" + + " \"rightColumn\": 1224,\n" + + " \"snapColumns\": 16,\n" + + " \"detachFromLayout\": true,\n" + + " \"widgetId\": \"0\",\n" + + " \"topRow\": 0,\n" + + " \"bottomRow\": 1250,\n" + + " \"containerStyle\": \"none\",\n" + + " \"snapRows\": 33,\n" + + " \"parentRowSpace\": 1,\n" + + " \"type\": \"CANVAS_WIDGET\",\n" + + " \"canExtend\": true,\n" + + " \"dynamicBindingPathList\": [],\n" + + " \"dynamicTriggerPathList\": [],\n" + + " \"version\": 4,\n" + + " \"minHeight\": 1292,\n" + + " \"parentColumnSpace\": 1,\n" + + " \"leftColumn\": 0,\n" + + " \"children\": []\n" + + "}"; public static String ANONYMOUS_USER = "anonymousUser"; public static String USERNAMES = "usernames"; public static String ACTION = "action"; @@ -120,15 +121,15 @@ public class FieldNameCE { public static final String EDIT_MODE_THEME = "editModeTheme"; public static final String FLOW_NAME = "flowName"; public static final String ADMINISTRATOR = "Administrator"; - public static final String WORKSPACE_ADMINISTRATOR_DESCRIPTION = "Can modify all workspace settings including " + - "editing applications, inviting other users to the workspace and exporting applications " + - "from the workspace"; + public static final String WORKSPACE_ADMINISTRATOR_DESCRIPTION = "Can modify all workspace settings including " + + "editing applications, inviting other users to the workspace and exporting applications " + + "from the workspace"; public static final String DEVELOPER = "Developer"; - public static String WORKSPACE_DEVELOPER_DESCRIPTION = "Can edit and view applications along with inviting other " + - "users to the workspace"; + public static String WORKSPACE_DEVELOPER_DESCRIPTION = + "Can edit and view applications along with inviting other " + "users to the workspace"; public static final String VIEWER = "App Viewer"; - public static final String WORKSPACE_VIEWER_DESCRIPTION = "Can view applications and invite other users to view " + - "applications"; + public static final String WORKSPACE_VIEWER_DESCRIPTION = + "Can view applications and invite other users to view " + "applications"; public static final String USER_GROUP = "userGroup"; public static final Object GROUP_ID = "groupId"; public static final Object USERNAME = "username"; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/UrlCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/UrlCE.java index d791631cce14..f3437fe6cf31 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/UrlCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/UrlCE.java @@ -3,41 +3,41 @@ import com.appsmith.server.constants.Entity; public class UrlCE { - final static String BASE_URL = "/api"; - final static String VERSION = "/v1"; - final public static String HEALTH_CHECK = BASE_URL + VERSION + "/health"; - final public static String LOGIN_URL = BASE_URL + VERSION + "/login"; - final public static String LOGOUT_URL = BASE_URL + VERSION + "/logout"; - final public static String WORKSPACE_URL = BASE_URL + VERSION + "/workspaces"; - final public static String LAYOUT_URL = BASE_URL + VERSION + "/layouts"; - final public static String PLUGIN_URL = BASE_URL + VERSION + "/plugins"; - final public static String DATASOURCE_URL = BASE_URL + VERSION + "/datasources"; - final public static String SAAS_URL = BASE_URL + VERSION + "/saas"; - final public static String ACTION_URL = BASE_URL + VERSION + "/actions"; - final public static String USER_URL = BASE_URL + VERSION + "/users"; - final public static String APPLICATION_URL = BASE_URL + VERSION + "/" + Entity.APPLICATIONS; - final public static String PAGE_URL = BASE_URL + VERSION + "/" + Entity.PAGES; - final public static String CONFIG_URL = BASE_URL + VERSION + "/configs"; - final public static String GROUP_URL = BASE_URL + VERSION + "/groups"; - final public static String COLLECTION_URL = BASE_URL + VERSION + "/collections"; - final public static String ACTION_COLLECTION_URL = COLLECTION_URL + "/actions"; - final public static String IMPORT_URL = BASE_URL + VERSION + "/import"; - final public static String PROVIDER_URL = BASE_URL + VERSION + "/providers"; - final public static String MARKETPLACE_URL = BASE_URL + VERSION + "/marketplace"; - final public static String API_TEMPLATE_URL = BASE_URL + VERSION + "/templates"; - final public static String MARKETPLACE_ITEM_URL = BASE_URL + VERSION + "/items"; - final public static String ASSET_URL = BASE_URL + VERSION + "/assets"; - final public static String COMMENT_URL = BASE_URL + VERSION + "/comments"; - final public static String NOTIFICATION_URL = BASE_URL + VERSION + "/notifications"; - final public static String INSTANCE_ADMIN_URL = BASE_URL + VERSION + "/admin"; - final public static String GIT_URL = BASE_URL + VERSION + "/git"; - final public static String THEME_URL = BASE_URL + VERSION + "/themes"; - final public static String APP_TEMPLATE_URL = BASE_URL + VERSION + "/app-templates"; - final public static String USAGE_PULSE_URL = BASE_URL + VERSION + "/usage-pulse"; - final public static String TENANT_URL = BASE_URL + VERSION + "/tenants"; - final public static String CUSTOM_JS_LIB_URL = BASE_URL + VERSION + "/libraries"; + static final String BASE_URL = "/api"; + static final String VERSION = "/v1"; + public static final String HEALTH_CHECK = BASE_URL + VERSION + "/health"; + public static final String LOGIN_URL = BASE_URL + VERSION + "/login"; + public static final String LOGOUT_URL = BASE_URL + VERSION + "/logout"; + public static final String WORKSPACE_URL = BASE_URL + VERSION + "/workspaces"; + public static final String LAYOUT_URL = BASE_URL + VERSION + "/layouts"; + public static final String PLUGIN_URL = BASE_URL + VERSION + "/plugins"; + public static final String DATASOURCE_URL = BASE_URL + VERSION + "/datasources"; + public static final String SAAS_URL = BASE_URL + VERSION + "/saas"; + public static final String ACTION_URL = BASE_URL + VERSION + "/actions"; + public static final String USER_URL = BASE_URL + VERSION + "/users"; + public static final String APPLICATION_URL = BASE_URL + VERSION + "/" + Entity.APPLICATIONS; + public static final String PAGE_URL = BASE_URL + VERSION + "/" + Entity.PAGES; + public static final String CONFIG_URL = BASE_URL + VERSION + "/configs"; + public static final String GROUP_URL = BASE_URL + VERSION + "/groups"; + public static final String COLLECTION_URL = BASE_URL + VERSION + "/collections"; + public static final String ACTION_COLLECTION_URL = COLLECTION_URL + "/actions"; + public static final String IMPORT_URL = BASE_URL + VERSION + "/import"; + public static final String PROVIDER_URL = BASE_URL + VERSION + "/providers"; + public static final String MARKETPLACE_URL = BASE_URL + VERSION + "/marketplace"; + public static final String API_TEMPLATE_URL = BASE_URL + VERSION + "/templates"; + public static final String MARKETPLACE_ITEM_URL = BASE_URL + VERSION + "/items"; + public static final String ASSET_URL = BASE_URL + VERSION + "/assets"; + public static final String COMMENT_URL = BASE_URL + VERSION + "/comments"; + public static final String NOTIFICATION_URL = BASE_URL + VERSION + "/notifications"; + public static final String INSTANCE_ADMIN_URL = BASE_URL + VERSION + "/admin"; + public static final String GIT_URL = BASE_URL + VERSION + "/git"; + public static final String THEME_URL = BASE_URL + VERSION + "/themes"; + public static final String APP_TEMPLATE_URL = BASE_URL + VERSION + "/app-templates"; + public static final String USAGE_PULSE_URL = BASE_URL + VERSION + "/usage-pulse"; + public static final String TENANT_URL = BASE_URL + VERSION + "/tenants"; + public static final String CUSTOM_JS_LIB_URL = BASE_URL + VERSION + "/libraries"; // Sub-paths - final public static String MOCKS = "/mocks"; - final public static String RELEASE_ITEMS = "/releaseItems"; + public static final String MOCKS = "/mocks"; + public static final String RELEASE_ITEMS = "/releaseItems"; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionCollectionController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionCollectionController.java index 0f16b128ea05..156a47e0a42d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionCollectionController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionCollectionController.java @@ -11,10 +11,9 @@ @RequestMapping(Url.ACTION_COLLECTION_URL) public class ActionCollectionController extends ActionCollectionControllerCE { - public ActionCollectionController(ActionCollectionService actionCollectionService, - LayoutCollectionService layoutCollectionService) { + public ActionCollectionController( + ActionCollectionService actionCollectionService, LayoutCollectionService layoutCollectionService) { super(actionCollectionService, layoutCollectionService); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionController.java index c5aa3032aa3b..03e8827915e3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionController.java @@ -15,13 +15,12 @@ @Slf4j public class ActionController extends ActionControllerCE { - public ActionController(LayoutActionService layoutActionService, - NewActionService newActionService, - RefactoringSolution refactoringSolution, - ActionExecutionSolution actionExecutionSolution) { + public ActionController( + LayoutActionService layoutActionService, + NewActionService newActionService, + RefactoringSolution refactoringSolution, + ActionExecutionSolution actionExecutionSolution) { super(layoutActionService, newActionService, refactoringSolution, actionExecutionSolution); - } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApiTemplateController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApiTemplateController.java index 31c7093d1955..30984533ce9d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApiTemplateController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApiTemplateController.java @@ -15,5 +15,4 @@ public class ApiTemplateController extends ApiTemplateControllerCE { public ApiTemplateController(ApiTemplateService service) { super(service); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApplicationController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApplicationController.java index 3c83beaf0ddc..733d0b3fc4f1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApplicationController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApplicationController.java @@ -16,16 +16,22 @@ @RequestMapping(Url.APPLICATION_URL) public class ApplicationController extends ApplicationControllerCE { - public ApplicationController(ApplicationService service, - ApplicationPageService applicationPageService, - ApplicationFetcher applicationFetcher, - ApplicationForkingService applicationForkingService, - ImportExportApplicationService importExportApplicationService, - ThemeService themeService, - ApplicationSnapshotService applicationSnapshotService) { - - super(service, applicationPageService, applicationFetcher, applicationForkingService, - importExportApplicationService, themeService, applicationSnapshotService); + public ApplicationController( + ApplicationService service, + ApplicationPageService applicationPageService, + ApplicationFetcher applicationFetcher, + ApplicationForkingService applicationForkingService, + ImportExportApplicationService importExportApplicationService, + ThemeService themeService, + ApplicationSnapshotService applicationSnapshotService) { + super( + service, + applicationPageService, + applicationFetcher, + applicationForkingService, + importExportApplicationService, + themeService, + applicationSnapshotService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/CustomJSLibController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/CustomJSLibController.java index b8d9452f1998..ea667fea94c0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/CustomJSLibController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/CustomJSLibController.java @@ -14,4 +14,4 @@ public class CustomJSLibController extends CustomJSLibControllerCE { public CustomJSLibController(CustomJSLibServiceImpl customJSLibService) { super(customJSLibService); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/DatasourceController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/DatasourceController.java index f74a3e90ee01..9373d1348995 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/DatasourceController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/DatasourceController.java @@ -3,7 +3,6 @@ import com.appsmith.server.constants.Url; import com.appsmith.server.controllers.ce.DatasourceControllerCE; import com.appsmith.server.services.DatasourceService; -import com.appsmith.server.services.DatasourceStorageService; import com.appsmith.server.services.MockDataService; import com.appsmith.server.solutions.AuthenticationService; import com.appsmith.server.solutions.DatasourceStructureSolution; @@ -15,11 +14,17 @@ @RequestMapping(Url.DATASOURCE_URL) public class DatasourceController extends DatasourceControllerCE { - public DatasourceController(DatasourceService service, - DatasourceStructureSolution datasourceStructureSolution, - AuthenticationService authenticationService, - MockDataService datasourceService, - DatasourceTriggerSolution datasourceTriggerSolution) { - super(service, datasourceStructureSolution, authenticationService, datasourceService, datasourceTriggerSolution); + public DatasourceController( + DatasourceService service, + DatasourceStructureSolution datasourceStructureSolution, + AuthenticationService authenticationService, + MockDataService datasourceService, + DatasourceTriggerSolution datasourceTriggerSolution) { + super( + service, + datasourceStructureSolution, + authenticationService, + datasourceService, + datasourceTriggerSolution); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java index 8d198fea5a56..d5d0c1ad7213 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java @@ -15,5 +15,4 @@ public class GitController extends GitControllerCE { public GitController(GitService service) { super(service); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/IndexController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/IndexController.java index a6e315e89245..8781bd966993 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/IndexController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/IndexController.java @@ -13,9 +13,8 @@ @RequestMapping("") public class IndexController extends IndexControllerCE { - public IndexController(SessionUserService service, - ReactiveRedisTemplate<String, String> reactiveTemplate, - ChannelTopic topic) { + public IndexController( + SessionUserService service, ReactiveRedisTemplate<String, String> reactiveTemplate, ChannelTopic topic) { super(service, reactiveTemplate, topic); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/InstanceAdminController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/InstanceAdminController.java index 9b9a8c88f0b0..c1e793a68d9a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/InstanceAdminController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/InstanceAdminController.java @@ -15,5 +15,4 @@ public class InstanceAdminController extends InstanceAdminControllerCE { public InstanceAdminController(EnvManager envManager) { super(envManager); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/LayoutController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/LayoutController.java index d8de7e3fec15..b1c8be367ef5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/LayoutController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/LayoutController.java @@ -14,11 +14,11 @@ @Slf4j public class LayoutController extends LayoutControllerCE { - public LayoutController(LayoutService layoutService, - LayoutActionService layoutActionService, - RefactoringSolution refactoringSolution) { + public LayoutController( + LayoutService layoutService, + LayoutActionService layoutActionService, + RefactoringSolution refactoringSolution) { super(layoutService, layoutActionService, refactoringSolution); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/MarketplaceController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/MarketplaceController.java index c404b604f4c5..00e29c1de471 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/MarketplaceController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/MarketplaceController.java @@ -13,8 +13,7 @@ @Slf4j public class MarketplaceController extends MarketplaceControllerCE { - public MarketplaceController(ObjectMapper objectMapper, - MarketplaceService marketplaceService) { + public MarketplaceController(ObjectMapper objectMapper, MarketplaceService marketplaceService) { super(objectMapper, marketplaceService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/NotificationController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/NotificationController.java index 84ce830083ab..5fc93478470b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/NotificationController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/NotificationController.java @@ -15,5 +15,4 @@ public class NotificationController extends NotificationControllerCE { public NotificationController(NotificationService service) { super(service); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/PageController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/PageController.java index bb1656f989d8..b61b3adc675b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/PageController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/PageController.java @@ -14,9 +14,10 @@ @Slf4j public class PageController extends PageControllerCE { - public PageController(ApplicationPageService applicationPageService, - NewPageService newPageService, - CreateDBTablePageSolution createDBTablePageSolution) { + public PageController( + ApplicationPageService applicationPageService, + NewPageService newPageService, + CreateDBTablePageSolution createDBTablePageSolution) { super(applicationPageService, newPageService, createDBTablePageSolution); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/PluginController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/PluginController.java index 7036a29c2a44..a484b1476890 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/PluginController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/PluginController.java @@ -6,7 +6,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; - @RestController @RequestMapping(Url.PLUGIN_URL) public class PluginController extends PluginControllerCE { @@ -14,5 +13,4 @@ public class PluginController extends PluginControllerCE { public PluginController(PluginService service) { super(service); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/RestApiImportController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/RestApiImportController.java index 91baf6209931..6db54a2ff01c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/RestApiImportController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/RestApiImportController.java @@ -13,8 +13,8 @@ @Slf4j public class RestApiImportController extends RestApiImportControllerCE { - public RestApiImportController(CurlImporterService curlImporterService, - PostmanImporterService postmanImporterService) { + public RestApiImportController( + CurlImporterService curlImporterService, PostmanImporterService postmanImporterService) { super(curlImporterService, postmanImporterService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/SaasController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/SaasController.java index c36533c47009..c455a3dba1a6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/SaasController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/SaasController.java @@ -15,5 +15,4 @@ public class SaasController extends SaasControllerCE { public SaasController(AuthenticationService authenticationService) { super(authenticationService); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/UsagePulseController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/UsagePulseController.java index dd44e607078b..e9c1b7d39dfa 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/UsagePulseController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/UsagePulseController.java @@ -13,5 +13,4 @@ public class UsagePulseController extends UsagePulseControllerCE { public UsagePulseController(UsagePulseService service) { super(service); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/UserController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/UserController.java index 7536b85325cf..56065e1d6a8b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/UserController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/UserController.java @@ -17,13 +17,20 @@ @Slf4j public class UserController extends UserControllerCE { - public UserController(UserService service, - SessionUserService sessionUserService, - UserWorkspaceService userWorkspaceService, - UserSignup userSignup, - UserDataService userDataService, - UserAndAccessManagementService userAndAccessManagementService) { + public UserController( + UserService service, + SessionUserService sessionUserService, + UserWorkspaceService userWorkspaceService, + UserSignup userSignup, + UserDataService userDataService, + UserAndAccessManagementService userAndAccessManagementService) { - super(service, sessionUserService, userWorkspaceService, userSignup, userDataService, userAndAccessManagementService); + super( + service, + sessionUserService, + userWorkspaceService, + userSignup, + userDataService, + userAndAccessManagementService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/WorkspaceController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/WorkspaceController.java index ec0835eddaba..52c281cb79eb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/WorkspaceController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/WorkspaceController.java @@ -11,8 +11,7 @@ @RequestMapping(Url.WORKSPACE_URL) public class WorkspaceController extends WorkspaceControllerCE { - public WorkspaceController(WorkspaceService workspaceService, - UserWorkspaceService userWorkspaceService) { + public WorkspaceController(WorkspaceService workspaceService, UserWorkspaceService userWorkspaceService) { super(workspaceService, userWorkspaceService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionCollectionControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionCollectionControllerCE.java index 7d360c1b28c0..b5bc5782a438 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionCollectionControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionCollectionControllerCE.java @@ -39,8 +39,8 @@ public class ActionCollectionControllerCE { private final LayoutCollectionService layoutCollectionService; @Autowired - public ActionCollectionControllerCE(ActionCollectionService actionCollectionService, - LayoutCollectionService layoutCollectionService) { + public ActionCollectionControllerCE( + ActionCollectionService actionCollectionService, LayoutCollectionService layoutCollectionService) { this.actionCollectionService = actionCollectionService; this.layoutCollectionService = layoutCollectionService; } @@ -48,10 +48,15 @@ public ActionCollectionControllerCE(ActionCollectionService actionCollectionServ @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<ActionCollectionDTO>> create(@Valid @RequestBody ActionCollectionDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - log.debug("Going to create action collection {}, branch: {}", resource.getClass().getName(), branchName); - return layoutCollectionService.createCollection(resource, branchName) + public Mono<ResponseDTO<ActionCollectionDTO>> create( + @Valid @RequestBody ActionCollectionDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + log.debug( + "Going to create action collection {}, branch: {}", + resource.getClass().getName(), + branchName); + return layoutCollectionService + .createCollection(resource, branchName) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @@ -61,64 +66,84 @@ public Mono<ResponseDTO<List<ActionCollectionDTO>>> getAllUnpublishedActionColle @RequestParam MultiValueMap<String, String> params, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get all unpublished action collections with params: {}, branch: {}", params, branchName); - return actionCollectionService.getPopulatedActionCollectionsByViewMode(params, false, branchName) + return actionCollectionService + .getPopulatedActionCollectionsByViewMode(params, false, branchName) .collectList() .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @JsonView(Views.Public.class) @PutMapping("/move") - public Mono<ResponseDTO<ActionCollectionDTO>> moveActionCollection(@RequestBody @Valid ActionCollectionMoveDTO actionCollectionMoveDTO, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - log.debug("Going to move action collection with id {} to page {}, on branch:{}", actionCollectionMoveDTO.getCollectionId(), actionCollectionMoveDTO.getDestinationPageId(), branchName); - return layoutCollectionService.moveCollection(actionCollectionMoveDTO, branchName) + public Mono<ResponseDTO<ActionCollectionDTO>> moveActionCollection( + @RequestBody @Valid ActionCollectionMoveDTO actionCollectionMoveDTO, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + log.debug( + "Going to move action collection with id {} to page {}, on branch:{}", + actionCollectionMoveDTO.getCollectionId(), + actionCollectionMoveDTO.getDestinationPageId(), + branchName); + return layoutCollectionService + .moveCollection(actionCollectionMoveDTO, branchName) .map(actionCollection -> new ResponseDTO<>(HttpStatus.OK.value(), actionCollection, null)); } @JsonView(Views.Public.class) @PutMapping("/refactor") - public Mono<ResponseDTO<LayoutDTO>> refactorActionCollectionName(@RequestBody RefactorActionCollectionNameDTO refactorActionCollectionNameDTO, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return layoutCollectionService.refactorCollectionName(refactorActionCollectionNameDTO, branchName) + public Mono<ResponseDTO<LayoutDTO>> refactorActionCollectionName( + @RequestBody RefactorActionCollectionNameDTO refactorActionCollectionNameDTO, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return layoutCollectionService + .refactorCollectionName(refactorActionCollectionNameDTO, branchName) .map(created -> new ResponseDTO<>(HttpStatus.OK.value(), created, null)); } @JsonView(Views.Public.class) @GetMapping("/view") - public Mono<ResponseDTO<List<ActionCollectionViewDTO>>> getAllPublishedActionCollections(@RequestParam String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - log.debug("Going to get all published action collections with application Id: {}, branch: {}", applicationId, branchName); - return actionCollectionService.getActionCollectionsForViewMode(applicationId, branchName) + public Mono<ResponseDTO<List<ActionCollectionViewDTO>>> getAllPublishedActionCollections( + @RequestParam String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + log.debug( + "Going to get all published action collections with application Id: {}, branch: {}", + applicationId, + branchName); + return actionCollectionService + .getActionCollectionsForViewMode(applicationId, branchName) .collectList() .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @JsonView(Views.Public.class) @PutMapping("/{id}") - public Mono<ResponseDTO<ActionCollectionDTO>> updateActionCollection(@PathVariable String id, - @Valid @RequestBody ActionCollectionDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<ActionCollectionDTO>> updateActionCollection( + @PathVariable String id, + @Valid @RequestBody ActionCollectionDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to update action collection with id: {}, branch: {}", id, branchName); - return layoutCollectionService.updateUnpublishedActionCollection(id, resource, branchName) + return layoutCollectionService + .updateUnpublishedActionCollection(id, resource, branchName) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); } @JsonView(Views.Public.class) @PutMapping("/refactorAction") - public Mono<ResponseDTO<LayoutDTO>> refactorActionCollection(@Valid @RequestBody RefactorActionNameInCollectionDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - log.debug("Going to refactor action collection with id: {}", resource.getActionCollection().getId()); - return layoutCollectionService.refactorAction(resource, branchName) + public Mono<ResponseDTO<LayoutDTO>> refactorActionCollection( + @Valid @RequestBody RefactorActionNameInCollectionDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + log.debug( + "Going to refactor action collection with id: {}", + resource.getActionCollection().getId()); + return layoutCollectionService + .refactorAction(resource, branchName) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); } @JsonView(Views.Public.class) @DeleteMapping("/{id}") - public Mono<ResponseDTO<ActionCollectionDTO>> deleteActionCollection(@PathVariable String id, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<ActionCollectionDTO>> deleteActionCollection( + @PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to delete unpublished action collection with id: {}", id); - return actionCollectionService.deleteUnpublishedActionCollection(id, branchName) + return actionCollectionService + .deleteUnpublishedActionCollection(id, branchName) .map(deletedResource -> new ResponseDTO<>(HttpStatus.OK.value(), deletedResource, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionControllerCE.java index 914dcd49cc95..8c44094a8b2c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionControllerCE.java @@ -48,9 +48,11 @@ public class ActionControllerCE { private final ActionExecutionSolution actionExecutionSolution; @Autowired - public ActionControllerCE(LayoutActionService layoutActionService, - NewActionService newActionService, - RefactoringSolution refactoringSolution, ActionExecutionSolution actionExecutionSolution) { + public ActionControllerCE( + LayoutActionService layoutActionService, + NewActionService newActionService, + RefactoringSolution refactoringSolution, + ActionExecutionSolution actionExecutionSolution) { this.layoutActionService = layoutActionService; this.newActionService = newActionService; this.refactoringSolution = refactoringSolution; @@ -60,75 +62,100 @@ public ActionControllerCE(LayoutActionService layoutActionService, @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<ActionDTO>> createAction(@Valid @RequestBody ActionDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = "Origin", required = false) String originHeader, - ServerWebExchange exchange) { + public Mono<ResponseDTO<ActionDTO>> createAction( + @Valid @RequestBody ActionDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = "Origin", required = false) String originHeader, + ServerWebExchange exchange) { log.debug("Going to create resource {}", resource.getClass().getName()); - return layoutActionService.createSingleActionWithBranch(resource, branchName) + return layoutActionService + .createSingleActionWithBranch(resource, branchName) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @JsonView(Views.Public.class) @PutMapping("/{defaultActionId}") - public Mono<ResponseDTO<ActionDTO>> updateAction(@PathVariable String defaultActionId, - @Valid @RequestBody ActionDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<ActionDTO>> updateAction( + @PathVariable String defaultActionId, + @Valid @RequestBody ActionDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to update resource with defaultActionId: {}, branch: {}", defaultActionId, branchName); - return layoutActionService.updateSingleActionWithBranchName(defaultActionId, resource, branchName) + return layoutActionService + .updateSingleActionWithBranchName(defaultActionId, resource, branchName) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); } @JsonView(Views.Public.class) @PostMapping(value = "/execute", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public Mono<ResponseDTO<ActionExecutionResult>> executeAction(@RequestBody Flux<Part> partFlux, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { - return actionExecutionSolution.executeAction(partFlux, branchName, environmentId) + public Mono<ResponseDTO<ActionExecutionResult>> executeAction( + @RequestBody Flux<Part> partFlux, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + return actionExecutionSolution + .executeAction(partFlux, branchName, environmentId) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); } @JsonView(Views.Public.class) @PutMapping("/move") - public Mono<ResponseDTO<ActionDTO>> moveAction(@RequestBody @Valid ActionMoveDTO actionMoveDTO, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - log.debug("Going to move action {} from page {} to page {} on branch {}", actionMoveDTO.getAction().getName(), actionMoveDTO.getAction().getPageId(), actionMoveDTO.getDestinationPageId(), branchName); - return layoutActionService.moveAction(actionMoveDTO, branchName) + public Mono<ResponseDTO<ActionDTO>> moveAction( + @RequestBody @Valid ActionMoveDTO actionMoveDTO, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + log.debug( + "Going to move action {} from page {} to page {} on branch {}", + actionMoveDTO.getAction().getName(), + actionMoveDTO.getAction().getPageId(), + actionMoveDTO.getDestinationPageId(), + branchName); + return layoutActionService + .moveAction(actionMoveDTO, branchName) .map(action -> new ResponseDTO<>(HttpStatus.OK.value(), action, null)); } @JsonView(Views.Public.class) @PutMapping("/refactor") - public Mono<ResponseDTO<LayoutDTO>> refactorActionName(@RequestBody RefactorActionNameDTO refactorActionNameDTO, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return refactoringSolution.refactorActionName(refactorActionNameDTO, branchName) + public Mono<ResponseDTO<LayoutDTO>> refactorActionName( + @RequestBody RefactorActionNameDTO refactorActionNameDTO, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return refactoringSolution + .refactorActionName(refactorActionNameDTO, branchName) .map(created -> new ResponseDTO<>(HttpStatus.OK.value(), created, null)); } @JsonView(Views.Public.class) @GetMapping("/view") - public Mono<ResponseDTO<List<ActionViewDTO>>> getActionsForViewMode(@RequestParam String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return newActionService.getActionsForViewMode(applicationId, branchName).collectList() + public Mono<ResponseDTO<List<ActionViewDTO>>> getActionsForViewMode( + @RequestParam String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return newActionService + .getActionsForViewMode(applicationId, branchName) + .collectList() .map(actions -> new ResponseDTO<>(HttpStatus.OK.value(), actions, null)); } @JsonView(Views.Public.class) @PutMapping("/executeOnLoad/{defaultActionId}") - public Mono<ResponseDTO<ActionDTO>> setExecuteOnLoad(@PathVariable String defaultActionId, - @RequestParam Boolean flag, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - log.debug("Going to set execute on load for action id {} and branchName {} to {}", defaultActionId, branchName, flag); - return layoutActionService.setExecuteOnLoad(defaultActionId, branchName, flag) + public Mono<ResponseDTO<ActionDTO>> setExecuteOnLoad( + @PathVariable String defaultActionId, + @RequestParam Boolean flag, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + log.debug( + "Going to set execute on load for action id {} and branchName {} to {}", + defaultActionId, + branchName, + flag); + return layoutActionService + .setExecuteOnLoad(defaultActionId, branchName, flag) .map(action -> new ResponseDTO<>(HttpStatus.OK.value(), action, null)); } @JsonView(Views.Public.class) @DeleteMapping("/{id}") - public Mono<ResponseDTO<ActionDTO>> deleteAction(@PathVariable String id, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<ActionDTO>> deleteAction( + @PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to delete unpublished action with id: {}, branchName: {}", id, branchName); - return layoutActionService.deleteUnpublishedAction(id, branchName) + return layoutActionService + .deleteUnpublishedAction(id, branchName) .map(deletedResource -> new ResponseDTO<>(HttpStatus.OK.value(), deletedResource, null)); } @@ -144,11 +171,14 @@ public Mono<ResponseDTO<ActionDTO>> deleteAction(@PathVariable String id, */ @JsonView(Views.Public.class) @GetMapping("") - public Mono<ResponseDTO<List<ActionDTO>>> getAllUnpublishedActions(@RequestParam MultiValueMap<String, String> params, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<List<ActionDTO>>> getAllUnpublishedActions( + @RequestParam MultiValueMap<String, String> params, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get all actions with params: {}, branch: {}", params, branchName); - // We handle JS actions as part of the collections request, so that all the contextual variables are also picked up - return newActionService.getUnpublishedActionsExceptJs(params, branchName) + // We handle JS actions as part of the collections request, so that all the contextual variables are also picked + // up + return newActionService + .getUnpublishedActionsExceptJs(params, branchName) .collectList() .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationControllerCE.java index d9d9b9fac69c..75a61acb988b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationControllerCE.java @@ -83,31 +83,35 @@ public ApplicationControllerCE( @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<Application>> create(@Valid @RequestBody Application resource, - @RequestParam String workspaceId, - ServerWebExchange exchange) { + public Mono<ResponseDTO<Application>> create( + @Valid @RequestBody Application resource, @RequestParam String workspaceId, ServerWebExchange exchange) { if (workspaceId == null) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "workspace id")); } log.debug("Going to create application in workspace {}", workspaceId); - return applicationPageService.createApplication(resource, workspaceId) + return applicationPageService + .createApplication(resource, workspaceId) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @JsonView(Views.Public.class) @PostMapping("/publish/{defaultApplicationId}") - public Mono<ResponseDTO<Boolean>> publish(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return applicationPageService.publish(defaultApplicationId, branchName, true) + public Mono<ResponseDTO<Boolean>> publish( + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return applicationPageService + .publish(defaultApplicationId, branchName, true) .thenReturn(new ResponseDTO<>(HttpStatus.OK.value(), true, null)); } @JsonView(Views.Public.class) @PutMapping("/{defaultApplicationId}/page/{defaultPageId}/makeDefault") - public Mono<ResponseDTO<Application>> makeDefault(@PathVariable String defaultApplicationId, - @PathVariable String defaultPageId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return applicationPageService.makePageDefault(defaultApplicationId, defaultPageId, branchName) + public Mono<ResponseDTO<Application>> makeDefault( + @PathVariable String defaultApplicationId, + @PathVariable String defaultPageId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return applicationPageService + .makePageDefault(defaultApplicationId, defaultPageId, branchName) .map(updatedApplication -> new ResponseDTO<>(HttpStatus.OK.value(), updatedApplication, null)); } @@ -118,17 +122,19 @@ public Mono<ResponseDTO<ApplicationPagesDTO>> reorderPage( @PathVariable String defaultPageId, @RequestParam Integer order, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return applicationPageService.reorderPage(defaultApplicationId, defaultPageId, order, branchName) + return applicationPageService + .reorderPage(defaultApplicationId, defaultPageId, order, branchName) .map(updatedApplication -> new ResponseDTO<>(HttpStatus.OK.value(), updatedApplication, null)); } @Override @JsonView(Views.Public.class) @DeleteMapping("/{id}") - public Mono<ResponseDTO<Application>> delete(@PathVariable String id, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Application>> delete( + @PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to delete application with id: {}", id); - return applicationPageService.deleteApplication(id) + return applicationPageService + .deleteApplication(id) .map(deletedResource -> new ResponseDTO<>(HttpStatus.OK.value(), deletedResource, null)); } @@ -136,7 +142,8 @@ public Mono<ResponseDTO<Application>> delete(@PathVariable String id, @GetMapping("/new") public Mono<ResponseDTO<UserHomepageDTO>> getAllApplicationsForHome() { log.debug("Going to get all applications grouped by workspace"); - return applicationFetcher.getAllApplications() + return applicationFetcher + .getAllApplications() .map(applications -> new ResponseDTO<>(HttpStatus.OK.value(), applications, null)); } @@ -144,32 +151,41 @@ public Mono<ResponseDTO<UserHomepageDTO>> getAllApplicationsForHome() { @GetMapping(Url.RELEASE_ITEMS) public Mono<ResponseDTO<ReleaseItemsDTO>> getReleaseItemsInformation() { log.debug("Going to get version release items"); - return applicationFetcher.getReleaseItems() + return applicationFetcher + .getReleaseItems() .map(applications -> new ResponseDTO<>(HttpStatus.OK.value(), applications, null)); } @JsonView(Views.Public.class) @PutMapping("/{defaultApplicationId}/changeAccess") - public Mono<ResponseDTO<Application>> shareApplication(@PathVariable String defaultApplicationId, - @RequestBody ApplicationAccessDTO applicationAccessDTO, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - log.debug("Going to change access for application {}, branch {} to {}", defaultApplicationId, branchName, applicationAccessDTO.getPublicAccess()); + public Mono<ResponseDTO<Application>> shareApplication( + @PathVariable String defaultApplicationId, + @RequestBody ApplicationAccessDTO applicationAccessDTO, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + log.debug( + "Going to change access for application {}, branch {} to {}", + defaultApplicationId, + branchName, + applicationAccessDTO.getPublicAccess()); return service.changeViewAccess(defaultApplicationId, branchName, applicationAccessDTO) .map(application -> new ResponseDTO<>(HttpStatus.OK.value(), application, null)); } @JsonView(Views.Public.class) @PostMapping("/clone/{applicationId}") - public Mono<ResponseDTO<Application>> cloneApplication(@PathVariable String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return applicationPageService.cloneApplication(applicationId, branchName) + public Mono<ResponseDTO<Application>> cloneApplication( + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return applicationPageService + .cloneApplication(applicationId, branchName) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @JsonView(Views.Public.class) @GetMapping("/view/{defaultApplicationId}") - public Mono<ResponseDTO<Application>> getApplicationInViewMode(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Application>> getApplicationInViewMode( + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { return service.getApplicationInViewMode(defaultApplicationId, branchName) .map(application -> new ResponseDTO<>(HttpStatus.OK.value(), application, null)); } @@ -180,79 +196,87 @@ public Mono<ResponseDTO<ApplicationImportDTO>> forkApplication( @PathVariable String defaultApplicationId, @PathVariable String workspaceId, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return applicationForkingService.forkApplicationToWorkspace(defaultApplicationId, workspaceId, branchName) + return applicationForkingService + .forkApplicationToWorkspace(defaultApplicationId, workspaceId, branchName) .map(fetchedResource -> new ResponseDTO<>(HttpStatus.OK.value(), fetchedResource, null)); } @JsonView(Views.Public.class) @GetMapping("/export/{id}") - public Mono<ResponseEntity<Object>> getApplicationFile(@PathVariable String id, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseEntity<Object>> getApplicationFile( + @PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to export application with id: {}, branch: {}", id, branchName); - return importExportApplicationService.getApplicationFile(id, branchName) - .map(fetchedResource -> { - HttpHeaders responseHeaders = fetchedResource.getHttpHeaders(); - Object applicationResource = fetchedResource.getApplicationResource(); - return new ResponseEntity<>(applicationResource, responseHeaders, HttpStatus.OK); - }); + return importExportApplicationService.getApplicationFile(id, branchName).map(fetchedResource -> { + HttpHeaders responseHeaders = fetchedResource.getHttpHeaders(); + Object applicationResource = fetchedResource.getApplicationResource(); + return new ResponseEntity<>(applicationResource, responseHeaders, HttpStatus.OK); + }); } @JsonView(Views.Public.class) @PostMapping("/snapshot/{id}") @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<Boolean>> createSnapshot(@PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Boolean>> createSnapshot( + @PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to create snapshot with application id: {}, branch: {}", id, branchName); - return applicationSnapshotService.createApplicationSnapshot(id, branchName) + return applicationSnapshotService + .createApplicationSnapshot(id, branchName) .map(result -> new ResponseDTO<>(HttpStatus.CREATED.value(), result, null)); } @JsonView(Views.Public.class) @GetMapping("/snapshot/{id}") - public Mono<ResponseDTO<ApplicationSnapshot>> getSnapshotWithoutApplicationJson(@PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<ApplicationSnapshot>> getSnapshotWithoutApplicationJson( + @PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get snapshot with application id: {}, branch: {}", id, branchName); - return applicationSnapshotService.getWithoutDataByApplicationId(id, branchName) + return applicationSnapshotService + .getWithoutDataByApplicationId(id, branchName) .map(applicationSnapshot -> new ResponseDTO<>(HttpStatus.OK.value(), applicationSnapshot, null)); } @JsonView(Views.Public.class) @DeleteMapping("/snapshot/{id}") - public Mono<ResponseDTO<Boolean>> deleteSnapshotWithoutApplicationJson(@PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Boolean>> deleteSnapshotWithoutApplicationJson( + @PathVariable String id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to delete snapshot with application id: {}, branch: {}", id, branchName); - return applicationSnapshotService.deleteSnapshot(id, branchName) + return applicationSnapshotService + .deleteSnapshot(id, branchName) .map(isDeleted -> new ResponseDTO<>(HttpStatus.OK.value(), isDeleted, null)); } @JsonView(Views.Public.class) @PostMapping("/snapshot/{id}/restore") - public Mono<ResponseDTO<Application>> restoreSnapshot(@PathVariable String id, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + public Mono<ResponseDTO<Application>> restoreSnapshot( + @PathVariable String id, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { log.debug("Going to restore snapshot with application id: {}, branch: {}", id, branchName); - return applicationSnapshotService.restoreSnapshot(id, branchName) + return applicationSnapshotService + .restoreSnapshot(id, branchName) .map(application -> new ResponseDTO<>(HttpStatus.OK.value(), application, null)); } - @JsonView(Views.Public.class) @PostMapping(value = "/import/{workspaceId}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public Mono<ResponseDTO<ApplicationImportDTO>> importApplicationFromFile(@RequestPart("file") Mono<Part> fileMono, - @PathVariable String workspaceId, - @RequestParam(name = FieldName.APPLICATION_ID, required = false) String applicationId) { + public Mono<ResponseDTO<ApplicationImportDTO>> importApplicationFromFile( + @RequestPart("file") Mono<Part> fileMono, + @PathVariable String workspaceId, + @RequestParam(name = FieldName.APPLICATION_ID, required = false) String applicationId) { log.debug("Going to import application in workspace with id: {}", workspaceId); - return fileMono - .flatMap(file -> importExportApplicationService.extractFileAndSaveApplication(workspaceId, file, applicationId)) + return fileMono.flatMap(file -> + importExportApplicationService.extractFileAndSaveApplication(workspaceId, file, applicationId)) .map(fetchedResource -> new ResponseDTO<>(HttpStatus.OK.value(), fetchedResource, null)); } @JsonView(Views.Public.class) @PostMapping("/ssh-keypair/{applicationId}") - public Mono<ResponseDTO<GitAuth>> generateSSHKeyPair(@PathVariable String applicationId, - @RequestParam(required = false) String keyType) { + public Mono<ResponseDTO<GitAuth>> generateSSHKeyPair( + @PathVariable String applicationId, @RequestParam(required = false) String keyType) { return service.createOrUpdateSshKeyPair(applicationId, keyType) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @@ -267,9 +291,10 @@ public Mono<ResponseDTO<GitAuthDTO>> getSSHKey(@PathVariable String applicationI @Override @JsonView(Views.Public.class) @PutMapping("/{defaultApplicationId}") - public Mono<ResponseDTO<Application>> update(@PathVariable String defaultApplicationId, - @RequestBody Application resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Application>> update( + @PathVariable String defaultApplicationId, + @RequestBody Application resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to update resource from base controller with id: {}", defaultApplicationId); return service.update(defaultApplicationId, resource, branchName) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); @@ -277,45 +302,51 @@ public Mono<ResponseDTO<Application>> update(@PathVariable String defaultApplica @JsonView(Views.Public.class) @PatchMapping("{applicationId}/themes/{themeId}") - public Mono<ResponseDTO<Theme>> setCurrentTheme(@PathVariable String applicationId, @PathVariable String themeId, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return themeService.changeCurrentTheme(themeId, applicationId, branchName) + public Mono<ResponseDTO<Theme>> setCurrentTheme( + @PathVariable String applicationId, + @PathVariable String themeId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return themeService + .changeCurrentTheme(themeId, applicationId, branchName) .map(theme -> new ResponseDTO<>(HttpStatus.OK.value(), theme, null)); } @JsonView(Views.Public.class) @GetMapping("/import/{workspaceId}/datasources") - public Mono<ResponseDTO<List<Datasource>>> getUnConfiguredDatasource(@PathVariable String workspaceId, @RequestParam String defaultApplicationId) { - return importExportApplicationService.findDatasourceByApplicationId(defaultApplicationId, workspaceId) + public Mono<ResponseDTO<List<Datasource>>> getUnConfiguredDatasource( + @PathVariable String workspaceId, @RequestParam String defaultApplicationId) { + return importExportApplicationService + .findDatasourceByApplicationId(defaultApplicationId, workspaceId) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); } @JsonView(Views.Public.class) @PostMapping(value = "/{defaultApplicationId}/logo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public Mono<ResponseDTO<Application>> uploadAppNavigationLogo(@PathVariable String defaultApplicationId, - @RequestPart("file") Mono<Part> fileMono, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return fileMono - .flatMap(part -> service.saveAppNavigationLogo(branchName, defaultApplicationId, part)) + public Mono<ResponseDTO<Application>> uploadAppNavigationLogo( + @PathVariable String defaultApplicationId, + @RequestPart("file") Mono<Part> fileMono, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return fileMono.flatMap(part -> service.saveAppNavigationLogo(branchName, defaultApplicationId, part)) .map(url -> new ResponseDTO<>(HttpStatus.OK.value(), url, null)); } @JsonView(Views.Public.class) @DeleteMapping("/{defaultApplicationId}/logo") - public Mono<ResponseDTO<Void>> deleteAppNavigationLogo(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Void>> deleteAppNavigationLogo( + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { return service.deleteAppNavigationLogo(branchName, defaultApplicationId) .map(ignored -> new ResponseDTO<>(HttpStatus.OK.value(), null, null)); } - // !! This API endpoint should not be exposed !! @Override @JsonView(Views.Public.class) @GetMapping("") - public Mono<ResponseDTO<List<Application>>> getAll(@RequestParam MultiValueMap<String, String> params, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return Mono.just( - new ResponseDTO<>(HttpStatus.BAD_REQUEST.value(), null, AppsmithError.UNSUPPORTED_OPERATION.getMessage()) - ); + public Mono<ResponseDTO<List<Application>>> getAll( + @RequestParam MultiValueMap<String, String> params, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return Mono.just(new ResponseDTO<>( + HttpStatus.BAD_REQUEST.value(), null, AppsmithError.UNSUPPORTED_OPERATION.getMessage())); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationTemplateControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationTemplateControllerCE.java index 68f453544e6d..4ae29c04bbfb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationTemplateControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationTemplateControllerCE.java @@ -32,54 +32,64 @@ public ApplicationTemplateControllerCE(ApplicationTemplateService applicationTem @JsonView(Views.Public.class) @GetMapping public Mono<ResponseDTO<List<ApplicationTemplate>>> getAll() { - return applicationTemplateService.getActiveTemplates(null) + return applicationTemplateService + .getActiveTemplates(null) .map(templates -> new ResponseDTO<>(HttpStatus.OK.value(), templates, null)); } @JsonView(Views.Public.class) @GetMapping("{templateId}") public Mono<ResponseDTO<ApplicationTemplate>> getTemplateDetails(@PathVariable String templateId) { - return applicationTemplateService.getTemplateDetails(templateId) + return applicationTemplateService + .getTemplateDetails(templateId) .map(templates -> new ResponseDTO<>(HttpStatus.OK.value(), templates, null)); } @JsonView(Views.Public.class) @GetMapping("{templateId}/similar") - public Mono<ResponseDTO<List<ApplicationTemplate>>> getSimilarTemplates(@PathVariable String templateId, @RequestParam MultiValueMap<String, String> params) { - return applicationTemplateService.getSimilarTemplates(templateId, params).collectList() + public Mono<ResponseDTO<List<ApplicationTemplate>>> getSimilarTemplates( + @PathVariable String templateId, @RequestParam MultiValueMap<String, String> params) { + return applicationTemplateService + .getSimilarTemplates(templateId, params) + .collectList() .map(templates -> new ResponseDTO<>(HttpStatus.OK.value(), templates, null)); } @JsonView(Views.Public.class) @GetMapping("filters") public Mono<ResponseDTO<ApplicationTemplate>> getFilters() { - return applicationTemplateService.getFilters() + return applicationTemplateService + .getFilters() .map(filters -> new ResponseDTO<>(HttpStatus.OK.value(), filters, null)); } @JsonView(Views.Public.class) @PostMapping("{templateId}/import/{workspaceId}") - public Mono<ResponseDTO<ApplicationImportDTO>> importApplicationFromTemplate(@PathVariable String templateId, - @PathVariable String workspaceId) { - return applicationTemplateService.importApplicationFromTemplate(templateId, workspaceId) + public Mono<ResponseDTO<ApplicationImportDTO>> importApplicationFromTemplate( + @PathVariable String templateId, @PathVariable String workspaceId) { + return applicationTemplateService + .importApplicationFromTemplate(templateId, workspaceId) .map(importedApp -> new ResponseDTO<>(HttpStatus.OK.value(), importedApp, null)); } @JsonView(Views.Public.class) @GetMapping("recent") public Mono<ResponseDTO<List<ApplicationTemplate>>> getRecentlyUsedTemplates() { - return applicationTemplateService.getRecentlyUsedTemplates() + return applicationTemplateService + .getRecentlyUsedTemplates() .map(templates -> new ResponseDTO<>(HttpStatus.OK.value(), templates, null)); } @JsonView(Views.Public.class) @PostMapping("{templateId}/merge/{applicationId}/{organizationId}") - public Mono<ResponseDTO<ApplicationImportDTO>> mergeTemplateWithApplication(@PathVariable String templateId, - @PathVariable String applicationId, - @PathVariable String organizationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestBody(required = false) List<String> pagesToImport) { - return applicationTemplateService.mergeTemplateWithApplication(templateId, applicationId, organizationId, branchName, pagesToImport) + public Mono<ResponseDTO<ApplicationImportDTO>> mergeTemplateWithApplication( + @PathVariable String templateId, + @PathVariable String applicationId, + @PathVariable String organizationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestBody(required = false) List<String> pagesToImport) { + return applicationTemplateService + .mergeTemplateWithApplication(templateId, applicationId, organizationId, branchName, pagesToImport) .map(importedApp -> new ResponseDTO<>(HttpStatus.OK.value(), importedApp, null)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/AssetControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/AssetControllerCE.java index f29b98c39410..9a0f936c281c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/AssetControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/AssetControllerCE.java @@ -24,5 +24,4 @@ public Mono<Void> getById(@PathVariable String id, ServerWebExchange exchange) { exchange.getResponse().getHeaders().set(HttpHeaders.CACHE_CONTROL, "public, max-age=7776000, immutable"); return service.makeImageResponse(exchange, id); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/BaseController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/BaseController.java index ba2f67e59019..6125ce9c7fa2 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/BaseController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/BaseController.java @@ -36,12 +36,14 @@ public abstract class BaseController<S extends CrudService<T, ID>, T extends Bas @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<T>> create(@Valid @RequestBody T resource, - @RequestHeader(name = "Origin", required = false) String originHeader, - ServerWebExchange exchange) { - log.debug("Going to create resource from base controller {}", resource.getClass().getName()); - return service.create(resource) - .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); + public Mono<ResponseDTO<T>> create( + @Valid @RequestBody T resource, + @RequestHeader(name = "Origin", required = false) String originHeader, + ServerWebExchange exchange) { + log.debug( + "Going to create resource from base controller {}", + resource.getClass().getName()); + return service.create(resource).map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } /** @@ -55,21 +57,23 @@ public Mono<ResponseDTO<T>> create(@Valid @RequestBody T resource, */ @JsonView(Views.Public.class) @GetMapping("") - public Mono<ResponseDTO<List<T>>> getAll(@RequestParam MultiValueMap<String, String> params, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<List<T>>> getAll( + @RequestParam MultiValueMap<String, String> params, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get all resources from base controller {}", params); MultiValueMap<String, String> modifiableParams = new LinkedMultiValueMap<>(params); if (!StringUtils.isEmpty(branchName)) { modifiableParams.add(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME, branchName); } - return service.get(modifiableParams).collectList() + return service.get(modifiableParams) + .collectList() .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @JsonView(Views.Public.class) @GetMapping("/{id}") - public Mono<ResponseDTO<T>> getByIdAndBranchName(@PathVariable ID id, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<T>> getByIdAndBranchName( + @PathVariable ID id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get resource from base controller for id: {}", id); return service.findByIdAndBranchName(id, branchName) .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); @@ -77,9 +81,10 @@ public Mono<ResponseDTO<T>> getByIdAndBranchName(@PathVariable ID id, @JsonView(Views.Public.class) @PutMapping("/{id}") - public Mono<ResponseDTO<T>> update(@PathVariable ID id, - @RequestBody T resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<T>> update( + @PathVariable ID id, + @RequestBody T resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to update resource from base controller with id: {}", id); return service.update(id, resource) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); @@ -87,11 +92,10 @@ public Mono<ResponseDTO<T>> update(@PathVariable ID id, @JsonView(Views.Public.class) @DeleteMapping("/{id}") - public Mono<ResponseDTO<T>> delete(@PathVariable ID id, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<T>> delete( + @PathVariable ID id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to delete resource from base controller with id: {}", id); return service.archiveByIdAndBranchName(id, branchName) .map(deletedResource -> new ResponseDTO<>(HttpStatus.OK.value(), deletedResource, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ConfigControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ConfigControllerCE.java index 54b40fa2033b..1ed7f46f770e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ConfigControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ConfigControllerCE.java @@ -26,14 +26,12 @@ public ConfigControllerCE(ConfigService service) { @JsonView(Views.Public.class) @GetMapping("/name/{name}") public Mono<ResponseDTO<Config>> getByName(@PathVariable String name) { - return service.getByName(name) - .map(resource -> new ResponseDTO<>(HttpStatus.OK.value(), resource, null)); + return service.getByName(name).map(resource -> new ResponseDTO<>(HttpStatus.OK.value(), resource, null)); } @JsonView(Views.Public.class) @PutMapping("/name/{name}") public Mono<ResponseDTO<Config>> updateByName(@PathVariable String name, @RequestBody Config config) { - return service.updateByName(config) - .map(resource -> new ResponseDTO<>(HttpStatus.OK.value(), resource, null)); + return service.updateByName(config).map(resource -> new ResponseDTO<>(HttpStatus.OK.value(), resource, null)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/CustomJSLibControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/CustomJSLibControllerCE.java index f5499b79ca57..1d53dd8c0507 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/CustomJSLibControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/CustomJSLibControllerCE.java @@ -31,49 +31,59 @@ public CustomJSLibControllerCE(CustomJSLibService customJSLibService) { @JsonView(Views.Public.class) @PatchMapping("/{applicationId}/add") - public Mono<ResponseDTO<Boolean>> addJSLibToApplication(@RequestBody @Valid CustomJSLib customJSLib, - @PathVariable String applicationId, @RequestHeader(name = - FieldName.BRANCH_NAME, required = false) String branchName, @RequestHeader(name = - FieldName.IS_FORCE_INSTALL, defaultValue = "false") Boolean isForceInstall) { - log.debug("Going to add JS lib: {}_{} to application: {}, on branch:{}", customJSLib.getName(), - customJSLib.getVersion(), applicationId, branchName); - return customJSLibService.addJSLibToApplication(applicationId, customJSLib, branchName, isForceInstall) + public Mono<ResponseDTO<Boolean>> addJSLibToApplication( + @RequestBody @Valid CustomJSLib customJSLib, + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = FieldName.IS_FORCE_INSTALL, defaultValue = "false") Boolean isForceInstall) { + log.debug( + "Going to add JS lib: {}_{} to application: {}, on branch:{}", + customJSLib.getName(), + customJSLib.getVersion(), + applicationId, + branchName); + return customJSLibService + .addJSLibToApplication(applicationId, customJSLib, branchName, isForceInstall) .map(actionCollection -> new ResponseDTO<>(HttpStatus.OK.value(), actionCollection, null)); } @JsonView(Views.Public.class) @PatchMapping("/{applicationId}/remove") - public Mono<ResponseDTO<Boolean>> removeJSLibFromApplication(@RequestBody @Valid CustomJSLib customJSLib, - @PathVariable String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, - required = false) String branchName, - @RequestHeader(name = FieldName.IS_FORCE_REMOVE, - defaultValue = "false") Boolean isForceRemove) { - log.debug("Going to remove JS lib: {}_{} from application: {}, on branch:{}", customJSLib.getName(), - customJSLib.getVersion(), applicationId, branchName); - return customJSLibService.removeJSLibFromApplication(applicationId, customJSLib, branchName, isForceRemove) + public Mono<ResponseDTO<Boolean>> removeJSLibFromApplication( + @RequestBody @Valid CustomJSLib customJSLib, + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = FieldName.IS_FORCE_REMOVE, defaultValue = "false") Boolean isForceRemove) { + log.debug( + "Going to remove JS lib: {}_{} from application: {}, on branch:{}", + customJSLib.getName(), + customJSLib.getVersion(), + applicationId, + branchName); + return customJSLibService + .removeJSLibFromApplication(applicationId, customJSLib, branchName, isForceRemove) .map(actionCollection -> new ResponseDTO<>(HttpStatus.OK.value(), actionCollection, null)); } @JsonView(Views.Public.class) @GetMapping("/{applicationId}") - public Mono<ResponseDTO<List<CustomJSLib>>> getAllUserInstalledJSLibInApplication(@PathVariable String applicationId, - @RequestHeader(name = - FieldName.BRANCH_NAME, - required = false) String branchName) { + public Mono<ResponseDTO<List<CustomJSLib>>> getAllUserInstalledJSLibInApplication( + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get all unpublished JS libs in application: {}, on branch: {}", applicationId, branchName); - return customJSLibService.getAllJSLibsInApplication(applicationId, branchName, false) + return customJSLibService + .getAllJSLibsInApplication(applicationId, branchName, false) .map(actionCollection -> new ResponseDTO<>(HttpStatus.OK.value(), actionCollection, null)); } @JsonView(Views.Public.class) @GetMapping("/{applicationId}/view") - public Mono<ResponseDTO<List<CustomJSLib>>> getAllUserInstalledJSLibInApplicationForViewMode(@PathVariable String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, - required = false) - String branchName) { + public Mono<ResponseDTO<List<CustomJSLib>>> getAllUserInstalledJSLibInApplicationForViewMode( + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get all published JS libs in application: {}, on branch: {}", applicationId, branchName); - return customJSLibService.getAllJSLibsInApplication(applicationId, branchName, true) + return customJSLibService + .getAllJSLibsInApplication(applicationId, branchName, true) .map(actionCollection -> new ResponseDTO<>(HttpStatus.OK.value(), actionCollection, null)); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/DatasourceControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/DatasourceControllerCE.java index 250889175ff2..532923be3c7d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/DatasourceControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/DatasourceControllerCE.java @@ -52,11 +52,12 @@ public class DatasourceControllerCE { private final DatasourceService datasourceService; @Autowired - public DatasourceControllerCE(DatasourceService service, - DatasourceStructureSolution datasourceStructureSolution, - AuthenticationService authenticationService, - MockDataService datasourceService, - DatasourceTriggerSolution datasourceTriggerSolution) { + public DatasourceControllerCE( + DatasourceService service, + DatasourceStructureSolution datasourceStructureSolution, + AuthenticationService authenticationService, + MockDataService datasourceService, + DatasourceTriggerSolution datasourceTriggerSolution) { this.datasourceService = service; this.datasourceStructureSolution = datasourceStructureSolution; this.authenticationService = authenticationService; @@ -68,38 +69,48 @@ public DatasourceControllerCE(DatasourceService service, @GetMapping("") public Mono<ResponseDTO<List<Datasource>>> getAll(@RequestParam MultiValueMap<String, String> params) { log.debug("Going to get all resources from datasource controller {}", params); - return datasourceService.getAllWithStorages(params).collectList() + return datasourceService + .getAllWithStorages(params) + .collectList() .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<Datasource>> create(@Valid @RequestBody Datasource resource, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String activeEnvironmentId) { + public Mono<ResponseDTO<Datasource>> create( + @Valid @RequestBody Datasource resource, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String activeEnvironmentId) { log.debug("Going to create resource from datasource controller"); - return datasourceService.create(resource) + return datasourceService + .create(resource) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @JsonView(Views.Public.class) @PutMapping("/{id}") - public Mono<ResponseDTO<Datasource>> update(@PathVariable String id, - @RequestBody Datasource datasource, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + public Mono<ResponseDTO<Datasource>> update( + @PathVariable String id, + @RequestBody Datasource datasource, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { log.debug("Going to update resource from datasource controller with id: {}", id); - return datasourceService.updateDatasource(id, datasource, environmentId, Boolean.TRUE) + return datasourceService + .updateDatasource(id, datasource, environmentId, Boolean.TRUE) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); } @JsonView(Views.Public.class) @PutMapping("/datasource-storages") - public Mono<ResponseDTO<Datasource>> updateDatasourceStorages(@RequestBody DatasourceStorageDTO datasourceStorageDTO, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String activeEnvironmentId) { - log.debug("Going to update datasource from datasource controller with id: {} and environmentId: {}", - datasourceStorageDTO.getDatasourceId(), datasourceStorageDTO.getEnvironmentId()); - - return datasourceService.updateDatasourceStorage(datasourceStorageDTO, activeEnvironmentId , Boolean.TRUE) + public Mono<ResponseDTO<Datasource>> updateDatasourceStorages( + @RequestBody DatasourceStorageDTO datasourceStorageDTO, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String activeEnvironmentId) { + log.debug( + "Going to update datasource from datasource controller with id: {} and environmentId: {}", + datasourceStorageDTO.getDatasourceId(), + datasourceStorageDTO.getEnvironmentId()); + + return datasourceService + .updateDatasourceStorage(datasourceStorageDTO, activeEnvironmentId, Boolean.TRUE) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); } @@ -107,36 +118,47 @@ public Mono<ResponseDTO<Datasource>> updateDatasourceStorages(@RequestBody Datas @DeleteMapping("/{id}") public Mono<ResponseDTO<Datasource>> delete(@PathVariable String id) { log.debug("Going to delete resource from datasource controller with id: {}", id); - return datasourceService.archiveById(id) + return datasourceService + .archiveById(id) .map(deletedResource -> new ResponseDTO<>(HttpStatus.OK.value(), deletedResource, null)); } @JsonView(Views.Public.class) @PostMapping("/test") - public Mono<ResponseDTO<DatasourceTestResult>> testDatasource(@RequestBody DatasourceStorageDTO datasourceStorageDTO, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String activeEnvironmentId) { + public Mono<ResponseDTO<DatasourceTestResult>> testDatasource( + @RequestBody DatasourceStorageDTO datasourceStorageDTO, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String activeEnvironmentId) { log.debug("Going to test the datasource with id: {}", datasourceStorageDTO.getDatasourceId()); - return datasourceService.testDatasource(datasourceStorageDTO, activeEnvironmentId) + return datasourceService + .testDatasource(datasourceStorageDTO, activeEnvironmentId) .map(testResult -> new ResponseDTO<>(HttpStatus.OK.value(), testResult, null)); } @JsonView(Views.Public.class) @GetMapping("/{datasourceId}/structure") - public Mono<ResponseDTO<DatasourceStructure>> getStructure(@PathVariable String datasourceId, - @RequestParam(required = false, defaultValue = "false") Boolean ignoreCache, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + public Mono<ResponseDTO<DatasourceStructure>> getStructure( + @PathVariable String datasourceId, + @RequestParam(required = false, defaultValue = "false") Boolean ignoreCache, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { log.debug("Going to get structure for datasource with id: '{}'.", datasourceId); - return datasourceStructureSolution.getStructure(datasourceId, BooleanUtils.isTrue(ignoreCache), environmentId) + return datasourceStructureSolution + .getStructure(datasourceId, BooleanUtils.isTrue(ignoreCache), environmentId) .map(structure -> new ResponseDTO<>(HttpStatus.OK.value(), structure, null)); } @JsonView(Views.Public.class) @GetMapping("/{datasourceId}/pages/{pageId}/code") - public Mono<Void> getTokenRequestUrl(@PathVariable String datasourceId, @PathVariable String pageId, ServerWebExchange serverWebExchange, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { - log.debug("Going to retrieve token request URL for datasource with id: {} and page id: {}", datasourceId, pageId); - return authenticationService.getAuthorizationCodeURLForGenericOAuth2(datasourceId, environmentId, pageId, serverWebExchange.getRequest(), Boolean.TRUE) + public Mono<Void> getTokenRequestUrl( + @PathVariable String datasourceId, + @PathVariable String pageId, + ServerWebExchange serverWebExchange, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + log.debug( + "Going to retrieve token request URL for datasource with id: {} and page id: {}", datasourceId, pageId); + return authenticationService + .getAuthorizationCodeURLForGenericOAuth2( + datasourceId, environmentId, pageId, serverWebExchange.getRequest(), Boolean.TRUE) .flatMap(url -> { serverWebExchange.getResponse().setStatusCode(HttpStatus.FOUND); serverWebExchange.getResponse().getHeaders().setLocation(URI.create(url)); @@ -148,36 +170,40 @@ public Mono<Void> getTokenRequestUrl(@PathVariable String datasourceId, @PathVar @GetMapping("/authorize") public Mono<Void> getAccessToken(AuthorizationCodeCallbackDTO callbackDTO, ServerWebExchange serverWebExchange) { log.debug("Received callback for an OAuth2 authorization request"); - return authenticationService.getAccessTokenForGenericOAuth2(callbackDTO) - .flatMap(url -> { - serverWebExchange.getResponse().setStatusCode(HttpStatus.FOUND); - serverWebExchange.getResponse().getHeaders().setLocation(URI.create(url)); - return serverWebExchange.getResponse().setComplete(); - }); + return authenticationService.getAccessTokenForGenericOAuth2(callbackDTO).flatMap(url -> { + serverWebExchange.getResponse().setStatusCode(HttpStatus.FOUND); + serverWebExchange.getResponse().getHeaders().setLocation(URI.create(url)); + return serverWebExchange.getResponse().setComplete(); + }); } @JsonView(Views.Public.class) @GetMapping(Url.MOCKS) public Mono<ResponseDTO<List<MockDataSet>>> getMockDataSets() { - return mockDataService.getMockDataSet() + return mockDataService + .getMockDataSet() .map(config -> new ResponseDTO<>(HttpStatus.OK.value(), config.getMockdbs(), null)); } @JsonView(Views.Public.class) @PostMapping(Url.MOCKS) - public Mono<ResponseDTO<Datasource>> createMockDataSet(@RequestBody MockDataSource mockDataSource, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { - return mockDataService.createMockDataSet(mockDataSource, environmentId) + public Mono<ResponseDTO<Datasource>> createMockDataSet( + @RequestBody MockDataSource mockDataSource, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + return mockDataService + .createMockDataSet(mockDataSource, environmentId) .map(datasource -> new ResponseDTO<>(HttpStatus.OK.value(), datasource, null)); } @JsonView(Views.Public.class) @PostMapping("/{datasourceId}/trigger") - public Mono<ResponseDTO<TriggerResultDTO>> trigger(@PathVariable String datasourceId, - @RequestBody TriggerRequestDTO triggerRequestDTO, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + public Mono<ResponseDTO<TriggerResultDTO>> trigger( + @PathVariable String datasourceId, + @RequestBody TriggerRequestDTO triggerRequestDTO, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { log.debug("Trigger received for datasource {}", datasourceId); - return datasourceTriggerSolution.trigger(datasourceId, environmentId, triggerRequestDTO) + return datasourceTriggerSolution + .trigger(datasourceId, environmentId, triggerRequestDTO) .map(triggerResultDTO -> new ResponseDTO<>(HttpStatus.OK.value(), triggerResultDTO, null)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java index 06ef5d3defa5..31f215e16d20 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java @@ -58,7 +58,6 @@ public GitControllerCE(GitService service) { * This is stored in gitApplicationMetadata * Note : The master branch here refers to the app that was created even before connecting to git */ - @JsonView(Views.Public.class) @PostMapping("/profile/default") public Mono<ResponseDTO<Map<String, GitProfile>>> saveGitProfile(@RequestBody GitProfile gitProfile) { @@ -69,8 +68,8 @@ public Mono<ResponseDTO<Map<String, GitProfile>>> saveGitProfile(@RequestBody Gi @JsonView(Views.Public.class) @PutMapping("/profile/app/{defaultApplicationId}") - public Mono<ResponseDTO<Map<String, GitProfile>>> saveGitProfile(@PathVariable String defaultApplicationId, - @RequestBody GitProfile gitProfile) { + public Mono<ResponseDTO<Map<String, GitProfile>>> saveGitProfile( + @PathVariable String defaultApplicationId, @RequestBody GitProfile gitProfile) { log.debug("Going to add repo specific git profile for application: {}", defaultApplicationId); return service.updateOrCreateGitProfileForCurrentUser(gitProfile, defaultApplicationId) .map(response -> new ResponseDTO<>(HttpStatus.ACCEPTED.value(), response, null)); @@ -99,9 +98,10 @@ public Mono<ResponseDTO<GitApplicationMetadata>> getGitMetadata(@PathVariable St @JsonView(Views.Public.class) @PostMapping("/connect/app/{defaultApplicationId}") - public Mono<ResponseDTO<Application>> connectApplicationToRemoteRepo(@PathVariable String defaultApplicationId, - @RequestBody GitConnectDTO gitConnectDTO, - @RequestHeader("Origin") String originHeader) { + public Mono<ResponseDTO<Application>> connectApplicationToRemoteRepo( + @PathVariable String defaultApplicationId, + @RequestBody GitConnectDTO gitConnectDTO, + @RequestHeader("Origin") String originHeader) { return service.connectApplicationToGit(defaultApplicationId, gitConnectDTO, originHeader) .map(application -> new ResponseDTO<>(HttpStatus.OK.value(), application, null)); } @@ -109,10 +109,11 @@ public Mono<ResponseDTO<Application>> connectApplicationToRemoteRepo(@PathVariab @JsonView(Views.Public.class) @PostMapping("/commit/app/{defaultApplicationId}") @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<String>> commit(@RequestBody GitCommitDTO commitDTO, - @PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestParam(required = false, defaultValue = "false") Boolean doAmend) { + public Mono<ResponseDTO<String>> commit( + @RequestBody GitCommitDTO commitDTO, + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestParam(required = false, defaultValue = "false") Boolean doAmend) { log.debug("Going to commit application {}, branch : {}", defaultApplicationId, branchName); return service.commitApplication(commitDTO, defaultApplicationId, branchName, doAmend) .map(result -> new ResponseDTO<>(HttpStatus.CREATED.value(), result, null)); @@ -120,8 +121,9 @@ public Mono<ResponseDTO<String>> commit(@RequestBody GitCommitDTO commitDTO, @JsonView(Views.Public.class) @GetMapping("/commit-history/app/{defaultApplicationId}") - public Mono<ResponseDTO<List<GitLogDTO>>> getCommitHistory(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<List<GitLogDTO>>> getCommitHistory( + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Fetching commit-history for application {}, branch : {}", defaultApplicationId, branchName); return service.getCommitHistory(defaultApplicationId, branchName) .map(logs -> new ResponseDTO<>(HttpStatus.OK.value(), logs, null)); @@ -130,8 +132,9 @@ public Mono<ResponseDTO<List<GitLogDTO>>> getCommitHistory(@PathVariable String @JsonView(Views.Public.class) @PostMapping("/push/app/{defaultApplicationId}") @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<String>> push(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<String>> push( + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to push application application {}, branch : {}", defaultApplicationId, branchName); return service.pushApplication(defaultApplicationId, branchName) .map(result -> new ResponseDTO<>(HttpStatus.CREATED.value(), result, null)); @@ -140,9 +143,10 @@ public Mono<ResponseDTO<String>> push(@PathVariable String defaultApplicationId, @JsonView(Views.Public.class) @PostMapping("/create-branch/app/{defaultApplicationId}") @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<Application>> createBranch(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String srcBranch, - @RequestBody GitBranchDTO branchDTO) { + public Mono<ResponseDTO<Application>> createBranch( + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String srcBranch, + @RequestBody GitBranchDTO branchDTO) { log.debug("Going to create a branch from root application {}, srcBranch {}", defaultApplicationId, srcBranch); return service.createBranch(defaultApplicationId, branchDTO, srcBranch) .map(result -> new ResponseDTO<>(HttpStatus.CREATED.value(), result, null)); @@ -150,8 +154,9 @@ public Mono<ResponseDTO<Application>> createBranch(@PathVariable String defaultA @JsonView(Views.Public.class) @GetMapping("/checkout-branch/app/{defaultApplicationId}") - public Mono<ResponseDTO<Application>> checkoutBranch(@PathVariable String defaultApplicationId, - @RequestParam(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Application>> checkoutBranch( + @PathVariable String defaultApplicationId, + @RequestParam(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to checkout to branch {} application {} ", branchName, defaultApplicationId); return service.checkoutBranch(defaultApplicationId, branchName) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); @@ -167,8 +172,9 @@ public Mono<ResponseDTO<Application>> disconnectFromRemote(@PathVariable String @JsonView(Views.Public.class) @GetMapping("/pull/app/{defaultApplicationId}") - public Mono<ResponseDTO<GitPullDTO>> pull(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<GitPullDTO>> pull( + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to pull the latest for application {}, branch {}", defaultApplicationId, branchName); return service.pullApplication(defaultApplicationId, branchName) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); @@ -176,9 +182,10 @@ public Mono<ResponseDTO<GitPullDTO>> pull(@PathVariable String defaultApplicatio @JsonView(Views.Public.class) @GetMapping("/branch/app/{defaultApplicationId}") - public Mono<ResponseDTO<List<GitBranchDTO>>> branch(@PathVariable String defaultApplicationId, - @RequestParam(required = false, defaultValue = "false") Boolean pruneBranches, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<List<GitBranchDTO>>> branch( + @PathVariable String defaultApplicationId, + @RequestParam(required = false, defaultValue = "false") Boolean pruneBranches, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get branch list for application {}", defaultApplicationId); return service.listBranchForApplication(defaultApplicationId, BooleanUtils.isTrue(pruneBranches), branchName) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); @@ -186,8 +193,9 @@ public Mono<ResponseDTO<List<GitBranchDTO>>> branch(@PathVariable String default @JsonView(Views.Public.class) @GetMapping("/status/app/{defaultApplicationId}") - public Mono<ResponseDTO<GitStatusDTO>> getStatus(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<GitStatusDTO>> getStatus( + @PathVariable String defaultApplicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to get status for default application {}, branch {}", defaultApplicationId, branchName); return service.getStatus(defaultApplicationId, branchName) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); @@ -195,26 +203,34 @@ public Mono<ResponseDTO<GitStatusDTO>> getStatus(@PathVariable String defaultApp @JsonView(Views.Public.class) @PostMapping("/merge/app/{defaultApplicationId}") - public Mono<ResponseDTO<MergeStatusDTO>> merge(@PathVariable String defaultApplicationId, - @RequestBody GitMergeDTO gitMergeDTO) { - log.debug("Going to merge branch {} with branch {} for application {}", gitMergeDTO.getSourceBranch(), gitMergeDTO.getDestinationBranch(), defaultApplicationId); + public Mono<ResponseDTO<MergeStatusDTO>> merge( + @PathVariable String defaultApplicationId, @RequestBody GitMergeDTO gitMergeDTO) { + log.debug( + "Going to merge branch {} with branch {} for application {}", + gitMergeDTO.getSourceBranch(), + gitMergeDTO.getDestinationBranch(), + defaultApplicationId); return service.mergeBranch(defaultApplicationId, gitMergeDTO) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); } @JsonView(Views.Public.class) @PostMapping("/merge/status/app/{defaultApplicationId}") - public Mono<ResponseDTO<MergeStatusDTO>> mergeStatus(@PathVariable String defaultApplicationId, - @RequestBody GitMergeDTO gitMergeDTO) { - log.debug("Check if branch {} can be merged with branch {} for application {}", gitMergeDTO.getSourceBranch(), gitMergeDTO.getDestinationBranch(), defaultApplicationId); + public Mono<ResponseDTO<MergeStatusDTO>> mergeStatus( + @PathVariable String defaultApplicationId, @RequestBody GitMergeDTO gitMergeDTO) { + log.debug( + "Check if branch {} can be merged with branch {} for application {}", + gitMergeDTO.getSourceBranch(), + gitMergeDTO.getDestinationBranch(), + defaultApplicationId); return service.isBranchMergeable(defaultApplicationId, gitMergeDTO) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); } @JsonView(Views.Public.class) @PostMapping("/conflicted-branch/app/{defaultApplicationId}") - public Mono<ResponseDTO<String>> createConflictedBranch(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME) String branchName) { + public Mono<ResponseDTO<String>> createConflictedBranch( + @PathVariable String defaultApplicationId, @RequestHeader(name = FieldName.BRANCH_NAME) String branchName) { log.debug("Going to create conflicted state branch {} for application {}", branchName, defaultApplicationId); return service.createConflictedBranch(defaultApplicationId, branchName) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); @@ -223,14 +239,13 @@ public Mono<ResponseDTO<String>> createConflictedBranch(@PathVariable String def @JsonView(Views.Public.class) @GetMapping("/import/keys") public Mono<ResponseDTO<GitAuth>> generateKeyForGitImport(@RequestParam(required = false) String keyType) { - return service.generateSSHKey(keyType) - .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); + return service.generateSSHKey(keyType).map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); } @JsonView(Views.Public.class) @PostMapping("/import/{workspaceId}") - public Mono<ResponseDTO<ApplicationImportDTO>> importApplicationFromGit(@PathVariable String workspaceId, - @RequestBody GitConnectDTO gitConnectDTO) { + public Mono<ResponseDTO<ApplicationImportDTO>> importApplicationFromGit( + @PathVariable String workspaceId, @RequestBody GitConnectDTO gitConnectDTO) { return service.importApplicationFromGit(workspaceId, gitConnectDTO) .map(result -> new ResponseDTO<>(HttpStatus.CREATED.value(), result, null)); } @@ -244,7 +259,8 @@ public Mono<ResponseDTO<Boolean>> testGitConnection(@PathVariable String default @JsonView(Views.Public.class) @DeleteMapping("/branch/app/{defaultApplicationId}") - public Mono<ResponseDTO<Application>> deleteBranch(@PathVariable String defaultApplicationId, @RequestParam String branchName) { + public Mono<ResponseDTO<Application>> deleteBranch( + @PathVariable String defaultApplicationId, @RequestParam String branchName) { log.debug("Going to delete branch {} for defaultApplicationId {}", branchName, defaultApplicationId); return service.deleteBranch(defaultApplicationId, branchName) .map(application -> new ResponseDTO<>(HttpStatus.OK.value(), application, null)); @@ -252,9 +268,12 @@ public Mono<ResponseDTO<Application>> deleteBranch(@PathVariable String defaultA @JsonView(Views.Public.class) @PutMapping("/discard/app/{defaultApplicationId}") - public Mono<ResponseDTO<Application>> discardChanges(@PathVariable String defaultApplicationId, - @RequestHeader(name = FieldName.BRANCH_NAME) String branchName) { - log.debug("Going to discard changes for branch {} with defaultApplicationId {}", branchName, defaultApplicationId); + public Mono<ResponseDTO<Application>> discardChanges( + @PathVariable String defaultApplicationId, @RequestHeader(name = FieldName.BRANCH_NAME) String branchName) { + log.debug( + "Going to discard changes for branch {} with defaultApplicationId {}", + branchName, + defaultApplicationId); return service.discardChanges(defaultApplicationId, branchName) .map(result -> new ResponseDTO<>((HttpStatus.OK.value()), result, null)); } @@ -270,8 +289,6 @@ public Mono<ResponseDTO<List<GitDeployKeyDTO>>> getSupportedKeys() { @JsonView(Views.Public.class) @GetMapping("/doc-urls") public Mono<ResponseDTO<List<GitDocsDTO>>> getGitDocs() { - return service.getGitDocUrls() - .map(gitDocDTO -> new ResponseDTO<>(HttpStatus.OK.value(), gitDocDTO, null)); + return service.getGitDocUrls().map(gitDocDTO -> new ResponseDTO<>(HttpStatus.OK.value(), gitDocDTO, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/IndexControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/IndexControllerCE.java index fcc16377f18f..90f49d556ba4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/IndexControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/IndexControllerCE.java @@ -27,9 +27,7 @@ public class IndexControllerCE { @GetMapping public Mono<String> index(Mono<Principal> principal) { Mono<User> userMono = service.getCurrentUser(); - return userMono - .map(obj -> obj.getUsername()) - .map(name -> String.format("Hello %s", name)); + return userMono.map(obj -> obj.getUsername()).map(name -> String.format("Hello %s", name)); } /* @@ -41,5 +39,4 @@ public Mono<String> index(Mono<Principal> principal) { public Mono<Long> pubRedisMessage() { return reactiveTemplate.convertAndSend(topic.getTopic(), "This is a test message"); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/InstanceAdminControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/InstanceAdminControllerCE.java index ba15efa00c06..abde37a48484 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/InstanceAdminControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/InstanceAdminControllerCE.java @@ -33,8 +33,7 @@ public class InstanceAdminControllerCE { @GetMapping("/env") public Mono<ResponseDTO<Map<String, String>>> getAll() { log.debug("Getting all env configuration"); - return envManager.getAllNonEmpty() - .map(data -> new ResponseDTO<>(HttpStatus.OK.value(), data, null)); + return envManager.getAllNonEmpty().map(data -> new ResponseDTO<>(HttpStatus.OK.value(), data, null)); } @JsonView(Views.Public.class) @@ -46,20 +45,20 @@ public Mono<Void> download(ServerWebExchange exchange) { @Deprecated @JsonView(Views.Public.class) - @PutMapping(value = "/env", consumes = {MediaType.APPLICATION_JSON_VALUE}) + @PutMapping( + value = "/env", + consumes = {MediaType.APPLICATION_JSON_VALUE}) public Mono<ResponseDTO<EnvChangesResponseDTO>> saveEnvChangesJSON( - @Valid @RequestBody Map<String, String> changes - ) { + @Valid @RequestBody Map<String, String> changes) { log.debug("Applying env updates {}", changes.keySet()); - return envManager.applyChanges(changes) - .map(res -> new ResponseDTO<>(HttpStatus.OK.value(), res, null)); + return envManager.applyChanges(changes).map(res -> new ResponseDTO<>(HttpStatus.OK.value(), res, null)); } @JsonView(Views.Public.class) - @PutMapping(value = "/env", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) - public Mono<ResponseDTO<EnvChangesResponseDTO>> saveEnvChangesMultipartFormData( - ServerWebExchange exchange - ) { + @PutMapping( + value = "/env", + consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) + public Mono<ResponseDTO<EnvChangesResponseDTO>> saveEnvChangesMultipartFormData(ServerWebExchange exchange) { log.debug("Applying env updates from form data"); return exchange.getMultipartData() .flatMap(envManager::applyChangesFromMultipartFormData) @@ -70,16 +69,13 @@ public Mono<ResponseDTO<EnvChangesResponseDTO>> saveEnvChangesMultipartFormData( @PostMapping("/restart") public Mono<ResponseDTO<Boolean>> restart() { log.debug("Received restart request"); - return envManager.restart() - .thenReturn(new ResponseDTO<>(HttpStatus.OK.value(), true, null)); + return envManager.restart().thenReturn(new ResponseDTO<>(HttpStatus.OK.value(), true, null)); } @JsonView(Views.Public.class) @PostMapping("/send-test-email") public Mono<ResponseDTO<Boolean>> sendTestEmail(@RequestBody @Valid TestEmailConfigRequestDTO requestDTO) { log.debug("Sending test email"); - return envManager.sendTestEmail(requestDTO) - .thenReturn(new ResponseDTO<>(HttpStatus.OK.value(), true, null)); + return envManager.sendTestEmail(requestDTO).thenReturn(new ResponseDTO<>(HttpStatus.OK.value(), true, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ItemControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ItemControllerCE.java index aa63ee208c26..ebec2abd5ec5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ItemControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ItemControllerCE.java @@ -33,15 +33,19 @@ public ItemControllerCE(ItemService service) { @GetMapping("") public Mono<ResponseDTO<List<ItemDTO>>> getAll(@RequestParam MultiValueMap<String, String> params) { log.debug("Going to get all items by parameters " + params); - return service.get(params).collectList() + return service.get(params) + .collectList() .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @JsonView(Views.Public.class) @PostMapping("/addToPage") public Mono<ResponseDTO<ActionDTO>> addItemToPage(@RequestBody AddItemToPageDTO addItemToPageDTO) { - log.debug("Going to add item {} to page {} with new name {}", addItemToPageDTO.getMarketplaceElement().getItem().getName(), - addItemToPageDTO.getPageId(), addItemToPageDTO.getName()); + log.debug( + "Going to add item {} to page {} with new name {}", + addItemToPageDTO.getMarketplaceElement().getItem().getName(), + addItemToPageDTO.getPageId(), + addItemToPageDTO.getName()); return service.addItemToPage(addItemToPageDTO) .map(action -> new ResponseDTO<>(HttpStatus.CREATED.value(), action, null)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/LayoutControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/LayoutControllerCE.java index b6b6b51a6eaa..7405c97e505d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/LayoutControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/LayoutControllerCE.java @@ -26,7 +26,6 @@ import org.springframework.web.bind.annotation.RequestParam; import reactor.core.publisher.Mono; - @RequestMapping(Url.LAYOUT_URL) @Slf4j public class LayoutControllerCE { @@ -37,9 +36,10 @@ public class LayoutControllerCE { private final RefactoringSolution refactoringSolution; @Autowired - public LayoutControllerCE(LayoutService layoutService, - LayoutActionService layoutActionService, - RefactoringSolution refactoringSolution) { + public LayoutControllerCE( + LayoutService layoutService, + LayoutActionService layoutActionService, + RefactoringSolution refactoringSolution) { this.service = layoutService; this.layoutActionService = layoutActionService; this.refactoringSolution = refactoringSolution; @@ -47,60 +47,67 @@ public LayoutControllerCE(LayoutService layoutService, @JsonView(Views.Public.class) @PostMapping("/pages/{defaultPageId}") - public Mono<ResponseDTO<Layout>> createLayout(@PathVariable String defaultPageId, - @Valid @RequestBody Layout layout, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Layout>> createLayout( + @PathVariable String defaultPageId, + @Valid @RequestBody Layout layout, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { return service.createLayout(defaultPageId, layout, branchName) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @JsonView(Views.Public.class) @GetMapping("/{layoutId}/pages/{defaultPageId}") - public Mono<ResponseDTO<Layout>> getLayout(@PathVariable String defaultPageId, - @PathVariable String layoutId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Layout>> getLayout( + @PathVariable String defaultPageId, + @PathVariable String layoutId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { return service.getLayout(defaultPageId, layoutId, false, branchName) .map(created -> new ResponseDTO<>(HttpStatus.OK.value(), created, null)); } @JsonView(Views.Public.class) @PutMapping("/application/{applicationId}") - public Mono<ResponseDTO<Integer>> updateMultipleLayouts(@PathVariable String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestBody @Valid UpdateMultiplePageLayoutDTO request) { + public Mono<ResponseDTO<Integer>> updateMultipleLayouts( + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestBody @Valid UpdateMultiplePageLayoutDTO request) { log.debug("update multiple layout received for application {} branch {}", applicationId, branchName); - return layoutActionService.updateMultipleLayouts(applicationId, branchName, request) + return layoutActionService + .updateMultipleLayouts(applicationId, branchName, request) .map(updatedCount -> new ResponseDTO<>(HttpStatus.OK.value(), updatedCount, null)); } @JsonView(Views.Public.class) @PutMapping("/{layoutId}/pages/{pageId}") - public Mono<ResponseDTO<LayoutDTO>> updateLayout(@PathVariable String pageId, - @RequestParam String applicationId, - @PathVariable String layoutId, - @RequestBody Layout layout, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<LayoutDTO>> updateLayout( + @PathVariable String pageId, + @RequestParam String applicationId, + @PathVariable String layoutId, + @RequestBody Layout layout, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("update layout received for page {}", pageId); - return layoutActionService.updateLayout(pageId, applicationId, layoutId, layout, branchName) + return layoutActionService + .updateLayout(pageId, applicationId, layoutId, layout, branchName) .map(created -> new ResponseDTO<>(HttpStatus.OK.value(), created, null)); } @JsonView(Views.Public.class) @GetMapping("/{layoutId}/pages/{pageId}/view") - public Mono<ResponseDTO<Layout>> getLayoutView(@PathVariable String pageId, - @PathVariable String layoutId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Layout>> getLayoutView( + @PathVariable String pageId, + @PathVariable String layoutId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { return service.getLayout(pageId, layoutId, true, branchName) .map(created -> new ResponseDTO<>(HttpStatus.OK.value(), created, null)); } @JsonView(Views.Public.class) @PutMapping("/refactor") - public Mono<ResponseDTO<LayoutDTO>> refactorWidgetName(@RequestBody RefactorNameDTO refactorNameDTO, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return refactoringSolution.refactorWidgetName(refactorNameDTO, branchName) + public Mono<ResponseDTO<LayoutDTO>> refactorWidgetName( + @RequestBody RefactorNameDTO refactorNameDTO, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return refactoringSolution + .refactorWidgetName(refactorNameDTO, branchName) .map(created -> new ResponseDTO<>(HttpStatus.OK.value(), created, null)); } - - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/MarketplaceControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/MarketplaceControllerCE.java index d61560df1ba0..c7783ad2e0dc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/MarketplaceControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/MarketplaceControllerCE.java @@ -21,42 +21,44 @@ import java.util.List; - @RequestMapping(Url.MARKETPLACE_URL) @Slf4j public class MarketplaceControllerCE { private final MarketplaceService marketplaceService; - public MarketplaceControllerCE(ObjectMapper objectMapper, - MarketplaceService marketplaceService) { + public MarketplaceControllerCE(ObjectMapper objectMapper, MarketplaceService marketplaceService) { this.marketplaceService = marketplaceService; } @JsonView(Views.Public.class) @GetMapping("/search") - Mono<ResponseDTO<SearchResponseDTO>> searchAPIOrProviders(@RequestParam String searchKey, @RequestParam(required = false) Integer limit) { + Mono<ResponseDTO<SearchResponseDTO>> searchAPIOrProviders( + @RequestParam String searchKey, @RequestParam(required = false) Integer limit) { - return marketplaceService.searchProviderByName(searchKey) - .map(result -> { - SearchResponseDTO searchResponseDTO = new SearchResponseDTO(); - searchResponseDTO.setProviders(result); - return new ResponseDTO<>(HttpStatus.OK.value(), searchResponseDTO, null); - }); + return marketplaceService.searchProviderByName(searchKey).map(result -> { + SearchResponseDTO searchResponseDTO = new SearchResponseDTO(); + searchResponseDTO.setProviders(result); + return new ResponseDTO<>(HttpStatus.OK.value(), searchResponseDTO, null); + }); } @JsonView(Views.Public.class) @GetMapping("/templates") - public Mono<ResponseDTO<List<ApiTemplate>>> getAllTemplatesFromMarketplace(@RequestParam MultiValueMap<String, String> params) { + public Mono<ResponseDTO<List<ApiTemplate>>> getAllTemplatesFromMarketplace( + @RequestParam MultiValueMap<String, String> params) { log.debug("Going to get all templates from Marketplace"); - return marketplaceService.getTemplates(params) + return marketplaceService + .getTemplates(params) .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @JsonView(Views.Public.class) @GetMapping("/providers") - public Mono<ResponseDTO<ProviderPaginatedDTO>> getAllProvidersFromMarketplace(@RequestParam MultiValueMap<String, String> params) { + public Mono<ResponseDTO<ProviderPaginatedDTO>> getAllProvidersFromMarketplace( + @RequestParam MultiValueMap<String, String> params) { log.debug("Going to get all providers from Marketplace"); - return marketplaceService.getProviders(params) + return marketplaceService + .getProviders(params) .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @@ -64,7 +66,8 @@ public Mono<ResponseDTO<ProviderPaginatedDTO>> getAllProvidersFromMarketplace(@R @GetMapping("/providers/{id}") public Mono<ResponseDTO<Provider>> getProviderByIdFromMarketplace(@PathVariable String id) { log.debug("Going to get provider from Marketplace with id {}", id); - return marketplaceService.getProviderById(id) + return marketplaceService + .getProviderById(id) .map(resource -> new ResponseDTO<>(HttpStatus.OK.value(), resource, null)); } @@ -72,8 +75,8 @@ public Mono<ResponseDTO<Provider>> getProviderByIdFromMarketplace(@PathVariable @GetMapping("/categories") public Mono<ResponseDTO<List<String>>> getAllCategoriesFromMarketplace() { log.debug("Going to get all categories from Marketplace"); - return marketplaceService.getCategories() + return marketplaceService + .getCategories() .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/NotificationControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/NotificationControllerCE.java index ed2aadc74d12..a23b94dd0de7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/NotificationControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/NotificationControllerCE.java @@ -32,8 +32,7 @@ public NotificationControllerCE(NotificationService service) { @JsonView(Views.Public.class) @GetMapping("count/unread") public Mono<ResponseDTO<Long>> getUnreadCount() { - return service.getUnreadCount() - .map(response -> new ResponseDTO<>(HttpStatus.OK.value(), response, null)); + return service.getUnreadCount().map(response -> new ResponseDTO<>(HttpStatus.OK.value(), response, null)); } @JsonView(Views.Public.class) @@ -41,9 +40,7 @@ public Mono<ResponseDTO<Long>> getUnreadCount() { public Mono<ResponseDTO<UpdateIsReadNotificationByIdDTO>> updateIsRead( @RequestBody @Valid UpdateIsReadNotificationByIdDTO body) { log.debug("Going to set isRead to notifications by id"); - return service.updateIsRead(body).map( - dto -> new ResponseDTO<>(HttpStatus.OK.value(), dto, null, true) - ); + return service.updateIsRead(body).map(dto -> new ResponseDTO<>(HttpStatus.OK.value(), dto, null, true)); } @JsonView(Views.Public.class) @@ -51,13 +48,12 @@ public Mono<ResponseDTO<UpdateIsReadNotificationByIdDTO>> updateIsRead( public Mono<ResponseDTO<UpdateIsReadNotificationDTO>> updateIsRead( @RequestBody @Valid UpdateIsReadNotificationDTO body) { log.debug("Going to set isRead to all notifications"); - return service.updateIsRead(body).map( - dto -> new ResponseDTO<>(HttpStatus.OK.value(), dto, null, true) - ); + return service.updateIsRead(body).map(dto -> new ResponseDTO<>(HttpStatus.OK.value(), dto, null, true)); } @Override - public Mono<ResponseDTO<Notification>> create(Notification resource, String originHeader, ServerWebExchange exchange) { + public Mono<ResponseDTO<Notification>> create( + Notification resource, String originHeader, ServerWebExchange exchange) { return Mono.error(new AppsmithException(UNSUPPORTED_OPERATION)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/PageControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/PageControllerCE.java index f84ca4764e23..d9c61f243393 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/PageControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/PageControllerCE.java @@ -33,7 +33,6 @@ import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; - @RequestMapping(Url.PAGE_URL) @Slf4j public class PageControllerCE { @@ -43,10 +42,10 @@ public class PageControllerCE { private final CreateDBTablePageSolution createDBTablePageSolution; @Autowired - public PageControllerCE(ApplicationPageService applicationPageService, - NewPageService newPageService, - CreateDBTablePageSolution createDBTablePageSolution - ) { + public PageControllerCE( + ApplicationPageService applicationPageService, + NewPageService newPageService, + CreateDBTablePageSolution createDBTablePageSolution) { this.applicationPageService = applicationPageService; this.newPageService = newPageService; this.createDBTablePageSolution = createDBTablePageSolution; @@ -55,76 +54,90 @@ public PageControllerCE(ApplicationPageService applicationPageService, @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<PageDTO>> createPage(@Valid @RequestBody PageDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = "Origin", required = false) String originHeader, - ServerWebExchange exchange) { + public Mono<ResponseDTO<PageDTO>> createPage( + @Valid @RequestBody PageDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = "Origin", required = false) String originHeader, + ServerWebExchange exchange) { log.debug("Going to create resource {}", resource.getClass().getName()); - return applicationPageService.createPageWithBranchName(resource, branchName) + return applicationPageService + .createPageWithBranchName(resource, branchName) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @JsonView(Views.Public.class) @PostMapping("/crud-page") @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<CRUDPageResponseDTO>> createCRUDPage(@RequestBody @NonNull CRUDPageResourceDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { - log.debug("Going to create crud-page in application {}, branchName {}", resource.getApplicationId(), branchName); - return createDBTablePageSolution.createPageFromDBTable(null, resource, environmentId, branchName, Boolean.TRUE) + public Mono<ResponseDTO<CRUDPageResponseDTO>> createCRUDPage( + @RequestBody @NonNull CRUDPageResourceDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + log.debug( + "Going to create crud-page in application {}, branchName {}", resource.getApplicationId(), branchName); + return createDBTablePageSolution + .createPageFromDBTable(null, resource, environmentId, branchName, Boolean.TRUE) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @JsonView(Views.Public.class) @PutMapping("/crud-page/{defaultPageId}") @ResponseStatus(HttpStatus.OK) - public Mono<ResponseDTO<CRUDPageResponseDTO>> createCRUDPage(@PathVariable String defaultPageId, - @NonNull @RequestBody CRUDPageResourceDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + public Mono<ResponseDTO<CRUDPageResponseDTO>> createCRUDPage( + @PathVariable String defaultPageId, + @NonNull @RequestBody CRUDPageResourceDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { log.debug("Going to create CRUD page {}, branchName {}", defaultPageId, branchName); - return createDBTablePageSolution.createPageFromDBTable(defaultPageId, resource, environmentId, branchName, Boolean.TRUE) + return createDBTablePageSolution + .createPageFromDBTable(defaultPageId, resource, environmentId, branchName, Boolean.TRUE) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @Deprecated @JsonView(Views.Public.class) @GetMapping("/application/{applicationId}") - public Mono<ResponseDTO<ApplicationPagesDTO>> getPageNamesByApplicationId(@PathVariable String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return newPageService.findApplicationPagesByApplicationIdViewModeAndBranch(applicationId, branchName, false, true) + public Mono<ResponseDTO<ApplicationPagesDTO>> getPageNamesByApplicationId( + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return newPageService + .findApplicationPagesByApplicationIdViewModeAndBranch(applicationId, branchName, false, true) .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @JsonView(Views.Public.class) @GetMapping("/view/application/{applicationId}") - public Mono<ResponseDTO<ApplicationPagesDTO>> getPageNamesByApplicationIdInViewMode(@PathVariable String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return newPageService.findApplicationPagesByApplicationIdViewModeAndBranch(applicationId, branchName, true, true) + public Mono<ResponseDTO<ApplicationPagesDTO>> getPageNamesByApplicationIdInViewMode( + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return newPageService + .findApplicationPagesByApplicationIdViewModeAndBranch(applicationId, branchName, true, true) .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } @JsonView(Views.Public.class) @GetMapping("/{defaultPageId}") - public Mono<ResponseDTO<PageDTO>> getPageById(@PathVariable String defaultPageId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return applicationPageService.getPageByBranchAndDefaultPageId(defaultPageId, branchName, false) + public Mono<ResponseDTO<PageDTO>> getPageById( + @PathVariable String defaultPageId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return applicationPageService + .getPageByBranchAndDefaultPageId(defaultPageId, branchName, false) .map(page -> new ResponseDTO<>(HttpStatus.OK.value(), page, null)); } - @JsonView(Views.Public.class) @GetMapping("/{defaultPageId}/view") - public Mono<ResponseDTO<PageDTO>> getPageView(@PathVariable String defaultPageId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return applicationPageService.getPageByBranchAndDefaultPageId(defaultPageId, branchName, true) + public Mono<ResponseDTO<PageDTO>> getPageView( + @PathVariable String defaultPageId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return applicationPageService + .getPageByBranchAndDefaultPageId(defaultPageId, branchName, true) .map(page -> new ResponseDTO<>(HttpStatus.OK.value(), page, null)); } @JsonView(Views.Public.class) @GetMapping("{pageName}/application/{applicationName}/view") - public Mono<ResponseDTO<PageDTO>> getPageViewByName(@PathVariable String applicationName, - @PathVariable String pageName) { + public Mono<ResponseDTO<PageDTO>> getPageViewByName( + @PathVariable String applicationName, @PathVariable String pageName) { return Mono.error(new AppsmithException(AppsmithError.DEPRECATED_API)); } @@ -140,28 +153,34 @@ public Mono<ResponseDTO<PageDTO>> getPageViewByName(@PathVariable String applica */ @JsonView(Views.Public.class) @DeleteMapping("/{defaultPageId}") - public Mono<ResponseDTO<PageDTO>> deletePage(@PathVariable String defaultPageId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<PageDTO>> deletePage( + @PathVariable String defaultPageId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to delete page with id: {}, branchName: {}", defaultPageId, branchName); - return applicationPageService.deleteUnpublishedPageByBranchAndDefaultPageId(defaultPageId, branchName) + return applicationPageService + .deleteUnpublishedPageByBranchAndDefaultPageId(defaultPageId, branchName) .map(deletedResource -> new ResponseDTO<>(HttpStatus.OK.value(), deletedResource, null)); } @JsonView(Views.Public.class) @PostMapping("/clone/{defaultPageId}") - public Mono<ResponseDTO<PageDTO>> clonePage(@PathVariable String defaultPageId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return applicationPageService.clonePageByDefaultPageIdAndBranch(defaultPageId, branchName) + public Mono<ResponseDTO<PageDTO>> clonePage( + @PathVariable String defaultPageId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return applicationPageService + .clonePageByDefaultPageIdAndBranch(defaultPageId, branchName) .map(page -> new ResponseDTO<>(HttpStatus.CREATED.value(), page, null)); } @JsonView(Views.Public.class) @PutMapping("/{defaultPageId}") - public Mono<ResponseDTO<PageDTO>> updatePage(@PathVariable String defaultPageId, - @RequestBody PageDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<PageDTO>> updatePage( + @PathVariable String defaultPageId, + @RequestBody PageDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to update page with id: {}, branchName: {}", defaultPageId, branchName); - return newPageService.updatePageByDefaultPageIdAndBranch(defaultPageId, resource, branchName) + return newPageService + .updatePageByDefaultPageIdAndBranch(defaultPageId, resource, branchName) .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); } @@ -179,12 +198,19 @@ public Mono<ResponseDTO<PageDTO>> updatePage(@PathVariable String defaultPageId, */ @JsonView(Views.Public.class) @GetMapping - public Mono<ResponseDTO<ApplicationPagesDTO>> getAllPages(@RequestParam(required = false) String applicationId, - @RequestParam(required = false) String pageId, - @RequestParam(required = true, defaultValue = "EDIT") ApplicationMode mode, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - log.debug("Going to fetch applicationPageDTO for applicationId: {}, pageId: {}, branchName: {}, mode: {}", applicationId, pageId, branchName, mode); - return newPageService.findApplicationPages(applicationId, pageId, branchName, mode) + public Mono<ResponseDTO<ApplicationPagesDTO>> getAllPages( + @RequestParam(required = false) String applicationId, + @RequestParam(required = false) String pageId, + @RequestParam(required = true, defaultValue = "EDIT") ApplicationMode mode, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + log.debug( + "Going to fetch applicationPageDTO for applicationId: {}, pageId: {}, branchName: {}, mode: {}", + applicationId, + pageId, + branchName, + mode); + return newPageService + .findApplicationPages(applicationId, pageId, branchName, mode) .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/PluginControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/PluginControllerCE.java index 1709abca8da8..842b1e950d73 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/PluginControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/PluginControllerCE.java @@ -21,7 +21,6 @@ import java.util.List; - @RequestMapping(Url.PLUGIN_URL) public class PluginControllerCE extends BaseController<PluginService, Plugin, String> { @@ -49,8 +48,7 @@ public Mono<ResponseDTO<Workspace>> uninstall(@Valid @RequestBody PluginWorkspac @JsonView(Views.Public.class) @GetMapping("/{pluginId}/form") public Mono<ResponseDTO<Object>> getDatasourceForm(@PathVariable String pluginId) { - return service.getFormConfig(pluginId) - .map(form -> new ResponseDTO<>(HttpStatus.OK.value(), form, null)); + return service.getFormConfig(pluginId).map(form -> new ResponseDTO<>(HttpStatus.OK.value(), form, null)); } @JsonView(Views.Public.class) diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ProviderControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ProviderControllerCE.java index f46e7d2555ba..94703b218308 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ProviderControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ProviderControllerCE.java @@ -14,7 +14,6 @@ import java.util.List; - @RequestMapping(Url.PROVIDER_URL) @Slf4j public class ProviderControllerCE extends BaseController<ProviderService, Provider, String> { @@ -25,7 +24,6 @@ public ProviderControllerCE(ProviderService service) { @JsonView(Views.Public.class) @GetMapping("/categories") public Mono<ResponseDTO<List<String>>> getAllCategories() { - return service.getAllCategories() - .map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); + return service.getAllCategories().map(resources -> new ResponseDTO<>(HttpStatus.OK.value(), resources, null)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/RestApiImportControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/RestApiImportControllerCE.java index 11efba6568b6..dcdc2e0447eb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/RestApiImportControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/RestApiImportControllerCE.java @@ -26,7 +26,6 @@ import java.util.List; - @RequestMapping(Url.IMPORT_URL) @Slf4j public class RestApiImportControllerCE { @@ -34,8 +33,8 @@ public class RestApiImportControllerCE { private final CurlImporterService curlImporterService; private final PostmanImporterService postmanImporterService; - public RestApiImportControllerCE(CurlImporterService curlImporterService, - PostmanImporterService postmanImporterService) { + public RestApiImportControllerCE( + CurlImporterService curlImporterService, PostmanImporterService postmanImporterService) { this.curlImporterService = curlImporterService; this.postmanImporterService = postmanImporterService; } @@ -43,14 +42,14 @@ public RestApiImportControllerCE(CurlImporterService curlImporterService, @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<ActionDTO>> create(@RequestBody(required = false) Object input, - @RequestParam RestApiImporterType type, - @RequestParam String pageId, - @RequestParam String name, - @RequestParam String workspaceId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = "Origin", required = false) String originHeader - ) { + public Mono<ResponseDTO<ActionDTO>> create( + @RequestBody(required = false) Object input, + @RequestParam RestApiImporterType type, + @RequestParam String pageId, + @RequestParam String name, + @RequestParam String workspaceId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = "Origin", required = false) String originHeader) { log.debug("Going to import API"); ApiImporter service; @@ -69,8 +68,8 @@ public Mono<ResponseDTO<ActionDTO>> create(@RequestBody(required = false) Object @JsonView(Views.Public.class) @PostMapping("/postman") @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<TemplateCollection>> importPostmanCollection(@RequestBody Object input, - @RequestParam String type) { + public Mono<ResponseDTO<TemplateCollection>> importPostmanCollection( + @RequestBody Object input, @RequestParam String type) { return Mono.just(postmanImporterService.importPostmanCollection(input)) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @@ -88,5 +87,4 @@ public Mono<ResponseDTO<TemplateCollection>> deletePostmanCollection(@PathVariab return Mono.just(postmanImporterService.deletePostmanCollection(id)) .map(deleted -> new ResponseDTO<>(HttpStatus.OK.value(), deleted, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/SaasControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/SaasControllerCE.java index 66dad23b20d1..a173360ff24d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/SaasControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/SaasControllerCE.java @@ -31,15 +31,18 @@ public SaasControllerCE(AuthenticationService authenticationService) { @JsonView(Views.Public.class) @PostMapping("/{datasourceId}/pages/{pageId}/oauth") - public Mono<ResponseDTO<String>> getAppsmithToken(@PathVariable String datasourceId, - @PathVariable String pageId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId, - @RequestParam(required = false) String importForGit, - ServerWebExchange serverWebExchange) { + public Mono<ResponseDTO<String>> getAppsmithToken( + @PathVariable String datasourceId, + @PathVariable String pageId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId, + @RequestParam(required = false) String importForGit, + ServerWebExchange serverWebExchange) { - log.debug("Going to retrieve token request URL for datasource with id: {} and page id: {}", datasourceId, pageId); - return authenticationService.getAppsmithToken( + log.debug( + "Going to retrieve token request URL for datasource with id: {} and page id: {}", datasourceId, pageId); + return authenticationService + .getAppsmithToken( datasourceId, environmentId, pageId, @@ -52,14 +55,15 @@ public Mono<ResponseDTO<String>> getAppsmithToken(@PathVariable String datasourc @JsonView(Views.Public.class) @PostMapping("/{datasourceId}/token") - public Mono<ResponseDTO<OAuth2ResponseDTO>> getAccessToken(@PathVariable String datasourceId, - @RequestParam String appsmithToken, - @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId, - ServerWebExchange serverWebExchange) { + public Mono<ResponseDTO<OAuth2ResponseDTO>> getAccessToken( + @PathVariable String datasourceId, + @RequestParam String appsmithToken, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId, + ServerWebExchange serverWebExchange) { log.debug("Received callback for an OAuth2 authorization request"); - return authenticationService.getAccessTokenFromCloud(datasourceId, environmentId, appsmithToken, Boolean.TRUE) + return authenticationService + .getAccessTokenFromCloud(datasourceId, environmentId, appsmithToken, Boolean.TRUE) .map(datasource -> new ResponseDTO<>(HttpStatus.OK.value(), datasource, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/TenantControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/TenantControllerCE.java index ee752232da5d..e4b4cbc0ba4c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/TenantControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/TenantControllerCE.java @@ -46,5 +46,4 @@ public Mono<ResponseDTO<Tenant>> updateTenantConfiguration(@RequestBody TenantCo return service.updateDefaultTenantConfiguration(tenantConfiguration) .map(tenant -> new ResponseDTO<>(HttpStatus.OK.value(), tenant, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ThemeControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ThemeControllerCE.java index 8683bda17667..1c0a1b1d9ce7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ThemeControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ThemeControllerCE.java @@ -40,35 +40,40 @@ public Mono<ResponseDTO<Theme>> create(Theme resource, String originHeader, Serv @JsonView(Views.Public.class) @GetMapping("applications/{applicationId}") - public Mono<ResponseDTO<List<Theme>>> getApplicationThemes(@PathVariable String applicationId, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { - return service.getApplicationThemes(applicationId, branchName).collectList() + public Mono<ResponseDTO<List<Theme>>> getApplicationThemes( + @PathVariable String applicationId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return service.getApplicationThemes(applicationId, branchName) + .collectList() .map(themes -> new ResponseDTO<>(HttpStatus.OK.value(), themes, null)); } @JsonView(Views.Public.class) @GetMapping("applications/{applicationId}/current") - public Mono<ResponseDTO<Theme>> getCurrentTheme(@PathVariable String applicationId, - @RequestParam(required = false, defaultValue = "EDIT") ApplicationMode mode, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Theme>> getCurrentTheme( + @PathVariable String applicationId, + @RequestParam(required = false, defaultValue = "EDIT") ApplicationMode mode, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { return service.getApplicationTheme(applicationId, mode, branchName) .map(theme -> new ResponseDTO<>(HttpStatus.OK.value(), theme, null)); } @JsonView(Views.Public.class) @PutMapping("applications/{applicationId}") - public Mono<ResponseDTO<Theme>> updateTheme(@PathVariable String applicationId, - @Valid @RequestBody Theme resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Theme>> updateTheme( + @PathVariable String applicationId, + @Valid @RequestBody Theme resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { return service.updateTheme(applicationId, branchName, resource) .map(theme -> new ResponseDTO<>(HttpStatus.OK.value(), theme, null)); } @JsonView(Views.Public.class) @PatchMapping("applications/{applicationId}") - public Mono<ResponseDTO<Theme>> publishCurrentTheme(@PathVariable String applicationId, - @RequestBody Theme resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + public Mono<ResponseDTO<Theme>> publishCurrentTheme( + @PathVariable String applicationId, + @RequestBody Theme resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { return service.persistCurrentTheme(applicationId, branchName, resource) .map(theme -> new ResponseDTO<>(HttpStatus.OK.value(), theme, null)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/UsagePulseControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/UsagePulseControllerCE.java index 49ff17abb526..3c82234eba7e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/UsagePulseControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/UsagePulseControllerCE.java @@ -25,8 +25,6 @@ public class UsagePulseControllerCE { @PostMapping @ResponseStatus(HttpStatus.CREATED) public Mono<ResponseDTO<Boolean>> create(@RequestBody @Valid UsagePulseDTO usagePulseDTO) { - return service.createPulse(usagePulseDTO) - .thenReturn(new ResponseDTO<>(HttpStatus.CREATED.value(), true, null)); + return service.createPulse(usagePulseDTO).thenReturn(new ResponseDTO<>(HttpStatus.CREATED.value(), true, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/UserControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/UserControllerCE.java index b47062e322eb..5790f061fdd8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/UserControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/UserControllerCE.java @@ -40,7 +40,6 @@ import java.util.List; import java.util.Map; - @RequestMapping(Url.USER_URL) @Slf4j public class UserControllerCE extends BaseController<UserService, User, String> { @@ -52,12 +51,13 @@ public class UserControllerCE extends BaseController<UserService, User, String> private final UserAndAccessManagementService userAndAccessManagementService; @Autowired - public UserControllerCE(UserService service, - SessionUserService sessionUserService, - UserWorkspaceService userWorkspaceService, - UserSignup userSignup, - UserDataService userDataService, - UserAndAccessManagementService userAndAccessManagementService) { + public UserControllerCE( + UserService service, + SessionUserService sessionUserService, + UserWorkspaceService userWorkspaceService, + UserSignup userSignup, + UserDataService userDataService, + UserAndAccessManagementService userAndAccessManagementService) { super(service); this.sessionUserService = sessionUserService; this.userWorkspaceService = userWorkspaceService; @@ -69,10 +69,12 @@ public UserControllerCE(UserService service, @JsonView(Views.Public.class) @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE}) @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<User>> create(@Valid @RequestBody User resource, - @RequestHeader(name = "Origin", required = false) String originHeader, - ServerWebExchange exchange) { - return userSignup.signupAndLogin(resource, exchange) + public Mono<ResponseDTO<User>> create( + @Valid @RequestBody User resource, + @RequestHeader(name = "Origin", required = false) String originHeader, + ServerWebExchange exchange) { + return userSignup + .signupAndLogin(resource, exchange) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @@ -84,17 +86,20 @@ public Mono<Void> createFormEncoded(ServerWebExchange exchange) { } @JsonView(Views.Public.class) - @PostMapping(value = "/super", consumes = {MediaType.APPLICATION_JSON_VALUE}) + @PostMapping( + value = "/super", + consumes = {MediaType.APPLICATION_JSON_VALUE}) public Mono<ResponseDTO<User>> createSuperUser( - @Valid @RequestBody UserSignupRequestDTO resource, - ServerWebExchange exchange - ) { - return userSignup.signupAndLoginSuper(resource, exchange) + @Valid @RequestBody UserSignupRequestDTO resource, ServerWebExchange exchange) { + return userSignup + .signupAndLoginSuper(resource, exchange) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } @JsonView(Views.Public.class) - @PostMapping(value = "/super", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) + @PostMapping( + value = "/super", + consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) public Mono<Void> createSuperUserFromFormData(ServerWebExchange exchange) { return userSignup.signupAndLoginSuperFromFormData(exchange); } @@ -109,7 +114,8 @@ public Mono<ResponseDTO<User>> update(@RequestBody UserUpdateDTO updates, Server @JsonView(Views.Public.class) @PutMapping("/leaveWorkspace/{workspaceId}") public Mono<ResponseDTO<User>> leaveWorkspace(@PathVariable String workspaceId) { - return userWorkspaceService.leaveWorkspace(workspaceId) + return userWorkspaceService + .leaveWorkspace(workspaceId) .map(user -> new ResponseDTO<>(HttpStatus.OK.value(), user, null)); } @@ -123,8 +129,8 @@ public Mono<ResponseDTO<User>> leaveWorkspace(@PathVariable String workspaceId) */ @JsonView(Views.Public.class) @PostMapping("/forgotPassword") - public Mono<ResponseDTO<Boolean>> forgotPasswordRequest(@RequestBody ResetUserPasswordDTO userPasswordDTO, - @RequestHeader("Origin") String originHeader) { + public Mono<ResponseDTO<Boolean>> forgotPasswordRequest( + @RequestBody ResetUserPasswordDTO userPasswordDTO, @RequestHeader("Origin") String originHeader) { userPasswordDTO.setBaseUrl(originHeader); // We shouldn't leak information on whether this operation was successful or not to the client. This can enable // username scraping, where the response of this API can prove whether an email has an account or not. @@ -143,7 +149,8 @@ public Mono<ResponseDTO<Boolean>> verifyPasswordResetToken(@RequestParam String @JsonView(Views.Public.class) @PutMapping("/resetPassword") - public Mono<ResponseDTO<Boolean>> resetPasswordAfterForgotPassword(@RequestBody ResetUserPasswordDTO userPasswordDTO) { + public Mono<ResponseDTO<Boolean>> resetPasswordAfterForgotPassword( + @RequestBody ResetUserPasswordDTO userPasswordDTO) { return service.resetPasswordAfterForgotPassword(userPasswordDTO.getToken(), userPasswordDTO) .map(result -> new ResponseDTO<>(HttpStatus.OK.value(), result, null)); } @@ -151,7 +158,8 @@ public Mono<ResponseDTO<Boolean>> resetPasswordAfterForgotPassword(@RequestBody @JsonView(Views.Public.class) @GetMapping("/me") public Mono<ResponseDTO<UserProfileDTO>> getUserProfile() { - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .flatMap(service::buildUserProfileDTO) .map(profile -> new ResponseDTO<>(HttpStatus.OK.value(), profile, null)); } @@ -166,16 +174,18 @@ public Mono<ResponseDTO<UserProfileDTO>> getUserProfile() { */ @JsonView(Views.Public.class) @PostMapping("/invite") - public Mono<ResponseDTO<List<User>>> inviteUsers(@RequestBody InviteUsersDTO inviteUsersDTO, - @RequestHeader("Origin") String originHeader) { - return userAndAccessManagementService.inviteUsers(inviteUsersDTO, originHeader) + public Mono<ResponseDTO<List<User>>> inviteUsers( + @RequestBody InviteUsersDTO inviteUsersDTO, @RequestHeader("Origin") String originHeader) { + return userAndAccessManagementService + .inviteUsers(inviteUsersDTO, originHeader) .map(users -> new ResponseDTO<>(HttpStatus.OK.value(), users, null)); } @JsonView(Views.Public.class) @PutMapping("/setReleaseNotesViewed") public Mono<ResponseDTO<Void>> setReleaseNotesViewed() { - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .flatMap(userDataService::setViewedCurrentVersionReleaseNotes) .thenReturn(new ResponseDTO<>(HttpStatus.OK.value(), null, null)); } @@ -183,8 +193,7 @@ public Mono<ResponseDTO<Void>> setReleaseNotesViewed() { @JsonView(Views.Public.class) @PostMapping(value = "/photo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public Mono<ResponseDTO<UserData>> uploadProfilePhoto(@RequestPart("file") Mono<Part> fileMono) { - return fileMono - .flatMap(userDataService::saveProfilePhoto) + return fileMono.flatMap(userDataService::saveProfilePhoto) .map(url -> new ResponseDTO<>(HttpStatus.OK.value(), url, null)); } @@ -199,25 +208,24 @@ public Mono<ResponseDTO<Void>> deleteProfilePhoto() { @JsonView(Views.Public.class) @GetMapping("/photo") public Mono<Void> getProfilePhoto(ServerWebExchange exchange) { - return userDataService.makeProfilePhotoResponse(exchange) - .switchIfEmpty(Mono.fromRunnable(() -> { - exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); - })); + return userDataService.makeProfilePhotoResponse(exchange).switchIfEmpty(Mono.fromRunnable(() -> { + exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); + })); } @JsonView(Views.Public.class) @GetMapping("/photo/{email}") public Mono<Void> getProfilePhoto(ServerWebExchange exchange, @PathVariable String email) { - return userDataService.makeProfilePhotoResponse(exchange, email) - .switchIfEmpty(Mono.fromRunnable(() -> { - exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); - })); + return userDataService.makeProfilePhotoResponse(exchange, email).switchIfEmpty(Mono.fromRunnable(() -> { + exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); + })); } @JsonView(Views.Public.class) @GetMapping("/features") public Mono<ResponseDTO<Map<String, Boolean>>> getFeatureFlags() { - return userDataService.getFeatureFlagsForCurrentUser() + return userDataService + .getFeatureFlagsForCurrentUser() .map(map -> new ResponseDTO<>(HttpStatus.OK.value(), map, null)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/WorkspaceControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/WorkspaceControllerCE.java index 46d7dd80c093..f0089c2fd091 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/WorkspaceControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/WorkspaceControllerCE.java @@ -26,7 +26,6 @@ import java.util.List; - @RequestMapping(Url.WORKSPACE_URL) public class WorkspaceControllerCE extends BaseController<WorkspaceService, Workspace, String> { private final UserWorkspaceService userWorkspaceService; @@ -44,7 +43,8 @@ public WorkspaceControllerCE(WorkspaceService workspaceService, UserWorkspaceSer */ @JsonView(Views.Public.class) @GetMapping("/{workspaceId}/permissionGroups") - public Mono<ResponseDTO<List<PermissionGroupInfoDTO>>> getPermissionGroupsForWorkspace(@PathVariable String workspaceId) { + public Mono<ResponseDTO<List<PermissionGroupInfoDTO>>> getPermissionGroupsForWorkspace( + @PathVariable String workspaceId) { return service.getPermissionGroupsForWorkspace(workspaceId) .map(groupInfoList -> new ResponseDTO<>(HttpStatus.OK.value(), groupInfoList, null)); } @@ -52,25 +52,27 @@ public Mono<ResponseDTO<List<PermissionGroupInfoDTO>>> getPermissionGroupsForWor @JsonView(Views.Public.class) @GetMapping("/{workspaceId}/members") public Mono<ResponseDTO<List<MemberInfoDTO>>> getUserMembersOfWorkspace(@PathVariable String workspaceId) { - return userWorkspaceService.getWorkspaceMembers(workspaceId) + return userWorkspaceService + .getWorkspaceMembers(workspaceId) .map(users -> new ResponseDTO<>(HttpStatus.OK.value(), users, null)); } @JsonView(Views.Public.class) @PutMapping("/{workspaceId}/permissionGroup") - public Mono<ResponseDTO<MemberInfoDTO>> updatePermissionGroupForMember(@RequestBody UpdatePermissionGroupDTO updatePermissionGroupDTO, - @PathVariable String workspaceId, - @RequestHeader(name = "Origin", required = false) String originHeader) { - return userWorkspaceService.updatePermissionGroupForMember(workspaceId, updatePermissionGroupDTO, originHeader) + public Mono<ResponseDTO<MemberInfoDTO>> updatePermissionGroupForMember( + @RequestBody UpdatePermissionGroupDTO updatePermissionGroupDTO, + @PathVariable String workspaceId, + @RequestHeader(name = "Origin", required = false) String originHeader) { + return userWorkspaceService + .updatePermissionGroupForMember(workspaceId, updatePermissionGroupDTO, originHeader) .map(user -> new ResponseDTO<>(HttpStatus.OK.value(), user, null)); } @JsonView(Views.Public.class) @PostMapping("/{workspaceId}/logo") - public Mono<ResponseDTO<Workspace>> uploadLogo(@PathVariable String workspaceId, - @RequestPart("file") Mono<Part> fileMono) { - return fileMono - .flatMap(filePart -> service.uploadLogo(workspaceId, filePart)) + public Mono<ResponseDTO<Workspace>> uploadLogo( + @PathVariable String workspaceId, @RequestPart("file") Mono<Part> fileMono) { + return fileMono.flatMap(filePart -> service.uploadLogo(workspaceId, filePart)) .map(url -> new ResponseDTO<>(HttpStatus.OK.value(), url, null)); } @@ -80,5 +82,4 @@ public Mono<ResponseDTO<Workspace>> deleteLogo(@PathVariable String workspaceId) return service.deleteLogo(workspaceId) .map(workspace -> new ResponseDTO<>(HttpStatus.OK.value(), workspace, null)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Action.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Action.java index 46c262511722..074e32114c3a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Action.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Action.java @@ -34,7 +34,7 @@ public class Action extends BaseDomain { @JsonView(Views.Public.class) Datasource datasource; - //Organizations migrated to workspaces, kept the field as depricated to support the old migration + // Organizations migrated to workspaces, kept the field as depricated to support the old migration @Deprecated @JsonView(Views.Public.class) String organizationId; @@ -72,7 +72,6 @@ public class Action extends BaseDomain { @JsonView(Views.Public.class) Set<String> invalids; - // This is a list of keys that the client whose values the client needs to send during action execution. // These are the Mustache keys that the server will replace before invoking the API @JsonProperty(access = JsonProperty.Access.READ_ONLY) @@ -83,10 +82,10 @@ public class Action extends BaseDomain { String cacheResponse; @JsonView(Views.Public.class) - String templateId; //If action is created via a template, store the id here. + String templateId; // If action is created via a template, store the id here. @JsonView(Views.Public.class) - String providerId; //If action is created via a template, store the template's provider id here. + String providerId; // If action is created via a template, store the template's provider id here. @Transient @JsonView(Views.Public.class) diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionCollection.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionCollection.java index 933b99494a1d..1d52921d8289 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionCollection.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionCollection.java @@ -20,11 +20,12 @@ @NoArgsConstructor @Document public class ActionCollection extends BranchAwareDomain { - // Default resources from BranchAwareDomain will be used to store branchName, defaultApplicationId and defaultActionCollectionId + // Default resources from BranchAwareDomain will be used to store branchName, defaultApplicationId and + // defaultActionCollectionId @JsonView(Views.Public.class) String applicationId; - //Organizations migrated to workspaces, kept the field as depricated to support the old migration + // Organizations migrated to workspaces, kept the field as depricated to support the old migration @Deprecated @JsonView(Views.Public.class) String organizationId; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionDependencyEdge.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionDependencyEdge.java index 20774b8bf58b..d8009e9b3bfe 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionDependencyEdge.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionDependencyEdge.java @@ -32,7 +32,10 @@ public boolean equals(Object obj) { if (obj instanceof ActionDependencyEdge) { final ActionDependencyEdge actionDependencyEdge = (ActionDependencyEdge) obj; - if (sourceNode == null || targetNode == null || actionDependencyEdge.sourceNode == null || actionDependencyEdge.targetNode == null) { + if (sourceNode == null + || targetNode == null + || actionDependencyEdge.sourceNode == null + || actionDependencyEdge.targetNode == null) { return false; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java index 6da35b029aee..4e899f11c535 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java @@ -36,11 +36,10 @@ @Document public class Application extends BaseDomain { - @NotNull - @JsonView(Views.Public.class) + @NotNull @JsonView(Views.Public.class) String name; - //Organizations migrated to workspaces, kept the field as deprecated to support the old migration + // Organizations migrated to workspaces, kept the field as deprecated to support the old migration @Deprecated @JsonView(Views.Public.class) String organizationId; @@ -193,7 +192,7 @@ public String getLastDeployedAt() { @JsonView(Views.Public.class) Boolean exportWithConfiguration; - //forkWithConfiguration represents whether credentials are shared or not while forking an app + // forkWithConfiguration represents whether credentials are shared or not while forking an app @JsonView(Views.Public.class) Boolean forkWithConfiguration; @@ -211,8 +210,12 @@ public Application(Application application) { this.clonedFromApplicationId = application.getId(); this.color = application.getColor(); this.icon = application.getIcon(); - this.unpublishedAppLayout = application.getUnpublishedAppLayout() == null ? null : new AppLayout(application.getUnpublishedAppLayout().type); - this.publishedAppLayout = application.getPublishedAppLayout() == null ? null : new AppLayout(application.getPublishedAppLayout().type); + this.unpublishedAppLayout = application.getUnpublishedAppLayout() == null + ? null + : new AppLayout(application.getUnpublishedAppLayout().type); + this.publishedAppLayout = application.getPublishedAppLayout() == null + ? null + : new AppLayout(application.getPublishedAppLayout().type); this.setUnpublishedApplicationDetail(new ApplicationDetail()); this.setPublishedApplicationDetail(new ApplicationDetail()); if (application.getUnpublishedApplicationDetail() == null) { @@ -221,12 +224,28 @@ public Application(Application application) { if (application.getPublishedApplicationDetail() == null) { application.setPublishedApplicationDetail(new ApplicationDetail()); } - AppPositioning unpublishedAppPositioning = application.getUnpublishedApplicationDetail().getAppPositioning() == null ? null : new AppPositioning(application.getUnpublishedApplicationDetail().getAppPositioning().type); + AppPositioning unpublishedAppPositioning = + application.getUnpublishedApplicationDetail().getAppPositioning() == null + ? null + : new AppPositioning( + application.getUnpublishedApplicationDetail().getAppPositioning().type); this.getUnpublishedApplicationDetail().setAppPositioning(unpublishedAppPositioning); - AppPositioning publishedAppPositioning = application.getPublishedApplicationDetail().getAppPositioning() == null ? null : new AppPositioning(application.getPublishedApplicationDetail().getAppPositioning().type); + AppPositioning publishedAppPositioning = + application.getPublishedApplicationDetail().getAppPositioning() == null + ? null + : new AppPositioning( + application.getPublishedApplicationDetail().getAppPositioning().type); this.getPublishedApplicationDetail().setAppPositioning(publishedAppPositioning); - this.getUnpublishedApplicationDetail().setNavigationSetting(application.getUnpublishedApplicationDetail().getNavigationSetting() == null ? null : new NavigationSetting()); - this.getPublishedApplicationDetail().setNavigationSetting(application.getPublishedApplicationDetail().getNavigationSetting() == null ? null : new NavigationSetting()); + this.getUnpublishedApplicationDetail() + .setNavigationSetting( + application.getUnpublishedApplicationDetail().getNavigationSetting() == null + ? null + : new NavigationSetting()); + this.getPublishedApplicationDetail() + .setNavigationSetting( + application.getPublishedApplicationDetail().getNavigationSetting() == null + ? null + : new NavigationSetting()); this.unpublishedCustomJSLibs = application.getUnpublishedCustomJSLibs(); this.collapseInvisibleWidgets = application.getCollapseInvisibleWidgets(); } @@ -369,7 +388,6 @@ public static class NavigationSetting { private Boolean showSignIn; } - /** * AppPositioning captures widget positioning Mode of the application */ @@ -387,8 +405,5 @@ public enum Type { FIXED, AUTO } - } - - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationDetail.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationDetail.java index 09fa3c102ed6..66390fc98949 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationDetail.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationDetail.java @@ -17,5 +17,4 @@ public ApplicationDetail() { this.appPositioning = null; this.navigationSetting = null; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationMode.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationMode.java index af222ce81383..fbd103b4b9f4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationMode.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationMode.java @@ -1,5 +1,6 @@ package com.appsmith.server.domains; public enum ApplicationMode { - EDIT, PUBLISHED + EDIT, + PUBLISHED } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationPage.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationPage.java index 8aadfdab478d..ac54d86286bb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationPage.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationPage.java @@ -38,5 +38,4 @@ public class ApplicationPage { public boolean isDefault() { return Boolean.TRUE.equals(isDefault); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationSnapshot.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationSnapshot.java index 7847f1c9a5e7..6eb2bdfd62b4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationSnapshot.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationSnapshot.java @@ -36,7 +36,7 @@ public class ApplicationSnapshot extends BaseDomain { * @return Updated at timestamp in ISO format */ public String getUpdatedTime() { - if(this.getUpdatedAt() == null) return null; + if (this.getUpdatedAt() == null) return null; return DateUtils.ISO_FORMATTER.format(this.getUpdatedAt()); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Asset.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Asset.java index d41cb783c395..09f6467e970c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Asset.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Asset.java @@ -18,5 +18,4 @@ public Asset(MediaType mediaType, byte[] data) { String contentType; byte[] data; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Collection.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Collection.java index 790bcf1b2614..8c56ef354e94 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Collection.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Collection.java @@ -20,7 +20,7 @@ public class Collection extends BaseDomain { String applicationId; - //Organizations migrated to workspaces, kept the field as depricated to support the old migration + // Organizations migrated to workspaces, kept the field as depricated to support the old migration @Deprecated String organizationId; @@ -28,6 +28,6 @@ public class Collection extends BaseDomain { Boolean shared; - //To save space, when creating/updating collection, only add Action's id field instead of the entire action. + // To save space, when creating/updating collection, only add Action's id field instead of the entire action. List<NewAction> actions; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/CustomJSLib.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/CustomJSLib.java index 9d81e4034fac..6defd1a0f055 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/CustomJSLib.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/CustomJSLib.java @@ -49,9 +49,13 @@ public class CustomJSLib extends BranchAwareDomain { String defs; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) - public CustomJSLib(@JsonProperty("name") String name, @JsonProperty("accessor") Set<String> accessor, - @JsonProperty("url") String url, @JsonProperty("docsUrl") String docsUrl, - @JsonProperty("version") String version, @JsonProperty("defs") String defs) { + public CustomJSLib( + @JsonProperty("name") String name, + @JsonProperty("accessor") Set<String> accessor, + @JsonProperty("url") String url, + @JsonProperty("docsUrl") String docsUrl, + @JsonProperty("version") String version, + @JsonProperty("defs") String defs) { this.name = name; this.accessor = accessor; this.url = url; @@ -91,4 +95,4 @@ public boolean equals(Object o) { public int hashCode() { return this.uidString.hashCode(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/DatasourceContextIdentifier.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/DatasourceContextIdentifier.java index 8659efe11a8c..40005fd67ea4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/DatasourceContextIdentifier.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/DatasourceContextIdentifier.java @@ -44,12 +44,13 @@ private boolean isEnvironmentIdEqual(String otherEnvironmentId) { public int hashCode() { int result = 0; result = hasText(this.getDatasourceId()) ? this.getDatasourceId().hashCode() : result; - result = hasText(this.getEnvironmentId()) ? result * 31 + this.getEnvironmentId().hashCode() : result; + result = hasText(this.getEnvironmentId()) + ? result * 31 + this.getEnvironmentId().hashCode() + : result; return result; } public boolean isKeyValid() { return hasText(this.getDatasourceId()) && hasText(this.getEnvironmentId()); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitAuth.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitAuth.java index 3bd457c0b293..445b098d19d3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitAuth.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitAuth.java @@ -13,8 +13,7 @@ public class GitAuth implements AppsmithDomain { @JsonView(Views.Internal.class) - @Encrypted - String privateKey; + @Encrypted String privateKey; @JsonView(Views.Public.class) String publicKey; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitConfig.java index 31c957d9847d..297f6ff0e537 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitConfig.java @@ -19,5 +19,4 @@ public class GitConfig implements AppsmithDomain { String authorName; String authorEmail; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Group.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Group.java index edb4693e31ff..7b8ae6ddc67f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Group.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Group.java @@ -16,18 +16,15 @@ @Document public class Group extends BaseDomain { - @NotNull - private String name; + @NotNull private String name; private String displayName; - //Organizations migrated to workspaces, kept the field as deprecated to support the old migration + // Organizations migrated to workspaces, kept the field as deprecated to support the old migration @Deprecated - @NotNull - private String organizationId; + @NotNull private String organizationId; - @NotNull - String workspaceId; + @NotNull String workspaceId; /** * This is a list of name of permissions. We will query with permission collection by name diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Layout.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Layout.java index 328d957650ee..4b0ed19779c8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Layout.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Layout.java @@ -51,7 +51,8 @@ public String getId() { return super.getId(); } - // this attribute will be used to display errors caused white calculating allOnLoadAction PageLoadActionsUtilCEImpl.java + // this attribute will be used to display errors caused white calculating allOnLoadAction + // PageLoadActionsUtilCEImpl.java @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonView({Views.Public.class, Views.Export.class}) List<ErrorDTO> layoutOnLoadActionErrors; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/License.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/License.java index ccf5fc2c6b01..47094fb73510 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/License.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/License.java @@ -4,6 +4,4 @@ import lombok.Data; @Data -public class License extends LicenseCE { - -} \ No newline at end of file +public class License extends LicenseCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/LoginSource.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/LoginSource.java index 970ed1471ce6..00e2305d06f4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/LoginSource.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/LoginSource.java @@ -7,7 +7,11 @@ import java.util.stream.Collectors; public enum LoginSource { - GOOGLE, FORM, GITHUB, KEYCLOAK, OIDC; + GOOGLE, + FORM, + GITHUB, + KEYCLOAK, + OIDC; public static final Set<LoginSource> oauthSources = Set.of(GOOGLE, GITHUB, KEYCLOAK, OIDC); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewAction.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewAction.java index f7a3e021c4ae..e5f545bab59f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewAction.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewAction.java @@ -23,7 +23,7 @@ public class NewAction extends BranchAwareDomain { @JsonView(Views.Public.class) String applicationId; - //Organizations migrated to workspaces, kept the field as deprecated to support the old migration + // Organizations migrated to workspaces, kept the field as deprecated to support the old migration @Deprecated @JsonView(Views.Public.class) String organizationId; @@ -38,10 +38,10 @@ public class NewAction extends BranchAwareDomain { String pluginId; @JsonView(Views.Public.class) - String templateId; //If action is created via a template, store the id here. + String templateId; // If action is created via a template, store the id here. @JsonView(Views.Public.class) - String providerId; //If action is created via a template, store the template's provider id here. + String providerId; // If action is created via a template, store the template's provider id here. @JsonView(Views.Public.class) Documentation documentation; // Documentation for the template using which this action was created diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Notification.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Notification.java index 617e2008a7a9..824a30c17c61 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Notification.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Notification.java @@ -13,7 +13,8 @@ @Document public class Notification extends BaseDomain { - // TODO: This class extends BaseDomain, so it has policies. Should we use information from policies instead of this field? + // TODO: This class extends BaseDomain, so it has policies. Should we use information from policies instead of this + // field? String forUsername; /** diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Organization.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Organization.java index 6930974e55dc..e3a30e2382af 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Organization.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Organization.java @@ -14,7 +14,6 @@ import java.util.List; import java.util.Set; - @Getter @Setter @ToString @@ -55,5 +54,4 @@ public class Organization extends BaseDomain { public String getLogoUrl() { return Url.ASSET_URL + "/" + logoAssetId; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Page.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Page.java index b366772e56cb..833fcd330659 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Page.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Page.java @@ -19,8 +19,7 @@ public class Page extends BaseDomain { String name; - @NotNull - String applicationId; + @NotNull String applicationId; List<Layout> layouts; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/PermissionGroup.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/PermissionGroup.java index be0dc18e0e06..f7d5bebaee75 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/PermissionGroup.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/PermissionGroup.java @@ -23,8 +23,8 @@ public class PermissionGroup extends BaseDomain { String description; - //TODO: refactor this to defaultDocumentId, as we can use this to store associated document id for - //which we are auto creating this permission group. + // TODO: refactor this to defaultDocumentId, as we can use this to store associated document id for + // which we are auto creating this permission group. @Deprecated String defaultWorkspaceId; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Plugin.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Plugin.java index cb9f3700dde6..8a22851fe886 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Plugin.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Plugin.java @@ -106,7 +106,8 @@ public enum ResponseType { @JsonView(Views.Public.class) Map<String, String> templates; - // Field to distinguish if the plugin is supported in air-gap instance, by default all the plugins will be supported. + // Field to distinguish if the plugin is supported in air-gap instance, by default all the plugins will be + // supported. // One can opt out by adding this field in DB object. Generally SaaS plugins and DB which can't be self-hosted can // be a candidate for opting out of air-gap @JsonView(Views.Internal.class) @@ -115,5 +116,4 @@ public enum ResponseType { // Config to set if the plugin has any dependency on cloud-services @JsonView(Views.Internal.class) Boolean isDependentOnCS; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/PricingPlan.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/PricingPlan.java index 2a7159dd547c..b216f0c78faf 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/PricingPlan.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/PricingPlan.java @@ -1,10 +1,12 @@ package com.appsmith.server.domains; - /** * Deprecated since we use plans based on the license and this information is stored inside license tenant pricingPlan is no longer used */ @Deprecated public enum PricingPlan { - FREE, STARTUP, BUSINESS, ENTERPRISE + FREE, + STARTUP, + BUSINESS, + ENTERPRISE } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Role.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Role.java index bc5b9f8a1e12..49059f330521 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Role.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Role.java @@ -1,6 +1,5 @@ package com.appsmith.server.domains; - import com.appsmith.external.models.BaseDomain; import jakarta.validation.constraints.NotEmpty; import lombok.AllArgsConstructor; @@ -9,7 +8,6 @@ import lombok.ToString; import org.springframework.data.mongodb.core.mapping.Document; - @Document @Getter @Setter diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ScreenType.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ScreenType.java index e32735a7c374..23b79bf4beba 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ScreenType.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ScreenType.java @@ -1,5 +1,6 @@ package com.appsmith.server.domains; public enum ScreenType { - DESKTOP, MOBILE + DESKTOP, + MOBILE } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Sequence.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Sequence.java index 9edb2b2c1470..33da0c70f2c6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Sequence.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Sequence.java @@ -10,5 +10,4 @@ public class Sequence { private String name; private Long nextNumber; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Tenant.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Tenant.java index 299a382fef81..9dd2cfb05c9b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Tenant.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Tenant.java @@ -15,8 +15,7 @@ @Document public class Tenant extends BaseDomain { - @Unique - String slug; + @Unique String slug; String displayName; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/TenantConfiguration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/TenantConfiguration.java index 12b9f54e6996..53d9372fed1c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/TenantConfiguration.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/TenantConfiguration.java @@ -4,6 +4,4 @@ import lombok.Data; @Data -public class TenantConfiguration extends TenantConfigurationCE { - -} +public class TenantConfiguration extends TenantConfigurationCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Theme.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Theme.java index 38f19fdc2a77..8a5ad47e0b5f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Theme.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Theme.java @@ -32,7 +32,7 @@ public class Theme extends BaseDomain { @JsonView(Views.Public.class) private String applicationId; - //Organizations migrated to workspaces, kept the field as deprecated to support the old migration + // Organizations migrated to workspaces, kept the field as deprecated to support the old migration @Deprecated @JsonView(Views.Public.class) private String organizationId; @@ -49,9 +49,9 @@ public class Theme extends BaseDomain { @JsonView(Views.Public.class) private Map<String, Object> stylesheet; - @JsonProperty("isSystemTheme") // manually setting property name to make sure it's compatible with Gson + @JsonProperty("isSystemTheme") // manually setting property name to make sure it's compatible with Gson @JsonView({Views.Public.class}) - private boolean isSystemTheme = false; // should be false by default + private boolean isSystemTheme = false; // should be false by default @Data @AllArgsConstructor diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UsagePulse.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UsagePulse.java index 5b9ff6ea7527..36ed0e074d83 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UsagePulse.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UsagePulse.java @@ -18,5 +18,4 @@ public class UsagePulse extends BaseDomain { private String tenantId; private Boolean viewMode; private Boolean isAnonymousUser; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/User.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/User.java index 68eddca7ebae..fe20988941ee 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/User.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/User.java @@ -22,7 +22,6 @@ import java.util.Map; import java.util.Set; - @Getter @Setter @ToString @@ -38,7 +37,7 @@ public class User extends BaseDomain implements UserDetails, OidcUser { @JsonView(Views.Public.class) private String hashedEmail; - //TODO: This is deprecated in favour of groups + // TODO: This is deprecated in favour of groups @JsonView(Views.Public.class) private Set<Role> roles; @@ -58,7 +57,7 @@ public class User extends BaseDomain implements UserDetails, OidcUser { @JsonView(Views.Public.class) private Boolean isEnabled = true; - //Organizations migrated to workspaces, kept the field as depricated to support the old migration + // Organizations migrated to workspaces, kept the field as depricated to support the old migration @Deprecated @JsonView(Views.Public.class) private String currentOrganizationId; @@ -66,7 +65,7 @@ public class User extends BaseDomain implements UserDetails, OidcUser { @JsonView(Views.Public.class) private String currentWorkspaceId; - //Organizations migrated to workspaces, kept the field as depricated to support the old migration + // Organizations migrated to workspaces, kept the field as depricated to support the old migration @Deprecated @JsonView(Views.Public.class) private Set<String> organizationIds; @@ -74,7 +73,7 @@ public class User extends BaseDomain implements UserDetails, OidcUser { @JsonView(Views.Public.class) private Set<String> workspaceIds; - //Organizations migrated to workspaces, kept the field as depricated to support the old migration + // Organizations migrated to workspaces, kept the field as depricated to support the old migration @Deprecated @JsonView(Views.Public.class) private String examplesOrganizationId; @@ -87,7 +86,8 @@ public class User extends BaseDomain implements UserDetails, OidcUser { @JsonView(Views.Public.class) private Set<String> groupIds = new HashSet<>(); - // These permissions are in addition to the privileges provided by the groupIds. We can assign individual permissions + // These permissions are in addition to the privileges provided by the groupIds. We can assign individual + // permissions // to users instead of creating a group for them. To be used only for one-off permissions. // During evaluation a union of the group permissions and user-specific permissions will take effect. @JsonView(Views.Public.class) diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserData.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserData.java index 231354be9f69..c37c69e67b97 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserData.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserData.java @@ -46,7 +46,7 @@ public class UserData extends BaseDomain { @JsonView(Views.Public.class) private String releaseNotesViewedVersion; - //Organizations migrated to workspaces, kept the field as deprecated to support the old migration + // Organizations migrated to workspaces, kept the field as deprecated to support the old migration @Deprecated @JsonView(Views.Public.class) private List<String> recentlyUsedOrgIds; @@ -59,7 +59,6 @@ public class UserData extends BaseDomain { @JsonView(Views.Public.class) private List<String> recentlyUsedAppIds; - // Map of defaultApplicationIds with the GitProfiles. For fallback/default git profile per user default will be the // the key for the map @JsonView(Views.Internal.class) @@ -100,5 +99,4 @@ public Map<String, GitProfile> setGitProfileByKey(String key, GitProfile gitProf public UserData(String userId) { this.userId = userId; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserState.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserState.java index 66d821610270..6b3c34ff254b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserState.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserState.java @@ -1,5 +1,7 @@ package com.appsmith.server.domains; public enum UserState { - NEW, INVITED, ACTIVATED + NEW, + INVITED, + ACTIVATED } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Workspace.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Workspace.java index 66d4b052353f..ac6da75d20c4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Workspace.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Workspace.java @@ -14,7 +14,6 @@ import java.util.List; import java.util.Set; - @Getter @Setter @ToString @@ -41,7 +40,7 @@ public class Workspace extends BaseDomain { @JsonView(Views.Public.class) private String slug; - //Organizations migrated to workspaces, kept the field as deprecated to support the old migration + // Organizations migrated to workspaces, kept the field as deprecated to support the old migration @Deprecated @JsonView(Views.Public.class) private Boolean isAutoGeneratedOrganization; @@ -77,5 +76,4 @@ public static String toSlug(String text) { public String getLogoUrl() { return Url.ASSET_URL + "/" + logoAssetId; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/WorkspacePlugin.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/WorkspacePlugin.java index 8d308b6b1e19..1ed5e33738be 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/WorkspacePlugin.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/WorkspacePlugin.java @@ -20,5 +20,4 @@ public class WorkspacePlugin extends BaseDomain { String pluginId; WorkspacePluginStatus status; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/LicenseCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/LicenseCE.java index fc230761ffee..4010e91186b5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/LicenseCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/LicenseCE.java @@ -6,4 +6,4 @@ @Data public class LicenseCE { LicensePlan plan; -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/TenantConfigurationCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/TenantConfigurationCE.java index ac70b2863030..9ae6081c3038 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/TenantConfigurationCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/TenantConfigurationCE.java @@ -41,5 +41,4 @@ public void copyNonSensitiveValues(TenantConfiguration tenantConfiguration) { } public License license; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java index 51741c816093..ebb0f4835007 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java @@ -54,7 +54,7 @@ public class ActionCollectionDTO { @JsonView(Views.Public.class) String pluginId; - //this attribute carries error messages while processing the actionCollection + // this attribute carries error messages while processing the actionCollection @Transient @JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonView(Views.Public.class) @@ -69,7 +69,7 @@ public class ActionCollectionDTO { // TODO can be used as template for new actions in collection, // or as default configuration for all actions in the collection -// ActionDTO defaultAction; + // ActionDTO defaultAction; // This property is not shared with the client since the reference is only useful to server // Map<defaultActionId, branchedActionId> @@ -81,7 +81,8 @@ public class ActionCollectionDTO { Set<String> actionIds = Set.of(); // This property is not shared with the client since the reference is only useful to server - // Archived actions represent actions that have been removed from a js object but may be subject to re-use by the user + // Archived actions represent actions that have been removed from a js object but may be subject to re-use by the + // user // Map<defaultActionId, branchedActionId> @JsonView(Views.Internal.class) Map<String, String> defaultToBranchedArchivedActionIdsMap = Map.of(); @@ -109,7 +110,8 @@ public class ActionCollectionDTO { @JsonView(Views.Public.class) List<JSValue> variables; - // This will be used to store the defaultPageId but other fields like branchName, applicationId will act as transient + // This will be used to store the defaultPageId but other fields like branchName, applicationId will act as + // transient @JsonView(Views.Internal.class) DefaultResources defaultResources; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionMoveDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionMoveDTO.java index f00f5acb1ac7..54bf65f83586 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionMoveDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionMoveDTO.java @@ -8,12 +8,9 @@ @Setter public class ActionCollectionMoveDTO { - @NotNull - String name; + @NotNull String name; - @NotNull - String collectionId; + @NotNull String collectionId; - @NotNull - String destinationPageId; + @NotNull String destinationPageId; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionMoveDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionMoveDTO.java index 80e8fb22cbd6..b1fe5919ff0f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionMoveDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionMoveDTO.java @@ -9,9 +9,7 @@ @Setter public class ActionMoveDTO { - @NotNull - ActionDTO action; + @NotNull ActionDTO action; - @NotNull - String destinationPageId; + @NotNull String destinationPageId; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionViewDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionViewDTO.java index c0ece3a9aba4..46a019572549 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionViewDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionViewDTO.java @@ -43,7 +43,8 @@ public class ActionViewDTO { // and hence would return an action execution error. @JsonView(Views.Public.class) public Integer getTimeoutInMillisecond() { - return (timeoutInMillisecond == null || timeoutInMillisecond <= 0) ? - DEFAULT_ACTION_EXECUTION_TIMEOUT_MS : timeoutInMillisecond; + return (timeoutInMillisecond == null || timeoutInMillisecond <= 0) + ? DEFAULT_ACTION_EXECUTION_TIMEOUT_MS + : timeoutInMillisecond; } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationAccessDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationAccessDTO.java index 1c4c21c29179..0bdec22974db 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationAccessDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationAccessDTO.java @@ -10,7 +10,5 @@ @NoArgsConstructor public class ApplicationAccessDTO { - @NotNull - Boolean publicAccess; - + @NotNull Boolean publicAccess; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationJson.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationJson.java index 3daf89170ed3..b03a19b3eda5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationJson.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationJson.java @@ -1,7 +1,7 @@ package com.appsmith.server.dtos; -import com.appsmith.external.models.DatasourceStorageStructure; import com.appsmith.external.models.DatasourceStorage; +import com.appsmith.external.models.DatasourceStorageStructure; import com.appsmith.external.models.DecryptedSensitiveFields; import com.appsmith.external.models.InvisibleActionFields; import com.appsmith.external.views.Views; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/AuthorizationCodeCallbackDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/AuthorizationCodeCallbackDTO.java index 069207fa4d1a..f21d53f6af2b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/AuthorizationCodeCallbackDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/AuthorizationCodeCallbackDTO.java @@ -1,6 +1,5 @@ package com.appsmith.server.dtos; - import lombok.Getter; import lombok.Setter; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/CRUDPageResponseDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/CRUDPageResponseDTO.java index 0deec432a018..ab83610b6553 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/CRUDPageResponseDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/CRUDPageResponseDTO.java @@ -14,7 +14,8 @@ public class CRUDPageResponseDTO { PageDTO page; - // This field will give some guidelines how to interact with the widgets on the canvas created by CreateDBTablePageSolution + // This field will give some guidelines how to interact with the widgets on the canvas created by + // CreateDBTablePageSolution // e.g. We have generated the table from Datasource. You can use the Form> to modify it. Since all your data is // already connected you can add more queries and modify the bindings String successMessage; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/CustomJSLibApplicationDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/CustomJSLibApplicationDTO.java index 913c37c0196d..da646c3d362e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/CustomJSLibApplicationDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/CustomJSLibApplicationDTO.java @@ -36,4 +36,4 @@ public static CustomJSLibApplicationDTO getDTOFromCustomJSLib(CustomJSLib jsLib) return customJSLibApplicationDTO; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/EnvChangesResponseDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/EnvChangesResponseDTO.java index 48f44ec26d0d..285623af8902 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/EnvChangesResponseDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/EnvChangesResponseDTO.java @@ -10,5 +10,4 @@ public class EnvChangesResponseDTO { @JsonProperty(value = "isRestartRequired") boolean isRestartRequired; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ExportFileDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ExportFileDTO.java index a5ae30e6ae90..49b1129a0646 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ExportFileDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ExportFileDTO.java @@ -3,7 +3,6 @@ import lombok.Data; import org.springframework.http.HttpHeaders; - @Data public class ExportFileDTO { HttpHeaders httpHeaders; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/GitAuthDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/GitAuthDTO.java index 8213b7f81976..a044c8ee8f9c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/GitAuthDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/GitAuthDTO.java @@ -21,5 +21,4 @@ public class GitAuthDTO { @JsonView(Views.Public.class) List<GitDeployKeyDTO> gitSupportedSSHKeyType; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/GitCheckoutBranchDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/GitCheckoutBranchDTO.java index 79d2f573b0c8..54af5b0ac807 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/GitCheckoutBranchDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/GitCheckoutBranchDTO.java @@ -6,5 +6,4 @@ public class GitCheckoutBranchDTO { Boolean isRemote; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/InviteUsersDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/InviteUsersDTO.java index 4403525f0f80..acafc4983709 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/InviteUsersDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/InviteUsersDTO.java @@ -8,6 +8,4 @@ @Getter @Setter @NoArgsConstructor -public class InviteUsersDTO extends InviteUsersCE_DTO { - -} +public class InviteUsersDTO extends InviteUsersCE_DTO {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ItemType.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ItemType.java index 182474b7b875..eef0ad686472 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ItemType.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ItemType.java @@ -1,5 +1,6 @@ package com.appsmith.server.dtos; public enum ItemType { - TEMPLATE, ACTION + TEMPLATE, + ACTION } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/LayoutDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/LayoutDTO.java index 7a7ba6f29cb4..b4f5241c8fb7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/LayoutDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/LayoutDTO.java @@ -24,7 +24,8 @@ public class LayoutDTO { List<Set<DslActionDTO>> layoutOnLoadActions; - // this attribute will be used to display errors caused white calculating allOnLoadAction PageLoadActionsUtilCEImpl.java + // this attribute will be used to display errors caused white calculating allOnLoadAction + // PageLoadActionsUtilCEImpl.java @Transient @JsonProperty(access = JsonProperty.Access.READ_ONLY) List<ErrorDTO> layoutOnLoadActionErrors; @@ -32,7 +33,8 @@ public class LayoutDTO { // All the actions which have been updated as part of updateLayout function call List<LayoutActionUpdateDTO> actionUpdates; - // All the toast messages that the developer user should be displayed to inform about the consequences of update layout. + // All the toast messages that the developer user should be displayed to inform about the consequences of update + // layout. List<String> messages; public Set<String> userPermissions = new HashSet<>(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/MemberInfoDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/MemberInfoDTO.java index 6c8349f5e0e0..ef94935e6c9c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/MemberInfoDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/MemberInfoDTO.java @@ -12,7 +12,8 @@ public class MemberInfoDTO extends MemberInfoCE_DTO { @Builder - public MemberInfoDTO(String userId, String username, String name, List<PermissionGroupInfoDTO> roles, String photoId) { + public MemberInfoDTO( + String userId, String username, String name, List<PermissionGroupInfoDTO> roles, String photoId) { super(userId, username, name, roles, photoId); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/MockDataSource.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/MockDataSource.java index d073cdcccda9..8d6b83456322 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/MockDataSource.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/MockDataSource.java @@ -14,5 +14,4 @@ public class MockDataSource { String pluginId; String packageName; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/OAuth2AuthorizedClientDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/OAuth2AuthorizedClientDTO.java index ce34fce9638e..3bc081d851f9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/OAuth2AuthorizedClientDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/OAuth2AuthorizedClientDTO.java @@ -93,21 +93,19 @@ public static OAuth2AuthorizedClientDTO fromOAuth2AuthorizedClient(final OAuth2A pd.getIssuerUri(), pd.getUserInfoEndpoint().getUri(), pd.getUserInfoEndpoint().getAuthenticationMethod().getValue(), - pd.getUserInfoEndpoint().getUserNameAttributeName() - ), + pd.getUserInfoEndpoint().getUserNameAttributeName()), new OAuth2AccessTokenDTO( at.getTokenType().getValue(), at.getTokenValue(), ObjectUtils.defaultIfNull(at.getIssuedAt(), "").toString(), ObjectUtils.defaultIfNull(at.getExpiresAt(), "").toString(), - at.getScopes() - ), - rt == null ? null : new OAuth2RefreshTokenDTO( - rt.getTokenValue(), - ObjectUtils.defaultIfNull(rt.getIssuedAt(), "").toString(), - ObjectUtils.defaultIfNull(rt.getExpiresAt(), "").toString() - ) - ); + at.getScopes()), + rt == null + ? null + : new OAuth2RefreshTokenDTO( + rt.getTokenValue(), + ObjectUtils.defaultIfNull(rt.getIssuedAt(), "").toString(), + ObjectUtils.defaultIfNull(rt.getExpiresAt(), "").toString())); } public OAuth2AuthorizedClient makeOAuth2AuthorizedClient() { @@ -115,16 +113,17 @@ public OAuth2AuthorizedClient makeOAuth2AuthorizedClient() { if (OAuth2AccessToken.TokenType.BEARER.getValue().equals(accessToken.tokenType)) { tokenType = OAuth2AccessToken.TokenType.BEARER; } else { - throw new IllegalArgumentException("Could not deserialize OAuth2AuthorizedClient, unknown token type: " + accessToken.tokenType); + throw new IllegalArgumentException( + "Could not deserialize OAuth2AuthorizedClient, unknown token type: " + accessToken.tokenType); } return new OAuth2AuthorizedClient( - ClientRegistration - .withRegistrationId(clientRegistration.registrationId) + ClientRegistration.withRegistrationId(clientRegistration.registrationId) .clientId(clientRegistration.clientId) .clientSecret(clientRegistration.clientSecret) // TODO: Don't recreate this object, use one of the static constants already in that class. - .clientAuthenticationMethod(new ClientAuthenticationMethod(clientRegistration.clientAuthenticationMethod)) + .clientAuthenticationMethod( + new ClientAuthenticationMethod(clientRegistration.clientAuthenticationMethod)) // TODO: Don't recreate this object, use one of the static constants already in that class. .authorizationGrantType(new AuthorizationGrantType(clientRegistration.authorizationGrantType)) .redirectUri(clientRegistration.redirectUri) @@ -135,7 +134,8 @@ public OAuth2AuthorizedClient makeOAuth2AuthorizedClient() { .issuerUri(clientRegistration.issuerUri) .jwkSetUri(clientRegistration.jwkSetUri) .userInfoUri(clientRegistration.userInfoUri) - .userInfoAuthenticationMethod(new AuthenticationMethod(clientRegistration.userInfoAuthenticationMethod)) + .userInfoAuthenticationMethod( + new AuthenticationMethod(clientRegistration.userInfoAuthenticationMethod)) .userNameAttributeName(clientRegistration.userNameAttributeName) .build(), principalName, @@ -144,18 +144,16 @@ public OAuth2AuthorizedClient makeOAuth2AuthorizedClient() { accessToken.tokenValue, parseInstant(accessToken.issuedAt), parseInstant(accessToken.expiresAt), - Set.copyOf(accessToken.scopes) - ), - refreshToken == null ? null : new OAuth2RefreshToken( - refreshToken.tokenValue, - parseInstant(refreshToken.issuedAt), - parseInstant(refreshToken.expiresAt) - ) - ); + Set.copyOf(accessToken.scopes)), + refreshToken == null + ? null + : new OAuth2RefreshToken( + refreshToken.tokenValue, + parseInstant(refreshToken.issuedAt), + parseInstant(refreshToken.expiresAt))); } private Instant parseInstant(String refreshToken) { return StringUtils.isEmpty(refreshToken) ? null : Instant.parse(refreshToken); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/Permission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/Permission.java index 2539cc7a2a4c..83d400b02245 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/Permission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/Permission.java @@ -19,5 +19,4 @@ public class Permission { String documentId; AclPermission aclPermission; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PermissionGroupInfoDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PermissionGroupInfoDTO.java index cbd84398dcb5..321e1a6e031f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PermissionGroupInfoDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PermissionGroupInfoDTO.java @@ -14,7 +14,8 @@ public PermissionGroupInfoDTO(String id, String name, String description) { super(id, name, description); } - public PermissionGroupInfoDTO(String id, String name, String description, String entityId, String entityType, String entityName) { + public PermissionGroupInfoDTO( + String id, String name, String description, String entityId, String entityType, String entityName) { super(id, name, description, entityId, entityType, entityName); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ResponseDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ResponseDTO.java index 2b5c6e9df059..85a701b6ce0f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ResponseDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ResponseDTO.java @@ -48,5 +48,4 @@ public String getErrorDisplay() { return error.getCode() + ": " + error.getMessage(); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/TestEmailConfigRequestDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/TestEmailConfigRequestDTO.java index d88d939fe7a0..876b3cf89e27 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/TestEmailConfigRequestDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/TestEmailConfigRequestDTO.java @@ -7,22 +7,18 @@ @Data public class TestEmailConfigRequestDTO { - @NotNull - @NotEmpty + @NotNull @NotEmpty private String smtpHost; - @NotNull - private Integer smtpPort; + @NotNull private Integer smtpPort; private String username; private String password; - @NotNull - @NotEmpty + @NotNull @NotEmpty @Email private String fromEmail; - @NotNull - private Boolean starttlsEnabled; + @NotNull private Boolean starttlsEnabled; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdateIsReadNotificationByIdDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdateIsReadNotificationByIdDTO.java index 880abece74a6..da5c762b790a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdateIsReadNotificationByIdDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdateIsReadNotificationByIdDTO.java @@ -12,7 +12,6 @@ @Setter @EqualsAndHashCode(callSuper = true) public class UpdateIsReadNotificationByIdDTO extends UpdateIsReadNotificationDTO { - @NotNull - @NotEmpty + @NotNull @NotEmpty private List<String> idList; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdateIsReadNotificationDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdateIsReadNotificationDTO.java index 91fec3b6b1fc..6649cd44c398 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdateIsReadNotificationDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdateIsReadNotificationDTO.java @@ -9,6 +9,5 @@ @Setter @EqualsAndHashCode public class UpdateIsReadNotificationDTO { - @NotNull - private Boolean isRead; + @NotNull private Boolean isRead; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdatePermissionGroupDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdatePermissionGroupDTO.java index 55333d65561b..be10a9b20424 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdatePermissionGroupDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UpdatePermissionGroupDTO.java @@ -6,6 +6,4 @@ @Data @NoArgsConstructor -public class UpdatePermissionGroupDTO extends UpdatePermissionGroupCE_DTO { - -} +public class UpdatePermissionGroupDTO extends UpdatePermissionGroupCE_DTO {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserProfileDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserProfileDTO.java index 74f7dfe1b4ac..8b77e8d12643 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserProfileDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserProfileDTO.java @@ -1,13 +1,7 @@ package com.appsmith.server.dtos; import com.appsmith.server.dtos.ce.UserProfileCE_DTO; -import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - @Data -public class UserProfileDTO extends UserProfileCE_DTO { -} \ No newline at end of file +public class UserProfileDTO extends UserProfileCE_DTO {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserSessionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserSessionDTO.java index a6f2315ce89d..06f7b1e17954 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserSessionDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserSessionDTO.java @@ -53,8 +53,7 @@ public class UserSessionDTO { /** * We don't expect this class to be instantiated outside this class. Remove this constructor when needed. */ - private UserSessionDTO() { - } + private UserSessionDTO() {} /** * Given an authentication token, typically from a Spring Security context, create a UserSession object. This @@ -82,11 +81,13 @@ public static UserSessionDTO fromToken(Authentication authentication) { session.authorities = authentication.getAuthorities(); if (authentication instanceof OAuth2AuthenticationToken) { - session.authorizedClientRegistrationId = ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(); + session.authorizedClientRegistrationId = + ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(); } else if (authentication instanceof UsernamePasswordAuthenticationToken) { session.authorizedClientRegistrationId = PASSWORD_PROVIDER; } else { - throw new IllegalArgumentException("Unsupported authentication type: " + authentication.getClass().getName()); + throw new IllegalArgumentException("Unsupported authentication type: " + + authentication.getClass().getName()); } return session; @@ -117,10 +118,8 @@ public Authentication makeToken() { } else if (ALLOWED_OAUTH_PROVIDERS.contains(authorizedClientRegistrationId)) { return new OAuth2AuthenticationToken(user, authorities, authorizedClientRegistrationId); - } throw new IllegalArgumentException("Invalid registration ID " + authorizedClientRegistrationId); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserSignupRequestDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserSignupRequestDTO.java index 912057d306f2..d1d02ec3af35 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserSignupRequestDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserSignupRequestDTO.java @@ -26,5 +26,4 @@ public class UserSignupRequestDTO { private boolean allowCollectingAnonymousData; private boolean signupForNewsletter; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserUpdateDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserUpdateDTO.java index 8210368b1175..b1ad33999669 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserUpdateDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/UserUpdateDTO.java @@ -23,5 +23,4 @@ public boolean hasUserUpdates() { public boolean hasUserDataUpdates() { return role != null || useCase != null || isIntercomConsentGiven; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/WorkspacePluginStatus.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/WorkspacePluginStatus.java index e51acd2e6968..bf4de22afc77 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/WorkspacePluginStatus.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/WorkspacePluginStatus.java @@ -1,5 +1,7 @@ package com.appsmith.server.dtos; public enum WorkspacePluginStatus { - FREE, TRIAL, ACTIVATED + FREE, + TRIAL, + ACTIVATED } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/ImportActionCollectionResultDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/ImportActionCollectionResultDTO.java index 21fd63cd792d..cf62eb8233b8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/ImportActionCollectionResultDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/ImportActionCollectionResultDTO.java @@ -25,9 +25,8 @@ public class ImportActionCollectionResultDTO { * @return */ public String getGist() { - return String.format("existing action collections: %d, imported action collections: %d", - existingActionCollections.size(), - savedActionCollectionIds.size() - ); + return String.format( + "existing action collections: %d, imported action collections: %d", + existingActionCollections.size(), savedActionCollectionIds.size()); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/ImportActionResultDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/ImportActionResultDTO.java index 6eb24e47cde8..458e59893098 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/ImportActionResultDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/ImportActionResultDTO.java @@ -43,6 +43,7 @@ public ImportActionResultDTO() { * @return */ public String getGist() { - return String.format("existing actions: %d, imported actions: %d", existingActions.size(), importedActionIds.size()); + return String.format( + "existing actions: %d, imported actions: %d", existingActions.size(), importedActionIds.size()); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/InviteUsersCE_DTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/InviteUsersCE_DTO.java index 9f9923446210..c7a4688652be 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/InviteUsersCE_DTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/InviteUsersCE_DTO.java @@ -12,7 +12,5 @@ public class InviteUsersCE_DTO { List<String> usernames; - @NotNull - String permissionGroupId; - + @NotNull String permissionGroupId; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/PermissionGroupInfoCE_DTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/PermissionGroupInfoCE_DTO.java index 7b4a1306009e..af5d35b8bef4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/PermissionGroupInfoCE_DTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/PermissionGroupInfoCE_DTO.java @@ -28,7 +28,8 @@ public PermissionGroupInfoCE_DTO(String id, String name, String description) { this.description = description; } - public PermissionGroupInfoCE_DTO(String id, String name, String description, String entityId, String entityType, String entityName) { + public PermissionGroupInfoCE_DTO( + String id, String name, String description, String entityId, String entityType, String entityName) { this.id = id; this.name = name; this.description = description; @@ -36,4 +37,4 @@ public PermissionGroupInfoCE_DTO(String id, String name, String description, Str this.entityType = entityType; this.entityName = entityName; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/UpdateMultiplePageLayoutDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/UpdateMultiplePageLayoutDTO.java index 0b6dd2596d18..a28b4818eaee 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/UpdateMultiplePageLayoutDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/UpdateMultiplePageLayoutDTO.java @@ -12,18 +12,16 @@ @Setter public class UpdateMultiplePageLayoutDTO { - @NotNull - @Valid + @NotNull @Valid private List<UpdatePageLayoutDTO> pageLayouts; @Getter @Setter public static class UpdatePageLayoutDTO { - @NotNull - private String pageId; + @NotNull private String pageId; + + @NotNull private String layoutId; - @NotNull - private String layoutId; private Layout layout; } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/UserProfileCE_DTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/UserProfileCE_DTO.java index cedc6c5e10db..bc951a12bf59 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/UserProfileCE_DTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ce/UserProfileCE_DTO.java @@ -54,4 +54,4 @@ public boolean isAccountNonLocked() { public boolean isCredentialsNonExpired() { return this.isEnabled; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/events/UserChangedEvent.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/events/UserChangedEvent.java index af2d27d93756..3db0ccd76c34 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/events/UserChangedEvent.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/events/UserChangedEvent.java @@ -7,5 +7,4 @@ public class UserChangedEvent { private final User user; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppSmithErrorWebExceptionHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppSmithErrorWebExceptionHandler.java index 4a7a249bcdc9..dd6e8ccadc99 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppSmithErrorWebExceptionHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppSmithErrorWebExceptionHandler.java @@ -37,10 +37,13 @@ public class AppSmithErrorWebExceptionHandler extends DefaultErrorWebExceptionHa "Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer"; @Autowired - public AppSmithErrorWebExceptionHandler(ErrorAttributes errorAttributes, WebProperties webProperties, - ServerProperties serverProperties, ApplicationContext applicationContext, - ObjectProvider<ViewResolver> viewResolvers, - ServerCodecConfigurer serverCodecConfigurer) { + public AppSmithErrorWebExceptionHandler( + ErrorAttributes errorAttributes, + WebProperties webProperties, + ServerProperties serverProperties, + ApplicationContext applicationContext, + ObjectProvider<ViewResolver> viewResolvers, + ServerCodecConfigurer serverCodecConfigurer) { super(errorAttributes, webProperties.getResources(), serverProperties.getError(), applicationContext); this.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList())); this.setMessageWriters(serverCodecConfigurer.getWriters()); @@ -54,28 +57,28 @@ protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes erro @Nonnull private Mono<ServerResponse> render(ServerRequest request) { - Map<String, Object> error = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.STACK_TRACE)); + Map<String, Object> error = + getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.STACK_TRACE)); int errorCode = getHttpStatus(error); - ServerResponse.BodyBuilder responseBuilder = ServerResponse.status(errorCode) - .contentType(MediaType.APPLICATION_JSON); + ServerResponse.BodyBuilder responseBuilder = + ServerResponse.status(errorCode).contentType(MediaType.APPLICATION_JSON); if (errorCode == 500 && String.valueOf(error.get("trace")).contains(DESERIALIZATION_ERROR_MESSAGE)) { - // If the error is regarding a deserialization error in the session data, then the user is essentially locked out. - // They have to use a different browser, or Incognito, or clear their cookies to get back in. So, we'll delete - // the SESSION cookie here, so that the user gets sent back to the Login page, and they can unblock themselves. - responseBuilder = responseBuilder.cookie( - ResponseCookie.from("SESSION", "") - .httpOnly(true) - .path("/") - .maxAge(0) - .build() - ); + // If the error is regarding a deserialization error in the session data, then the user is essentially + // locked out. + // They have to use a different browser, or Incognito, or clear their cookies to get back in. So, we'll + // delete + // the SESSION cookie here, so that the user gets sent back to the Login page, and they can unblock + // themselves. + responseBuilder = responseBuilder.cookie(ResponseCookie.from("SESSION", "") + .httpOnly(true) + .path("/") + .maxAge(0) + .build()); } - return responseBuilder.body( - BodyInserters - .fromValue(new ResponseDTO<>(errorCode, new ErrorDTO(String.valueOf(errorCode), String.valueOf(error.get("error"))))) - ); + return responseBuilder.body(BodyInserters.fromValue(new ResponseDTO<>( + errorCode, new ErrorDTO(String.valueOf(errorCode), String.valueOf(error.get("error")))))); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java index e3b90c01bd48..60b56c0bfc5a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java @@ -10,159 +10,886 @@ @Getter public enum AppsmithError { - // Ref syntax for message templates: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/MessageFormat.html - INVALID_PARAMETER(400, AppsmithErrorCode.INVALID_PARAMETER.getCode(), "Please enter a valid parameter {0}.", AppsmithErrorAction.DEFAULT, "Invalid parameter", ErrorType.ARGUMENT_ERROR, null), - EMPTY_CURL_INPUT_STATEMENT(400, AppsmithErrorCode.EMPTY_CURL_INPUT_STATEMENT.getCode(), "Input CURL statement is empty / null. Please edit the input box to provide a valid CURL statement.", AppsmithErrorAction.DEFAULT, "Invalid parameter", ErrorType.ARGUMENT_ERROR, null), - PLUGIN_NOT_INSTALLED(400, AppsmithErrorCode.PLUGIN_NOT_INSTALLED.getCode(), "Plugin {0} not installed", AppsmithErrorAction.DEFAULT, "Plugin not installed", ErrorType.INTERNAL_ERROR, null), - PLUGIN_ID_NOT_GIVEN(400, AppsmithErrorCode.PLUGIN_ID_NOT_GIVEN.getCode(), "Missing plugin id. Please enter one.", AppsmithErrorAction.DEFAULT, "Missing plugin id", ErrorType.INTERNAL_ERROR, null), - DATASOURCE_NOT_GIVEN(400, AppsmithErrorCode.DATASOURCE_NOT_GIVEN.getCode(), "Missing datasource. Add/enter/connect a datasource to create a valid action.", - AppsmithErrorAction.DEFAULT, "Missing datasource", ErrorType.ARGUMENT_ERROR, null), - PAGE_ID_NOT_GIVEN(400, AppsmithErrorCode.PAGE_ID_NOT_GIVEN.getCode(), "Missing page id. Please enter one.", AppsmithErrorAction.DEFAULT, "Missing page id", ErrorType.ARGUMENT_ERROR, null), - DUPLICATE_KEY_USER_ERROR(400, AppsmithErrorCode.DUPLICATE_KEY_USER_ERROR.getCode(), "{0} already exists. Please use a different {1}", AppsmithErrorAction.DEFAULT, "Name already used", ErrorType.BAD_REQUEST, null), - PAGE_DOESNT_BELONG_TO_USER_WORKSPACE(400, AppsmithErrorCode.PAGE_DOESNT_BELONG_TO_USER_WORKSPACE.getCode(), "Page {0} does not belong to the current user {1} " + - "workspace", AppsmithErrorAction.LOG_EXTERNALLY, "Page doesn''t belong to this workspace", ErrorType.BAD_REQUEST, null), - UNSUPPORTED_OPERATION(400, AppsmithErrorCode.UNSUPPORTED_OPERATION.getCode(), "Unsupported operation", AppsmithErrorAction.DEFAULT, "Unsupported operation", ErrorType.BAD_REQUEST, null), - DEPRECATED_API(400, AppsmithErrorCode.DEPRECATED_API.getCode(), "This API has been deprecated, please contact the Appsmith support for more details.", AppsmithErrorAction.DEFAULT, "Deprecated API", ErrorType.BAD_REQUEST, null), - USER_DOESNT_BELONG_ANY_WORKSPACE(400, AppsmithErrorCode.USER_DOESNT_BELONG_ANY_WORKSPACE.getCode(), "User {0} does not belong to any workspace", - AppsmithErrorAction.LOG_EXTERNALLY, "User doesn''t belong to any workspace", ErrorType.INTERNAL_ERROR, null), - USER_DOESNT_BELONG_TO_WORKSPACE(400, AppsmithErrorCode.USER_DOESNT_BELONG_TO_WORKSPACE.getCode(), "User {0} does not belong to the workspace with id {1}", - AppsmithErrorAction.LOG_EXTERNALLY, "User doesn''t belong to this workspace", ErrorType.INTERNAL_ERROR, null), - NO_CONFIGURATION_FOUND_IN_DATASOURCE(400, AppsmithErrorCode.NO_CONFIGURATION_FOUND_IN_DATASOURCE.getCode(), "No datasource configuration found. Please configure it and try again.", - AppsmithErrorAction.DEFAULT, "Datasource configuration is invalid", ErrorType.DATASOURCE_CONFIGURATION_ERROR, null), - INVALID_ACTION_COLLECTION(400, AppsmithErrorCode.INVALID_ACTION_COLLECTION.getCode(), "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", - AppsmithErrorAction.DEFAULT, "Collection configuration is invalid", ErrorType.CONFIGURATION_ERROR, null), - INVALID_ACTION(400, AppsmithErrorCode.INVALID_ACTION.getCode(), "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", - AppsmithErrorAction.DEFAULT, "Action configuration is invalid", ErrorType.CONFIGURATION_ERROR, null), - INVALID_DATASOURCE(400, AppsmithErrorCode.INVALID_DATASOURCE.getCode(), "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", - AppsmithErrorAction.DEFAULT, "Datasource configuration is invalid", ErrorType.DATASOURCE_CONFIGURATION_ERROR, null), - INVALID_DATASOURCE_CONFIGURATION(400, AppsmithErrorCode.INVALID_DATASOURCE_CONFIGURATION.getCode(), "Datasource configuration is invalid", - AppsmithErrorAction.DEFAULT, "Datasource configuration is invalid", ErrorType.DATASOURCE_CONFIGURATION_ERROR, null), - INVALID_ACTION_NAME(400, AppsmithErrorCode.INVALID_ACTION_NAME.getCode(), "Appsmith expects all entities to follow Javascript variable naming conventions. " - + "It must be a single word containing alphabets, numbers, or \"_\". Any other special characters like hyphens (\"-\"), comma (\",\"), hash (\"#\") etc. " - + "are not allowed. " - + "Please change the name.", AppsmithErrorAction.DEFAULT, "Invalid action name", ErrorType.CONFIGURATION_ERROR, null), - NO_CONFIGURATION_FOUND_IN_ACTION(400, AppsmithErrorCode.NO_CONFIGURATION_FOUND_IN_ACTION.getCode(), "No configurations found in this action", AppsmithErrorAction.DEFAULT, "No configurations found in this action", ErrorType.CONFIGURATION_ERROR, null), - NAME_CLASH_NOT_ALLOWED_IN_REFACTOR(400, AppsmithErrorCode.NAME_CLASH_NOT_ALLOWED_IN_REFACTOR.getCode(), "The new name {1} already exists in the current page. Choose another name.", AppsmithErrorAction.DEFAULT, "Name already taken", - ErrorType.BAD_REQUEST, null), - PAGE_DOESNT_BELONG_TO_APPLICATION(400, AppsmithErrorCode.PAGE_DOESNT_BELONG_TO_APPLICATION.getCode(), "Unexpected state. Page {0} does not seem belong to the application {1}. Please reach out to Appsmith customer support to resolve this.", - AppsmithErrorAction.LOG_EXTERNALLY, "Page doesn''t belong to this application", ErrorType.BAD_REQUEST, null), - INVALID_DYNAMIC_BINDING_REFERENCE(400, AppsmithErrorCode.INVALID_DYNAMIC_BINDING_REFERENCE.getCode(), - " \"widgetType\" : \"{0}\"," + - " \"bindingPath\" : \"{3}\"," + - " \"currentKey\" : \"{7}\"," + - " \"message\" : \"Binding path in the widget not found. Please reach out to Appsmith customer support to resolve this.\"," + - " \"widgetName\" : \"{1}\"," + - " \"widgetId\" : \"{2}\"," + - " \"pageId\" : \"{4}\"," + - " \"layoutId\" : \"{5}\"," + - " \"errorDetail\" : \"{8}\"," + - " \"dynamicBinding\" : {6}", - AppsmithErrorAction.LOG_EXTERNALLY, "Invalid dynamic binding reference", ErrorType.BAD_REQUEST, null), - USER_ALREADY_EXISTS_IN_WORKSPACE(400, AppsmithErrorCode.USER_ALREADY_EXISTS_IN_WORKSPACE.getCode(), "The user {0} has already been added to the workspace with role {1}. To change the role, please navigate to `Manage Users` page.", - AppsmithErrorAction.DEFAULT, "User already exists in this workspace", ErrorType.BAD_REQUEST, null), - UNAUTHORIZED_DOMAIN(401, AppsmithErrorCode.UNAUTHORIZED_DOMAIN.getCode(), "Invalid email domain {0} used for sign in/sign up. Please contact the administrator to configure this domain if this is unexpected.", - AppsmithErrorAction.DEFAULT, "Invalid or unauthorized email domain", ErrorType.AUTHENTICATION_ERROR, null), - USER_NOT_SIGNED_IN(401, AppsmithErrorCode.USER_NOT_SIGNED_IN.getCode(), "You are not logged in. Please sign in with the registered email ID or sign up", - AppsmithErrorAction.DEFAULT, "User not signed in", ErrorType.AUTHENTICATION_ERROR, null), - INVALID_PASSWORD_RESET(400, AppsmithErrorCode.INVALID_PASSWORD_RESET.getCode(), "Cannot find an outstanding reset password request for this email. Please initiate a request via \"forgot password\" " + - "button to reset your password", AppsmithErrorAction.DEFAULT, "Invalid password reset request", ErrorType.INTERNAL_ERROR, null), - INVALID_PASSWORD_LENGTH(400, AppsmithErrorCode.INVALID_PASSWORD_LENGTH.getCode(), "Password length should be between {0} and {1}", AppsmithErrorAction.DEFAULT, "Invalid password length", ErrorType.INTERNAL_ERROR, null), - JSON_PROCESSING_ERROR(400, AppsmithErrorCode.JSON_PROCESSING_ERROR.getCode(), "Json processing error with error {0}", AppsmithErrorAction.LOG_EXTERNALLY, "Json processing error", ErrorType.INTERNAL_ERROR, null), - INVALID_CREDENTIALS(200, AppsmithErrorCode.INVALID_CREDENTIALS.getCode(), "Invalid credentials provided. Did you input the credentials correctly?", AppsmithErrorAction.DEFAULT, "Invalid credentials", ErrorType.AUTHENTICATION_ERROR, null), - UNAUTHORIZED_ACCESS(403, AppsmithErrorCode.UNAUTHORIZED_ACCESS.getCode(), "Unauthorized access", AppsmithErrorAction.DEFAULT, "Unauthorized access", ErrorType.AUTHENTICATION_ERROR, null), - DUPLICATE_KEY(409, AppsmithErrorCode.DUPLICATE_KEY.getCode(), "Duplicate key error: An object with the name {0} already exists. Please use a different name or reach out to Appsmith customer support to resolve this.", - AppsmithErrorAction.DEFAULT, "Duplicate key", ErrorType.BAD_REQUEST, null), - DUPLICATE_KEY_PAGE_RELOAD(409, AppsmithErrorCode.DUPLICATE_KEY_OBJECT_CREATION.getCode(), "Duplicate key error: An object with the name {0} already exists. Please reload the page and try again.", - AppsmithErrorAction.DEFAULT, "Duplicate key", ErrorType.BAD_REQUEST, null), - USER_ALREADY_EXISTS_SIGNUP(409, AppsmithErrorCode.USER_ALREADY_EXISTS_SIGNUP.getCode(), "There is already an account registered with this email {0}. Please sign in instead.", - AppsmithErrorAction.DEFAULT, "Account already exists with this email", ErrorType.BAD_REQUEST, null), - ACTION_IS_NOT_AUTHORIZED(403, AppsmithErrorCode.ACTION_IS_NOT_AUTHORIZED.getCode(), "Uh oh! You do not have permissions to do : {0}", AppsmithErrorAction.DEFAULT, "Permission denied", ErrorType.AUTHENTICATION_ERROR, null), - NO_RESOURCE_FOUND(404, AppsmithErrorCode.NO_RESOURCE_FOUND.getCode(), "Unable to find {0} {1}", AppsmithErrorAction.DEFAULT, "No resource found", ErrorType.INTERNAL_ERROR, null), - USER_NOT_FOUND(404, AppsmithErrorCode.USER_NOT_FOUND.getCode(), "Unable to find user with email {0}", AppsmithErrorAction.DEFAULT, "No user found", ErrorType.INTERNAL_ERROR, null), - ACL_NO_RESOURCE_FOUND(404, AppsmithErrorCode.ACL_NO_RESOURCE_FOUND.getCode(), "Unable to find {0} {1}. Either the asset doesn''t exist or you don''t have required permissions", - AppsmithErrorAction.DEFAULT, "No resource found or permission denied", ErrorType.INTERNAL_ERROR, null), - GENERIC_BAD_REQUEST(400, AppsmithErrorCode.GENERIC_BAD_REQUEST.getCode(), "Bad request: {0}", AppsmithErrorAction.DEFAULT, "Invalid request", ErrorType.BAD_REQUEST, null), - GENERIC_REQUEST_BODY_PARSE_ERROR(400, AppsmithErrorCode.MALFORMED_REQUEST.getCode(), "Server cannot understand the request, malformed payload. Contact support for help.", AppsmithErrorAction.DEFAULT, "Malformed request body", ErrorType.BAD_REQUEST, null), - VALIDATION_FAILURE(400, AppsmithErrorCode.VALIDATION_FAILURE.getCode(), "Validation Failure(s): {0}", AppsmithErrorAction.DEFAULT, "Validation failed", ErrorType.INTERNAL_ERROR, null), - INVALID_CURL_COMMAND(400, AppsmithErrorCode.INVALID_CURL_COMMAND.getCode(), "Invalid cURL command, couldn''t import.", AppsmithErrorAction.DEFAULT, "Invalid cURL command", ErrorType.ARGUMENT_ERROR, null), - INVALID_LOGIN_METHOD(401, AppsmithErrorCode.INVALID_LOGIN_METHOD.getCode(), "Please use {0} authentication to login to Appsmith", AppsmithErrorAction.DEFAULT, "Invalid login method", ErrorType.INTERNAL_ERROR, null), - INVALID_GIT_CONFIGURATION(400, AppsmithErrorCode.INVALID_GIT_CONFIGURATION.getCode(), "Git configuration is invalid. Details: {0}", AppsmithErrorAction.DEFAULT, "Invalid Git configuration", ErrorType.GIT_CONFIGURATION_ERROR, null), - INVALID_GIT_SSH_CONFIGURATION(400, AppsmithErrorCode.INVALID_GIT_SSH_CONFIGURATION.getCode(), "SSH key is not configured correctly. Did you forget to add the SSH key to your remote repository? Please try again by reconfiguring the SSH key with write access.", AppsmithErrorAction.DEFAULT, "SSH key not configured", ErrorType.GIT_CONFIGURATION_ERROR, ErrorReferenceDocUrl.GIT_DEPLOY_KEY.getDocUrl()), - INVALID_GIT_REPO(400, AppsmithErrorCode.INVALID_GIT_REPO.getCode(), "The remote repository is not empty. Please create a new empty repository and configure the SSH keys. " + - "If you wish to clone and build an application from an existing remote repository, please use the \"Import from a Git repository\" option in the home page.", AppsmithErrorAction.DEFAULT, "Invalid Git repository", ErrorType.GIT_CONFIGURATION_ERROR, null), - DEFAULT_RESOURCES_UNAVAILABLE(400, AppsmithErrorCode.DEFAULT_RESOURCES_UNAVAILABLE.getCode(), "Unexpected state. Default resources are unavailable for {0} with id {1}. Please reach out to Appsmith customer support to resolve this.", - AppsmithErrorAction.LOG_EXTERNALLY, "Default resources not found", ErrorType.BAD_REQUEST, null), - GIT_MERGE_FAILED_REMOTE_CHANGES(406, AppsmithErrorCode.GIT_MERGE_FAILED_REMOTE_CHANGES.getCode(), "Remote is ahead of local by {0} commits on branch {1}. Please pull remote changes first and try again.", AppsmithErrorAction.DEFAULT, "Git merge failed for remote changes", ErrorType.GIT_ACTION_EXECUTION_ERROR, ErrorReferenceDocUrl.GIT_UPSTREAM_CHANGES.getDocUrl()), - GIT_MERGE_FAILED_LOCAL_CHANGES(406, AppsmithErrorCode.GIT_MERGE_FAILED_LOCAL_CHANGES.getCode(), "There are uncommitted changes present in your local branch {0}. Please commit them first and try again", AppsmithErrorAction.DEFAULT, "Git merge failed for local changes", ErrorType.GIT_ACTION_EXECUTION_ERROR, null), - REMOVE_LAST_WORKSPACE_ADMIN_ERROR(400, AppsmithErrorCode.REMOVE_LAST_WORKSPACE_ADMIN_ERROR.getCode(), "The last admin cannot be removed from the workspace", AppsmithErrorAction.DEFAULT, "Last admin cannot be removed", ErrorType.INTERNAL_ERROR, null), - INVALID_CRUD_PAGE_REQUEST(400, AppsmithErrorCode.INVALID_CRUD_PAGE_REQUEST.getCode(), "Unable to process page generation request, {0}", AppsmithErrorAction.DEFAULT, "Invalid page generation request", ErrorType.BAD_REQUEST, null), - UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH(400, AppsmithErrorCode.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH.getCode(), "This operation is not supported for remote branch {0}. Please use local branches only to proceed", AppsmithErrorAction.DEFAULT, "Unsupported Operation", ErrorType.BAD_REQUEST, null), - ROLES_FROM_SAME_WORKSPACE(400, AppsmithErrorCode.ROLES_FROM_SAME_WORKSPACE.getCode(), "Roles for the same Workspace provided or already exists.", AppsmithErrorAction.DEFAULT, "Roles already exist", ErrorType.ARGUMENT_ERROR, null), - INTERNAL_SERVER_ERROR(500, AppsmithErrorCode.INTERNAL_SERVER_ERROR.getCode(), "Internal server error while processing request", AppsmithErrorAction.LOG_EXTERNALLY, "Internal server error", ErrorType.INTERNAL_ERROR, null), - REPOSITORY_SAVE_FAILED(500, AppsmithErrorCode.REPOSITORY_SAVE_FAILED.getCode(), "Failed to save the repository. Please try again later.", AppsmithErrorAction.DEFAULT, "Failed to save", ErrorType.INTERNAL_ERROR, null), - PLUGIN_INSTALLATION_FAILED_DOWNLOAD_ERROR(500, AppsmithErrorCode.PLUGIN_INSTALLATION_FAILED_DOWNLOAD_ERROR.getCode(), "Plugin installation failed due to an error while " + - "downloading it. Check the jar location & try again.", AppsmithErrorAction.LOG_EXTERNALLY, "Plugin installation failed", ErrorType.INTERNAL_ERROR, null), - PLUGIN_RUN_FAILED(500, AppsmithErrorCode.PLUGIN_RUN_FAILED.getCode(), "Plugin execution failed with error {0}", AppsmithErrorAction.DEFAULT, "Plugin execution failed", ErrorType.INTERNAL_ERROR, null), - PLUGIN_EXECUTION_TIMEOUT(504, AppsmithErrorCode.PLUGIN_EXECUTION_TIMEOUT.getCode(), "Plugin execution exceeded the maximum allowed time. Please increase the timeout in your action settings or check your backend action endpoint", - AppsmithErrorAction.DEFAULT, "Timeout in plugin execution", ErrorType.CONNECTIVITY_ERROR, null), - PLUGIN_LOAD_FORM_JSON_FAIL(500, AppsmithErrorCode.PLUGIN_LOAD_FORM_JSON_FAIL.getCode(), "[{0}] Unable to load datasource form configuration. Details: {1}.", - AppsmithErrorAction.LOG_EXTERNALLY, "Unable to load datasource form configuration", ErrorType.INTERNAL_ERROR, null), - PLUGIN_LOAD_TEMPLATES_FAIL(500, AppsmithErrorCode.PLUGIN_LOAD_TEMPLATES_FAIL.getCode(), "Unable to load datasource templates. Details: {0}.", - AppsmithErrorAction.LOG_EXTERNALLY, "Unable to load datasource templates", ErrorType.INTERNAL_ERROR, null), - IO_ERROR(503, AppsmithErrorCode.IO_ERROR.getCode(), "IO action failed with error {0}", AppsmithErrorAction.DEFAULT, "I/O error", ErrorType.INTERNAL_ERROR, null), - MARKETPLACE_TIMEOUT(504, AppsmithErrorCode.MARKETPLACE_TIMEOUT.getCode(), "Marketplace is responding too slowly. Please try again later", - AppsmithErrorAction.DEFAULT, "Timeout in marketplace", ErrorType.CONNECTIVITY_ERROR, null), - DATASOURCE_HAS_ACTIONS(409, AppsmithErrorCode.DATASOURCE_HAS_ACTIONS.getCode(), "Cannot delete datasource since it has {0} action(s) using it.", - AppsmithErrorAction.DEFAULT, "Datasource cannot be deleted", ErrorType.BAD_REQUEST, null), - WORKSPACE_ID_NOT_GIVEN(400, AppsmithErrorCode.WORKSPACE_ID_NOT_GIVEN.getCode(), "Missing workspace id. Please enter one.", AppsmithErrorAction.DEFAULT, "Missing workspace id", ErrorType.ARGUMENT_ERROR, null), - INVALID_CURL_METHOD(400, AppsmithErrorCode.INVALID_CURL_METHOD.getCode(), "Invalid method in cURL command: {0}.", AppsmithErrorAction.DEFAULT, "Invalid method in cURL command", ErrorType.ARGUMENT_ERROR, null), - OAUTH_NOT_AVAILABLE(500, AppsmithErrorCode.OAUTH_NOT_AVAILABLE.getCode(), "Login with {0} is not supported.", AppsmithErrorAction.LOG_EXTERNALLY, "Unsupported login method", ErrorType.BAD_REQUEST, null), - MARKETPLACE_NOT_CONFIGURED(500, AppsmithErrorCode.MARKETPLACE_NOT_CONFIGURED.getCode(), "Marketplace is not configured.", AppsmithErrorAction.DEFAULT, "Marketplace not configured", ErrorType.CONFIGURATION_ERROR, null), - PAYLOAD_TOO_LARGE(413, AppsmithErrorCode.PAYLOAD_TOO_LARGE.getCode(), "The request payload is too large. Max allowed size for request payload is {0} KB", - AppsmithErrorAction.DEFAULT, "Payload exceeds max allowed size", ErrorType.CONNECTIVITY_ERROR, null), - SIGNUP_DISABLED(403, AppsmithErrorCode.SIGNUP_DISABLED.getCode(), "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite for user {0}.", - AppsmithErrorAction.DEFAULT, "Signup disabled", ErrorType.INTERNAL_ERROR, null), - FAIL_UPDATE_USER_IN_SESSION(500, AppsmithErrorCode.FAIL_UPDATE_USER_IN_SESSION.getCode(), "Unable to update user in session.", AppsmithErrorAction.LOG_EXTERNALLY, "Unable to update user in session", ErrorType.INTERNAL_ERROR, null), - APPLICATION_FORKING_NOT_ALLOWED(403, AppsmithErrorCode.APPLICATION_FORKING_NOT_ALLOWED.getCode(), "Forking this application is not permitted at this time.", AppsmithErrorAction.DEFAULT, "Forking application not permitted", ErrorType.INTERNAL_ERROR, null), - GOOGLE_RECAPTCHA_TIMEOUT(504, AppsmithErrorCode.GOOGLE_RECAPTCHA_TIMEOUT.getCode(), "Google recaptcha verification timeout. Please try again.", AppsmithErrorAction.DEFAULT, "Timeout in Google recaptcha verification", ErrorType.INTERNAL_ERROR, null), - GOOGLE_RECAPTCHA_FAILED(401, AppsmithErrorCode.GOOGLE_RECAPTCHA_FAILED.getCode(), "Google recaptcha verification failed. Please try again.", AppsmithErrorAction.DEFAULT, "Google recaptcha verification failed", ErrorType.INTERNAL_ERROR, null), - UNKNOWN_ACTION_RESULT_DATA_TYPE(500, AppsmithErrorCode.UNKNOWN_ACTION_RESULT_DATA_TYPE.getCode(), "Appsmith has encountered an unknown action result data type: {0}. " + - "Please contact Appsmith customer support to resolve this.", AppsmithErrorAction.LOG_EXTERNALLY, "Unexpected data type", ErrorType.BAD_REQUEST, null), - INVALID_CURL_HEADER(400, AppsmithErrorCode.INVALID_CURL_HEADER.getCode(), "Invalid header in cURL command: {0}.", AppsmithErrorAction.DEFAULT, "Invalid header in cURL command", ErrorType.ARGUMENT_ERROR, null), - AUTHENTICATION_FAILURE(500, AppsmithErrorCode.AUTHENTICATION_FAILURE.getCode(), "Authentication failed with error: {0}", AppsmithErrorAction.DEFAULT, "Authentication failed", ErrorType.AUTHENTICATION_ERROR, null), - INSTANCE_REGISTRATION_FAILURE(500, AppsmithErrorCode.INSTANCE_REGISTRATION_FAILURE.getCode(), "Registration for instance failed with error: {0}", AppsmithErrorAction.LOG_EXTERNALLY, "Registration failed for this instance", ErrorType.INTERNAL_ERROR, null), - TOO_MANY_REQUESTS(429, AppsmithErrorCode.TOO_MANY_REQUESTS.getCode(), "Too many requests received. Please try later.", AppsmithErrorAction.DEFAULT, "Too many requests", ErrorType.INTERNAL_ERROR, null), - INVALID_JS_ACTION(400, AppsmithErrorCode.INVALID_JS_ACTION.getCode(), "Something went wrong while trying to parse this action. Please check the JS Object for errors.", AppsmithErrorAction.DEFAULT, "Invalid action in JS Object", ErrorType.BAD_REQUEST, null), - CYCLICAL_DEPENDENCY_ERROR(400, AppsmithErrorCode.CYCLICAL_DEPENDENCY_ERROR.getCode(), "Cyclical dependency error encountered while parsing relationship [{0}] where the relationship is denoted as (source : target).", AppsmithErrorAction.DEFAULT, "Cyclical Dependency in Page Load Actions", ErrorType.CONFIGURATION_ERROR, null), - CLOUD_SERVICES_ERROR(500, AppsmithErrorCode.CLOUD_SERVICES_ERROR.getCode(), "Received error from cloud services {0}", AppsmithErrorAction.DEFAULT, "Error in cloud services", ErrorType.INTERNAL_ERROR, null), - GIT_APPLICATION_LIMIT_ERROR(402, AppsmithErrorCode.GIT_APPLICATION_LIMIT_ERROR.getCode(), "You have reached the maximum number of private git repo counts which can be connected to the workspace. Please reach out to Appsmith support to opt for commercial plan.", AppsmithErrorAction.DEFAULT, "Maximum number of Git repo connection limit reached", ErrorType.EE_FEATURE_ERROR, null), - GIT_ACTION_FAILED(400, AppsmithErrorCode.GIT_ACTION_FAILED.getCode(), "git {0} failed. \nDetails: {1}", AppsmithErrorAction.DEFAULT, "Git failed", ErrorType.GIT_ACTION_EXECUTION_ERROR, null), - GIT_FILE_SYSTEM_ERROR(503, AppsmithErrorCode.GIT_FILE_SYSTEM_ERROR.getCode(), "Error while accessing the file system. {0}", AppsmithErrorAction.DEFAULT, "Git file system error", ErrorType.GIT_CONFIGURATION_ERROR, ErrorReferenceDocUrl.FILE_PATH_NOT_SET.getDocUrl()), - GIT_EXECUTION_TIMEOUT(504, AppsmithErrorCode.GIT_EXECUTION_TIMEOUT.getCode(), "Git command execution exceeded the maximum allowed time, please contact Appsmith support for more details", AppsmithErrorAction.DEFAULT, "Timeout in Git command execution", ErrorType.CONNECTIVITY_ERROR, null), - INCOMPATIBLE_IMPORTED_JSON(400, AppsmithErrorCode.INCOMPATIBLE_IMPORTED_JSON.getCode(), "Provided file is incompatible, please upgrade your instance to resolve this conflict.", AppsmithErrorAction.DEFAULT, "Incompatible Json file", ErrorType.BAD_REQUEST, null), - GIT_MERGE_CONFLICTS(400, AppsmithErrorCode.GIT_MERGE_CONFLICTS.getCode(), "Merge conflicts found: {0}", AppsmithErrorAction.DEFAULT, "Merge conflicts found", ErrorType.GIT_ACTION_EXECUTION_ERROR, ErrorReferenceDocUrl.GIT_MERGE_CONFLICT.getDocUrl()), - GIT_PULL_CONFLICTS(400, AppsmithErrorCode.GIT_PULL_CONFLICTS.getCode(), "Merge conflicts found during the pull operation: {0}", AppsmithErrorAction.DEFAULT, "Merge conflicts found during the pull operation", ErrorType.GIT_ACTION_EXECUTION_ERROR, ErrorReferenceDocUrl.GIT_PULL_CONFLICT.getDocUrl()), - SSH_KEY_GENERATION_ERROR(500, AppsmithErrorCode.SSH_KEY_GENERATION_ERROR.getCode(), "Failed to generate SSH keys, please contact Appsmith support for more details", AppsmithErrorAction.DEFAULT, "Failed to generate SSH keys", ErrorType.GIT_CONFIGURATION_ERROR, null), - GIT_GENERIC_ERROR(504, AppsmithErrorCode.GIT_GENERIC_ERROR.getCode(), "Git command execution error: {0}", AppsmithErrorAction.DEFAULT, "Git command execution error", ErrorType.GIT_ACTION_EXECUTION_ERROR, null), - GIT_UPSTREAM_CHANGES(400, AppsmithErrorCode.GIT_UPSTREAM_CHANGES.getCode(), "Looks like there are pending upstream changes. To prevent you from losing history, we will pull the changes and push them to your repo.", AppsmithErrorAction.DEFAULT, "Git push failed for pending upstream changes", ErrorType.GIT_UPSTREAM_CHANGES_PUSH_EXECUTION_ERROR, ErrorReferenceDocUrl.GIT_UPSTREAM_CHANGES.getDocUrl()), - GENERIC_JSON_IMPORT_ERROR(400, AppsmithErrorCode.GENERIC_JSON_IMPORT_ERROR.getCode(), "Unable to import application in workspace {0}. {1}", AppsmithErrorAction.DEFAULT, "Unable to import application in workspace", ErrorType.BAD_REQUEST, null), - FILE_PART_DATA_BUFFER_ERROR(500, AppsmithErrorCode.FILE_PART_DATA_BUFFER_ERROR.getCode(), "Failed to upload file with error: {0}", AppsmithErrorAction.DEFAULT, "Failed to upload file", ErrorType.BAD_REQUEST, null), - MIGRATION_ERROR(500, AppsmithErrorCode.MIGRATION_ERROR.getCode(), "This action is already migrated", AppsmithErrorAction.DEFAULT, "Action already migrated", ErrorType.INTERNAL_ERROR, null), - INVALID_GIT_SSH_URL(400, AppsmithErrorCode.INVALID_GIT_SSH_URL.getCode(), "Please enter valid SSH URL of your repository", AppsmithErrorAction.DEFAULT, "Invalid SSH URL", ErrorType.GIT_CONFIGURATION_ERROR, null), - REPOSITORY_NOT_FOUND(404, AppsmithErrorCode.REPOSITORY_NOT_FOUND.getCode(), "Unable to find the remote repository for application {0}, please check the deploy key configuration in your remote repository.", AppsmithErrorAction.DEFAULT, "Repository not found", ErrorType.REPOSITORY_NOT_FOUND, null), - UNKNOWN_PLUGIN_REFERENCE(400, AppsmithErrorCode.UNKNOWN_PLUGIN_REFERENCE.getCode(), "Unable to find the plugin {0}. Please reach out to Appsmith customer support to resolve this.", AppsmithErrorAction.DEFAULT, "Unknown plugin", ErrorType.CONFIGURATION_ERROR, null), - ENV_FILE_NOT_FOUND(500, AppsmithErrorCode.ENV_FILE_NOT_FOUND.getCode(), "Admin Settings is unavailable. Unable to read and write to Environment file.", AppsmithErrorAction.DEFAULT, "Environment file not found", ErrorType.CONFIGURATION_ERROR, null), - PUBLIC_APP_NO_PERMISSION_GROUP(500, AppsmithErrorCode.PUBLIC_APP_NO_PERMISSION_GROUP.getCode(), "Invalid state. Public application does not have the required roles set for public access. Please reach out to Appsmith customer support to resolve this.", AppsmithErrorAction.LOG_EXTERNALLY, "Required permission missing for public access", ErrorType.INTERNAL_ERROR, null), - RTS_SERVER_ERROR(500, AppsmithErrorCode.RTS_SERVER_ERROR.getCode(), "RTS server error while processing request: {0}", AppsmithErrorAction.LOG_EXTERNALLY, "RTS server error", ErrorType.INTERNAL_ERROR, null), - SCHEMA_MISMATCH_ERROR(500, AppsmithErrorCode.SCHEMA_MISMATCH_ERROR.getCode(), "Looks like you skipped some required update(s), please go back to the mandatory upgrade path {0}, or refer to ''https://docs.appsmith.com/'' for more info", AppsmithErrorAction.LOG_EXTERNALLY, "Schema mismatch error", ErrorType.INTERNAL_ERROR, null), - SCHEMA_VERSION_NOT_FOUND_ERROR(500, AppsmithErrorCode.SCHEMA_VERSION_NOT_FOUND_ERROR.getCode(), "Could not find mandatory instance schema version config. Please reach out to Appsmith customer support to resolve this.", AppsmithErrorAction.LOG_EXTERNALLY, "Schema version not found", ErrorType.INTERNAL_ERROR, null), - HEALTHCHECK_TIMEOUT(408, AppsmithErrorCode.HEALTHCHECK_TIMEOUT.getCode(), "{0} connection timed out.", AppsmithErrorAction.DEFAULT, "Connection timeout during health check", ErrorType.CONNECTIVITY_ERROR, null), - SERVER_NOT_READY(500, AppsmithErrorCode.SERVER_NOT_READY.getCode(), "Appsmith server is not ready. Please try again in some time.", AppsmithErrorAction.LOG_EXTERNALLY, "Server not ready", ErrorType.INTERNAL_ERROR, null), - SESSION_BAD_STATE(500, AppsmithErrorCode.SESSION_BAD_STATE.getCode(), "User session is invalid. Please log out and log in again.", AppsmithErrorAction.LOG_EXTERNALLY, "Invalid user session", ErrorType.INTERNAL_ERROR, null), - INVALID_LICENSE_KEY_ENTERED(400, AppsmithErrorCode.INVALID_LICENSE_KEY_ENTERED.getCode(), "The license key entered is invalid. Please try again.", AppsmithErrorAction.DEFAULT, "Invalid license key", ErrorType.ARGUMENT_ERROR, null), - GIT_FILE_IN_USE(500, AppsmithErrorCode.GIT_FILE_IN_USE.getCode(), "Your Git repo is in use by another member of your team. Usually, this takes a few seconds. Please try again a little later.", AppsmithErrorAction.DEFAULT, "Git repo is locked", ErrorType.GIT_ACTION_EXECUTION_ERROR, null), - CSRF_TOKEN_INVALID(403, AppsmithErrorCode.CSRF_TOKEN_INVALID.getCode(), "CSRF token missing/invalid. Please try again.", AppsmithErrorAction.DEFAULT, "CSRF token missing/invalid", ErrorType.BAD_REQUEST, null), - UNSUPPORTED_IMPORT_OPERATION_FOR_GIT_CONNECTED_APPLICATION(400, AppsmithErrorCode.UNSUPPORTED_IMPORT_OPERATION.getCode(), "Import application via file is not supported for git connected application. Please use Git Pull to update and sync your application.", AppsmithErrorAction.DEFAULT, "Unsupported operation", ErrorType.BAD_REQUEST, null), + // Ref syntax for message templates: + // https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/MessageFormat.html + INVALID_PARAMETER( + 400, + AppsmithErrorCode.INVALID_PARAMETER.getCode(), + "Please enter a valid parameter {0}.", + AppsmithErrorAction.DEFAULT, + "Invalid parameter", + ErrorType.ARGUMENT_ERROR, + null), + EMPTY_CURL_INPUT_STATEMENT( + 400, + AppsmithErrorCode.EMPTY_CURL_INPUT_STATEMENT.getCode(), + "Input CURL statement is empty / null. Please edit the input box to provide a valid CURL statement.", + AppsmithErrorAction.DEFAULT, + "Invalid parameter", + ErrorType.ARGUMENT_ERROR, + null), + PLUGIN_NOT_INSTALLED( + 400, + AppsmithErrorCode.PLUGIN_NOT_INSTALLED.getCode(), + "Plugin {0} not installed", + AppsmithErrorAction.DEFAULT, + "Plugin not installed", + ErrorType.INTERNAL_ERROR, + null), + PLUGIN_ID_NOT_GIVEN( + 400, + AppsmithErrorCode.PLUGIN_ID_NOT_GIVEN.getCode(), + "Missing plugin id. Please enter one.", + AppsmithErrorAction.DEFAULT, + "Missing plugin id", + ErrorType.INTERNAL_ERROR, + null), + DATASOURCE_NOT_GIVEN( + 400, + AppsmithErrorCode.DATASOURCE_NOT_GIVEN.getCode(), + "Missing datasource. Add/enter/connect a datasource to create a valid action.", + AppsmithErrorAction.DEFAULT, + "Missing datasource", + ErrorType.ARGUMENT_ERROR, + null), + PAGE_ID_NOT_GIVEN( + 400, + AppsmithErrorCode.PAGE_ID_NOT_GIVEN.getCode(), + "Missing page id. Please enter one.", + AppsmithErrorAction.DEFAULT, + "Missing page id", + ErrorType.ARGUMENT_ERROR, + null), + DUPLICATE_KEY_USER_ERROR( + 400, + AppsmithErrorCode.DUPLICATE_KEY_USER_ERROR.getCode(), + "{0} already exists. Please use a different {1}", + AppsmithErrorAction.DEFAULT, + "Name already used", + ErrorType.BAD_REQUEST, + null), + PAGE_DOESNT_BELONG_TO_USER_WORKSPACE( + 400, + AppsmithErrorCode.PAGE_DOESNT_BELONG_TO_USER_WORKSPACE.getCode(), + "Page {0} does not belong to the current user {1} " + "workspace", + AppsmithErrorAction.LOG_EXTERNALLY, + "Page doesn''t belong to this workspace", + ErrorType.BAD_REQUEST, + null), + UNSUPPORTED_OPERATION( + 400, + AppsmithErrorCode.UNSUPPORTED_OPERATION.getCode(), + "Unsupported operation", + AppsmithErrorAction.DEFAULT, + "Unsupported operation", + ErrorType.BAD_REQUEST, + null), + DEPRECATED_API( + 400, + AppsmithErrorCode.DEPRECATED_API.getCode(), + "This API has been deprecated, please contact the Appsmith support for more details.", + AppsmithErrorAction.DEFAULT, + "Deprecated API", + ErrorType.BAD_REQUEST, + null), + USER_DOESNT_BELONG_ANY_WORKSPACE( + 400, + AppsmithErrorCode.USER_DOESNT_BELONG_ANY_WORKSPACE.getCode(), + "User {0} does not belong to any workspace", + AppsmithErrorAction.LOG_EXTERNALLY, + "User doesn''t belong to any workspace", + ErrorType.INTERNAL_ERROR, + null), + USER_DOESNT_BELONG_TO_WORKSPACE( + 400, + AppsmithErrorCode.USER_DOESNT_BELONG_TO_WORKSPACE.getCode(), + "User {0} does not belong to the workspace with id {1}", + AppsmithErrorAction.LOG_EXTERNALLY, + "User doesn''t belong to this workspace", + ErrorType.INTERNAL_ERROR, + null), + NO_CONFIGURATION_FOUND_IN_DATASOURCE( + 400, + AppsmithErrorCode.NO_CONFIGURATION_FOUND_IN_DATASOURCE.getCode(), + "No datasource configuration found. Please configure it and try again.", + AppsmithErrorAction.DEFAULT, + "Datasource configuration is invalid", + ErrorType.DATASOURCE_CONFIGURATION_ERROR, + null), + INVALID_ACTION_COLLECTION( + 400, + AppsmithErrorCode.INVALID_ACTION_COLLECTION.getCode(), + "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", + AppsmithErrorAction.DEFAULT, + "Collection configuration is invalid", + ErrorType.CONFIGURATION_ERROR, + null), + INVALID_ACTION( + 400, + AppsmithErrorCode.INVALID_ACTION.getCode(), + "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", + AppsmithErrorAction.DEFAULT, + "Action configuration is invalid", + ErrorType.CONFIGURATION_ERROR, + null), + INVALID_DATASOURCE( + 400, + AppsmithErrorCode.INVALID_DATASOURCE.getCode(), + "{0} is not correctly configured. Please fix the following and then re-run: \n{1}", + AppsmithErrorAction.DEFAULT, + "Datasource configuration is invalid", + ErrorType.DATASOURCE_CONFIGURATION_ERROR, + null), + INVALID_DATASOURCE_CONFIGURATION( + 400, + AppsmithErrorCode.INVALID_DATASOURCE_CONFIGURATION.getCode(), + "Datasource configuration is invalid", + AppsmithErrorAction.DEFAULT, + "Datasource configuration is invalid", + ErrorType.DATASOURCE_CONFIGURATION_ERROR, + null), + INVALID_ACTION_NAME( + 400, + AppsmithErrorCode.INVALID_ACTION_NAME.getCode(), + "Appsmith expects all entities to follow Javascript variable naming conventions. " + + "It must be a single word containing alphabets, numbers, or \"_\". Any other special characters like hyphens (\"-\"), comma (\",\"), hash (\"#\") etc. " + + "are not allowed. " + + "Please change the name.", + AppsmithErrorAction.DEFAULT, + "Invalid action name", + ErrorType.CONFIGURATION_ERROR, + null), + NO_CONFIGURATION_FOUND_IN_ACTION( + 400, + AppsmithErrorCode.NO_CONFIGURATION_FOUND_IN_ACTION.getCode(), + "No configurations found in this action", + AppsmithErrorAction.DEFAULT, + "No configurations found in this action", + ErrorType.CONFIGURATION_ERROR, + null), + NAME_CLASH_NOT_ALLOWED_IN_REFACTOR( + 400, + AppsmithErrorCode.NAME_CLASH_NOT_ALLOWED_IN_REFACTOR.getCode(), + "The new name {1} already exists in the current page. Choose another name.", + AppsmithErrorAction.DEFAULT, + "Name already taken", + ErrorType.BAD_REQUEST, + null), + PAGE_DOESNT_BELONG_TO_APPLICATION( + 400, + AppsmithErrorCode.PAGE_DOESNT_BELONG_TO_APPLICATION.getCode(), + "Unexpected state. Page {0} does not seem belong to the application {1}. Please reach out to Appsmith customer support to resolve this.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Page doesn''t belong to this application", + ErrorType.BAD_REQUEST, + null), + INVALID_DYNAMIC_BINDING_REFERENCE( + 400, + AppsmithErrorCode.INVALID_DYNAMIC_BINDING_REFERENCE.getCode(), + " \"widgetType\" : \"{0}\"," + " \"bindingPath\" : \"{3}\"," + + " \"currentKey\" : \"{7}\"," + + " \"message\" : \"Binding path in the widget not found. Please reach out to Appsmith customer support to resolve this.\"," + + " \"widgetName\" : \"{1}\"," + + " \"widgetId\" : \"{2}\"," + + " \"pageId\" : \"{4}\"," + + " \"layoutId\" : \"{5}\"," + + " \"errorDetail\" : \"{8}\"," + + " \"dynamicBinding\" : {6}", + AppsmithErrorAction.LOG_EXTERNALLY, + "Invalid dynamic binding reference", + ErrorType.BAD_REQUEST, + null), + USER_ALREADY_EXISTS_IN_WORKSPACE( + 400, + AppsmithErrorCode.USER_ALREADY_EXISTS_IN_WORKSPACE.getCode(), + "The user {0} has already been added to the workspace with role {1}. To change the role, please navigate to `Manage Users` page.", + AppsmithErrorAction.DEFAULT, + "User already exists in this workspace", + ErrorType.BAD_REQUEST, + null), + UNAUTHORIZED_DOMAIN( + 401, + AppsmithErrorCode.UNAUTHORIZED_DOMAIN.getCode(), + "Invalid email domain {0} used for sign in/sign up. Please contact the administrator to configure this domain if this is unexpected.", + AppsmithErrorAction.DEFAULT, + "Invalid or unauthorized email domain", + ErrorType.AUTHENTICATION_ERROR, + null), + USER_NOT_SIGNED_IN( + 401, + AppsmithErrorCode.USER_NOT_SIGNED_IN.getCode(), + "You are not logged in. Please sign in with the registered email ID or sign up", + AppsmithErrorAction.DEFAULT, + "User not signed in", + ErrorType.AUTHENTICATION_ERROR, + null), + INVALID_PASSWORD_RESET( + 400, + AppsmithErrorCode.INVALID_PASSWORD_RESET.getCode(), + "Cannot find an outstanding reset password request for this email. Please initiate a request via \"forgot password\" " + + "button to reset your password", + AppsmithErrorAction.DEFAULT, + "Invalid password reset request", + ErrorType.INTERNAL_ERROR, + null), + INVALID_PASSWORD_LENGTH( + 400, + AppsmithErrorCode.INVALID_PASSWORD_LENGTH.getCode(), + "Password length should be between {0} and {1}", + AppsmithErrorAction.DEFAULT, + "Invalid password length", + ErrorType.INTERNAL_ERROR, + null), + JSON_PROCESSING_ERROR( + 400, + AppsmithErrorCode.JSON_PROCESSING_ERROR.getCode(), + "Json processing error with error {0}", + AppsmithErrorAction.LOG_EXTERNALLY, + "Json processing error", + ErrorType.INTERNAL_ERROR, + null), + INVALID_CREDENTIALS( + 200, + AppsmithErrorCode.INVALID_CREDENTIALS.getCode(), + "Invalid credentials provided. Did you input the credentials correctly?", + AppsmithErrorAction.DEFAULT, + "Invalid credentials", + ErrorType.AUTHENTICATION_ERROR, + null), + UNAUTHORIZED_ACCESS( + 403, + AppsmithErrorCode.UNAUTHORIZED_ACCESS.getCode(), + "Unauthorized access", + AppsmithErrorAction.DEFAULT, + "Unauthorized access", + ErrorType.AUTHENTICATION_ERROR, + null), + DUPLICATE_KEY( + 409, + AppsmithErrorCode.DUPLICATE_KEY.getCode(), + "Duplicate key error: An object with the name {0} already exists. Please use a different name or reach out to Appsmith customer support to resolve this.", + AppsmithErrorAction.DEFAULT, + "Duplicate key", + ErrorType.BAD_REQUEST, + null), + DUPLICATE_KEY_PAGE_RELOAD( + 409, + AppsmithErrorCode.DUPLICATE_KEY_OBJECT_CREATION.getCode(), + "Duplicate key error: An object with the name {0} already exists. Please reload the page and try again.", + AppsmithErrorAction.DEFAULT, + "Duplicate key", + ErrorType.BAD_REQUEST, + null), + USER_ALREADY_EXISTS_SIGNUP( + 409, + AppsmithErrorCode.USER_ALREADY_EXISTS_SIGNUP.getCode(), + "There is already an account registered with this email {0}. Please sign in instead.", + AppsmithErrorAction.DEFAULT, + "Account already exists with this email", + ErrorType.BAD_REQUEST, + null), + ACTION_IS_NOT_AUTHORIZED( + 403, + AppsmithErrorCode.ACTION_IS_NOT_AUTHORIZED.getCode(), + "Uh oh! You do not have permissions to do : {0}", + AppsmithErrorAction.DEFAULT, + "Permission denied", + ErrorType.AUTHENTICATION_ERROR, + null), + NO_RESOURCE_FOUND( + 404, + AppsmithErrorCode.NO_RESOURCE_FOUND.getCode(), + "Unable to find {0} {1}", + AppsmithErrorAction.DEFAULT, + "No resource found", + ErrorType.INTERNAL_ERROR, + null), + USER_NOT_FOUND( + 404, + AppsmithErrorCode.USER_NOT_FOUND.getCode(), + "Unable to find user with email {0}", + AppsmithErrorAction.DEFAULT, + "No user found", + ErrorType.INTERNAL_ERROR, + null), + ACL_NO_RESOURCE_FOUND( + 404, + AppsmithErrorCode.ACL_NO_RESOURCE_FOUND.getCode(), + "Unable to find {0} {1}. Either the asset doesn''t exist or you don''t have required permissions", + AppsmithErrorAction.DEFAULT, + "No resource found or permission denied", + ErrorType.INTERNAL_ERROR, + null), + GENERIC_BAD_REQUEST( + 400, + AppsmithErrorCode.GENERIC_BAD_REQUEST.getCode(), + "Bad request: {0}", + AppsmithErrorAction.DEFAULT, + "Invalid request", + ErrorType.BAD_REQUEST, + null), + GENERIC_REQUEST_BODY_PARSE_ERROR( + 400, + AppsmithErrorCode.MALFORMED_REQUEST.getCode(), + "Server cannot understand the request, malformed payload. Contact support for help.", + AppsmithErrorAction.DEFAULT, + "Malformed request body", + ErrorType.BAD_REQUEST, + null), + VALIDATION_FAILURE( + 400, + AppsmithErrorCode.VALIDATION_FAILURE.getCode(), + "Validation Failure(s): {0}", + AppsmithErrorAction.DEFAULT, + "Validation failed", + ErrorType.INTERNAL_ERROR, + null), + INVALID_CURL_COMMAND( + 400, + AppsmithErrorCode.INVALID_CURL_COMMAND.getCode(), + "Invalid cURL command, couldn''t import.", + AppsmithErrorAction.DEFAULT, + "Invalid cURL command", + ErrorType.ARGUMENT_ERROR, + null), + INVALID_LOGIN_METHOD( + 401, + AppsmithErrorCode.INVALID_LOGIN_METHOD.getCode(), + "Please use {0} authentication to login to Appsmith", + AppsmithErrorAction.DEFAULT, + "Invalid login method", + ErrorType.INTERNAL_ERROR, + null), + INVALID_GIT_CONFIGURATION( + 400, + AppsmithErrorCode.INVALID_GIT_CONFIGURATION.getCode(), + "Git configuration is invalid. Details: {0}", + AppsmithErrorAction.DEFAULT, + "Invalid Git configuration", + ErrorType.GIT_CONFIGURATION_ERROR, + null), + INVALID_GIT_SSH_CONFIGURATION( + 400, + AppsmithErrorCode.INVALID_GIT_SSH_CONFIGURATION.getCode(), + "SSH key is not configured correctly. Did you forget to add the SSH key to your remote repository? Please try again by reconfiguring the SSH key with write access.", + AppsmithErrorAction.DEFAULT, + "SSH key not configured", + ErrorType.GIT_CONFIGURATION_ERROR, + ErrorReferenceDocUrl.GIT_DEPLOY_KEY.getDocUrl()), + INVALID_GIT_REPO( + 400, + AppsmithErrorCode.INVALID_GIT_REPO.getCode(), + "The remote repository is not empty. Please create a new empty repository and configure the SSH keys. " + + "If you wish to clone and build an application from an existing remote repository, please use the \"Import from a Git repository\" option in the home page.", + AppsmithErrorAction.DEFAULT, + "Invalid Git repository", + ErrorType.GIT_CONFIGURATION_ERROR, + null), + DEFAULT_RESOURCES_UNAVAILABLE( + 400, + AppsmithErrorCode.DEFAULT_RESOURCES_UNAVAILABLE.getCode(), + "Unexpected state. Default resources are unavailable for {0} with id {1}. Please reach out to Appsmith customer support to resolve this.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Default resources not found", + ErrorType.BAD_REQUEST, + null), + GIT_MERGE_FAILED_REMOTE_CHANGES( + 406, + AppsmithErrorCode.GIT_MERGE_FAILED_REMOTE_CHANGES.getCode(), + "Remote is ahead of local by {0} commits on branch {1}. Please pull remote changes first and try again.", + AppsmithErrorAction.DEFAULT, + "Git merge failed for remote changes", + ErrorType.GIT_ACTION_EXECUTION_ERROR, + ErrorReferenceDocUrl.GIT_UPSTREAM_CHANGES.getDocUrl()), + GIT_MERGE_FAILED_LOCAL_CHANGES( + 406, + AppsmithErrorCode.GIT_MERGE_FAILED_LOCAL_CHANGES.getCode(), + "There are uncommitted changes present in your local branch {0}. Please commit them first and try again", + AppsmithErrorAction.DEFAULT, + "Git merge failed for local changes", + ErrorType.GIT_ACTION_EXECUTION_ERROR, + null), + REMOVE_LAST_WORKSPACE_ADMIN_ERROR( + 400, + AppsmithErrorCode.REMOVE_LAST_WORKSPACE_ADMIN_ERROR.getCode(), + "The last admin cannot be removed from the workspace", + AppsmithErrorAction.DEFAULT, + "Last admin cannot be removed", + ErrorType.INTERNAL_ERROR, + null), + INVALID_CRUD_PAGE_REQUEST( + 400, + AppsmithErrorCode.INVALID_CRUD_PAGE_REQUEST.getCode(), + "Unable to process page generation request, {0}", + AppsmithErrorAction.DEFAULT, + "Invalid page generation request", + ErrorType.BAD_REQUEST, + null), + UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH( + 400, + AppsmithErrorCode.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH.getCode(), + "This operation is not supported for remote branch {0}. Please use local branches only to proceed", + AppsmithErrorAction.DEFAULT, + "Unsupported Operation", + ErrorType.BAD_REQUEST, + null), + ROLES_FROM_SAME_WORKSPACE( + 400, + AppsmithErrorCode.ROLES_FROM_SAME_WORKSPACE.getCode(), + "Roles for the same Workspace provided or already exists.", + AppsmithErrorAction.DEFAULT, + "Roles already exist", + ErrorType.ARGUMENT_ERROR, + null), + INTERNAL_SERVER_ERROR( + 500, + AppsmithErrorCode.INTERNAL_SERVER_ERROR.getCode(), + "Internal server error while processing request", + AppsmithErrorAction.LOG_EXTERNALLY, + "Internal server error", + ErrorType.INTERNAL_ERROR, + null), + REPOSITORY_SAVE_FAILED( + 500, + AppsmithErrorCode.REPOSITORY_SAVE_FAILED.getCode(), + "Failed to save the repository. Please try again later.", + AppsmithErrorAction.DEFAULT, + "Failed to save", + ErrorType.INTERNAL_ERROR, + null), + PLUGIN_INSTALLATION_FAILED_DOWNLOAD_ERROR( + 500, + AppsmithErrorCode.PLUGIN_INSTALLATION_FAILED_DOWNLOAD_ERROR.getCode(), + "Plugin installation failed due to an error while " + "downloading it. Check the jar location & try again.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Plugin installation failed", + ErrorType.INTERNAL_ERROR, + null), + PLUGIN_RUN_FAILED( + 500, + AppsmithErrorCode.PLUGIN_RUN_FAILED.getCode(), + "Plugin execution failed with error {0}", + AppsmithErrorAction.DEFAULT, + "Plugin execution failed", + ErrorType.INTERNAL_ERROR, + null), + PLUGIN_EXECUTION_TIMEOUT( + 504, + AppsmithErrorCode.PLUGIN_EXECUTION_TIMEOUT.getCode(), + "Plugin execution exceeded the maximum allowed time. Please increase the timeout in your action settings or check your backend action endpoint", + AppsmithErrorAction.DEFAULT, + "Timeout in plugin execution", + ErrorType.CONNECTIVITY_ERROR, + null), + PLUGIN_LOAD_FORM_JSON_FAIL( + 500, + AppsmithErrorCode.PLUGIN_LOAD_FORM_JSON_FAIL.getCode(), + "[{0}] Unable to load datasource form configuration. Details: {1}.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Unable to load datasource form configuration", + ErrorType.INTERNAL_ERROR, + null), + PLUGIN_LOAD_TEMPLATES_FAIL( + 500, + AppsmithErrorCode.PLUGIN_LOAD_TEMPLATES_FAIL.getCode(), + "Unable to load datasource templates. Details: {0}.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Unable to load datasource templates", + ErrorType.INTERNAL_ERROR, + null), + IO_ERROR( + 503, + AppsmithErrorCode.IO_ERROR.getCode(), + "IO action failed with error {0}", + AppsmithErrorAction.DEFAULT, + "I/O error", + ErrorType.INTERNAL_ERROR, + null), + MARKETPLACE_TIMEOUT( + 504, + AppsmithErrorCode.MARKETPLACE_TIMEOUT.getCode(), + "Marketplace is responding too slowly. Please try again later", + AppsmithErrorAction.DEFAULT, + "Timeout in marketplace", + ErrorType.CONNECTIVITY_ERROR, + null), + DATASOURCE_HAS_ACTIONS( + 409, + AppsmithErrorCode.DATASOURCE_HAS_ACTIONS.getCode(), + "Cannot delete datasource since it has {0} action(s) using it.", + AppsmithErrorAction.DEFAULT, + "Datasource cannot be deleted", + ErrorType.BAD_REQUEST, + null), + WORKSPACE_ID_NOT_GIVEN( + 400, + AppsmithErrorCode.WORKSPACE_ID_NOT_GIVEN.getCode(), + "Missing workspace id. Please enter one.", + AppsmithErrorAction.DEFAULT, + "Missing workspace id", + ErrorType.ARGUMENT_ERROR, + null), + INVALID_CURL_METHOD( + 400, + AppsmithErrorCode.INVALID_CURL_METHOD.getCode(), + "Invalid method in cURL command: {0}.", + AppsmithErrorAction.DEFAULT, + "Invalid method in cURL command", + ErrorType.ARGUMENT_ERROR, + null), + OAUTH_NOT_AVAILABLE( + 500, + AppsmithErrorCode.OAUTH_NOT_AVAILABLE.getCode(), + "Login with {0} is not supported.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Unsupported login method", + ErrorType.BAD_REQUEST, + null), + MARKETPLACE_NOT_CONFIGURED( + 500, + AppsmithErrorCode.MARKETPLACE_NOT_CONFIGURED.getCode(), + "Marketplace is not configured.", + AppsmithErrorAction.DEFAULT, + "Marketplace not configured", + ErrorType.CONFIGURATION_ERROR, + null), + PAYLOAD_TOO_LARGE( + 413, + AppsmithErrorCode.PAYLOAD_TOO_LARGE.getCode(), + "The request payload is too large. Max allowed size for request payload is {0} KB", + AppsmithErrorAction.DEFAULT, + "Payload exceeds max allowed size", + ErrorType.CONNECTIVITY_ERROR, + null), + SIGNUP_DISABLED( + 403, + AppsmithErrorCode.SIGNUP_DISABLED.getCode(), + "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite for user {0}.", + AppsmithErrorAction.DEFAULT, + "Signup disabled", + ErrorType.INTERNAL_ERROR, + null), + FAIL_UPDATE_USER_IN_SESSION( + 500, + AppsmithErrorCode.FAIL_UPDATE_USER_IN_SESSION.getCode(), + "Unable to update user in session.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Unable to update user in session", + ErrorType.INTERNAL_ERROR, + null), + APPLICATION_FORKING_NOT_ALLOWED( + 403, + AppsmithErrorCode.APPLICATION_FORKING_NOT_ALLOWED.getCode(), + "Forking this application is not permitted at this time.", + AppsmithErrorAction.DEFAULT, + "Forking application not permitted", + ErrorType.INTERNAL_ERROR, + null), + GOOGLE_RECAPTCHA_TIMEOUT( + 504, + AppsmithErrorCode.GOOGLE_RECAPTCHA_TIMEOUT.getCode(), + "Google recaptcha verification timeout. Please try again.", + AppsmithErrorAction.DEFAULT, + "Timeout in Google recaptcha verification", + ErrorType.INTERNAL_ERROR, + null), + GOOGLE_RECAPTCHA_FAILED( + 401, + AppsmithErrorCode.GOOGLE_RECAPTCHA_FAILED.getCode(), + "Google recaptcha verification failed. Please try again.", + AppsmithErrorAction.DEFAULT, + "Google recaptcha verification failed", + ErrorType.INTERNAL_ERROR, + null), + UNKNOWN_ACTION_RESULT_DATA_TYPE( + 500, + AppsmithErrorCode.UNKNOWN_ACTION_RESULT_DATA_TYPE.getCode(), + "Appsmith has encountered an unknown action result data type: {0}. " + + "Please contact Appsmith customer support to resolve this.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Unexpected data type", + ErrorType.BAD_REQUEST, + null), + INVALID_CURL_HEADER( + 400, + AppsmithErrorCode.INVALID_CURL_HEADER.getCode(), + "Invalid header in cURL command: {0}.", + AppsmithErrorAction.DEFAULT, + "Invalid header in cURL command", + ErrorType.ARGUMENT_ERROR, + null), + AUTHENTICATION_FAILURE( + 500, + AppsmithErrorCode.AUTHENTICATION_FAILURE.getCode(), + "Authentication failed with error: {0}", + AppsmithErrorAction.DEFAULT, + "Authentication failed", + ErrorType.AUTHENTICATION_ERROR, + null), + INSTANCE_REGISTRATION_FAILURE( + 500, + AppsmithErrorCode.INSTANCE_REGISTRATION_FAILURE.getCode(), + "Registration for instance failed with error: {0}", + AppsmithErrorAction.LOG_EXTERNALLY, + "Registration failed for this instance", + ErrorType.INTERNAL_ERROR, + null), + TOO_MANY_REQUESTS( + 429, + AppsmithErrorCode.TOO_MANY_REQUESTS.getCode(), + "Too many requests received. Please try later.", + AppsmithErrorAction.DEFAULT, + "Too many requests", + ErrorType.INTERNAL_ERROR, + null), + INVALID_JS_ACTION( + 400, + AppsmithErrorCode.INVALID_JS_ACTION.getCode(), + "Something went wrong while trying to parse this action. Please check the JS Object for errors.", + AppsmithErrorAction.DEFAULT, + "Invalid action in JS Object", + ErrorType.BAD_REQUEST, + null), + CYCLICAL_DEPENDENCY_ERROR( + 400, + AppsmithErrorCode.CYCLICAL_DEPENDENCY_ERROR.getCode(), + "Cyclical dependency error encountered while parsing relationship [{0}] where the relationship is denoted as (source : target).", + AppsmithErrorAction.DEFAULT, + "Cyclical Dependency in Page Load Actions", + ErrorType.CONFIGURATION_ERROR, + null), + CLOUD_SERVICES_ERROR( + 500, + AppsmithErrorCode.CLOUD_SERVICES_ERROR.getCode(), + "Received error from cloud services {0}", + AppsmithErrorAction.DEFAULT, + "Error in cloud services", + ErrorType.INTERNAL_ERROR, + null), + GIT_APPLICATION_LIMIT_ERROR( + 402, + AppsmithErrorCode.GIT_APPLICATION_LIMIT_ERROR.getCode(), + "You have reached the maximum number of private git repo counts which can be connected to the workspace. Please reach out to Appsmith support to opt for commercial plan.", + AppsmithErrorAction.DEFAULT, + "Maximum number of Git repo connection limit reached", + ErrorType.EE_FEATURE_ERROR, + null), + GIT_ACTION_FAILED( + 400, + AppsmithErrorCode.GIT_ACTION_FAILED.getCode(), + "git {0} failed. \nDetails: {1}", + AppsmithErrorAction.DEFAULT, + "Git failed", + ErrorType.GIT_ACTION_EXECUTION_ERROR, + null), + GIT_FILE_SYSTEM_ERROR( + 503, + AppsmithErrorCode.GIT_FILE_SYSTEM_ERROR.getCode(), + "Error while accessing the file system. {0}", + AppsmithErrorAction.DEFAULT, + "Git file system error", + ErrorType.GIT_CONFIGURATION_ERROR, + ErrorReferenceDocUrl.FILE_PATH_NOT_SET.getDocUrl()), + GIT_EXECUTION_TIMEOUT( + 504, + AppsmithErrorCode.GIT_EXECUTION_TIMEOUT.getCode(), + "Git command execution exceeded the maximum allowed time, please contact Appsmith support for more details", + AppsmithErrorAction.DEFAULT, + "Timeout in Git command execution", + ErrorType.CONNECTIVITY_ERROR, + null), + INCOMPATIBLE_IMPORTED_JSON( + 400, + AppsmithErrorCode.INCOMPATIBLE_IMPORTED_JSON.getCode(), + "Provided file is incompatible, please upgrade your instance to resolve this conflict.", + AppsmithErrorAction.DEFAULT, + "Incompatible Json file", + ErrorType.BAD_REQUEST, + null), + GIT_MERGE_CONFLICTS( + 400, + AppsmithErrorCode.GIT_MERGE_CONFLICTS.getCode(), + "Merge conflicts found: {0}", + AppsmithErrorAction.DEFAULT, + "Merge conflicts found", + ErrorType.GIT_ACTION_EXECUTION_ERROR, + ErrorReferenceDocUrl.GIT_MERGE_CONFLICT.getDocUrl()), + GIT_PULL_CONFLICTS( + 400, + AppsmithErrorCode.GIT_PULL_CONFLICTS.getCode(), + "Merge conflicts found during the pull operation: {0}", + AppsmithErrorAction.DEFAULT, + "Merge conflicts found during the pull operation", + ErrorType.GIT_ACTION_EXECUTION_ERROR, + ErrorReferenceDocUrl.GIT_PULL_CONFLICT.getDocUrl()), + SSH_KEY_GENERATION_ERROR( + 500, + AppsmithErrorCode.SSH_KEY_GENERATION_ERROR.getCode(), + "Failed to generate SSH keys, please contact Appsmith support for more details", + AppsmithErrorAction.DEFAULT, + "Failed to generate SSH keys", + ErrorType.GIT_CONFIGURATION_ERROR, + null), + GIT_GENERIC_ERROR( + 504, + AppsmithErrorCode.GIT_GENERIC_ERROR.getCode(), + "Git command execution error: {0}", + AppsmithErrorAction.DEFAULT, + "Git command execution error", + ErrorType.GIT_ACTION_EXECUTION_ERROR, + null), + GIT_UPSTREAM_CHANGES( + 400, + AppsmithErrorCode.GIT_UPSTREAM_CHANGES.getCode(), + "Looks like there are pending upstream changes. To prevent you from losing history, we will pull the changes and push them to your repo.", + AppsmithErrorAction.DEFAULT, + "Git push failed for pending upstream changes", + ErrorType.GIT_UPSTREAM_CHANGES_PUSH_EXECUTION_ERROR, + ErrorReferenceDocUrl.GIT_UPSTREAM_CHANGES.getDocUrl()), + GENERIC_JSON_IMPORT_ERROR( + 400, + AppsmithErrorCode.GENERIC_JSON_IMPORT_ERROR.getCode(), + "Unable to import application in workspace {0}. {1}", + AppsmithErrorAction.DEFAULT, + "Unable to import application in workspace", + ErrorType.BAD_REQUEST, + null), + FILE_PART_DATA_BUFFER_ERROR( + 500, + AppsmithErrorCode.FILE_PART_DATA_BUFFER_ERROR.getCode(), + "Failed to upload file with error: {0}", + AppsmithErrorAction.DEFAULT, + "Failed to upload file", + ErrorType.BAD_REQUEST, + null), + MIGRATION_ERROR( + 500, + AppsmithErrorCode.MIGRATION_ERROR.getCode(), + "This action is already migrated", + AppsmithErrorAction.DEFAULT, + "Action already migrated", + ErrorType.INTERNAL_ERROR, + null), + INVALID_GIT_SSH_URL( + 400, + AppsmithErrorCode.INVALID_GIT_SSH_URL.getCode(), + "Please enter valid SSH URL of your repository", + AppsmithErrorAction.DEFAULT, + "Invalid SSH URL", + ErrorType.GIT_CONFIGURATION_ERROR, + null), + REPOSITORY_NOT_FOUND( + 404, + AppsmithErrorCode.REPOSITORY_NOT_FOUND.getCode(), + "Unable to find the remote repository for application {0}, please check the deploy key configuration in your remote repository.", + AppsmithErrorAction.DEFAULT, + "Repository not found", + ErrorType.REPOSITORY_NOT_FOUND, + null), + UNKNOWN_PLUGIN_REFERENCE( + 400, + AppsmithErrorCode.UNKNOWN_PLUGIN_REFERENCE.getCode(), + "Unable to find the plugin {0}. Please reach out to Appsmith customer support to resolve this.", + AppsmithErrorAction.DEFAULT, + "Unknown plugin", + ErrorType.CONFIGURATION_ERROR, + null), + ENV_FILE_NOT_FOUND( + 500, + AppsmithErrorCode.ENV_FILE_NOT_FOUND.getCode(), + "Admin Settings is unavailable. Unable to read and write to Environment file.", + AppsmithErrorAction.DEFAULT, + "Environment file not found", + ErrorType.CONFIGURATION_ERROR, + null), + PUBLIC_APP_NO_PERMISSION_GROUP( + 500, + AppsmithErrorCode.PUBLIC_APP_NO_PERMISSION_GROUP.getCode(), + "Invalid state. Public application does not have the required roles set for public access. Please reach out to Appsmith customer support to resolve this.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Required permission missing for public access", + ErrorType.INTERNAL_ERROR, + null), + RTS_SERVER_ERROR( + 500, + AppsmithErrorCode.RTS_SERVER_ERROR.getCode(), + "RTS server error while processing request: {0}", + AppsmithErrorAction.LOG_EXTERNALLY, + "RTS server error", + ErrorType.INTERNAL_ERROR, + null), + SCHEMA_MISMATCH_ERROR( + 500, + AppsmithErrorCode.SCHEMA_MISMATCH_ERROR.getCode(), + "Looks like you skipped some required update(s), please go back to the mandatory upgrade path {0}, or refer to ''https://docs.appsmith.com/'' for more info", + AppsmithErrorAction.LOG_EXTERNALLY, + "Schema mismatch error", + ErrorType.INTERNAL_ERROR, + null), + SCHEMA_VERSION_NOT_FOUND_ERROR( + 500, + AppsmithErrorCode.SCHEMA_VERSION_NOT_FOUND_ERROR.getCode(), + "Could not find mandatory instance schema version config. Please reach out to Appsmith customer support to resolve this.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Schema version not found", + ErrorType.INTERNAL_ERROR, + null), + HEALTHCHECK_TIMEOUT( + 408, + AppsmithErrorCode.HEALTHCHECK_TIMEOUT.getCode(), + "{0} connection timed out.", + AppsmithErrorAction.DEFAULT, + "Connection timeout during health check", + ErrorType.CONNECTIVITY_ERROR, + null), + SERVER_NOT_READY( + 500, + AppsmithErrorCode.SERVER_NOT_READY.getCode(), + "Appsmith server is not ready. Please try again in some time.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Server not ready", + ErrorType.INTERNAL_ERROR, + null), + SESSION_BAD_STATE( + 500, + AppsmithErrorCode.SESSION_BAD_STATE.getCode(), + "User session is invalid. Please log out and log in again.", + AppsmithErrorAction.LOG_EXTERNALLY, + "Invalid user session", + ErrorType.INTERNAL_ERROR, + null), + INVALID_LICENSE_KEY_ENTERED( + 400, + AppsmithErrorCode.INVALID_LICENSE_KEY_ENTERED.getCode(), + "The license key entered is invalid. Please try again.", + AppsmithErrorAction.DEFAULT, + "Invalid license key", + ErrorType.ARGUMENT_ERROR, + null), + GIT_FILE_IN_USE( + 500, + AppsmithErrorCode.GIT_FILE_IN_USE.getCode(), + "Your Git repo is in use by another member of your team. Usually, this takes a few seconds. Please try again a little later.", + AppsmithErrorAction.DEFAULT, + "Git repo is locked", + ErrorType.GIT_ACTION_EXECUTION_ERROR, + null), + CSRF_TOKEN_INVALID( + 403, + AppsmithErrorCode.CSRF_TOKEN_INVALID.getCode(), + "CSRF token missing/invalid. Please try again.", + AppsmithErrorAction.DEFAULT, + "CSRF token missing/invalid", + ErrorType.BAD_REQUEST, + null), + UNSUPPORTED_IMPORT_OPERATION_FOR_GIT_CONNECTED_APPLICATION( + 400, + AppsmithErrorCode.UNSUPPORTED_IMPORT_OPERATION.getCode(), + "Import application via file is not supported for git connected application. Please use Git Pull to update and sync your application.", + AppsmithErrorAction.DEFAULT, + "Unsupported operation", + ErrorType.BAD_REQUEST, + null), ; private final Integer httpErrorCode; @@ -170,8 +897,9 @@ public enum AppsmithError { private final String message; private final String title; private final AppsmithErrorAction errorAction; - @NonNull - private final ErrorType errorType; + + @NonNull private final ErrorType errorType; + private final String referenceDoc; AppsmithError( @@ -181,8 +909,7 @@ public enum AppsmithError { AppsmithErrorAction errorAction, String title, @NonNull ErrorType errorType, - String referenceDoc - ) { + String referenceDoc) { this.httpErrorCode = httpErrorCode; this.appErrorCode = appErrorCode; this.errorType = errorType; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithException.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithException.java index db4fcd0e039c..fcd26ffe407a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithException.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithException.java @@ -30,18 +30,20 @@ public String getMessage() { @Override public String getDownstreamErrorMessage() { - //Downstream error message is not available for AppsmithError + // Downstream error message is not available for AppsmithError return null; } @Override public String getDownstreamErrorCode() { - //Downstream error code is not available for AppsmithError + // Downstream error code is not available for AppsmithError return null; } public String getAppErrorCode() { - return this.error == null ? AppsmithPluginErrorCode.GENERIC_PLUGIN_ERROR.getCode() : this.error.getAppErrorCode(); + return this.error == null + ? AppsmithPluginErrorCode.GENERIC_PLUGIN_ERROR.getCode() + : this.error.getAppErrorCode(); } public AppsmithErrorAction getErrorAction() { @@ -61,5 +63,4 @@ public String getErrorType() { public String getReferenceDoc() { return this.error.getReferenceDoc(); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java index d4a0068ccd78..7b6068a4e657 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java @@ -30,7 +30,6 @@ import java.util.HashMap; import java.util.Map; - /** * This class catches all the Exceptions and formats them into a proper ResponseDTO<ErrorDTO> object before * sending it to the client. @@ -53,17 +52,15 @@ private void doLog(Throwable error) { error.printStackTrace(printWriter); String stringStackTrace = stringWriter.toString(); - Sentry.configureScope( - scope -> { - /** - * Send stack trace as a string message. This is a work around till it is figured out why raw - * stack trace is not visible on Sentry dashboard. - * */ - scope.setExtra("Stack Trace", stringStackTrace); - scope.setLevel(SentryLevel.ERROR); - scope.setTag("source", "appsmith-internal-server"); - } - ); + Sentry.configureScope(scope -> { + /** + * Send stack trace as a string message. This is a work around till it is figured out why raw + * stack trace is not visible on Sentry dashboard. + * */ + scope.setExtra("Stack Trace", stringStackTrace); + scope.setLevel(SentryLevel.ERROR); + scope.setTag("source", "appsmith-internal-server"); + }); if (error instanceof BaseException) { BaseException baseError = (BaseException) error; @@ -100,10 +97,17 @@ public Mono<ResponseDTO<ErrorDTO>> catchAppsmithException(AppsmithException e, S ResponseDTO<ErrorDTO> response; // Do special formatting for this error to run the message string into valid jsonified string - if (AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE.getAppErrorCode().equals(e.getError().getAppErrorCode())) { - response = new ResponseDTO<>(e.getHttpStatus(), new ErrorDTO(e.getAppErrorCode(), e.getErrorType(), "{" + e.getMessage() + "}", e.getTitle())); + if (AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE + .getAppErrorCode() + .equals(e.getError().getAppErrorCode())) { + response = new ResponseDTO<>( + e.getHttpStatus(), + new ErrorDTO(e.getAppErrorCode(), e.getErrorType(), "{" + e.getMessage() + "}", e.getTitle())); } else { - response = new ResponseDTO<>(e.getHttpStatus(), new ErrorDTO(e.getAppErrorCode(), e.getErrorType(), e.getMessage(), e.getTitle(), e.getReferenceDoc())); + response = new ResponseDTO<>( + e.getHttpStatus(), + new ErrorDTO( + e.getAppErrorCode(), e.getErrorType(), e.getMessage(), e.getTitle(), e.getReferenceDoc())); } return getResponseDTOMono(urlPath, response); @@ -111,28 +115,41 @@ public Mono<ResponseDTO<ErrorDTO>> catchAppsmithException(AppsmithException e, S @ExceptionHandler @ResponseBody - public Mono<ResponseDTO<ErrorDTO>> catchDuplicateKeyException(org.springframework.dao.DuplicateKeyException e, ServerWebExchange exchange) { + public Mono<ResponseDTO<ErrorDTO>> catchDuplicateKeyException( + org.springframework.dao.DuplicateKeyException e, ServerWebExchange exchange) { AppsmithError appsmithError = AppsmithError.DUPLICATE_KEY; exchange.getResponse().setStatusCode(HttpStatus.resolve(appsmithError.getHttpErrorCode())); doLog(e); String urlPath = exchange.getRequest().getPath().toString(); - String conflictingObjectName = DuplicateKeyExceptionUtils.extractConflictingObjectName(e.getCause().getMessage()); - ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), appsmithError.getErrorType(), - appsmithError.getMessage(conflictingObjectName), appsmithError.getTitle())); + String conflictingObjectName = DuplicateKeyExceptionUtils.extractConflictingObjectName( + e.getCause().getMessage()); + ResponseDTO<ErrorDTO> response = new ResponseDTO<>( + appsmithError.getHttpErrorCode(), + new ErrorDTO( + appsmithError.getAppErrorCode(), + appsmithError.getErrorType(), + appsmithError.getMessage(conflictingObjectName), + appsmithError.getTitle())); return getResponseDTOMono(urlPath, response); } @ExceptionHandler @ResponseBody - public Mono<ResponseDTO<ErrorDTO>> catchTimeoutException(java.util.concurrent.TimeoutException e, ServerWebExchange exchange) { + public Mono<ResponseDTO<ErrorDTO>> catchTimeoutException( + java.util.concurrent.TimeoutException e, ServerWebExchange exchange) { AppsmithError appsmithError = AppsmithError.PLUGIN_EXECUTION_TIMEOUT; exchange.getResponse().setStatusCode(HttpStatus.resolve(appsmithError.getHttpErrorCode())); doLog(e); String urlPath = exchange.getRequest().getPath().toString(); - ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), appsmithError.getErrorType(), - appsmithError.getMessage(), appsmithError.getTitle())); + ResponseDTO<ErrorDTO> response = new ResponseDTO<>( + appsmithError.getHttpErrorCode(), + new ErrorDTO( + appsmithError.getAppErrorCode(), + appsmithError.getErrorType(), + appsmithError.getMessage(), + appsmithError.getTitle())); return getResponseDTOMono(urlPath, response); } @@ -144,25 +161,27 @@ public Mono<ResponseDTO<ErrorDTO>> catchWebExchangeBindException( AppsmithError appsmithError = AppsmithError.VALIDATION_FAILURE; exchange.getResponse().setStatusCode(HttpStatus.resolve(appsmithError.getHttpErrorCode())); Map<String, String> errors = new HashMap<>(); - exc.getBindingResult() - .getAllErrors() - .forEach( - (error) -> { - String fieldName = ((FieldError) error).getField(); - String errorMessage = error.getDefaultMessage(); - errors.put(fieldName, errorMessage); - }); + exc.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); String urlPath = exchange.getRequest().getPath().toString(); - ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), appsmithError.getErrorType(), - appsmithError.getMessage(errors.toString()), appsmithError.getTitle())); + ResponseDTO<ErrorDTO> response = new ResponseDTO<>( + appsmithError.getHttpErrorCode(), + new ErrorDTO( + appsmithError.getAppErrorCode(), + appsmithError.getErrorType(), + appsmithError.getMessage(errors.toString()), + appsmithError.getTitle())); return getResponseDTOMono(urlPath, response); } - @ExceptionHandler @ResponseBody - public Mono<ResponseDTO<ErrorDTO>> catchServerWebInputException(ServerWebInputException e, ServerWebExchange exchange) { + public Mono<ResponseDTO<ErrorDTO>> catchServerWebInputException( + ServerWebInputException e, ServerWebExchange exchange) { AppsmithError appsmithError = AppsmithError.GENERIC_BAD_REQUEST; exchange.getResponse().setStatusCode(HttpStatus.resolve(appsmithError.getHttpErrorCode())); doLog(e); @@ -170,12 +189,19 @@ public Mono<ResponseDTO<ErrorDTO>> catchServerWebInputException(ServerWebInputEx if (e.getMethodParameter() != null) { errorMessage = "Malformed parameter '" + e.getMethodParameter().getParameterName() + "' for " + e.getMethodParameter().getContainingClass().getSimpleName() - + (e.getMethodParameter().getMethod() != null ? "." + e.getMethodParameter().getMethod().getName() : ""); + + (e.getMethodParameter().getMethod() != null + ? "." + e.getMethodParameter().getMethod().getName() + : ""); } String urlPath = exchange.getRequest().getPath().toString(); - ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), appsmithError.getErrorType(), - appsmithError.getMessage(errorMessage), appsmithError.getTitle())); + ResponseDTO<ErrorDTO> response = new ResponseDTO<>( + appsmithError.getHttpErrorCode(), + new ErrorDTO( + appsmithError.getAppErrorCode(), + appsmithError.getErrorType(), + appsmithError.getMessage(errorMessage), + appsmithError.getTitle())); return getResponseDTOMono(urlPath, response); } @@ -187,8 +213,9 @@ public Mono<ResponseDTO<ErrorDTO>> catchPluginException(AppsmithPluginException exchange.getResponse().setStatusCode(HttpStatus.resolve(appsmithError.getHttpErrorCode())); doLog(e); String urlPath = exchange.getRequest().getPath().toString(); - ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), - e.getMessage(), e.getErrorType(), e.getTitle())); + ResponseDTO<ErrorDTO> response = new ResponseDTO<>( + appsmithError.getHttpErrorCode(), + new ErrorDTO(appsmithError.getAppErrorCode(), e.getMessage(), e.getErrorType(), e.getTitle())); return getResponseDTOMono(urlPath, response); } @@ -200,21 +227,32 @@ public Mono<ResponseDTO<ErrorDTO>> catchAccessDeniedException(AccessDeniedExcept exchange.getResponse().setStatusCode(HttpStatus.resolve(appsmithError.getHttpErrorCode())); doLog(e); String urlPath = exchange.getRequest().getPath().toString(); - ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), - appsmithError.getErrorType(), appsmithError.getMessage(), appsmithError.getTitle())); + ResponseDTO<ErrorDTO> response = new ResponseDTO<>( + appsmithError.getHttpErrorCode(), + new ErrorDTO( + appsmithError.getAppErrorCode(), + appsmithError.getErrorType(), + appsmithError.getMessage(), + appsmithError.getTitle())); return getResponseDTOMono(urlPath, response); } @ExceptionHandler @ResponseBody - public Mono<ResponseDTO<ErrorDTO>> catchDataBufferLimitException(DataBufferLimitException e, ServerWebExchange exchange) { + public Mono<ResponseDTO<ErrorDTO>> catchDataBufferLimitException( + DataBufferLimitException e, ServerWebExchange exchange) { AppsmithError appsmithError = AppsmithError.FILE_PART_DATA_BUFFER_ERROR; exchange.getResponse().setStatusCode(HttpStatus.resolve(appsmithError.getHttpErrorCode())); doLog(e); String urlPath = exchange.getRequest().getPath().toString(); - ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), appsmithError.getErrorType(), - appsmithError.getMessage(e.getMessage()), appsmithError.getTitle())); + ResponseDTO<ErrorDTO> response = new ResponseDTO<>( + appsmithError.getHttpErrorCode(), + new ErrorDTO( + appsmithError.getAppErrorCode(), + appsmithError.getErrorType(), + appsmithError.getMessage(e.getMessage()), + appsmithError.getTitle())); return getResponseDTOMono(urlPath, response); } @@ -234,8 +272,13 @@ public Mono<ResponseDTO<ErrorDTO>> catchException(Exception e, ServerWebExchange exchange.getResponse().setStatusCode(HttpStatus.resolve(appsmithError.getHttpErrorCode())); doLog(e); String urlPath = exchange.getRequest().getPath().toString(); - ResponseDTO<ErrorDTO> response = new ResponseDTO<>(appsmithError.getHttpErrorCode(), new ErrorDTO(appsmithError.getAppErrorCode(), appsmithError.getErrorType(), - appsmithError.getMessage(), appsmithError.getTitle())); + ResponseDTO<ErrorDTO> response = new ResponseDTO<>( + appsmithError.getHttpErrorCode(), + new ErrorDTO( + appsmithError.getAppErrorCode(), + appsmithError.getErrorType(), + appsmithError.getMessage(), + appsmithError.getTitle())); return getResponseDTOMono(urlPath, response); } @@ -246,9 +289,8 @@ private Mono<ResponseDTO<ErrorDTO>> getResponseDTOMono(String urlPath, ResponseD if (StringUtils.isEmpty(appId)) { return Mono.just(response); } - return redisUtils.releaseFileLock(appId) - .then(Mono.just(response)); + return redisUtils.releaseFileLock(appId).then(Mono.just(response)); } return Mono.just(response); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/DuplicateKeyExceptionUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/DuplicateKeyExceptionUtils.java index b4516c3b58e9..a44fd90e592d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/DuplicateKeyExceptionUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/DuplicateKeyExceptionUtils.java @@ -7,19 +7,20 @@ @Slf4j public class DuplicateKeyExceptionUtils { - private final static Pattern pattern = Pattern.compile("dup key: \\{ .*:(.*)}'"); + private static final Pattern pattern = Pattern.compile("dup key: \\{ .*:(.*)}'"); public static String extractConflictingObjectName(String duplicateKeyErrorMessage) { Matcher matcher = pattern.matcher(duplicateKeyErrorMessage); if (matcher.find()) { return matcher.group(1).trim(); } - log.warn("DuplicateKeyException regex needs attention. It's unable to extract object name from the error message. Possible reason: the underlying library may have changed the format of the error message."); + log.warn( + "DuplicateKeyException regex needs attention. It's unable to extract object name from the error message. Possible reason: the underlying library may have changed the format of the error message."); /* - [Fallback strategy] - AppsmithError.DUPLICATE_KEY has a placeholder where it expects the name of the object that conflicts with the existing names. - In case the execution reaches here we don't want to render `null` rather the string returned as below will yet make the message look good. - */ + [Fallback strategy] + AppsmithError.DUPLICATE_KEY has a placeholder where it expects the name of the object that conflicts with the existing names. + In case the execution reaches here we don't want to render `null` rather the string returned as below will yet make the message look good. + */ return "that you provided"; } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagIdentities.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagIdentities.java index 219da32ea244..a720d20cb64a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagIdentities.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagIdentities.java @@ -13,4 +13,4 @@ public class FeatureFlagIdentities { String instanceId; String tenantId; Set<String> userIdentifiers; -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagTrait.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagTrait.java index 8bca4920a7ce..ef01ce162492 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagTrait.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagTrait.java @@ -11,4 +11,4 @@ public class FeatureFlagTrait { String identifier; String traitKey; String traitValue; -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/strategies/AppsmithUserStrategy.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/strategies/AppsmithUserStrategy.java index 12771516b650..52682333bcb3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/strategies/AppsmithUserStrategy.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/strategies/AppsmithUserStrategy.java @@ -21,4 +21,4 @@ public boolean evaluate(String featureName, FeatureStore store, FlippingExecutio return StringUtils.endsWith(user.getEmail(), "@appsmith.com"); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/strategies/EmailBasedRolloutStrategy.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/strategies/EmailBasedRolloutStrategy.java index 9ab0f212d064..3171aa420fbf 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/strategies/EmailBasedRolloutStrategy.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/strategies/EmailBasedRolloutStrategy.java @@ -29,7 +29,8 @@ public class EmailBasedRolloutStrategy extends AbstractFlipStrategy { public void init(String featureName, Map<String, String> initParam) { super.init(featureName, initParam); if (!initParam.containsKey(PARAM_EMAIL_DOMAINS) && !initParam.containsKey(PARAM_EMAILS)) { - String msg = String.format("Either '%s' or '%s' is required for EmailBasedRolloutStrategy", PARAM_EMAIL_DOMAINS, PARAM_EMAILS); + String msg = String.format( + "Either '%s' or '%s' is required for EmailBasedRolloutStrategy", PARAM_EMAIL_DOMAINS, PARAM_EMAILS); throw new IllegalArgumentException(msg); } if (!StringUtils.isEmpty(initParam.get(PARAM_EMAIL_DOMAINS))) { @@ -58,6 +59,5 @@ public boolean evaluate(String featureName, FeatureStore store, FlippingExecutio } } return false; - } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/filters/CSRFFilter.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/filters/CSRFFilter.java index 71a377e237c2..185ff6aabbf8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/filters/CSRFFilter.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/filters/CSRFFilter.java @@ -19,9 +19,9 @@ public class CSRFFilter implements WebFilter { private static final Set<String> EXEMPT = Set.of( Url.LOGIN_URL, - Url.USER_URL, // For signup request - Url.USER_URL + "/super" // For superuser signup request - ); + Url.USER_URL, // For signup request + Url.USER_URL + "/super" // For superuser signup request + ); private static final String X_REQUESTED_BY_NAME = "X-Requested-By"; private static final String X_REQUESTED_BY_VALUE = "Appsmith"; @@ -42,12 +42,9 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { log.error("CSRF header requirements not satisfied to {}. Rejecting request.", request.getPath()); return Mono.error(new AppsmithException( - AppsmithError.CSRF_TOKEN_INVALID, - "CSRF header requirements not satisfied. Rejecting request." - )); + AppsmithError.CSRF_TOKEN_INVALID, "CSRF header requirements not satisfied. Rejecting request.")); } return chain.filter(exchange); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/filters/MDCFilter.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/filters/MDCFilter.java index 81114a57740c..54081025efb7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/filters/MDCFilter.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/filters/MDCFilter.java @@ -42,21 +42,21 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { // Using beforeCommit here ensures that the function `addContextToHttpResponse` isn't run immediately // It is only run when the response object is being created exchange.getResponse().beforeCommit(() -> addContextToHttpResponse(exchange.getResponse())); - return ReactiveSecurityContextHolder - .getContext() + return ReactiveSecurityContextHolder.getContext() .map(ctx -> ctx.getAuthentication().getPrincipal()) .flatMap(principal -> { final User user = principal instanceof User ? (User) principal : null; - return chain.filter(exchange).contextWrite(ctx -> addRequestHeadersToContext(exchange.getRequest(), ctx, user)); + return chain.filter(exchange) + .contextWrite(ctx -> addRequestHeadersToContext(exchange.getRequest(), ctx, user)); }); } finally { MDC.clear(); } } - private Context addRequestHeadersToContext(final ServerHttpRequest request, final Context context, final User user) { - final Map<String, String> contextMap = request.getHeaders().toSingleValueMap().entrySet() - .stream() + private Context addRequestHeadersToContext( + final ServerHttpRequest request, final Context context, final User user) { + final Map<String, String> contextMap = request.getHeaders().toSingleValueMap().entrySet().stream() .filter(x -> x.getKey().startsWith(MDC_HEADER_PREFIX)) .collect(toMap(v -> v.getKey().substring((MDC_HEADER_PREFIX.length())), Map.Entry::getValue)); @@ -78,15 +78,15 @@ private Context addRequestHeadersToContext(final ServerHttpRequest request, fina } private Mono<Void> addContextToHttpResponse(final ServerHttpResponse response) { - return Mono.deferContextual(Mono::just).doOnNext(ctx -> { - if (!ctx.hasKey(LogHelper.CONTEXT_MAP)) { - return; - } - - final HttpHeaders httpHeaders = response.getHeaders(); - // Add all the request MDC keys to the response object - ctx.<Map<String, String>>get(LogHelper.CONTEXT_MAP) - .forEach((key, value) -> { + return Mono.deferContextual(Mono::just) + .doOnNext(ctx -> { + if (!ctx.hasKey(LogHelper.CONTEXT_MAP)) { + return; + } + + final HttpHeaders httpHeaders = response.getHeaders(); + // Add all the request MDC keys to the response object + ctx.<Map<String, String>>get(LogHelper.CONTEXT_MAP).forEach((key, value) -> { if (!key.equalsIgnoreCase(USER_EMAIL)) { if (!key.contains(REQUEST_ID_LOG)) { httpHeaders.add(MDC_HEADER_PREFIX + key, value); @@ -95,13 +95,14 @@ private Mono<Void> addContextToHttpResponse(final ServerHttpResponse response) { } } }); - - }).then(); + }) + .then(); } private String getSessionId(final ServerHttpRequest request) { - if (request.getCookies().get(SESSION) != null && !request.getCookies().get(SESSION).isEmpty()) { + if (request.getCookies().get(SESSION) != null + && !request.getCookies().get(SESSION).isEmpty()) { return request.getCookies().get(SESSION).get(0).getValue(); } return ""; @@ -109,11 +110,12 @@ private String getSessionId(final ServerHttpRequest request) { private String getOrCreateRequestId(final ServerHttpRequest request) { if (!request.getHeaders().containsKey(REQUEST_ID_HEADER)) { - request.mutate().header(REQUEST_ID_HEADER, UUID.randomUUID().toString()).build(); + request.mutate() + .header(REQUEST_ID_HEADER, UUID.randomUUID().toString()) + .build(); } String header = request.getHeaders().get(REQUEST_ID_HEADER).get(0); return header; } } - diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/AppsmithComparators.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/AppsmithComparators.java index af44b9e9df56..394076a8a365 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/AppsmithComparators.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/AppsmithComparators.java @@ -2,5 +2,4 @@ import com.appsmith.server.helpers.ce.AppsmithComparatorsCE; -public class AppsmithComparators extends AppsmithComparatorsCE { -} +public class AppsmithComparators extends AppsmithComparatorsCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CollectionUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CollectionUtils.java index 82c7d53f421b..68740c7ccfa3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CollectionUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CollectionUtils.java @@ -1,6 +1,5 @@ package com.appsmith.server.helpers; - import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; @@ -41,7 +40,7 @@ public static boolean isNullOrEmpty(final Map<?, ?> m) { public static <E> void putAtFirst(List<E> list, E item) { // check if item already exists int index = list.indexOf(item); - if (index == -1) { // does not exist so put it at first + if (index == -1) { // does not exist so put it at first list.add(0, item); } else if (index > 0) { list.remove(item); @@ -93,5 +92,4 @@ private static <T> void putKeyForFindingSymmetricDiff(Map<T, Integer> map, T key map.put(key, 1); } } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java index b3592481f3d3..46bf5ba71137 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java @@ -10,8 +10,10 @@ public class CompareDslActionDTO implements Comparator<DslActionDTO>, Serializab // Method to compare DslActionDTO based on id @Override public int compare(DslActionDTO action1, DslActionDTO action2) { - if (action1 != null && !StringUtils.isEmpty(action1.getName()) - && action2 != null && !StringUtils.isEmpty(action2.getName())) { + if (action1 != null + && !StringUtils.isEmpty(action1.getName()) + && action2 != null + && !StringUtils.isEmpty(action2.getName())) { return action1.getName().compareTo(action2.getName()); } return 1; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DatasourceAnalyticsUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DatasourceAnalyticsUtils.java index 84f31de4c73a..fc09665c24b5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DatasourceAnalyticsUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DatasourceAnalyticsUtils.java @@ -39,8 +39,8 @@ public static Map<String, Object> getAnalyticsProperties(DatasourceStorage datas return analyticsProperties; } - public static Map<String, Object> getAnalyticsPropertiesForTestEventStatus - (DatasourceStorage datasourceStorage, boolean status, Throwable e) { + public static Map<String, Object> getAnalyticsPropertiesForTestEventStatus( + DatasourceStorage datasourceStorage, boolean status, Throwable e) { Map<String, Object> analyticsProperties = getAnalyticsPropertiesWithStorage(datasourceStorage); analyticsProperties.put("isSuccess", status); @@ -55,16 +55,16 @@ public static Map<String, Object> getAnalyticsProperties(DatasourceStorage datas return analyticsProperties; } - public static Map<String, Object> getAnalyticsPropertiesForTestEventStatus - (DatasourceStorage datasourceStorage, boolean status) { + public static Map<String, Object> getAnalyticsPropertiesForTestEventStatus( + DatasourceStorage datasourceStorage, boolean status) { Map<String, Object> analyticsProperties = getAnalyticsPropertiesWithStorage(datasourceStorage); analyticsProperties.put("isSuccess", status); analyticsProperties.put("errors", datasourceStorage.getInvalids()); return analyticsProperties; } - public static Map<String, Object> getAnalyticsPropertiesForTestEventStatus - (DatasourceStorage datasourceStorage, DatasourceTestResult datasourceTestResult) { + public static Map<String, Object> getAnalyticsPropertiesForTestEventStatus( + DatasourceStorage datasourceStorage, DatasourceTestResult datasourceTestResult) { Map<String, Object> analyticsProperties = getAnalyticsPropertiesWithStorage(datasourceStorage); analyticsProperties.put("isSuccess", datasourceTestResult.isSuccess()); analyticsProperties.put("errors", datasourceTestResult.getInvalids()); @@ -78,7 +78,9 @@ public static Map<String, Object> getAnalyticsPropertiesWithStorage(DatasourceSt analyticsProperties.put("dsName", datasourceStorage.getName()); analyticsProperties.put("envId", datasourceStorage.getEnvironmentId()); DatasourceConfiguration dsConfig = datasourceStorage.getDatasourceConfiguration(); - if (dsConfig != null && dsConfig.getAuthentication() != null && dsConfig.getAuthentication() instanceof OAuth2) { + if (dsConfig != null + && dsConfig.getAuthentication() != null + && dsConfig.getAuthentication() instanceof OAuth2) { analyticsProperties.put("oAuthStatus", dsConfig.getAuthentication().getAuthenticationStatus()); } return analyticsProperties; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DefaultResourcesUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DefaultResourcesUtils.java index 3c40f323c3dd..058413264d83 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DefaultResourcesUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DefaultResourcesUtils.java @@ -84,7 +84,8 @@ public static <T> T createDefaultIdsOrUpdateWithGivenResourceIds(T resource, Str // Copy layoutOnLoadAction Ids to defaultPageId updateOnLoadActionAndCollectionIds(page.getUnpublishedPage(), updateOnLoadAction); - if (page.getPublishedPage() != null && !CollectionUtils.isNullOrEmpty(page.getPublishedPage().getLayouts())) { + if (page.getPublishedPage() != null + && !CollectionUtils.isNullOrEmpty(page.getPublishedPage().getLayouts())) { updateOnLoadActionAndCollectionIds(page.getPublishedPage(), updateOnLoadAction); } page.setDefaultResources(pageDefaultResources); @@ -100,9 +101,10 @@ public static <T> T createDefaultIdsOrUpdateWithGivenResourceIds(T resource, Str ? actionCollection.getApplicationId() : actionCollectionDefaultResources.getApplicationId(); - final String defaultActionCollectionId = StringUtils.isEmpty(actionCollectionDefaultResources.getCollectionId()) - ? actionCollection.getId() - : actionCollectionDefaultResources.getCollectionId(); + final String defaultActionCollectionId = + StringUtils.isEmpty(actionCollectionDefaultResources.getCollectionId()) + ? actionCollection.getId() + : actionCollectionDefaultResources.getCollectionId(); actionCollectionDefaultResources.setApplicationId(defaultApplicationId); actionCollectionDefaultResources.setCollectionId(defaultActionCollectionId); actionCollectionDefaultResources.setPageId(null); @@ -135,7 +137,8 @@ public static <T> T createDefaultIdsOrUpdateWithGivenResourceIds(T resource, Str if (updateActionIds) { Map<String, String> updatedActionIds = new HashMap<>(); if (!CollectionUtils.isNullOrEmpty(collectionDTO.getDefaultToBranchedActionIdsMap())) { - collectionDTO.getDefaultToBranchedActionIdsMap() + collectionDTO + .getDefaultToBranchedActionIdsMap() .values() .forEach(val -> updatedActionIds.put(val, val)); collectionDTO.setDefaultToBranchedActionIdsMap(updatedActionIds); @@ -147,18 +150,17 @@ public static <T> T createDefaultIdsOrUpdateWithGivenResourceIds(T resource, Str } static void updateOnLoadActionAndCollectionIds(PageDTO page, boolean shouldUpdate) { - page.getLayouts() - .forEach(layout -> { - if (!CollectionUtils.isNullOrEmpty(layout.getLayoutOnLoadActions())) { - for (Set<DslActionDTO> layoutOnLoadAction : layout.getLayoutOnLoadActions()) { - for (DslActionDTO dslActionDTO : layoutOnLoadAction) { - if (shouldUpdate || StringUtils.isEmpty(dslActionDTO.getDefaultActionId())) { - dslActionDTO.setDefaultActionId(dslActionDTO.getId()); - dslActionDTO.setDefaultCollectionId(dslActionDTO.getCollectionId()); - } - } + page.getLayouts().forEach(layout -> { + if (!CollectionUtils.isNullOrEmpty(layout.getLayoutOnLoadActions())) { + for (Set<DslActionDTO> layoutOnLoadAction : layout.getLayoutOnLoadActions()) { + for (DslActionDTO dslActionDTO : layoutOnLoadAction) { + if (shouldUpdate || StringUtils.isEmpty(dslActionDTO.getDefaultActionId())) { + dslActionDTO.setDefaultActionId(dslActionDTO.getId()); + dslActionDTO.setDefaultCollectionId(dslActionDTO.getCollectionId()); } } - }); + } + } + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DslUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DslUtils.java index c4babda4864d..bd78d10a6e9b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DslUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/DslUtils.java @@ -17,7 +17,8 @@ public class DslUtils { - public static Set<MustacheBindingToken> getMustacheValueSetFromSpecificDynamicBindingPath(JsonNode dsl, String fieldPath) { + public static Set<MustacheBindingToken> getMustacheValueSetFromSpecificDynamicBindingPath( + JsonNode dsl, String fieldPath) { DslNodeWalkResponse dslWalkResponse = getDslWalkResponse(dsl, fieldPath); @@ -30,7 +31,8 @@ public static Set<MustacheBindingToken> getMustacheValueSetFromSpecificDynamicBi } // Stricter extraction of dynamic bindings - Set<MustacheBindingToken> mustacheKeysFromFields = MustacheHelper.extractMustacheKeysFromFields(((TextNode) dslWalkResponse.currentNode).asText()); + Set<MustacheBindingToken> mustacheKeysFromFields = + MustacheHelper.extractMustacheKeysFromFields(((TextNode) dslWalkResponse.currentNode).asText()); return mustacheKeysFromFields; } @@ -38,7 +40,8 @@ public static Set<MustacheBindingToken> getMustacheValueSetFromSpecificDynamicBi return new HashSet<>(); } - public static JsonNode replaceValuesInSpecificDynamicBindingPath(JsonNode dsl, String fieldPath, Map<MustacheBindingToken, String> replacementMap) { + public static JsonNode replaceValuesInSpecificDynamicBindingPath( + JsonNode dsl, String fieldPath, Map<MustacheBindingToken, String> replacementMap) { DslNodeWalkResponse dslWalkResponse = getDslWalkResponse(dsl, fieldPath); if (dslWalkResponse != null && dslWalkResponse.isLeafNode) { @@ -47,12 +50,16 @@ public static JsonNode replaceValuesInSpecificDynamicBindingPath(JsonNode dsl, S for (MustacheBindingToken mustacheBindingToken : replacementMap.keySet()) { String tokenValue = mustacheBindingToken.getValue(); int endIndex = mustacheBindingToken.getStartIndex() + tokenValue.length(); - if (oldValue.length() >= endIndex && oldValue.subSequence(mustacheBindingToken.getStartIndex(), endIndex).equals(tokenValue)) { - oldValue.replace(mustacheBindingToken.getStartIndex(), endIndex, replacementMap.get(mustacheBindingToken)); + if (oldValue.length() >= endIndex + && oldValue.subSequence(mustacheBindingToken.getStartIndex(), endIndex) + .equals(tokenValue)) { + oldValue.replace( + mustacheBindingToken.getStartIndex(), endIndex, replacementMap.get(mustacheBindingToken)); } } - ((ObjectNode) dslWalkResponse.parentNode).set(dslWalkResponse.currentKey, new TextNode(oldValue.toString())); + ((ObjectNode) dslWalkResponse.parentNode) + .set(dslWalkResponse.currentKey, new TextNode(oldValue.toString())); } return dsl; } @@ -65,7 +72,9 @@ private static DslNodeWalkResponse getDslWalkResponse(JsonNode dsl, String field // For nested fields, the parent dsl to search in would shift by one level every iteration Object currentNode = dsl; Object parent = null; - Iterator<String> fieldsIterator = Arrays.stream(fields).filter(fieldToken -> !fieldToken.isBlank()).iterator(); + Iterator<String> fieldsIterator = Arrays.stream(fields) + .filter(fieldToken -> !fieldToken.isBlank()) + .iterator(); boolean isLeafNode = false; String nextKey = null; // This loop will end at either a leaf node, or the last identified JSON field (by throwing an exception) diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ExchangeUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ExchangeUtils.java index 519eb8a1fd93..ea7d3e412726 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ExchangeUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ExchangeUtils.java @@ -23,9 +23,11 @@ private ExchangeUtils() { */ private static Mono<String> getHeaderFromCurrentRequest(String headerName) { return Mono.deferContextual(Mono::just) - .flatMap(contextView -> Mono.justOrEmpty( - contextView.get(ServerWebExchange.class).getRequest().getHeaders().getFirst(headerName) - )) + .flatMap(contextView -> Mono.justOrEmpty(contextView + .get(ServerWebExchange.class) + .getRequest() + .getHeaders() + .getFirst(headerName))) // An error is thrown when the context is not available. We don't want to fail the request in this case. .onErrorResume(error -> Mono.empty()); } @@ -38,13 +40,10 @@ private static Mono<String> getHeaderFromCurrentRequest(String headerName) { * @return a Mono that resolves to the value of the `X-Anonymous-User-Id` header, if present. Else, `FieldName.ANONYMOUS_USER`. */ public static Mono<String> getAnonymousUserIdFromCurrentRequest() { - return getHeaderFromCurrentRequest(HEADER_ANONYMOUS_USER_ID) - .defaultIfEmpty(FieldName.ANONYMOUS_USER); + return getHeaderFromCurrentRequest(HEADER_ANONYMOUS_USER_ID).defaultIfEmpty(FieldName.ANONYMOUS_USER); } public static Mono<String> getUserAgentFromCurrentRequest() { - return getHeaderFromCurrentRequest(USER_AGENT) - .defaultIfEmpty("unavailable"); + return getHeaderFromCurrentRequest(USER_AGENT).defaultIfEmpty("unavailable"); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitCloudServicesUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitCloudServicesUtils.java index 5e5dd8708599..0c7a07931caf 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitCloudServicesUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitCloudServicesUtils.java @@ -26,46 +26,50 @@ public class GitCloudServicesUtils { private final ConfigService configService; private final CloudServicesConfig cloudServicesConfig; - private final static Map<String, GitConnectionLimitDTO> gitLimitCache = new HashMap<>(); + private static final Map<String, GitConnectionLimitDTO> gitLimitCache = new HashMap<>(); public Mono<Integer> getPrivateRepoLimitForOrg(String workspaceId, boolean isClearCache) { final String baseUrl = cloudServicesConfig.getBaseUrl(); - return configService.getInstanceId().map(instanceId -> { - if (commonConfig.isCloudHosting()) { - return instanceId + "_" + workspaceId; - } else { - return instanceId; - } - }).flatMap(key -> { - // check the cache for the repo limit - if (Boolean.FALSE.equals(isClearCache) && gitLimitCache.containsKey(key)) { - return Mono.just(gitLimitCache.get(key).getRepoLimit()); - } - // Call the cloud service API - return WebClientUtils - .create(baseUrl + "/api/v1/git/limit/" + key) - .get() - .exchange() - .flatMap(response -> { - if (response.statusCode().is2xxSuccessful()) { - return response.bodyToMono(new ParameterizedTypeReference<ResponseDTO<Integer>>() { - }); - } else { - return Mono.error(new AppsmithException( - AppsmithError.CLOUD_SERVICES_ERROR, - "Unable to connect to cloud-services with error status {}", response.statusCode())); - } - }) - .map(ResponseDTO::getData) - // cache the repo limit - .map(limit -> { - GitConnectionLimitDTO gitConnectionLimitDTO = new GitConnectionLimitDTO(); - gitConnectionLimitDTO.setRepoLimit(limit); - gitConnectionLimitDTO.setExpiryTime(Instant.now().plusSeconds(24 * 60 * 60)); - gitLimitCache.put(key, gitConnectionLimitDTO); - return limit; - }) - .doOnError(error -> log.error("Error fetching config from cloud services", error)); - }); + return configService + .getInstanceId() + .map(instanceId -> { + if (commonConfig.isCloudHosting()) { + return instanceId + "_" + workspaceId; + } else { + return instanceId; + } + }) + .flatMap(key -> { + // check the cache for the repo limit + if (Boolean.FALSE.equals(isClearCache) && gitLimitCache.containsKey(key)) { + return Mono.just(gitLimitCache.get(key).getRepoLimit()); + } + // Call the cloud service API + return WebClientUtils.create(baseUrl + "/api/v1/git/limit/" + key) + .get() + .exchange() + .flatMap(response -> { + if (response.statusCode().is2xxSuccessful()) { + return response.bodyToMono( + new ParameterizedTypeReference<ResponseDTO<Integer>>() {}); + } else { + return Mono.error(new AppsmithException( + AppsmithError.CLOUD_SERVICES_ERROR, + "Unable to connect to cloud-services with error status {}", + response.statusCode())); + } + }) + .map(ResponseDTO::getData) + // cache the repo limit + .map(limit -> { + GitConnectionLimitDTO gitConnectionLimitDTO = new GitConnectionLimitDTO(); + gitConnectionLimitDTO.setRepoLimit(limit); + gitConnectionLimitDTO.setExpiryTime( + Instant.now().plusSeconds(24 * 60 * 60)); + gitLimitCache.put(key, gitConnectionLimitDTO); + return limit; + }) + .doOnError(error -> log.error("Error fetching config from cloud services", error)); + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitDeployKeyGenerator.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitDeployKeyGenerator.java index d3ca9aea9b46..d75697cdad63 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitDeployKeyGenerator.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitDeployKeyGenerator.java @@ -38,7 +38,6 @@ public GitDeployKeyDTO getProtocolDetails() { gitDeployKeyDTO.setPlatFormSupported(this.supportedPlatforms); return gitDeployKeyDTO; } - } public static GitAuth generateSSHKey(String keyType) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java index eaf4421b402c..5e04820e2429 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java @@ -74,9 +74,15 @@ public class GitFileUtils { private final Gson gson; // Only include the application helper fields in metadata object - private static final Set<String> blockedMetadataFields - = Set.of(EXPORTED_APPLICATION, DATASOURCE_LIST, PAGE_LIST, ACTION_LIST, ACTION_COLLECTION_LIST, - DECRYPTED_FIELDS, EDIT_MODE_THEME, CUSTOM_JS_LIB_LIST); + private static final Set<String> blockedMetadataFields = Set.of( + EXPORTED_APPLICATION, + DATASOURCE_LIST, + PAGE_LIST, + ACTION_LIST, + ACTION_COLLECTION_LIST, + DECRYPTED_FIELDS, + EDIT_MODE_THEME, + CUSTOM_JS_LIB_LIST); /** * This method will save the complete application in the local repo directory. @@ -87,34 +93,42 @@ public class GitFileUtils { * @param branchName name of the branch for the current application * @return repo path where the application is stored */ - public Mono<Path> saveApplicationToLocalRepo(Path baseRepoSuffix, - ApplicationJson applicationJson, - String branchName) throws IOException, GitAPIException { + public Mono<Path> saveApplicationToLocalRepo( + Path baseRepoSuffix, ApplicationJson applicationJson, String branchName) + throws IOException, GitAPIException { /* - 1. Checkout to branch - 2. Create application reference for appsmith-git module - 3. Save application to git repo - */ + 1. Checkout to branch + 2. Create application reference for appsmith-git module + 3. Save application to git repo + */ Stopwatch stopwatch = new Stopwatch(AnalyticsEvents.GIT_SERIALIZE_APP_RESOURCES_TO_LOCAL_FILE.getEventName()); ApplicationGitReference applicationReference = createApplicationReference(applicationJson); // Save application to git repo try { - Mono<Path> repoPathMono = fileUtils.saveApplicationToGitRepo(baseRepoSuffix, applicationReference, branchName).cache(); - return Mono.zip(repoPathMono, sessionUserService.getCurrentUser()) - .flatMap(tuple -> { - stopwatch.stopTimer(); - Path repoPath = tuple.getT1(); - // Path to repo will be : ./container-volumes/git-repo/workspaceId/defaultApplicationId/repoName/ - final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, repoPath.getParent().getFileName().toString(), - FieldName.ORGANIZATION_ID, repoPath.getParent().getParent().getFileName().toString(), - FieldName.FLOW_NAME, stopwatch.getFlow(), - "executionTime", stopwatch.getExecutionTime() - ); - return analyticsService.sendEvent(AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), tuple.getT2().getUsername(), data) - .thenReturn(repoPath); - }); + Mono<Path> repoPathMono = fileUtils + .saveApplicationToGitRepo(baseRepoSuffix, applicationReference, branchName) + .cache(); + return Mono.zip(repoPathMono, sessionUserService.getCurrentUser()).flatMap(tuple -> { + stopwatch.stopTimer(); + Path repoPath = tuple.getT1(); + // Path to repo will be : ./container-volumes/git-repo/workspaceId/defaultApplicationId/repoName/ + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, + repoPath.getParent().getFileName().toString(), + FieldName.ORGANIZATION_ID, + repoPath.getParent().getParent().getFileName().toString(), + FieldName.FLOW_NAME, + stopwatch.getFlow(), + "executionTime", + stopwatch.getExecutionTime()); + return analyticsService + .sendEvent( + AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), + tuple.getT2().getUsername(), + data) + .thenReturn(repoPath); + }); } catch (IOException | GitAPIException e) { log.error("Error occurred while saving files to local git repo: ", e); throw Exceptions.propagate(e); @@ -160,9 +174,7 @@ public ApplicationGitReference createApplicationReference(ApplicationJson applic Map<String, Object> resourceMap = new HashMap<>(); Map<String, String> resourceMapBody = new HashMap<>(); Map<String, String> dslBody = new HashMap<>(); - applicationJson - .getPageList() - .stream() + applicationJson.getPageList().stream() // As we are expecting the commit will happen only after the application is published, so we can safely // assume if the unpublished version is deleted entity should not be committed to git .filter(newPage -> newPage.getUnpublishedPage() != null @@ -172,7 +184,8 @@ public ApplicationGitReference createApplicationReference(ApplicationJson applic ? newPage.getUnpublishedPage().getName() : newPage.getPublishedPage().getName(); removeUnwantedFieldsFromPage(newPage); - JSONObject dsl = newPage.getUnpublishedPage().getLayouts().get(0).getDsl(); + JSONObject dsl = + newPage.getUnpublishedPage().getLayouts().get(0).getDsl(); // Get MainContainer widget data, remove the children and club with Canvas.json file JSONObject mainContainer = new JSONObject(dsl); mainContainer.remove("children"); @@ -187,33 +200,64 @@ public ApplicationGitReference createApplicationReference(ApplicationJson applic resourceMap.clear(); resourceMapBody.clear(); - // Insert active actions and also assign the keys which later will be used for saving the resource in actual filepath + // Insert active actions and also assign the keys which later will be used for saving the resource in actual + // filepath // For actions, we are referring to validNames to maintain unique file names as just name // field don't guarantee unique constraint for actions within JSObject // queryValidName_pageName => nomenclature for the keys - applicationJson - .getActionList() - .stream() + applicationJson.getActionList().stream() // As we are expecting the commit will happen only after the application is published, so we can safely // assume if the unpublished version is deleted entity should not be committed to git .filter(newAction -> newAction.getUnpublishedAction() != null && newAction.getUnpublishedAction().getDeletedAt() == null) .forEach(newAction -> { - String prefix = newAction.getUnpublishedAction() != null ? - newAction.getUnpublishedAction().getValidName() + NAME_SEPARATOR + newAction.getUnpublishedAction().getPageId() - : newAction.getPublishedAction().getValidName() + NAME_SEPARATOR + newAction.getPublishedAction().getPageId(); + String prefix = newAction.getUnpublishedAction() != null + ? newAction.getUnpublishedAction().getValidName() + + NAME_SEPARATOR + + newAction.getUnpublishedAction().getPageId() + : newAction.getPublishedAction().getValidName() + + NAME_SEPARATOR + + newAction.getPublishedAction().getPageId(); removeUnwantedFieldFromAction(newAction); - String body = newAction.getUnpublishedAction().getActionConfiguration().getBody() != null ? newAction.getUnpublishedAction().getActionConfiguration().getBody() : ""; + String body = newAction + .getUnpublishedAction() + .getActionConfiguration() + .getBody() + != null + ? newAction + .getUnpublishedAction() + .getActionConfiguration() + .getBody() + : ""; // This is a special case where we are handling REMOTE type plugins based actions such as Twilio - // The user configured values are stored in a attribute called formData which is a map unlike the body - if (newAction.getPluginType().toString().equals("REMOTE") && newAction.getUnpublishedAction().getActionConfiguration().getFormData() != null) { - body = new Gson().toJson(newAction.getUnpublishedAction().getActionConfiguration().getFormData(), Map.class); - newAction.getUnpublishedAction().getActionConfiguration().setFormData(null); + // The user configured values are stored in a attribute called formData which is a map unlike the + // body + if (newAction.getPluginType().toString().equals("REMOTE") + && newAction + .getUnpublishedAction() + .getActionConfiguration() + .getFormData() + != null) { + body = new Gson() + .toJson( + newAction + .getUnpublishedAction() + .getActionConfiguration() + .getFormData(), + Map.class); + newAction + .getUnpublishedAction() + .getActionConfiguration() + .setFormData(null); } - // This is a special case where we are handling JS actions as we don't want to commit the body of JS actions + // This is a special case where we are handling JS actions as we don't want to commit the body of JS + // actions if (newAction.getPluginType().equals(PluginType.JS)) { - newAction.getUnpublishedAction().getActionConfiguration().setBody(null); + newAction + .getUnpublishedAction() + .getActionConfiguration() + .setBody(null); newAction.getUnpublishedAction().setJsonPathKeys(null); } else { // For the regular actions we save the body field to git repo @@ -226,23 +270,30 @@ public ApplicationGitReference createApplicationReference(ApplicationJson applic resourceMap.clear(); resourceMapBody.clear(); - // Insert JSOObjects and also assign the keys which later will be used for saving the resource in actual filepath + // Insert JSOObjects and also assign the keys which later will be used for saving the resource in actual + // filepath // JSObjectName_pageName => nomenclature for the keys Map<String, String> resourceMapActionCollectionBody = new HashMap<>(); - applicationJson - .getActionCollectionList() - .stream() + applicationJson.getActionCollectionList().stream() // As we are expecting the commit will happen only after the application is published, so we can safely // assume if the unpublished version is deleted entity should not be committed to git .filter(collection -> collection.getUnpublishedCollection() != null && collection.getUnpublishedCollection().getDeletedAt() == null) .forEach(actionCollection -> { - String prefix = actionCollection.getUnpublishedCollection() != null ? - actionCollection.getUnpublishedCollection().getName() + NAME_SEPARATOR + actionCollection.getUnpublishedCollection().getPageId() - : actionCollection.getPublishedCollection().getName() + NAME_SEPARATOR + actionCollection.getPublishedCollection().getPageId(); + String prefix = actionCollection.getUnpublishedCollection() != null + ? actionCollection.getUnpublishedCollection().getName() + + NAME_SEPARATOR + + actionCollection + .getUnpublishedCollection() + .getPageId() + : actionCollection.getPublishedCollection().getName() + + NAME_SEPARATOR + + actionCollection.getPublishedCollection().getPageId(); removeUnwantedFieldFromActionCollection(actionCollection); - String body = actionCollection.getUnpublishedCollection().getBody() != null ? actionCollection.getUnpublishedCollection().getBody() : ""; + String body = actionCollection.getUnpublishedCollection().getBody() != null + ? actionCollection.getUnpublishedCollection().getBody() + : ""; actionCollection.getUnpublishedCollection().setBody(null); resourceMapActionCollectionBody.put(prefix, body); resourceMap.put(prefix, actionCollection); @@ -254,19 +305,15 @@ public ApplicationGitReference createApplicationReference(ApplicationJson applic resourceMapActionCollectionBody.clear(); // Send datasources - applicationJson - .getDatasourceList() - .forEach(datasource -> { - resourceMap.put(datasource.getName(), datasource); - }); + applicationJson.getDatasourceList().forEach(datasource -> { + resourceMap.put(datasource.getName(), datasource); + }); applicationReference.setDatasources(new HashMap<>(resourceMap)); resourceMap.clear(); - applicationJson - .getCustomJSLibList() - .forEach(jsLib -> { - resourceMap.put(jsLib.getUidString(), jsLib); - }); + applicationJson.getCustomJSLibList().forEach(jsLib -> { + resourceMap.put(jsLib.getUidString(), jsLib); + }); applicationReference.setJsLibraries(new HashMap<>(resourceMap)); resourceMap.clear(); @@ -281,30 +328,35 @@ public ApplicationGitReference createApplicationReference(ApplicationJson applic * @param branchName for which branch the application needs to rehydrate * @return application reference from which entire application can be rehydrated */ - public Mono<ApplicationJson> reconstructApplicationJsonFromGitRepo(String workspaceId, - String defaultApplicationId, - String repoName, - String branchName) { + public Mono<ApplicationJson> reconstructApplicationJsonFromGitRepo( + String workspaceId, String defaultApplicationId, String repoName, String branchName) { Stopwatch stopwatch = new Stopwatch(AnalyticsEvents.GIT_DESERIALIZE_APP_RESOURCES_FROM_FILE.getEventName()); - Mono<ApplicationGitReference> appReferenceMono = fileUtils - .reconstructApplicationReferenceFromGitRepo(workspaceId, defaultApplicationId, repoName, branchName); - return Mono.zip(appReferenceMono, sessionUserService.getCurrentUser()) - .flatMap(tuple -> { - ApplicationGitReference applicationReference = tuple.getT1(); - // Extract application metadata from the json - ApplicationJson metadata = getApplicationResource(applicationReference.getMetadata(), ApplicationJson.class); - ApplicationJson applicationJson = getApplicationJsonFromGitReference(applicationReference); - copyNestedNonNullProperties(metadata, applicationJson); - stopwatch.stopTimer(); - final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, defaultApplicationId, - FieldName.ORGANIZATION_ID, workspaceId, - FieldName.FLOW_NAME, stopwatch.getFlow(), - "executionTime", stopwatch.getExecutionTime() - ); - return analyticsService.sendEvent(AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), tuple.getT2().getUsername(), data) - .thenReturn(applicationJson); - }); + Mono<ApplicationGitReference> appReferenceMono = fileUtils.reconstructApplicationReferenceFromGitRepo( + workspaceId, defaultApplicationId, repoName, branchName); + return Mono.zip(appReferenceMono, sessionUserService.getCurrentUser()).flatMap(tuple -> { + ApplicationGitReference applicationReference = tuple.getT1(); + // Extract application metadata from the json + ApplicationJson metadata = + getApplicationResource(applicationReference.getMetadata(), ApplicationJson.class); + ApplicationJson applicationJson = getApplicationJsonFromGitReference(applicationReference); + copyNestedNonNullProperties(metadata, applicationJson); + stopwatch.stopTimer(); + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, + defaultApplicationId, + FieldName.ORGANIZATION_ID, + workspaceId, + FieldName.FLOW_NAME, + stopwatch.getFlow(), + "executionTime", + stopwatch.getExecutionTime()); + return analyticsService + .sendEvent( + AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), + tuple.getT2().getUsername(), + data) + .thenReturn(applicationJson); + }); } private <T> List<T> getApplicationResource(Map<String, Object> resources, Type type) { @@ -337,10 +389,9 @@ public <T> T getApplicationResource(Object resource, Type type) { * @param editModeUrl URL to deployed version of the application edit mode * @return Path where the Application is stored */ - public Mono<Path> initializeReadme(Path baseRepoSuffix, - String viewModeUrl, - String editModeUrl) throws IOException { - return fileUtils.initializeReadme(baseRepoSuffix, viewModeUrl, editModeUrl) + public Mono<Path> initializeReadme(Path baseRepoSuffix, String viewModeUrl, String editModeUrl) throws IOException { + return fileUtils + .initializeReadme(baseRepoSuffix, viewModeUrl, editModeUrl) .onErrorResume(e -> Mono.error(new AppsmithException(AppsmithError.GIT_FILE_SYSTEM_ERROR, e))); } @@ -355,7 +406,8 @@ public Mono<Boolean> deleteLocalRepo(Path baseRepoSuffix) { } public Mono<Boolean> checkIfDirectoryIsEmpty(Path baseRepoSuffix) throws IOException { - return fileUtils.checkIfDirectoryIsEmpty(baseRepoSuffix) + return fileUtils + .checkIfDirectoryIsEmpty(baseRepoSuffix) .onErrorResume(e -> Mono.error(new AppsmithException(AppsmithError.GIT_FILE_SYSTEM_ERROR, e))); } @@ -375,7 +427,8 @@ private void removeUnwantedFieldsFromApplication(Application application) { } private void removeUnwantedFieldFromAction(NewAction action) { - // As we are publishing the app and then committing to git we expect the published and unpublished ActionDTO will + // As we are publishing the app and then committing to git we expect the published and unpublished ActionDTO + // will // be same, so we only commit unpublished ActionDTO. action.setPublishedAction(null); } @@ -398,17 +451,21 @@ private ApplicationJson getApplicationJsonFromGitReference(ApplicationGitReferen if (application != null && !CollectionUtils.isNullOrEmpty(application.getPages())) { // Remove null values - org.apache.commons.collections.CollectionUtils.filter(application.getPages(), PredicateUtils.notNullPredicate()); + org.apache.commons.collections.CollectionUtils.filter( + application.getPages(), PredicateUtils.notNullPredicate()); // Create a deep clone of application pages to update independently application.setViewMode(false); - final List<ApplicationPage> applicationPages = new ArrayList<>(application.getPages().size()); - application.getPages() - .forEach(applicationPage -> applicationPages.add(gson.fromJson(gson.toJson(applicationPage), ApplicationPage.class))); + final List<ApplicationPage> applicationPages = + new ArrayList<>(application.getPages().size()); + application + .getPages() + .forEach(applicationPage -> + applicationPages.add(gson.fromJson(gson.toJson(applicationPage), ApplicationPage.class))); application.setPublishedPages(applicationPages); } - List<CustomJSLib> customJSLibList = getApplicationResource(applicationReference.getJsLibraries(), - CustomJSLib.class); + List<CustomJSLib> customJSLibList = + getApplicationResource(applicationReference.getJsLibraries(), CustomJSLib.class); applicationJson.setCustomJSLibList(customJSLibList); // Extract pages @@ -421,11 +478,17 @@ private ApplicationJson getApplicationJsonFromGitReference(ApplicationGitReferen JSONParser jsonParser = new JSONParser(); try { if (pageDsl != null && pageDsl.get(page.getUnpublishedPage().getName()) != null) { - page.getUnpublishedPage().getLayouts().get(0).setDsl( (JSONObject) jsonParser.parse(pageDsl.get(page.getUnpublishedPage().getName())) ); + page.getUnpublishedPage().getLayouts().get(0).setDsl((JSONObject) jsonParser.parse( + pageDsl.get(page.getUnpublishedPage().getName()))); } } catch (ParseException e) { - log.error("Error parsing the page dsl for page: {}", page.getUnpublishedPage().getName(), e); - throw new AppsmithException(AppsmithError.JSON_PROCESSING_ERROR, page.getUnpublishedPage().getName()); + log.error( + "Error parsing the page dsl for page: {}", + page.getUnpublishedPage().getName(), + e); + throw new AppsmithException( + AppsmithError.JSON_PROCESSING_ERROR, + page.getUnpublishedPage().getName()); } }); pages.forEach(newPage -> { @@ -446,21 +509,32 @@ private ApplicationJson getApplicationJsonFromGitReference(ApplicationGitReferen actions.forEach(newAction -> { // With the file version v4 we have split the actions and metadata separately into two files // So we need to set the body to the unpublished action - String keyName = newAction.getUnpublishedAction().getName() + newAction.getUnpublishedAction().getPageId(); - if (actionBody != null && (actionBody.containsKey(keyName)) && !StringUtils.isEmpty(actionBody.get(keyName))) { - // For REMOTE plugin like Twilio the user actions are stored in key value pairs and hence they need to be + String keyName = newAction.getUnpublishedAction().getName() + + newAction.getUnpublishedAction().getPageId(); + if (actionBody != null + && (actionBody.containsKey(keyName)) + && !StringUtils.isEmpty(actionBody.get(keyName))) { + // For REMOTE plugin like Twilio the user actions are stored in key value pairs and hence they need + // to be // deserialized separately unlike the body which is stored as string in the db. if (newAction.getPluginType().toString().equals("REMOTE")) { Map<String, Object> formData = gson.fromJson(actionBody.get(keyName), Map.class); - newAction.getUnpublishedAction().getActionConfiguration().setFormData(formData); + newAction + .getUnpublishedAction() + .getActionConfiguration() + .setFormData(formData); } else { - newAction.getUnpublishedAction().getActionConfiguration().setBody(actionBody.get(keyName)); + newAction + .getUnpublishedAction() + .getActionConfiguration() + .setBody(actionBody.get(keyName)); } } // As we are publishing the app and then committing to git we expect the published and unpublished // actionDTO will be same, so we create a deep copy for the published version for action from // unpublishedActionDTO - newAction.setPublishedAction(gson.fromJson(gson.toJson(newAction.getUnpublishedAction()), ActionDTO.class)); + newAction.setPublishedAction( + gson.fromJson(gson.toJson(newAction.getUnpublishedAction()), ActionDTO.class)); }); applicationJson.setActionList(actions); } @@ -470,26 +544,30 @@ private ApplicationJson getApplicationJsonFromGitReference(ApplicationGitReferen applicationJson.setActionCollectionList(new ArrayList<>()); } else { Map<String, String> actionCollectionBody = applicationReference.getActionCollectionBody(); - List<ActionCollection> actionCollections = getApplicationResource(applicationReference.getActionCollections(), ActionCollection.class); + List<ActionCollection> actionCollections = + getApplicationResource(applicationReference.getActionCollections(), ActionCollection.class); // Remove null values if present org.apache.commons.collections.CollectionUtils.filter(actionCollections, PredicateUtils.notNullPredicate()); actionCollections.forEach(actionCollection -> { // Set the js object body to the unpublished collection // Since file version v3 we are splitting the js object code and metadata separately - String keyName = actionCollection.getUnpublishedCollection().getName() + actionCollection.getUnpublishedCollection().getPageId(); + String keyName = actionCollection.getUnpublishedCollection().getName() + + actionCollection.getUnpublishedCollection().getPageId(); if (actionCollectionBody != null && actionCollectionBody.containsKey(keyName)) { actionCollection.getUnpublishedCollection().setBody(actionCollectionBody.get(keyName)); } // As we are publishing the app and then committing to git we expect the published and unpublished // actionCollectionDTO will be same, so we create a deep copy for the published version for // actionCollection from unpublishedActionCollectionDTO - actionCollection.setPublishedCollection(gson.fromJson(gson.toJson(actionCollection.getUnpublishedCollection()), ActionCollectionDTO.class)); + actionCollection.setPublishedCollection(gson.fromJson( + gson.toJson(actionCollection.getUnpublishedCollection()), ActionCollectionDTO.class)); }); applicationJson.setActionCollectionList(actionCollections); } // Extract datasources - applicationJson.setDatasourceList(getApplicationResource(applicationReference.getDatasources(), DatasourceStorage.class)); + applicationJson.setDatasourceList( + getApplicationResource(applicationReference.getDatasources(), DatasourceStorage.class)); return applicationJson; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java index 5276b786c11a..251b8fd8f4eb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java @@ -1,6 +1,5 @@ package com.appsmith.server.helpers; - import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.util.WebClientUtils; @@ -28,8 +27,7 @@ public static String convertSshUrlToBrowserSupportedUrl(String sshUrl) { if (StringUtils.isEmptyOrNull(sshUrl)) { throw new AppsmithException(AppsmithError.INVALID_PARAMETER, "ssh url"); } - return sshUrl - .replaceFirst(".*git@", "https://") + return sshUrl.replaceFirst(".*git@", "https://") .replaceFirst("(\\.[a-zA-Z0-9]*):", "$1/") .replaceFirst("\\.git$", ""); } @@ -44,15 +42,17 @@ public static String convertSshUrlToBrowserSupportedUrl(String sshUrl) { */ public static String getRepoName(String remoteUrl) { // Pattern to match git SSH URL - final Matcher matcher = Pattern.compile("((git|ssh|http(s)?)|(git@[\\w\\-\\.]+))(:(\\/\\/)?)([\\w.@:/\\-~]+)(\\.git|)(\\/)?").matcher(remoteUrl); + final Matcher matcher = Pattern.compile( + "((git|ssh|http(s)?)|(git@[\\w\\-\\.]+))(:(\\/\\/)?)([\\w.@:/\\-~]+)(\\.git|)(\\/)?") + .matcher(remoteUrl); if (matcher.find()) { // To trim the postfix and prefix - return matcher.group(7) - .replaceFirst("\\.git$", "") - .replaceFirst("^(.*[\\\\\\/])", ""); + return matcher.group(7).replaceFirst("\\.git$", "").replaceFirst("^(.*[\\\\\\/])", ""); } - throw new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, "Remote URL is incorrect, " + - "please add a URL in standard format. Example: [email protected]:username/reponame.git"); + throw new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, + "Remote URL is incorrect, " + + "please add a URL in standard format. Example: [email protected]:username/reponame.git"); } /** @@ -64,8 +64,7 @@ public static String getRepoName(String remoteUrl) { * @throws IOException exception thrown during openConnection */ public static Mono<Boolean> isRepoPrivate(String remoteHttpsUrl) { - return WebClientUtils - .create(remoteHttpsUrl) + return WebClientUtils.create(remoteHttpsUrl) .get() .httpRequest(httpRequest -> { HttpClientRequest reactorRequest = httpRequest.getNativeRequest(); @@ -94,7 +93,6 @@ public static String getGitProviderName(String sshUrl) { if (StringUtils.isEmptyOrNull(sshUrl)) { return ""; } - return sshUrl.split("\\.")[0] - .replaceFirst("git@", ""); + return sshUrl.split("\\.")[0].replaceFirst("git@", ""); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java index ae10f7c58120..23f1b591e4c3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java @@ -26,8 +26,8 @@ public static String getErrorMessage(Throwable throwable) { // TODO provide actionable insights for different error messages generated from import-export flow // Filter out transactional error as these are cryptic and don't provide much info on the error return throwable instanceof TransactionException - || throwable instanceof MongoTransactionException - || throwable instanceof InvalidDataAccessApiUsageException + || throwable instanceof MongoTransactionException + || throwable instanceof InvalidDataAccessApiUsageException ? "" : "Error: " + throwable.getMessage(); } @@ -41,11 +41,12 @@ public static String getErrorMessage(Throwable throwable) { * @param workspaceId workspace in which the application supposed to be imported * @return */ - public static String sanitizeDatasourceInActionDTO(ActionDTO actionDTO, - Map<String, String> datasourceMap, - Map<String, String> pluginMap, - String workspaceId, - boolean isExporting) { + public static String sanitizeDatasourceInActionDTO( + ActionDTO actionDTO, + Map<String, String> datasourceMap, + Map<String, String> pluginMap, + String workspaceId, + boolean isExporting) { if (actionDTO != null && actionDTO.getDatasource() != null) { @@ -54,7 +55,7 @@ public static String sanitizeDatasourceInActionDTO(ActionDTO actionDTO, ds.setUpdatedAt(null); } if (ds.getId() != null) { - //Mapping ds name in id field + // Mapping ds name in id field ds.setId(datasourceMap.get(ds.getId())); ds.setWorkspaceId(null); if (ds.getPluginId() != null) { @@ -73,7 +74,8 @@ public static String sanitizeDatasourceInActionDTO(ActionDTO actionDTO, return ""; } - public static void setPropertiesToExistingApplication(Application importedApplication, Application existingApplication) { + public static void setPropertiesToExistingApplication( + Application importedApplication, Application existingApplication) { importedApplication.setId(existingApplication.getId()); // For the existing application we don't need to default // value of the flag diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/InstanceConfigHelper.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/InstanceConfigHelper.java index 1e8f4ca819ef..9ce4069a7e73 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/InstanceConfigHelper.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/InstanceConfigHelper.java @@ -2,5 +2,4 @@ import com.appsmith.server.helpers.ce.InstanceConfigHelperCE; -public interface InstanceConfigHelper extends InstanceConfigHelperCE { -} +public interface InstanceConfigHelper extends InstanceConfigHelperCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/InstanceConfigHelperImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/InstanceConfigHelperImpl.java index fe808acb13b7..31e882b58ca4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/InstanceConfigHelperImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/InstanceConfigHelperImpl.java @@ -9,10 +9,11 @@ @Component public class InstanceConfigHelperImpl extends InstanceConfigHelperCEImpl implements InstanceConfigHelper { - public InstanceConfigHelperImpl(ConfigService configService, - CloudServicesConfig cloudServicesConfig, - CommonConfig commonConfig, - ApplicationContext applicationContext) { + public InstanceConfigHelperImpl( + ConfigService configService, + CloudServicesConfig cloudServicesConfig, + CommonConfig commonConfig, + ApplicationContext applicationContext) { super(configService, cloudServicesConfig, commonConfig, applicationContext); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/LogHelper.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/LogHelper.java index 8d22111425a4..0e9d5f7dbbcc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/LogHelper.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/LogHelper.java @@ -37,7 +37,8 @@ public static <T> Consumer<Signal<T>> logOnNext(Consumer<T> log) { return; } - Optional<Map<String, String>> maybeContextMap = signal.getContextView().getOrEmpty(CONTEXT_MAP); + Optional<Map<String, String>> maybeContextMap = + signal.getContextView().getOrEmpty(CONTEXT_MAP); if (maybeContextMap.isEmpty()) { log.accept(signal.get()); @@ -59,8 +60,8 @@ public static <T> Consumer<Signal<T>> logOnError(Consumer<Throwable> log) { return; } - Optional<Map<String, String>> maybeContextMap - = signal.getContextView().getOrEmpty(CONTEXT_MAP); + Optional<Map<String, String>> maybeContextMap = + signal.getContextView().getOrEmpty(CONTEXT_MAP); if (maybeContextMap.isEmpty()) { log.accept(signal.getThrowable()); @@ -75,5 +76,4 @@ public static <T> Consumer<Signal<T>> logOnError(Consumer<Throwable> log) { } }; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/NetworkUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/NetworkUtils.java index 4ec83ebf49b0..263d78e018e2 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/NetworkUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/NetworkUtils.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class NetworkUtils extends NetworkUtilsCE { -} +public class NetworkUtils extends NetworkUtilsCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ObjectMapperUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ObjectMapperUtils.java index efc205a3924f..eba57ac5502d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ObjectMapperUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ObjectMapperUtils.java @@ -14,20 +14,14 @@ public ObjectMapperUtils(ObjectMapper objectMapper) { } public <T> T readFromString(String src, Class viewsClass, Class<T> resultClass) throws IOException { - return objectMapper - .readerWithView(viewsClass) - .readValue(src, resultClass); + return objectMapper.readerWithView(viewsClass).readValue(src, resultClass); } public <T> T readFromFile(File file, Class viewsClass, Class<T> resultClass) throws IOException { - return objectMapper - .readerWithView(viewsClass) - .readValue(file, resultClass); + return objectMapper.readerWithView(viewsClass).readValue(file, resultClass); } public String writeAsString(Object src, Class viewsClass) throws JsonProcessingException { - return objectMapper - .writerWithView(viewsClass) - .writeValueAsString(src); + return objectMapper.writerWithView(viewsClass).writeValueAsString(src); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginExecutorHelper.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginExecutorHelper.java index ce32c84b5bf5..39d6f3085c66 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginExecutorHelper.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginExecutorHelper.java @@ -23,13 +23,14 @@ public PluginExecutorHelper(PluginManager pluginManager) { public Mono<PluginExecutor> getPluginExecutor(Mono<Plugin> pluginMono) { return pluginMono.flatMap(plugin -> { - List<PluginExecutor> executorList = pluginManager.getExtensions(PluginExecutor.class, plugin.getPackageName()); - if (executorList.isEmpty()) { - return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "plugin", plugin.getPackageName())); - } - return Mono.just(executorList.get(0)); - } - ); + List<PluginExecutor> executorList = + pluginManager.getExtensions(PluginExecutor.class, plugin.getPackageName()); + if (executorList.isEmpty()) { + return Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "plugin", plugin.getPackageName())); + } + return Mono.just(executorList.get(0)); + }); } public Mono<PluginExecutor> getPluginExecutorFromPackageName(String packageName) { @@ -39,6 +40,5 @@ public Mono<PluginExecutor> getPluginExecutorFromPackageName(String packageName) return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "plugin", packageName)); } return Mono.just(executorList.get(0)); - } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginScheduledTaskUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginScheduledTaskUtils.java index 5413a791fa07..d9dbfd951c2f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginScheduledTaskUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginScheduledTaskUtils.java @@ -2,5 +2,4 @@ import com.appsmith.server.helpers.ce.PluginScheduledTaskUtilsCE; -public interface PluginScheduledTaskUtils extends PluginScheduledTaskUtilsCE { -} +public interface PluginScheduledTaskUtils extends PluginScheduledTaskUtilsCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginScheduledTaskUtilsImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginScheduledTaskUtilsImpl.java index 26ecf5a795d6..10d183613e15 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginScheduledTaskUtilsImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/PluginScheduledTaskUtilsImpl.java @@ -9,11 +9,9 @@ @Component public class PluginScheduledTaskUtilsImpl extends PluginScheduledTaskUtilsCEImpl implements PluginScheduledTaskUtils { - public PluginScheduledTaskUtilsImpl(ConfigService configService, - PluginService pluginService, - CloudServicesConfig cloudServicesConfig) { + public PluginScheduledTaskUtilsImpl( + ConfigService configService, PluginService pluginService, CloudServicesConfig cloudServicesConfig) { super(configService, pluginService, cloudServicesConfig); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/RedirectHelper.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/RedirectHelper.java index f638ff87788c..eed8f99e8101 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/RedirectHelper.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/RedirectHelper.java @@ -23,7 +23,6 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; - @Component @RequiredArgsConstructor public class RedirectHelper { @@ -57,15 +56,13 @@ public Mono<String> getRedirectUrl(ServerHttpRequest request) { HttpHeaders httpHeaders = request.getHeaders(); if (queryParams.getFirst(REDIRECT_URL_QUERY_PARAM) != null) { - return Mono.just(fulfillRedirectUrl( - queryParams.getFirst(REDIRECT_URL_QUERY_PARAM), - httpHeaders - )); + return Mono.just(fulfillRedirectUrl(queryParams.getFirst(REDIRECT_URL_QUERY_PARAM), httpHeaders)); } else if (queryParams.getFirst(FORK_APP_ID_QUERY_PARAM) != null) { final String forkAppId = queryParams.getFirst(FORK_APP_ID_QUERY_PARAM); final String defaultRedirectUrl = httpHeaders.getOrigin() + DEFAULT_REDIRECT_URL; - return applicationRepository.findByClonedFromApplicationId(forkAppId, applicationPermission.getReadPermission()) + return applicationRepository + .findByClonedFromApplicationId(forkAppId, applicationPermission.getReadPermission()) .map(application -> { // Get the default page in the application, or if there's no default page, get the first page // in the application and redirect to edit that page. @@ -92,7 +89,6 @@ public Mono<String> getRedirectUrl(ServerHttpRequest request) { }) .defaultIfEmpty(defaultRedirectUrl) .last(); - } return Mono.just(getRedirectUrlFromHeader(httpHeaders)); @@ -171,7 +167,9 @@ public String getRedirectDomain(HttpHeaders httpHeaders) { } } else if (!StringUtils.isEmpty(httpHeaders.getHost())) { // For HTTP v1 requests - String port = httpHeaders.getHost().getPort() != 80 ? ":" + httpHeaders.getHost().getPort() : ""; + String port = httpHeaders.getHost().getPort() != 80 + ? ":" + httpHeaders.getHost().getPort() + : ""; redirectOrigin = httpHeaders.getHost().getHostName() + port; } @@ -180,9 +178,12 @@ public String getRedirectDomain(HttpHeaders httpHeaders) { public String buildApplicationUrl(Application application, HttpHeaders httpHeaders) { String redirectUrl = RedirectHelper.DEFAULT_REDIRECT_URL; - if (application != null && application.getPages() != null && application.getPages().size() > 0) { + if (application != null + && application.getPages() != null + && application.getPages().size() > 0) { ApplicationPage applicationPage = application.getPages().get(0); - redirectUrl = String.format(RedirectHelper.APPLICATION_PAGE_URL, application.getId(), applicationPage.getId()); + redirectUrl = + String.format(RedirectHelper.APPLICATION_PAGE_URL, application.getId(), applicationPage.getId()); } return fulfillRedirectUrl(redirectUrl, httpHeaders); } @@ -204,7 +205,8 @@ public boolean isDefaultRedirectUrl(String url) { } } - public Mono<Void> handleRedirect(WebFilterExchange webFilterExchange, Application defaultApplication, boolean isFromSignup) { + public Mono<Void> handleRedirect( + WebFilterExchange webFilterExchange, Application defaultApplication, boolean isFromSignup) { ServerWebExchange exchange = webFilterExchange.getExchange(); // On authentication success, we send a redirect to the client's home page. This ensures that the session @@ -246,7 +248,11 @@ public String buildSignupSuccessUrl(String redirectUrl, boolean enableFirstTimeU * @return Redirect URL */ private String buildFailureUrl(String redirectPrefix, String failureMessage) { - String url = redirectPrefix + CHARACTER_QUESTION_MARK + ERROR + CHARACTER_EQUALS + URLEncoder.encode(failureMessage, StandardCharsets.UTF_8); + String url = redirectPrefix + + CHARACTER_QUESTION_MARK + + ERROR + + CHARACTER_EQUALS + + URLEncoder.encode(failureMessage, StandardCharsets.UTF_8); return url; } @@ -258,7 +264,8 @@ private String buildFailureUrl(String redirectPrefix, String failureMessage) { * @param failureMessage Failure message to be added to redirect URL * @return Mono of void */ - public Mono<Void> handleErrorRedirect(WebFilterExchange webFilterExchange, String redirectPrefix, String failureMessage) { + public Mono<Void> handleErrorRedirect( + WebFilterExchange webFilterExchange, String redirectPrefix, String failureMessage) { ServerWebExchange exchange = webFilterExchange.getExchange(); URI redirectURI = URI.create(buildFailureUrl(redirectPrefix, failureMessage)); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/RedisUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/RedisUtils.java index 07cb1e022e23..5cd268f882eb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/RedisUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/RedisUtils.java @@ -14,18 +14,17 @@ public class RedisUtils { private final ReactiveRedisOperations<String, String> redisOperations; - private final static String REDIS_FILE_LOCK_VALUE = "inUse"; + private static final String REDIS_FILE_LOCK_VALUE = "inUse"; - private final static Duration FILE_LOCK_TIME_LIMIT = Duration.ofSeconds(20); + private static final Duration FILE_LOCK_TIME_LIMIT = Duration.ofSeconds(20); public Mono<Boolean> addFileLock(String key) { - return redisOperations.hasKey(key) - .flatMap(isKeyPresent -> { - if (Boolean.TRUE.equals(isKeyPresent)) { - return Mono.error(new AppsmithException(AppsmithError.GIT_FILE_IN_USE)); - } - return redisOperations.opsForValue().set(key, REDIS_FILE_LOCK_VALUE, FILE_LOCK_TIME_LIMIT); - }); + return redisOperations.hasKey(key).flatMap(isKeyPresent -> { + if (Boolean.TRUE.equals(isKeyPresent)) { + return Mono.error(new AppsmithException(AppsmithError.GIT_FILE_IN_USE)); + } + return redisOperations.opsForValue().set(key, REDIS_FILE_LOCK_VALUE, FILE_LOCK_TIME_LIMIT); + }); } public Mono<Boolean> releaseFileLock(String key) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ReleaseNotesUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ReleaseNotesUtils.java index 6571521a786a..ae79421c5b55 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ReleaseNotesUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ReleaseNotesUtils.java @@ -2,5 +2,4 @@ import com.appsmith.server.helpers.ce.ReleaseNotesUtilsCE; -public interface ReleaseNotesUtils extends ReleaseNotesUtilsCE { -} +public interface ReleaseNotesUtils extends ReleaseNotesUtilsCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ReleaseNotesUtilsImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ReleaseNotesUtilsImpl.java index 9afb14094fb1..9ee40c278fd9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ReleaseNotesUtilsImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ReleaseNotesUtilsImpl.java @@ -10,11 +10,12 @@ @Component public class ReleaseNotesUtilsImpl extends ReleaseNotesUtilsCEImpl implements ReleaseNotesUtils { - public ReleaseNotesUtilsImpl(CloudServicesConfig cloudServicesConfig, - CommonConfig commonConfig, - SegmentConfig segmentConfig, - ConfigService configService, - ProjectProperties projectProperties) { + public ReleaseNotesUtilsImpl( + CloudServicesConfig cloudServicesConfig, + CommonConfig commonConfig, + SegmentConfig segmentConfig, + ConfigService configService, + ProjectProperties projectProperties) { super(cloudServicesConfig, commonConfig, segmentConfig, configService, projectProperties); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ResponseUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ResponseUtils.java index bd3f60f82ed0..13a097c4dc66 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ResponseUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ResponseUtils.java @@ -49,8 +49,7 @@ public PageDTO updatePageDTOWithDefaultResources(PageDTO page) { page.setApplicationId(defaultResourceIds.getApplicationId()); page.setId(defaultResourceIds.getPageId()); - page.getLayouts() - .stream() + page.getLayouts().stream() .filter(layout -> !CollectionUtils.isEmpty(layout.getLayoutOnLoadActions())) .forEach(layout -> this.updateLayoutWithDefaultResources(layout)); return page; @@ -60,13 +59,11 @@ public NewPage updateNewPageWithDefaultResources(NewPage newPage) { DefaultResources defaultResourceIds = newPage.getDefaultResources(); if (defaultResourceIds == null || StringUtils.isEmpty(defaultResourceIds.getApplicationId()) - || StringUtils.isEmpty(defaultResourceIds.getPageId()) - ) { + || StringUtils.isEmpty(defaultResourceIds.getPageId())) { log.error( "Unable to find default ids for page: {}", newPage.getId(), - new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "page", newPage.getId()) - ); + new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "page", newPage.getId())); if (defaultResourceIds == null) { return newPage; @@ -96,8 +93,8 @@ public ApplicationPagesDTO updateApplicationPagesDTOWithDefaultResources(Applica log.error( "Unable to find default pageId for applicationPage: {}", page.getId(), - new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "applicationPage", page.getId()) - ); + new AppsmithException( + AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "applicationPage", page.getId())); continue; } page.setId(page.getDefaultPageId()); @@ -144,24 +141,23 @@ public LayoutDTO updateLayoutDTOWithDefaultResources(LayoutDTO layout) { .forEach(updateLayoutAction -> updateLayoutAction.setId(updateLayoutAction.getDefaultActionId())); } if (!CollectionUtils.isEmpty(layout.getLayoutOnLoadActions())) { - layout.getLayoutOnLoadActions().forEach(layoutOnLoadAction -> - layoutOnLoadAction.forEach(onLoadAction -> { + layout.getLayoutOnLoadActions() + .forEach(layoutOnLoadAction -> layoutOnLoadAction.forEach(onLoadAction -> { if (!StringUtils.isEmpty(onLoadAction.getDefaultActionId())) { onLoadAction.setId(onLoadAction.getDefaultActionId()); } if (!StringUtils.isEmpty(onLoadAction.getDefaultCollectionId())) { onLoadAction.setCollectionId(onLoadAction.getDefaultCollectionId()); } - }) - ); + })); } return layout; } public Layout updateLayoutWithDefaultResources(Layout layout) { if (!CollectionUtils.isEmpty(layout.getLayoutOnLoadActions())) { - layout.getLayoutOnLoadActions().forEach(layoutOnLoadAction -> - layoutOnLoadAction.forEach(onLoadAction -> { + layout.getLayoutOnLoadActions() + .forEach(layoutOnLoadAction -> layoutOnLoadAction.forEach(onLoadAction -> { if (!StringUtils.isEmpty(onLoadAction.getDefaultActionId())) { onLoadAction.setId(onLoadAction.getDefaultActionId()); } @@ -202,8 +198,7 @@ public NewAction updateNewActionWithDefaultResources(NewAction newAction) { log.error( "Unable to find default ids for newAction: {}", newAction.getId(), - new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "newAction", newAction.getId()) - ); + new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "newAction", newAction.getId())); if (defaultResourceIds == null) { return newAction; @@ -235,8 +230,8 @@ public ActionCollection updateActionCollectionWithDefaultResources(ActionCollect log.error( "Unable to find default ids for actionCollection: {}", actionCollection.getId(), - new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "actionCollection", actionCollection.getId()) - ); + new AppsmithException( + AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "actionCollection", actionCollection.getId())); if (defaultResourceIds == null) { return actionCollection; @@ -251,10 +246,12 @@ public ActionCollection updateActionCollectionWithDefaultResources(ActionCollect actionCollection.setId(defaultResourceIds.getCollectionId()); actionCollection.setApplicationId(defaultResourceIds.getApplicationId()); if (actionCollection.getUnpublishedCollection() != null) { - actionCollection.setUnpublishedCollection(this.updateCollectionDTOWithDefaultResources(actionCollection.getUnpublishedCollection())); + actionCollection.setUnpublishedCollection( + this.updateCollectionDTOWithDefaultResources(actionCollection.getUnpublishedCollection())); } if (actionCollection.getPublishedCollection() != null) { - actionCollection.setPublishedCollection(this.updateCollectionDTOWithDefaultResources(actionCollection.getPublishedCollection())); + actionCollection.setPublishedCollection( + this.updateCollectionDTOWithDefaultResources(actionCollection.getPublishedCollection())); } return actionCollection; } @@ -323,32 +320,28 @@ public Application updateApplicationWithDefaultResources(Application application application.setId(application.getGitApplicationMetadata().getDefaultApplicationId()); } if (!CollectionUtils.isEmpty(application.getPages())) { - application - .getPages() - .forEach(page -> { - if (!StringUtils.isEmpty(page.getDefaultPageId())) { - page.setId(page.getDefaultPageId()); - } - }); + application.getPages().forEach(page -> { + if (!StringUtils.isEmpty(page.getDefaultPageId())) { + page.setId(page.getDefaultPageId()); + } + }); } if (!CollectionUtils.isEmpty(application.getPublishedPages())) { - application - .getPublishedPages() - .forEach(page -> { - if (!StringUtils.isEmpty(page.getDefaultPageId())) { - page.setId(page.getDefaultPageId()); - } - }); + application.getPublishedPages().forEach(page -> { + if (!StringUtils.isEmpty(page.getDefaultPageId())) { + page.setId(page.getDefaultPageId()); + } + }); } - if (application.getClientSchemaVersion() == null || application.getServerSchemaVersion() == null + if (application.getClientSchemaVersion() == null + || application.getServerSchemaVersion() == null || (JsonSchemaVersions.clientVersion.equals(application.getClientSchemaVersion()) - && JsonSchemaVersions.serverVersion.equals(application.getServerSchemaVersion()))) { + && JsonSchemaVersions.serverVersion.equals(application.getServerSchemaVersion()))) { application.setIsAutoUpdate(false); } else { application.setIsAutoUpdate(true); } return application; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/UserUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/UserUtils.java index b8aa79e2f876..992e20a9f99f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/UserUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/UserUtils.java @@ -9,10 +9,11 @@ @Component public class UserUtils extends UserUtilsCE { - public UserUtils(ConfigRepository configRepository, - PermissionGroupRepository permissionGroupRepository, - CacheableRepositoryHelper cacheableRepositoryHelper, - PermissionGroupPermission permissionGroupPermission) { + public UserUtils( + ConfigRepository configRepository, + PermissionGroupRepository permissionGroupRepository, + CacheableRepositoryHelper cacheableRepositoryHelper, + PermissionGroupPermission permissionGroupPermission) { super(configRepository, permissionGroupRepository, cacheableRepositoryHelper, permissionGroupPermission); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ValidationUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ValidationUtils.java index a57bf68be5de..9dca6f543b71 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ValidationUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ValidationUtils.java @@ -11,9 +11,8 @@ public final class ValidationUtils { public static final int LOGIN_PASSWORD_MAX_LENGTH = 48; private static final String EMAIL_PATTERN = "[\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z]+"; - private static final Pattern EMAIL_CSV_PATTERN = Pattern.compile( - "^\\s*(" + EMAIL_PATTERN + "\\s*,\\s*)*(" + EMAIL_PATTERN + ")\\s*$" - ); + private static final Pattern EMAIL_CSV_PATTERN = + Pattern.compile("^\\s*(" + EMAIL_PATTERN + "\\s*,\\s*)*(" + EMAIL_PATTERN + ")\\s*$"); public static boolean validateEmail(String emailStr) { return EmailValidator.getInstance().isValid(emailStr); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSpecificUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSpecificUtils.java index 6ee12c0d7b34..fd13f9e2e712 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSpecificUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSpecificUtils.java @@ -68,5 +68,4 @@ public static JSONObject unEscapeTableWidgetPrimaryColumns(JSONObject dsl) { } return dsl; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSuggestionHelper.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSuggestionHelper.java index 683447abc509..41ce1723502a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSuggestionHelper.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSuggestionHelper.java @@ -53,7 +53,7 @@ private static List<WidgetSuggestionDTO> handleArrayNode(ArrayNode array) { if (array.isEmpty()) { return new ArrayList<>(); } - //TODO - check other data types + // TODO - check other data types if (array.isArray()) { int length = array.size(); JsonNode node = array.get(0); @@ -100,8 +100,10 @@ private static List<WidgetSuggestionDTO> handleJsonNode(JsonNode node) { if (node.get(nestedFieldName).size() == 0) { widgetTypeList.add(getWidget(WidgetType.TEXT_WIDGET)); } else { - dataFields = collectFieldsFromData(node.get(nestedFieldName).get(0).fields()); - widgetTypeList = getWidgetsForTypeNestedObject(nestedFieldName, dataFields.getFields(), dataFields.getNumericFields()); + dataFields = collectFieldsFromData( + node.get(nestedFieldName).get(0).fields()); + widgetTypeList = getWidgetsForTypeNestedObject( + nestedFieldName, dataFields.getFields(), dataFields.getNumericFields()); } } } else if (JsonNodeType.NUMBER.equals(nodeType)) { @@ -121,7 +123,7 @@ private static List<WidgetSuggestionDTO> handleList(List dataList) { List<String> fields = new ArrayList<>(); List<String> numericFields = new ArrayList<>(); - //Get all the fields from the object and check for the possible widget match + // Get all the fields from the object and check for the possible widget match for (Object key : fieldList) { if (map.get(key) instanceof String) { fields.add(((String) key)); @@ -202,9 +204,8 @@ private static List<WidgetSuggestionDTO> getWidgetsForTypeNumber() { * When the response from the action is has nested data(Ex : Object containing array of fields) and only 1 level is supported * For nested data, the binding query changes from data.map() --> data.nestedFieldName.map() */ - private static List<WidgetSuggestionDTO> getWidgetsForTypeNestedObject(String nestedFieldName, - List<String> fields, - List<String> numericFields) { + private static List<WidgetSuggestionDTO> getWidgetsForTypeNestedObject( + String nestedFieldName, List<String> fields, List<String> numericFields) { List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>(); /* * fields - contains all the fields inside the nested data and nested data is considered to only 1 level @@ -214,12 +215,15 @@ private static List<WidgetSuggestionDTO> getWidgetsForTypeNestedObject(String ne * */ if (!fields.isEmpty()) { if (fields.size() < 2) { - widgetTypeList.add(getWidgetNestedData(WidgetType.SELECT_WIDGET, nestedFieldName, fields.get(0), fields.get(0))); + widgetTypeList.add( + getWidgetNestedData(WidgetType.SELECT_WIDGET, nestedFieldName, fields.get(0), fields.get(0))); } else { - widgetTypeList.add(getWidgetNestedData(WidgetType.SELECT_WIDGET, nestedFieldName, fields.get(0), fields.get(1))); + widgetTypeList.add( + getWidgetNestedData(WidgetType.SELECT_WIDGET, nestedFieldName, fields.get(0), fields.get(1))); } if (!numericFields.isEmpty()) { - widgetTypeList.add(getWidgetNestedData(WidgetType.CHART_WIDGET, nestedFieldName, fields.get(0), numericFields.get(0))); + widgetTypeList.add(getWidgetNestedData( + WidgetType.CHART_WIDGET, nestedFieldName, fields.get(0), numericFields.get(0))); } } widgetTypeList.add(getWidgetNestedData(WidgetType.TABLE_WIDGET_V2, nestedFieldName)); @@ -234,7 +238,8 @@ public static WidgetSuggestionDTO getWidget(WidgetType widgetType, Object... arg return widgetSuggestionDTO; } - public static WidgetSuggestionDTO getWidgetNestedData(WidgetType widgetType, String nestedFieldName, Object... args) { + public static WidgetSuggestionDTO getWidgetNestedData( + WidgetType widgetType, String nestedFieldName, Object... args) { WidgetSuggestionDTO widgetSuggestionDTO = new WidgetSuggestionDTO(); widgetSuggestionDTO.setType(widgetType); String query = String.format(widgetType.getMessage(), args); @@ -244,5 +249,4 @@ public static WidgetSuggestionDTO getWidgetNestedData(WidgetType widgetType, Str widgetSuggestionDTO.setBindingQuery(query); return widgetSuggestionDTO; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/AppsmithComparatorsCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/AppsmithComparatorsCE.java index e7c4634932b2..ea8ed052ea06 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/AppsmithComparatorsCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/AppsmithComparatorsCE.java @@ -30,8 +30,10 @@ public int compare(MemberInfoDTO o1, MemberInfoDTO o2) { throw new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR); } - boolean workspaceRolePresent1 = o1.getRoles().stream().anyMatch(role -> Workspace.class.getSimpleName().equals(role.getEntityType())); - boolean workspaceRolePresent2 = o1.getRoles().stream().anyMatch(role -> Workspace.class.getSimpleName().equals(role.getEntityType())); + boolean workspaceRolePresent1 = o1.getRoles().stream() + .anyMatch(role -> Workspace.class.getSimpleName().equals(role.getEntityType())); + boolean workspaceRolePresent2 = o1.getRoles().stream() + .anyMatch(role -> Workspace.class.getSimpleName().equals(role.getEntityType())); if (!workspaceRolePresent1 || !workspaceRolePresent2) { throw new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR); @@ -53,7 +55,8 @@ public int compare(MemberInfoDTO o1, MemberInfoDTO o2) { private int getOrderBasedOnWorkspaceRole(MemberInfoDTO member) { PermissionGroupInfoDTO role = member.getRoles().stream() .filter(role1 -> Workspace.class.getSimpleName().equals(role1.getEntityType())) - .findFirst().get(); + .findFirst() + .get(); if (Objects.nonNull(role.getName()) && role.getName().startsWith(FieldName.ADMINISTRATOR)) { return 0; } else if (Objects.nonNull(role.getName()) && role.getName().startsWith(FieldName.DEVELOPER)) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ExecutionTimeLogging.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ExecutionTimeLogging.java index ea90ed46007c..33d598ac69ff 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ExecutionTimeLogging.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ExecutionTimeLogging.java @@ -23,22 +23,28 @@ public void stopTimer(String taskName) { public String print() { StringBuilder sb = new StringBuilder(); - sb.append("\nTime consumed for the operation ").append(System.currentTimeMillis() - startTime).append("\n"); + sb.append("\nTime consumed for the operation ") + .append(System.currentTimeMillis() - startTime) + .append("\n"); for (String taskName : taskStartTime.keySet()) { sb.append(taskName) - .append(";").append(taskStartTime.get(taskName)) - .append(";").append(taskEndTime.getOrDefault(taskName, 0L)) - .append(";").append(taskEndTime.getOrDefault(taskName, 0L) - taskStartTime.get(taskName)) + .append(";") + .append(taskStartTime.get(taskName)) + .append(";") + .append(taskEndTime.getOrDefault(taskName, 0L)) + .append(";") + .append(taskEndTime.getOrDefault(taskName, 0L) - taskStartTime.get(taskName)) .append("\n"); } return sb.toString(); } public <T> Mono<T> measureTask(String name, Mono<T> mono) { - //stopWatch.start(name); + // stopWatch.start(name); return mono.map(time -> { - stopTimer(name); - return time; - }).doOnSubscribe((s) -> startTimer(name)); + stopTimer(name); + return time; + }) + .doOnSubscribe((s) -> startTimer(name)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ImportApplicationPermissionProvider.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ImportApplicationPermissionProvider.java index 4c1880dda6cc..b4ed7061d06c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ImportApplicationPermissionProvider.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ImportApplicationPermissionProvider.java @@ -42,12 +42,16 @@ public class ImportApplicationPermissionProvider { @Getter(AccessLevel.NONE) private final ApplicationPermission applicationPermission; + @Getter(AccessLevel.NONE) private final PagePermission pagePermission; + @Getter(AccessLevel.NONE) private final ActionPermission actionPermission; + @Getter(AccessLevel.NONE) private final DatasourcePermission datasourcePermission; + @Getter(AccessLevel.NONE) private final WorkspacePermission workspacePermission; @@ -63,7 +67,7 @@ public class ImportApplicationPermissionProvider { // flag to indicate whether permission check is required on the create datasource operation private boolean permissionRequiredToCreateDatasource; - //flag to indicate whether permission check is required on the create page operation + // flag to indicate whether permission check is required on the create page operation private boolean permissionRequiredToCreatePage; // flag to indicate whether permission check is required on the edit page operation private boolean permissionRequiredToEditPage; @@ -91,7 +95,8 @@ private boolean hasPermission(AclPermission permission, BaseDomain baseDomain) { if (permission == null) { return true; } - return PolicyUtil.isPermissionPresentInPolicies(permission.getValue(), baseDomain.getPolicies(), currentUserPermissionGroups); + return PolicyUtil.isPermissionPresentInPolicies( + permission.getValue(), baseDomain.getPolicies(), currentUserPermissionGroups); } public boolean hasEditPermission(NewPage page) { @@ -136,12 +141,14 @@ public boolean canCreateDatasource(Workspace workspace) { return hasPermission(workspacePermission.getDatasourceCreatePermission(), workspace); } - public static Builder builder(ApplicationPermission applicationPermission, - PagePermission pagePermission, - ActionPermission actionPermission, - DatasourcePermission datasourcePermission, - WorkspacePermission workspacePermission) { - return new Builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission); + public static Builder builder( + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission, + DatasourcePermission datasourcePermission, + WorkspacePermission workspacePermission) { + return new Builder( + applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission); } @Setter @@ -165,7 +172,12 @@ public static class Builder { private boolean permissionRequiredToEditAction; private boolean permissionRequiredToEditDatasource; - private Builder(ApplicationPermission applicationPermission, PagePermission pagePermission, ActionPermission actionPermission, DatasourcePermission datasourcePermission, WorkspacePermission workspacePermission) { + private Builder( + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission, + DatasourcePermission datasourcePermission, + WorkspacePermission workspacePermission) { this.applicationPermission = applicationPermission; this.pagePermission = pagePermission; this.actionPermission = actionPermission; @@ -200,8 +212,7 @@ public ImportApplicationPermissionProvider build() { permissionRequiredToCreateAction, permissionRequiredToEditAction, permissionRequiredToEditDatasource, - currentUserPermissionGroups - ); + currentUserPermissionGroups); } } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/InstanceConfigHelperCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/InstanceConfigHelperCEImpl.java index 25c657ed21f3..2792ee0fee5a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/InstanceConfigHelperCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/InstanceConfigHelperCEImpl.java @@ -46,27 +46,29 @@ public Mono<? extends Config> registerInstance() { final String baseUrl = cloudServicesConfig.getBaseUrl(); if (baseUrl == null || StringUtils.isEmpty(baseUrl)) { return Mono.error(new AppsmithException( - AppsmithError.INSTANCE_REGISTRATION_FAILURE, "Unable to find cloud services base URL") - ); + AppsmithError.INSTANCE_REGISTRATION_FAILURE, "Unable to find cloud services base URL")); } return configService .getInstanceId() - .flatMap(instanceId -> WebClientUtils - .create(baseUrl + "/api/v1/installations") + .flatMap(instanceId -> WebClientUtils.create(baseUrl + "/api/v1/installations") .post() .body(BodyInserters.fromValue(Map.of("key", instanceId))) .headers(httpHeaders -> httpHeaders.set(HttpHeaders.CONTENT_TYPE, "application/json")) .exchange()) - .flatMap(clientResponse -> clientResponse.toEntity(new ParameterizedTypeReference<ResponseDTO<String>>() { - })) + .flatMap(clientResponse -> + clientResponse.toEntity(new ParameterizedTypeReference<ResponseDTO<String>>() {})) .flatMap(responseEntity -> { if (responseEntity.getStatusCode().is2xxSuccessful()) { - return Mono.justOrEmpty(Objects.requireNonNull(responseEntity.getBody()).getData()); + return Mono.justOrEmpty( + Objects.requireNonNull(responseEntity.getBody()).getData()); } return Mono.error(new AppsmithException( AppsmithError.INSTANCE_REGISTRATION_FAILURE, - Objects.requireNonNull(responseEntity.getBody()).getResponseMeta().getError().getMessage())); + Objects.requireNonNull(responseEntity.getBody()) + .getResponseMeta() + .getError() + .getMessage())); }) .flatMap(instanceId -> { log.debug("Registration successful, updating state ..."); @@ -76,17 +78,23 @@ public Mono<? extends Config> registerInstance() { @Override public Mono<Config> checkInstanceSchemaVersion() { - return configService.getByName(Appsmith.INSTANCE_SCHEMA_VERSION) + return configService + .getByName(Appsmith.INSTANCE_SCHEMA_VERSION) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.SCHEMA_VERSION_NOT_FOUND_ERROR))) - .onErrorMap(AppsmithException.class, e -> new AppsmithException(AppsmithError.SCHEMA_VERSION_NOT_FOUND_ERROR)) + .onErrorMap( + AppsmithException.class, + e -> new AppsmithException(AppsmithError.SCHEMA_VERSION_NOT_FOUND_ERROR)) .flatMap(config -> { - if (CommonConfig.LATEST_INSTANCE_SCHEMA_VERSION == config.getConfig().get("value")) { + if (CommonConfig.LATEST_INSTANCE_SCHEMA_VERSION + == config.getConfig().get("value")) { return Mono.just(config); } - return Mono.error(populateSchemaMismatchError((Integer) config.getConfig().get("value"))); + return Mono.error(populateSchemaMismatchError( + (Integer) config.getConfig().get("value"))); }) .doOnError(errorSignal -> { - log.error(""" + log.error( + """ ################################################ Error while trying to start up Appsmith instance:\s @@ -107,10 +115,11 @@ private AppsmithException populateSchemaMismatchError(Integer currentInstanceSch // Keep adding version numbers that brought in breaking instance schema migrations here switch (currentInstanceSchemaVersion) { - // Example, we expect that in v1.9.2, all instances will have been migrated to instanceSchemaVer 2 + // Example, we expect that in v1.9.2, all instances will have been migrated to instanceSchemaVer 2 case 1: versions.add("v1.9.2"); - docs.add("https://docs.appsmith.com/help-and-support/troubleshooting-guide/deployment-errors#server-shuts-down-with-schema-mismatch-error"); + docs.add( + "https://docs.appsmith.com/help-and-support/troubleshooting-guide/deployment-errors#server-shuts-down-with-schema-mismatch-error"); default: } @@ -120,8 +129,7 @@ private AppsmithException populateSchemaMismatchError(Integer currentInstanceSch public Mono<Void> performRtsHealthCheck() { log.debug("Performing RTS health check of this instance..."); - return WebClientUtils - .create(commonConfig.getRtsBaseUrl() + "/rts-api/v1/health-check") + return WebClientUtils.create(commonConfig.getRtsBaseUrl() + "/rts-api/v1/health-check") .get() .retrieve() .toBodilessEntity() @@ -132,8 +140,8 @@ public Mono<Void> performRtsHealthCheck() { .onErrorResume(errorSignal -> { log.debug("RTS health check failed with error: \n{}", errorSignal.getMessage()); return Mono.empty(); - - }).then(); + }) + .then(); } @Override @@ -149,8 +157,7 @@ public void printReady() { ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ Please open http://localhost:<port> in your browser to experience Appsmith! - """ - ); + """); } @Override @@ -163,5 +170,4 @@ public Mono<Boolean> isLicenseValid() { // As CE edition doesn't require license, default state should be valid return Mono.just(true); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/NetworkUtilsCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/NetworkUtilsCE.java index e106dd1d32f1..5a044ea580e6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/NetworkUtilsCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/NetworkUtilsCE.java @@ -11,13 +11,12 @@ public class NetworkUtilsCE { private static final URI GET_IP_URI = URI.create("https://api64.ipify.org"); - + protected static String cachedAddress = null; protected static final String FALLBACK_IP = "unknown"; - protected NetworkUtilsCE() { - } + protected NetworkUtilsCE() {} /** * This method hits an API endpoint that returns the external IP address of this server instance. @@ -29,8 +28,7 @@ public Mono<String> getExternalAddress() { return Mono.just(cachedAddress); } - return WebClientUtils - .create() + return WebClientUtils.create() .get() .uri(GET_IP_URI) .retrieve() @@ -45,5 +43,4 @@ public Mono<String> getExternalAddress() { return Mono.just(FALLBACK_IP); }); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PluginScheduledTaskUtilsCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PluginScheduledTaskUtilsCE.java index cfd8b6f6f242..f06e69046963 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PluginScheduledTaskUtilsCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PluginScheduledTaskUtilsCE.java @@ -7,5 +7,4 @@ public interface PluginScheduledTaskUtilsCE { Mono<Void> fetchAndUpdateRemotePlugins(Instant lastUpdatedAt); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PluginScheduledTaskUtilsCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PluginScheduledTaskUtilsCEImpl.java index 3c0c16b61ddf..3bf23bf3f6ef 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PluginScheduledTaskUtilsCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PluginScheduledTaskUtilsCEImpl.java @@ -37,84 +37,78 @@ private Mono<Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin>> getRemoteP return Mono.empty(); } - return configService.getInstanceId() - .flatMap(instanceId -> WebClientUtils - .create( - baseUrl + "/api/v1/plugins?instanceId=" + instanceId - + "&lastUpdatedAt=" + lastUpdatedAt) - .get() - .exchangeToMono(clientResponse -> clientResponse.bodyToMono(new ParameterizedTypeReference<ResponseDTO<List<Plugin>>>() { - })) - .map(listResponseDTO -> { - if (listResponseDTO.getData() == null) { - log.error("Error fetching plugins from cloud-services. Error: {}", listResponseDTO.getErrorDisplay()); - return Collections.<Plugin>emptyList(); - } - return listResponseDTO.getData(); - }) - .map(plugins -> { + return configService.getInstanceId().flatMap(instanceId -> WebClientUtils.create( + baseUrl + "/api/v1/plugins?instanceId=" + instanceId + "&lastUpdatedAt=" + lastUpdatedAt) + .get() + .exchangeToMono(clientResponse -> + clientResponse.bodyToMono(new ParameterizedTypeReference<ResponseDTO<List<Plugin>>>() {})) + .map(listResponseDTO -> { + if (listResponseDTO.getData() == null) { + log.error( + "Error fetching plugins from cloud-services. Error: {}", + listResponseDTO.getErrorDisplay()); + return Collections.<Plugin>emptyList(); + } + return listResponseDTO.getData(); + }) + .map(plugins -> { - // Parse plugins into map for easier manipulation - return plugins - .stream() - .collect(Collectors.toMap( - plugin -> new PluginScheduledTaskCEImpl.PluginIdentifier(plugin.getPluginName(), plugin.getVersion()), - plugin -> plugin - )); - })); + // Parse plugins into map for easier manipulation + return plugins.stream() + .collect(Collectors.toMap( + plugin -> new PluginScheduledTaskCEImpl.PluginIdentifier( + plugin.getPluginName(), plugin.getVersion()), + plugin -> plugin)); + })); } @Override public Mono<Void> fetchAndUpdateRemotePlugins(Instant lastUpdatedAt) { // Get all plugins on this instance - final Mono<Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin>> availablePluginsMono = - pluginService - .getAllRemotePlugins() - .collect(Collectors.toMap( - plugin -> new PluginScheduledTaskCEImpl.PluginIdentifier(plugin.getPluginName(), plugin.getVersion()), - plugin -> plugin - )); + final Mono<Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin>> availablePluginsMono = pluginService + .getAllRemotePlugins() + .collect(Collectors.toMap( + plugin -> new PluginScheduledTaskCEImpl.PluginIdentifier( + plugin.getPluginName(), plugin.getVersion()), + plugin -> plugin)); - final Mono<Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin>> newPluginsMono = getRemotePlugins(lastUpdatedAt); + final Mono<Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin>> newPluginsMono = + getRemotePlugins(lastUpdatedAt); - return Mono.zip(availablePluginsMono, newPluginsMono) - .flatMap(tuple -> { - final Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin> availablePlugins = tuple.getT1(); - final Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin> newPlugins = tuple.getT2(); - final List<Plugin> updatablePlugins = new ArrayList<>(); - final List<Plugin> insertablePlugins = new ArrayList<>(); - newPlugins.forEach((k, v) -> { - if (availablePlugins.containsKey(k)) { - v.setId(availablePlugins.get(k).getId()); - updatablePlugins.add(v); - } else { - v.setId(null); - insertablePlugins.add(v); - } - }); + return Mono.zip(availablePluginsMono, newPluginsMono).flatMap(tuple -> { + final Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin> availablePlugins = tuple.getT1(); + final Map<PluginScheduledTaskCEImpl.PluginIdentifier, Plugin> newPlugins = tuple.getT2(); + final List<Plugin> updatablePlugins = new ArrayList<>(); + final List<Plugin> insertablePlugins = new ArrayList<>(); + newPlugins.forEach((k, v) -> { + if (availablePlugins.containsKey(k)) { + v.setId(availablePlugins.get(k).getId()); + updatablePlugins.add(v); + } else { + v.setId(null); + insertablePlugins.add(v); + } + }); - // Save new data for this plugin, - // then make sure to install to workspaces in case the default installation flag changed - final Mono<List<Workspace>> updatedPluginsWorkspaceFlux = pluginService - .saveAll(updatablePlugins) - .filter(Plugin::getDefaultInstall) - .collectList() - .flatMapMany(pluginService::installDefaultPlugins) - .collectList(); + // Save new data for this plugin, + // then make sure to install to workspaces in case the default installation flag changed + final Mono<List<Workspace>> updatedPluginsWorkspaceFlux = pluginService + .saveAll(updatablePlugins) + .filter(Plugin::getDefaultInstall) + .collectList() + .flatMapMany(pluginService::installDefaultPlugins) + .collectList(); - // Create plugin, - // then install to all workspaces if default installation is turned on - final Mono<List<Workspace>> workspaceFlux = - Flux.fromIterable(insertablePlugins) - .flatMap(pluginService::create) - .filter(Plugin::getDefaultInstall) - .collectList() - .flatMapMany(pluginService::installDefaultPlugins) - .collectList(); + // Create plugin, + // then install to all workspaces if default installation is turned on + final Mono<List<Workspace>> workspaceFlux = Flux.fromIterable(insertablePlugins) + .flatMap(pluginService::create) + .filter(Plugin::getDefaultInstall) + .collectList() + .flatMapMany(pluginService::installDefaultPlugins) + .collectList(); - return updatedPluginsWorkspaceFlux - .zipWith(workspaceFlux) - .then(); - }); + return updatedPluginsWorkspaceFlux.zipWith(workspaceFlux).then(); + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PolicyUtil.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PolicyUtil.java index a56bf2719f16..9b3973f39355 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PolicyUtil.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PolicyUtil.java @@ -10,7 +10,8 @@ public class PolicyUtil { - public static boolean isPermissionPresentInPolicies(String permission, Set<Policy> policies, Set<String> userPermissionGroupIds) { + public static boolean isPermissionPresentInPolicies( + String permission, Set<Policy> policies, Set<String> userPermissionGroupIds) { Optional<Policy> interestingPolicyOptional = policies.stream() .filter(policy -> policy.getPermission().equals(permission)) diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ReleaseNotesUtilsCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ReleaseNotesUtilsCE.java index 9d7a5dddad21..8edfc7a958cc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ReleaseNotesUtilsCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ReleaseNotesUtilsCE.java @@ -9,5 +9,4 @@ public interface ReleaseNotesUtilsCE { Mono<List<ReleaseNode>> getReleaseNodes(List<ReleaseNode> releaseNodesCache, Instant cacheExpiryTime); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ReleaseNotesUtilsCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ReleaseNotesUtilsCEImpl.java index f522cd562e0e..49ad1582226e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ReleaseNotesUtilsCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ReleaseNotesUtilsCEImpl.java @@ -44,22 +44,23 @@ public Mono<List<ReleaseNode>> getReleaseNodes(List<ReleaseNode> releaseNodesCac return Mono.justOrEmpty(releaseNodesCache); } - return configService.getInstanceId() - .flatMap(instanceId -> WebClientUtils - .create( - baseUrl + "/api/v1/releases?instanceId=" + instanceId + - // isCloudHosted should be true only for our cloud instance, - // For docker images that burn the segment key with the image, the CE key will be present - "&isSourceInstall=" + (commonConfig.isCloudHosting() || StringUtils.isEmpty(segmentConfig.getCeKey())) + - (StringUtils.isEmpty(commonConfig.getRepo()) ? "" : ("&repo=" + commonConfig.getRepo())) + - "&version=" + projectProperties.getVersion() + - "&edition=" + ProjectProperties.EDITION - ) + return configService + .getInstanceId() + .flatMap(instanceId -> WebClientUtils.create(baseUrl + "/api/v1/releases?instanceId=" + instanceId + + // isCloudHosted should be true only for our cloud instance, + // For docker images that burn the segment key with the image, the CE key will be + // present + "&isSourceInstall=" + + (commonConfig.isCloudHosting() || StringUtils.isEmpty(segmentConfig.getCeKey())) + + (StringUtils.isEmpty(commonConfig.getRepo()) + ? "" + : ("&repo=" + commonConfig.getRepo())) + + "&version=" + + projectProperties.getVersion() + "&edition=" + + ProjectProperties.EDITION) .get() - .exchange() - ) - .flatMap(response -> response.bodyToMono(new ParameterizedTypeReference<ResponseDTO<Releases>>() { - })) + .exchange()) + .flatMap(response -> response.bodyToMono(new ParameterizedTypeReference<ResponseDTO<Releases>>() {})) .map(result -> result.getData().getNodes()) .map(nodes -> { releaseNodesCache.clear(); @@ -68,5 +69,4 @@ public Mono<List<ReleaseNode>> getReleaseNodes(List<ReleaseNode> releaseNodesCac }) .doOnError(error -> log.error("Error fetching release notes from cloud services", error)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/UserUtilsCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/UserUtilsCE.java index e9253ac7cadf..b080c7784c78 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/UserUtilsCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/UserUtilsCE.java @@ -42,10 +42,11 @@ public class UserUtilsCE { private final CacheableRepositoryHelper cacheableRepositoryHelper; private final PermissionGroupPermission permissionGroupPermission; - public UserUtilsCE(ConfigRepository configRepository, - PermissionGroupRepository permissionGroupRepository, - CacheableRepositoryHelper cacheableRepositoryHelper, - PermissionGroupPermission permissionGroupPermission) { + public UserUtilsCE( + ConfigRepository configRepository, + PermissionGroupRepository permissionGroupRepository, + CacheableRepositoryHelper cacheableRepositoryHelper, + PermissionGroupPermission permissionGroupPermission) { this.configRepository = configRepository; this.permissionGroupRepository = permissionGroupRepository; this.cacheableRepositoryHelper = cacheableRepositoryHelper; @@ -53,13 +54,15 @@ public UserUtilsCE(ConfigRepository configRepository, } public Mono<Boolean> isSuperUser(User user) { - return configRepository.findByNameAsUser(INSTANCE_CONFIG, user, AclPermission.MANAGE_INSTANCE_CONFIGURATION) + return configRepository + .findByNameAsUser(INSTANCE_CONFIG, user, AclPermission.MANAGE_INSTANCE_CONFIGURATION) .map(config -> Boolean.TRUE) .switchIfEmpty(Mono.just(Boolean.FALSE)); } public Mono<Boolean> isCurrentUserSuperUser() { - return configRepository.findByName(INSTANCE_CONFIG, AclPermission.MANAGE_INSTANCE_CONFIGURATION) + return configRepository + .findByName(INSTANCE_CONFIG, AclPermission.MANAGE_INSTANCE_CONFIGURATION) .map(config -> Boolean.TRUE) .switchIfEmpty(Mono.just(Boolean.FALSE)); } @@ -67,7 +70,6 @@ public Mono<Boolean> isCurrentUserSuperUser() { public Mono<Boolean> makeSuperUser(List<User> users) { return getSuperAdminPermissionGroup() .flatMap(permissionGroup -> { - Set<String> assignedToUserIds = new HashSet<>(); if (permissionGroup.getAssignedToUserIds() != null) { @@ -83,7 +85,8 @@ public Mono<Boolean> makeSuperUser(List<User> users) { }) .then(Mono.just(users)) .flatMapMany(Flux::fromIterable) - .flatMap(user -> permissionGroupRepository.evictAllPermissionGroupCachesForUser(user.getEmail(), user.getTenantId())) + .flatMap(user -> permissionGroupRepository.evictAllPermissionGroupCachesForUser( + user.getEmail(), user.getTenantId())) .then(Mono.just(Boolean.TRUE)); } @@ -93,22 +96,26 @@ public Mono<Boolean> removeSuperUser(List<User> users) { if (permissionGroup.getAssignedToUserIds() == null) { permissionGroup.setAssignedToUserIds(new HashSet<>()); } - permissionGroup.getAssignedToUserIds().removeAll(users.stream().map(User::getId).collect(Collectors.toList())); - return permissionGroupRepository.updateById(permissionGroup.getId(), permissionGroup, permissionGroupPermission.getAssignPermission()); + permissionGroup + .getAssignedToUserIds() + .removeAll(users.stream().map(User::getId).collect(Collectors.toList())); + return permissionGroupRepository.updateById( + permissionGroup.getId(), permissionGroup, permissionGroupPermission.getAssignPermission()); }) .then(Mono.just(users)) .flatMapMany(Flux::fromIterable) - .flatMap(user -> permissionGroupRepository.evictAllPermissionGroupCachesForUser(user.getEmail(), user.getTenantId())) + .flatMap(user -> permissionGroupRepository.evictAllPermissionGroupCachesForUser( + user.getEmail(), user.getTenantId())) .then(Mono.just(Boolean.TRUE)); } protected Mono<Config> createInstanceConfigForSuperUser() { - Mono<Tuple2<PermissionGroup, Config>> savedConfigAndPermissionGroupMono = createConfigAndPermissionGroupForSuperAdmin(); + Mono<Tuple2<PermissionGroup, Config>> savedConfigAndPermissionGroupMono = + createConfigAndPermissionGroupForSuperAdmin(); // return the saved instance config - return savedConfigAndPermissionGroupMono - .map(Tuple2::getT2); + return savedConfigAndPermissionGroupMono.map(Tuple2::getT2); } protected Mono<Tuple2<PermissionGroup, Config>> createConfigAndPermissionGroupForSuperAdmin() { @@ -119,24 +126,25 @@ protected Mono<Tuple2<PermissionGroup, Config>> createConfigAndPermissionGroupFo // Update the instance config with the permission group id savedInstanceConfig.setConfig( - new JSONObject(Map.of(DEFAULT_PERMISSION_GROUP, savedPermissionGroup.getId())) - ); + new JSONObject(Map.of(DEFAULT_PERMISSION_GROUP, savedPermissionGroup.getId()))); - Policy editConfigPolicy = Policy.builder().permission(MANAGE_INSTANCE_CONFIGURATION.getValue()) + Policy editConfigPolicy = Policy.builder() + .permission(MANAGE_INSTANCE_CONFIGURATION.getValue()) .permissionGroups(Set.of(savedPermissionGroup.getId())) .build(); - Policy readConfigPolicy = Policy.builder().permission(READ_INSTANCE_CONFIGURATION.getValue()) + Policy readConfigPolicy = Policy.builder() + .permission(READ_INSTANCE_CONFIGURATION.getValue()) .permissionGroups(Set.of(savedPermissionGroup.getId())) .build(); savedInstanceConfig.setPolicies(Set.of(editConfigPolicy, readConfigPolicy)); // Add config permissions to permission group - Set<Permission> configPermissions = Set.of( - new Permission(savedInstanceConfig.getId(), MANAGE_INSTANCE_CONFIGURATION) - ); + Set<Permission> configPermissions = + Set.of(new Permission(savedInstanceConfig.getId(), MANAGE_INSTANCE_CONFIGURATION)); - return Mono.zip(addPermissionsToPermissionGroup(savedPermissionGroup, configPermissions), + return Mono.zip( + addPermissionsToPermissionGroup(savedPermissionGroup, configPermissions), configRepository.save(savedInstanceConfig)); }); } @@ -152,34 +160,37 @@ private Mono<PermissionGroup> createInstanceAdminPermissionGroupWithoutPermissio PermissionGroup instanceAdminPermissionGroup = new PermissionGroup(); instanceAdminPermissionGroup.setName(FieldName.INSTANCE_ADMIN_ROLE); - return permissionGroupRepository.save(instanceAdminPermissionGroup) - .flatMap(savedPermissionGroup -> { - Set<Permission> permissions = Set.of( - new Permission(savedPermissionGroup.getId(), READ_PERMISSION_GROUP_MEMBERS), - new Permission(savedPermissionGroup.getId(), ASSIGN_PERMISSION_GROUPS), - new Permission(savedPermissionGroup.getId(), UNASSIGN_PERMISSION_GROUPS) - ); - savedPermissionGroup.setPermissions(permissions); - - Policy readPermissionGroupPolicy = Policy.builder().permission(READ_PERMISSION_GROUP_MEMBERS.getValue()) - .permissionGroups(Set.of(savedPermissionGroup.getId())) - .build(); - - Policy assignPermissionGroupPolicy = Policy.builder().permission(ASSIGN_PERMISSION_GROUPS.getValue()) - .permissionGroups(Set.of(savedPermissionGroup.getId())) - .build(); - - Policy unassignPermissionGroupPolicy = Policy.builder().permission(UNASSIGN_PERMISSION_GROUPS.getValue()) - .permissionGroups(Set.of(savedPermissionGroup.getId())) - .build(); - - savedPermissionGroup.setPolicies(Set.of(readPermissionGroupPolicy, assignPermissionGroupPolicy, unassignPermissionGroupPolicy)); - - return permissionGroupRepository.save(savedPermissionGroup); - }); + return permissionGroupRepository.save(instanceAdminPermissionGroup).flatMap(savedPermissionGroup -> { + Set<Permission> permissions = Set.of( + new Permission(savedPermissionGroup.getId(), READ_PERMISSION_GROUP_MEMBERS), + new Permission(savedPermissionGroup.getId(), ASSIGN_PERMISSION_GROUPS), + new Permission(savedPermissionGroup.getId(), UNASSIGN_PERMISSION_GROUPS)); + savedPermissionGroup.setPermissions(permissions); + + Policy readPermissionGroupPolicy = Policy.builder() + .permission(READ_PERMISSION_GROUP_MEMBERS.getValue()) + .permissionGroups(Set.of(savedPermissionGroup.getId())) + .build(); + + Policy assignPermissionGroupPolicy = Policy.builder() + .permission(ASSIGN_PERMISSION_GROUPS.getValue()) + .permissionGroups(Set.of(savedPermissionGroup.getId())) + .build(); + + Policy unassignPermissionGroupPolicy = Policy.builder() + .permission(UNASSIGN_PERMISSION_GROUPS.getValue()) + .permissionGroups(Set.of(savedPermissionGroup.getId())) + .build(); + + savedPermissionGroup.setPolicies( + Set.of(readPermissionGroupPolicy, assignPermissionGroupPolicy, unassignPermissionGroupPolicy)); + + return permissionGroupRepository.save(savedPermissionGroup); + }); } - protected Mono<PermissionGroup> addPermissionsToPermissionGroup(PermissionGroup permissionGroup, Set<Permission> permissions) { + protected Mono<PermissionGroup> addPermissionsToPermissionGroup( + PermissionGroup permissionGroup, Set<Permission> permissions) { Set<Permission> existingPermissions = new HashSet<>(permissionGroup.getPermissions()); existingPermissions.addAll(permissions); permissionGroup.setPermissions(existingPermissions); @@ -187,7 +198,8 @@ protected Mono<PermissionGroup> addPermissionsToPermissionGroup(PermissionGroup } public Mono<PermissionGroup> getSuperAdminPermissionGroup() { - return configRepository.findByName(INSTANCE_CONFIG) + return configRepository + .findByName(INSTANCE_CONFIG) .switchIfEmpty(Mono.defer(() -> createInstanceConfigForSuperUser())) .flatMap(instanceConfig -> { JSONObject config = instanceConfig.getConfig(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog0.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog0.java index 3eeca8e5e2e6..5543aeab4a27 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog0.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog0.java @@ -30,23 +30,18 @@ public class DatabaseChangelog0 { public void initializeSchemaVersion(MongoTemplate mongoTemplate) { Config instanceIdConfig = mongoTemplate.findOne( - query(where(fieldName(QConfig.config1.name)).is("instance-id")), - Config.class); + query(where(fieldName(QConfig.config1.name)).is("instance-id")), Config.class); if (instanceIdConfig != null) { // If instance id exists, this is an existing instance // Instantiate with the first version so that we expect to go through all the migrations - mongoTemplate.insert(new Config( - new JSONObject(Map.of("value", 1)), - Appsmith.INSTANCE_SCHEMA_VERSION - )); + mongoTemplate.insert(new Config(new JSONObject(Map.of("value", 1)), Appsmith.INSTANCE_SCHEMA_VERSION)); } else { // Is no instance id exists, this is a new instance // Instantiate with latest schema version that this Appsmith release shipped with mongoTemplate.insert(new Config( new JSONObject(Map.of("value", CommonConfig.LATEST_INSTANCE_SCHEMA_VERSION)), - Appsmith.INSTANCE_SCHEMA_VERSION - )); + Appsmith.INSTANCE_SCHEMA_VERSION)); } } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog1.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog1.java index 1be1fc03b8ca..e9751ef39da4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog1.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog1.java @@ -58,7 +58,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.github.cloudyrock.mongock.ChangeLog; import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.MongoCommandException; import com.mongodb.MongoException; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; @@ -182,19 +181,22 @@ public static Index makeIndex(String... fields) { * those indexes on the database behind the mongoTemplate instance. */ public static void ensureIndexes(MongoTemplate mongoTemplate, Class<?> entityClass, Index... indexes) { - final int dbNameLength = mongoTemplate.getMongoDatabaseFactory().getMongoDatabase().getName().length(); + final int dbNameLength = mongoTemplate + .getMongoDatabaseFactory() + .getMongoDatabase() + .getName() + .length(); for (Index index : indexes) { final String indexName = (String) index.getIndexOptions().get("name"); if (indexName == null) { throw new RuntimeException("Index name cannot be null"); } - // Index name length limitations on DocumentDB, at https://docs.aws.amazon.com/documentdb/latest/developerguide/limits.html. + // Index name length limitations on DocumentDB, at + // https://docs.aws.amazon.com/documentdb/latest/developerguide/limits.html. final int indexNameLength = indexName.length(); final int collectionNameLength = entityClass.getSimpleName().length(); - if ( - dbNameLength + indexNameLength + collectionNameLength + 3 > 127 - || indexNameLength + collectionNameLength + 1 > 63 - ) { + if (dbNameLength + indexNameLength + collectionNameLength + 3 > 127 + || indexNameLength + collectionNameLength + 1 > 63) { throw new RuntimeException("Index name is too long. Please give a shorter name."); } } @@ -238,7 +240,8 @@ public static void installPluginToAllWorkspaces(MongoTemplate mongoTemplate, Str Query queryToFetchWorkspacesWOPlugin = new Query(); /* Filter in only those workspaces that don't have the plugin installed */ - queryToFetchWorkspacesWOPlugin.addCriteria(Criteria.where("plugins.pluginId").ne(pluginId)); + queryToFetchWorkspacesWOPlugin.addCriteria( + Criteria.where("plugins.pluginId").ne(pluginId)); /* Add plugin to the workspace */ Update update = new Update(); @@ -318,77 +321,78 @@ public void removeOrgNameIndex(MongoTemplate mongoTemplate) { public void addInitialIndexes(MongoTemplate mongoTemplate) { Index createdAtIndex = makeIndex("createdAt"); - ensureIndexes(mongoTemplate, Action.class, + ensureIndexes( + mongoTemplate, + Action.class, createdAtIndex, - makeIndex("pageId", "name").unique().named("action_page_compound_index") - ); + makeIndex("pageId", "name").unique().named("action_page_compound_index")); - ensureIndexes(mongoTemplate, Application.class, + ensureIndexes( + mongoTemplate, + Application.class, createdAtIndex, - makeIndex("organizationId", "name").unique().named("organization_application_compound_index") - ); + makeIndex("organizationId", "name").unique().named("organization_application_compound_index")); - ensureIndexes(mongoTemplate, Collection.class, - createdAtIndex - ); + ensureIndexes(mongoTemplate, Collection.class, createdAtIndex); - ensureIndexes(mongoTemplate, Config.class, - createdAtIndex, - makeIndex("name").unique() - ); + ensureIndexes( + mongoTemplate, Config.class, createdAtIndex, makeIndex("name").unique()); - ensureIndexes(mongoTemplate, Datasource.class, + ensureIndexes( + mongoTemplate, + Datasource.class, createdAtIndex, - makeIndex("organizationId", "name").unique().named("organization_datasource_compound_index") - ); + makeIndex("organizationId", "name").unique().named("organization_datasource_compound_index")); - ensureIndexes(mongoTemplate, InviteUser.class, + ensureIndexes( + mongoTemplate, + InviteUser.class, createdAtIndex, makeIndex("token").unique().expire(3600, TimeUnit.SECONDS), - makeIndex("email").unique() - ); + makeIndex("email").unique()); - ensureIndexes(mongoTemplate, Page.class, + ensureIndexes( + mongoTemplate, + Page.class, createdAtIndex, - makeIndex("applicationId", "name").unique().named("application_page_compound_index") - ); + makeIndex("applicationId", "name").unique().named("application_page_compound_index")); - ensureIndexes(mongoTemplate, PasswordResetToken.class, + ensureIndexes( + mongoTemplate, + PasswordResetToken.class, createdAtIndex, - makeIndex("email").unique().expire(3600, TimeUnit.SECONDS) - ); + makeIndex("email").unique().expire(3600, TimeUnit.SECONDS)); /* Removing the code for ensuring index for a class which has never been used and now being removed. */ -// ensureIndexes(mongoTemplate, Permission.class, -// createdAtIndex -// ); + // ensureIndexes(mongoTemplate, Permission.class, + // createdAtIndex + // ); - ensureIndexes(mongoTemplate, Plugin.class, + ensureIndexes( + mongoTemplate, + Plugin.class, createdAtIndex, makeIndex("type"), - makeIndex("packageName").unique() - ); + makeIndex("packageName").unique()); - ensureIndexes(mongoTemplate, Role.class, - createdAtIndex - ); + ensureIndexes(mongoTemplate, Role.class, createdAtIndex); - ensureIndexes(mongoTemplate, User.class, - createdAtIndex, - makeIndex("email").unique() - ); + ensureIndexes( + mongoTemplate, User.class, createdAtIndex, makeIndex("email").unique()); } @ChangeSet(order = "005", id = "application-deleted-at", author = "") public void addApplicationDeletedAtFieldAndIndex(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, Application.class, "organization_application_compound_index"); - ensureIndexes(mongoTemplate, Application.class, + ensureIndexes( + mongoTemplate, + Application.class, makeIndex("organizationId", "name", "deletedAt") - .unique().named("organization_application_deleted_compound_index") - ); + .unique() + .named("organization_application_deleted_compound_index")); for (Application application : mongoTemplate.findAll(Application.class)) { if (application.isDeleted()) { @@ -400,10 +404,8 @@ public void addApplicationDeletedAtFieldAndIndex(MongoTemplate mongoTemplate) { @ChangeSet(order = "006", id = "hide-rapidapi-plugin", author = "") public void hideRapidApiPluginFromCreateDatasource(MongoTemplate mongoTemplate) { - final Plugin rapidApiPlugin = mongoTemplate.findOne( - query(where("packageName").is("rapidapi-plugin")), - Plugin.class - ); + final Plugin rapidApiPlugin = + mongoTemplate.findOne(query(where("packageName").is("rapidapi-plugin")), Plugin.class); if (rapidApiPlugin == null) { log.error("Couldn't find rapidapi-plugin, to set it's `allowUserDatasources` to false."); @@ -411,7 +413,6 @@ public void hideRapidApiPluginFromCreateDatasource(MongoTemplate mongoTemplate) } else { rapidApiPlugin.setAllowUserDatasources(false); mongoTemplate.save(rapidApiPlugin); - } } @@ -419,10 +420,12 @@ public void hideRapidApiPluginFromCreateDatasource(MongoTemplate mongoTemplate) public void addDatasourceDeletedAtFieldAndIndex(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, Datasource.class, "organization_datasource_compound_index"); - ensureIndexes(mongoTemplate, Datasource.class, + ensureIndexes( + mongoTemplate, + Datasource.class, makeIndex(FieldName.ORGANIZATION_ID, FieldName.NAME, FieldName.DELETED_AT) - .unique().named("organization_datasource_deleted_compound_index") - ); + .unique() + .named("organization_datasource_deleted_compound_index")); for (Datasource datasource : mongoTemplate.findAll(Datasource.class)) { if (datasource.isDeleted()) { @@ -436,10 +439,12 @@ public void addDatasourceDeletedAtFieldAndIndex(MongoTemplate mongoTemplate) { public void addPageDeletedAtFieldAndIndex(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, Page.class, "application_page_compound_index"); - ensureIndexes(mongoTemplate, Page.class, + ensureIndexes( + mongoTemplate, + Page.class, makeIndex(FieldName.APPLICATION_ID, FieldName.NAME, FieldName.DELETED_AT) - .unique().named("application_page_deleted_compound_index") - ); + .unique() + .named("application_page_deleted_compound_index")); for (Page page : mongoTemplate.findAll(Page.class)) { if (page.isDeleted()) { @@ -478,10 +483,8 @@ public void addDeleteDatasourcePermToExistingGroups(MongoTemplate mongoTemplate) @ChangeSet(order = "011", id = "install-default-plugins-to-all-organizations", author = "") public void installDefaultPluginsToAllOrganizations(MongoTemplate mongoTemplate) { - final List<Plugin> defaultPlugins = mongoTemplate.find( - query(where("defaultInstall").is(true)), - Plugin.class - ); + final List<Plugin> defaultPlugins = + mongoTemplate.find(query(where("defaultInstall").is(true)), Plugin.class); mongoTemplate.findAll(Plugin.class); @@ -490,12 +493,14 @@ public void installDefaultPluginsToAllOrganizations(MongoTemplate mongoTemplate) organization.setPlugins(new HashSet<>()); } - final Set<String> installedPlugins = organization.getPlugins() - .stream().map(WorkspacePlugin::getPluginId).collect(Collectors.toSet()); + final Set<String> installedPlugins = organization.getPlugins().stream() + .map(WorkspacePlugin::getPluginId) + .collect(Collectors.toSet()); for (Plugin defaultPlugin : defaultPlugins) { if (!installedPlugins.contains(defaultPlugin.getId())) { - organization.getPlugins() + organization + .getPlugins() .add(new WorkspacePlugin(defaultPlugin.getId(), WorkspacePluginStatus.FREE)); } } @@ -506,20 +511,16 @@ public void installDefaultPluginsToAllOrganizations(MongoTemplate mongoTemplate) @ChangeSet(order = "012", id = "ensure-datasource-created-and-updated-at-fields", author = "") public void ensureDatasourceCreatedAndUpdatedAt(MongoTemplate mongoTemplate) { - final List<Datasource> missingCreatedAt = mongoTemplate.find( - query(where("createdAt").exists(false)), - Datasource.class - ); + final List<Datasource> missingCreatedAt = + mongoTemplate.find(query(where("createdAt").exists(false)), Datasource.class); for (Datasource datasource : missingCreatedAt) { datasource.setCreatedAt(Instant.now()); mongoTemplate.save(datasource); } - final List<Datasource> missingUpdatedAt = mongoTemplate.find( - query(where("updatedAt").exists(false)), - Datasource.class - ); + final List<Datasource> missingUpdatedAt = + mongoTemplate.find(query(where("updatedAt").exists(false)), Datasource.class); for (Datasource datasource : missingUpdatedAt) { datasource.setUpdatedAt(Instant.now()); @@ -529,17 +530,15 @@ public void ensureDatasourceCreatedAndUpdatedAt(MongoTemplate mongoTemplate) { @ChangeSet(order = "013", id = "add-index-for-sequence-name", author = "") public void addIndexForSequenceName(MongoTemplate mongoTemplate) { - ensureIndexes(mongoTemplate, Sequence.class, - makeIndex(FieldName.NAME).unique() - ); + ensureIndexes(mongoTemplate, Sequence.class, makeIndex(FieldName.NAME).unique()); } @ChangeSet(order = "014", id = "set-initial-sequence-for-datasource", author = "") public void setInitialSequenceForDatasource(MongoTemplate mongoTemplate) { - final Long maxUntitledDatasourceNumber = mongoTemplate.find( + final Long maxUntitledDatasourceNumber = mongoTemplate + .find( query(where(FieldName.NAME).regex("^" + Datasource.DEFAULT_NAME_PREFIX + " \\d+$")), - Datasource.class - ) + Datasource.class) .stream() .map(datasource -> Long.parseLong(datasource.getName().split(" ")[2])) .max(Long::compareTo) @@ -548,8 +547,7 @@ public void setInitialSequenceForDatasource(MongoTemplate mongoTemplate) { mongoTemplate.upsert( query(where(FieldName.NAME).is(mongoTemplate.getCollectionName(Datasource.class))), update("nextNumber", maxUntitledDatasourceNumber + 1), - Sequence.class - ); + Sequence.class); } @ChangeSet(order = "015", id = "set-plugin-image-and-docs-link", author = "") @@ -570,7 +568,6 @@ public void setPluginImageAndDocsLink(MongoTemplate mongoTemplate) { } else { continue; - } mongoTemplate.save(plugin); @@ -579,10 +576,8 @@ public void setPluginImageAndDocsLink(MongoTemplate mongoTemplate) { @ChangeSet(order = "016", id = "fix-double-escapes", author = "") public void fixDoubleEscapes(MongoTemplate mongoTemplate) { - final List<Action> actions = mongoTemplate.find( - query(where("jsonPathKeys").exists(true)), - Action.class - ); + final List<Action> actions = + mongoTemplate.find(query(where("jsonPathKeys").exists(true)), Action.class); for (final Action action : actions) { final Set<String> keys = action.getJsonPathKeys(); @@ -593,10 +588,8 @@ public void fixDoubleEscapes(MongoTemplate mongoTemplate) { final Set<String> fixedKeys = new HashSet<>(); boolean hasFixes = false; for (final String key : keys) { - final String fixed = key - .replaceAll("\\\\n", "\n") - .replaceAll("\\\\r", "\r") - .replaceAll("\\\\t", "\t"); + final String fixed = + key.replaceAll("\\\\n", "\n").replaceAll("\\\\r", "\r").replaceAll("\\\\t", "\t"); fixedKeys.add(fixed); if (!hasFixes && !fixed.equals(key)) { hasFixes = true; @@ -613,12 +606,11 @@ public void fixDoubleEscapes(MongoTemplate mongoTemplate) { @ChangeSet(order = "017", id = "encrypt-password", author = "") public void encryptPassword(MongoTemplate mongoTemplate, EncryptionService encryptionService) { final List<Datasource> datasources = mongoTemplate.find( - query(where("datasourceConfiguration.authentication.password").exists(true)), - Datasource.class - ); + query(where("datasourceConfiguration.authentication.password").exists(true)), Datasource.class); for (final Datasource datasource : datasources) { - DBAuth authentication = (DBAuth) datasource.getDatasourceConfiguration().getAuthentication(); + DBAuth authentication = + (DBAuth) datasource.getDatasourceConfiguration().getAuthentication(); authentication.setPassword(encryptionService.encryptString(authentication.getPassword())); mongoTemplate.save(datasource); } @@ -647,16 +639,13 @@ public void mysqlPlugin(MongoTemplate mongoTemplate) { public void updateDatabaseDocumentationLinks(MongoTemplate mongoTemplate) { for (Plugin plugin : mongoTemplate.findAll(Plugin.class)) { if ("postgres-plugin".equals(plugin.getPackageName())) { - plugin.setDocumentationLink( - ""); + plugin.setDocumentationLink(""); } else if ("mongo-plugin".equals(plugin.getPackageName())) { - plugin.setDocumentationLink( - "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-mongodb"); + plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-mongodb"); } else { continue; - } mongoTemplate.save(plugin); @@ -665,26 +654,29 @@ public void updateDatabaseDocumentationLinks(MongoTemplate mongoTemplate) { @ChangeSet(order = "020", id = "execute-action-for-read-action", author = "") public void giveExecutePermissionToReadActionUsers(MongoTemplate mongoTemplate) { - final List<Action> actions = mongoTemplate.find( - query(where("policies").exists(true)), - Action.class - ); + final List<Action> actions = mongoTemplate.find(query(where("policies").exists(true)), Action.class); for (final Action action : actions) { Set<Policy> policies = action.getPolicies(); if (policies.size() > 0) { - Optional<Policy> readActionsOptional = policies.stream().filter(policy -> policy.getPermission().equals(READ_ACTIONS.getValue())).findFirst(); + Optional<Policy> readActionsOptional = policies.stream() + .filter(policy -> policy.getPermission().equals(READ_ACTIONS.getValue())) + .findFirst(); if (readActionsOptional.isPresent()) { Policy readActionPolicy = readActionsOptional.get(); - Optional<Policy> executeActionsOptional = policies.stream().filter(policy -> policy.getPermission().equals(EXECUTE_ACTIONS.getValue())).findFirst(); + Optional<Policy> executeActionsOptional = policies.stream() + .filter(policy -> policy.getPermission().equals(EXECUTE_ACTIONS.getValue())) + .findFirst(); if (executeActionsOptional.isPresent()) { Policy executeActionPolicy = executeActionsOptional.get(); executeActionPolicy.getUsers().addAll(readActionPolicy.getUsers()); } else { // this policy doesnt exist. create and add this to the policy set - Policy newExecuteActionPolicy = Policy.builder().permission(EXECUTE_ACTIONS.getValue()) - .users(readActionPolicy.getUsers()).build(); + Policy newExecuteActionPolicy = Policy.builder() + .permission(EXECUTE_ACTIONS.getValue()) + .users(readActionPolicy.getUsers()) + .build(); action.getPolicies().add(newExecuteActionPolicy); } mongoTemplate.save(action); @@ -695,20 +687,16 @@ public void giveExecutePermissionToReadActionUsers(MongoTemplate mongoTemplate) @ChangeSet(order = "021", id = "invite-and-public-permissions", author = "") public void giveInvitePermissionToOrganizationsAndPublicPermissionsToApplications(MongoTemplate mongoTemplate) { - final List<Organization> organizations = mongoTemplate.find( - query(where("userRoles").exists(true)), - Organization.class - ); + final List<Organization> organizations = + mongoTemplate.find(query(where("userRoles").exists(true)), Organization.class); for (final Organization organization : organizations) { - Set<String> adminUsernames = organization.getUserRoles() - .stream() + Set<String> adminUsernames = organization.getUserRoles().stream() .filter(role -> (role.getRole().equals(AppsmithRole.ORGANIZATION_ADMIN))) .map(role -> role.getUsername()) .collect(Collectors.toSet()); - Set<String> developerUsernames = organization.getUserRoles() - .stream() + Set<String> developerUsernames = organization.getUserRoles().stream() .filter(role -> (role.getRole().equals(AppsmithRole.ORGANIZATION_DEVELOPER))) .map(role -> role.getUsername()) .collect(Collectors.toSet()); @@ -723,14 +711,18 @@ public void giveInvitePermissionToOrganizationsAndPublicPermissionsToApplication policies = new HashSet<>(); } - Optional<Policy> inviteUsersOptional = policies.stream().filter(policy -> policy.getPermission().equals(WORKSPACE_INVITE_USERS.getValue())).findFirst(); + Optional<Policy> inviteUsersOptional = policies.stream() + .filter(policy -> policy.getPermission().equals(WORKSPACE_INVITE_USERS.getValue())) + .findFirst(); if (inviteUsersOptional.isPresent()) { Policy inviteUserPolicy = inviteUsersOptional.get(); inviteUserPolicy.getUsers().addAll(invitePermissionUsernames); } else { // this policy doesnt exist. create and add this to the policy set - Policy inviteUserPolicy = Policy.builder().permission(WORKSPACE_INVITE_USERS.getValue()) - .users(invitePermissionUsernames).build(); + Policy inviteUserPolicy = Policy.builder() + .permission(WORKSPACE_INVITE_USERS.getValue()) + .users(invitePermissionUsernames) + .build(); organization.getPolicies().add(inviteUserPolicy); } @@ -738,9 +730,9 @@ public void giveInvitePermissionToOrganizationsAndPublicPermissionsToApplication // Update the applications with public view policy for all administrators of the organization List<Application> orgApplications = mongoTemplate.find( - query(where(fieldName(QApplication.application.organizationId)).is(organization.getId())), - Application.class - ); + query(where(fieldName(QApplication.application.organizationId)) + .is(organization.getId())), + Application.class); for (final Application application : orgApplications) { Set<Policy> applicationPolicies = application.getPolicies(); @@ -748,14 +740,18 @@ public void giveInvitePermissionToOrganizationsAndPublicPermissionsToApplication applicationPolicies = new HashSet<>(); } - Optional<Policy> makePublicAppOptional = applicationPolicies.stream().filter(policy -> policy.getPermission().equals(MAKE_PUBLIC_APPLICATIONS.getValue())).findFirst(); + Optional<Policy> makePublicAppOptional = applicationPolicies.stream() + .filter(policy -> policy.getPermission().equals(MAKE_PUBLIC_APPLICATIONS.getValue())) + .findFirst(); if (makePublicAppOptional.isPresent()) { Policy makePublicPolicy = makePublicAppOptional.get(); makePublicPolicy.getUsers().addAll(adminUsernames); } else { // this policy doesnt exist. create and add this to the policy set - Policy newPublicAppPolicy = Policy.builder().permission(MAKE_PUBLIC_APPLICATIONS.getValue()) - .users(adminUsernames).build(); + Policy newPublicAppPolicy = Policy.builder() + .permission(MAKE_PUBLIC_APPLICATIONS.getValue()) + .users(adminUsernames) + .build(); application.getPolicies().add(newPublicAppPolicy); } @@ -766,262 +762,277 @@ public void giveInvitePermissionToOrganizationsAndPublicPermissionsToApplication // Examples organization is no longer getting used. Commenting out the migrations which add/update the same. // @SuppressWarnings({"unchecked", "rawtypes"}) -// @ChangeSet(order = "022", id = "examples-organization", author = "") -// public void examplesOrganization(MongoTemplate mongoTemplate, EncryptionService encryptionService) throws IOException { -// -// final Map<String, String> plugins = new HashMap<>(); -// -// final List<Map<String, Object>> organizationPlugins = mongoTemplate -// .find(query(where("defaultInstall").is(true)), Plugin.class) -// .stream() -// .map(plugin -> { -// assert plugin.getId() != null; -// plugins.put(plugin.getPackageName(), plugin.getId()); -// return Map.of( -// "pluginId", plugin.getId(), -// "status", "FREE", -// FieldName.DELETED, false, -// "policies", Collections.emptyList() -// ); -// }) -// .collect(Collectors.toList()); -// final String jsonContent = StreamUtils.copyToString( -// new DefaultResourceLoader().getResource("examples-organization.json").getInputStream(), -// Charset.defaultCharset() -// ); -// -// final Map<String, Object> organization = new Gson().fromJson(jsonContent, HashMap.class); -// -// final List<Map<String, Object>> datasources = (List) organization.remove("$datasources"); -// final List<Map<String, Object>> applications = (List) organization.remove("$applications"); -// -// organization.put("plugins", organizationPlugins); -// organization.put(FieldName.CREATED_AT, Instant.now()); -// final Map<String, Object> insertedOrganization = mongoTemplate.insert(organization, mongoTemplate.getCollectionName(Organization.class)); -// final String organizationId = ((ObjectId) insertedOrganization.get("_id")).toHexString(); -// -// final Map<String, String> datasourceIdsByName = new HashMap<>(); -// -// for (final Map<String, Object> datasource : datasources) { -// datasource.put("pluginId", plugins.get(datasource.remove("$pluginPackageName"))); -// final Map authentication = (Map) ((Map) datasource.get("datasourceConfiguration")).get("authentication"); -// if (authentication != null) { -// final String plainPassword = (String) authentication.get("password"); -// authentication.put("password", encryptionService.encryptString(plainPassword)); -// } -// datasource.put(FieldName.ORGANIZATION_ID, organizationId); -// datasource.put(FieldName.CREATED_AT, Instant.now()); -// final Map<String, Object> insertedDatasource = mongoTemplate.insert(datasource, mongoTemplate.getCollectionName(Datasource.class)); -// datasourceIdsByName.put((String) datasource.get("name"), ((ObjectId) insertedDatasource.get("_id")).toHexString()); -// } -// -// for (final Map<String, Object> application : applications) { -// final List<Map<String, Object>> fullPages = (List) application.remove("$pages"); -// final List<Map<String, Object>> embeddedPages = new ArrayList<>(); -// -// application.put(FieldName.ORGANIZATION_ID, organizationId); -// mongoTemplate.insert(application, mongoTemplate.getCollectionName(Application.class)); -// final String applicationId = ((ObjectId) application.get("_id")).toHexString(); -// -// for (final Map<String, Object> fullPage : fullPages) { -// final boolean isDefault = (boolean) fullPage.remove("$isDefault"); -// -// final List<Map<String, Object>> actions = (List) ObjectUtils.defaultIfNull( -// fullPage.remove("$actions"), Collections.emptyList()); -// -// final List<Map<String, Object>> layouts = (List) fullPage.getOrDefault("layouts", Collections.emptyList()); -// for (final Map<String, Object> layout : layouts) { -// layout.put("_id", new ObjectId()); -// } -// -// fullPage.put("applicationId", applicationId); -// fullPage.put(FieldName.CREATED_AT, Instant.now()); -// final Map<String, Object> insertedPage = mongoTemplate.insert(fullPage, mongoTemplate.getCollectionName(Page.class)); -// final String pageId = ((ObjectId) insertedPage.get("_id")).toHexString(); -// embeddedPages.add(Map.of( -// "_id", pageId, -// "isDefault", isDefault -// )); -// -// final Map<String, String> actionIdsByName = new HashMap<>(); -// for (final Map<String, Object> action : actions) { -// final Map<String, Object> datasource = (Map) action.get("datasource"); -// datasource.put("pluginId", plugins.get(datasource.remove("$pluginPackageName"))); -// datasource.put(FieldName.ORGANIZATION_ID, organizationId); -// if (FALSE.equals(datasource.remove("$isEmbedded"))) { -// datasource.put("_id", new ObjectId(datasourceIdsByName.get(datasource.get("name")))); -// } -// action.put(FieldName.ORGANIZATION_ID, organizationId); -// action.put("pageId", pageId); -// action.put("pluginId", plugins.get(action.remove("$pluginPackageName"))); -// action.put(FieldName.CREATED_AT, Instant.now()); -// final Map<String, Object> insertedAction = mongoTemplate.insert(action, mongoTemplate.getCollectionName(Action.class)); -// actionIdsByName.put((String) action.get("name"), ((ObjectId) insertedAction.get("_id")).toHexString()); -// } -// -// final List<Map<String, Object>> layouts1 = (List) insertedPage.get("layouts"); -// for (Map<String, Object> layout : layouts1) { -// final List<List<Map<String, Object>>> onLoadActions = (List) layout.getOrDefault("layoutOnLoadActions", Collections.emptyList()); -// for (final List<Map<String, Object>> actionSet : onLoadActions) { -// for (final Map<String, Object> action : actionSet) { -// action.put("_id", new ObjectId(actionIdsByName.get(action.get("name")))); -// } -// } -// final List<List<Map<String, Object>>> onLoadActions2 = (List) layout.getOrDefault("publishedLayoutOnLoadActions", Collections.emptyList()); -// for (final List<Map<String, Object>> actionSet : onLoadActions2) { -// for (final Map<String, Object> action : actionSet) { -// action.put("_id", new ObjectId(actionIdsByName.get(action.get("name")))); -// } -// } -// } -// mongoTemplate.updateFirst( -// query(where("_id").is(pageId)), -// update("layouts", layouts1), -// Page.class -// ); -// } -// -// application.put("pages", embeddedPages); -// mongoTemplate.updateFirst( -// query(where("_id").is(applicationId)), -// update("pages", embeddedPages), -// Application.class -// ); -// } -// -// Config config = new Config(); -// config.setName("template-organization"); -// config.setConfig(new JSONObject(Map.of("organizationId", organizationId))); -// mongoTemplate.insert(config); -// } -// -// @ChangeSet(order = "023", id = "set-example-apps-in-config", author = "") -// public void setExampleAppsInConfig(MongoTemplate mongoTemplate) { -// -// -// final org.springframework.data.mongodb.core.query.Query configQuery = query(where("name").is("template-organization")); -// -// final Config config = mongoTemplate.findOne( -// configQuery, -// Config.class -// ); -// -// if (config == null) { -// // No template organization configured. Nothing to migrate. -// return; -// } -// -// final String organizationId = config.getConfig().getAsString("organizationId"); -// -// final List<Application> applications = mongoTemplate.find( -// query(where(fieldName(QApplication.application.organizationId)).is(organizationId)), -// Application.class -// ); -// -// final List<String> applicationIds = new ArrayList<>(); -// for (final Application application : applications) { -// applicationIds.add(application.getId()); -// } -// -// mongoTemplate.updateFirst( -// configQuery, -// update("config.applicationIds", applicationIds), -// Config.class -// ); -// } -// -// @ChangeSet(order = "024", id = "update-erroneous-action-ids", author = "") -// public void updateErroneousActionIdsInPage(MongoTemplate mongoTemplate) { -// final org.springframework.data.mongodb.core.query.Query configQuery = query(where("name").is("template-organization")); -// -// final Config config = mongoTemplate.findOne( -// configQuery, -// Config.class -// ); -// -// if (config == null) { -// // No template organization configured. Nothing to migrate. -// return; -// } -// -// final String organizationId = config.getConfig().getAsString("organizationId"); -// -// final org.springframework.data.mongodb.core.query.Query query = query(where(FieldName.ORGANIZATION_ID).is(organizationId)); -// query.fields().include("_id"); -// -// // Get IDs of applications in the template org. -// final List<String> applicationIds = mongoTemplate -// .find(query, Application.class) -// .stream() -// .map(BaseDomain::getId) -// .collect(Collectors.toList()); -// -// // Get IDs of actions in the template org. -// final List<String> actionIds = mongoTemplate -// .find(query, Action.class) -// .stream() -// .map(BaseDomain::getId) -// .collect(Collectors.toList()); -// -// // Get pages that are not in applications in the template org, and have template org's action IDs in their -// // layoutOnload lists. -// final Criteria incorrectActionIdCriteria = new Criteria().orOperator( -// where("layouts.layoutOnLoadActions").elemMatch(new Criteria().elemMatch(where("_id").in(actionIds))), -// where("layouts.publishedLayoutOnLoadActions").elemMatch(new Criteria().elemMatch(where("_id").in(actionIds))) -// ); -// final List<Page> pagesToFix = mongoTemplate.find( -// query(where(FieldName.APPLICATION_ID).not().in(applicationIds)) -// .addCriteria(incorrectActionIdCriteria), -// Page.class -// ); -// -// -// for (Page page : pagesToFix) { -// for (Layout layout : page.getLayouts()) { -// final ArrayList<Set<DslActionDTO>> layoutOnLoadActions = new ArrayList<>(); -// if (layout.getLayoutOnLoadActions() != null) { -// layoutOnLoadActions.addAll(layout.getLayoutOnLoadActions()); -// } -// if (layout.getPublishedLayoutOnLoadActions() != null) { -// layoutOnLoadActions.addAll(layout.getPublishedLayoutOnLoadActions()); -// } -// for (Set<DslActionDTO> actionSet : layoutOnLoadActions) { -// for (DslActionDTO actionDTO : actionSet) { -// final String actionName = actionDTO.getName(); -// final Action action = mongoTemplate.findOne( -// query(where(FieldName.PAGE_ID).is(page.getId())) -// .addCriteria(where(FieldName.NAME).is(actionName)), -// Action.class -// ); -// if (action != null) { -// // Update the erroneous action id (template action id) to the cloned action id -// actionDTO.setId(action.getId()); -// } -// } -// } -// } -// -// mongoTemplate.save(page); -// } -// -// final long unfixablePagesCount = mongoTemplate.count( -// query(where(FieldName.APPLICATION_ID).not().in(applicationIds)) -// .addCriteria(where("layouts.layoutOnLoadActions").elemMatch(new Criteria().elemMatch(where("_id").in(actionIds)))), -// Page.class -// ); -// -// if (unfixablePagesCount > 0) { -// log.info("Not all pages' onLoad actions could be fixed. Some old applications might not auto-run actions."); -// -// } -// } + // @ChangeSet(order = "022", id = "examples-organization", author = "") + // public void examplesOrganization(MongoTemplate mongoTemplate, EncryptionService encryptionService) throws + // IOException { + // + // final Map<String, String> plugins = new HashMap<>(); + // + // final List<Map<String, Object>> organizationPlugins = mongoTemplate + // .find(query(where("defaultInstall").is(true)), Plugin.class) + // .stream() + // .map(plugin -> { + // assert plugin.getId() != null; + // plugins.put(plugin.getPackageName(), plugin.getId()); + // return Map.of( + // "pluginId", plugin.getId(), + // "status", "FREE", + // FieldName.DELETED, false, + // "policies", Collections.emptyList() + // ); + // }) + // .collect(Collectors.toList()); + // final String jsonContent = StreamUtils.copyToString( + // new DefaultResourceLoader().getResource("examples-organization.json").getInputStream(), + // Charset.defaultCharset() + // ); + // + // final Map<String, Object> organization = new Gson().fromJson(jsonContent, HashMap.class); + // + // final List<Map<String, Object>> datasources = (List) organization.remove("$datasources"); + // final List<Map<String, Object>> applications = (List) organization.remove("$applications"); + // + // organization.put("plugins", organizationPlugins); + // organization.put(FieldName.CREATED_AT, Instant.now()); + // final Map<String, Object> insertedOrganization = mongoTemplate.insert(organization, + // mongoTemplate.getCollectionName(Organization.class)); + // final String organizationId = ((ObjectId) insertedOrganization.get("_id")).toHexString(); + // + // final Map<String, String> datasourceIdsByName = new HashMap<>(); + // + // for (final Map<String, Object> datasource : datasources) { + // datasource.put("pluginId", plugins.get(datasource.remove("$pluginPackageName"))); + // final Map authentication = (Map) ((Map) + // datasource.get("datasourceConfiguration")).get("authentication"); + // if (authentication != null) { + // final String plainPassword = (String) authentication.get("password"); + // authentication.put("password", encryptionService.encryptString(plainPassword)); + // } + // datasource.put(FieldName.ORGANIZATION_ID, organizationId); + // datasource.put(FieldName.CREATED_AT, Instant.now()); + // final Map<String, Object> insertedDatasource = mongoTemplate.insert(datasource, + // mongoTemplate.getCollectionName(Datasource.class)); + // datasourceIdsByName.put((String) datasource.get("name"), ((ObjectId) + // insertedDatasource.get("_id")).toHexString()); + // } + // + // for (final Map<String, Object> application : applications) { + // final List<Map<String, Object>> fullPages = (List) application.remove("$pages"); + // final List<Map<String, Object>> embeddedPages = new ArrayList<>(); + // + // application.put(FieldName.ORGANIZATION_ID, organizationId); + // mongoTemplate.insert(application, mongoTemplate.getCollectionName(Application.class)); + // final String applicationId = ((ObjectId) application.get("_id")).toHexString(); + // + // for (final Map<String, Object> fullPage : fullPages) { + // final boolean isDefault = (boolean) fullPage.remove("$isDefault"); + // + // final List<Map<String, Object>> actions = (List) ObjectUtils.defaultIfNull( + // fullPage.remove("$actions"), Collections.emptyList()); + // + // final List<Map<String, Object>> layouts = (List) fullPage.getOrDefault("layouts", + // Collections.emptyList()); + // for (final Map<String, Object> layout : layouts) { + // layout.put("_id", new ObjectId()); + // } + // + // fullPage.put("applicationId", applicationId); + // fullPage.put(FieldName.CREATED_AT, Instant.now()); + // final Map<String, Object> insertedPage = mongoTemplate.insert(fullPage, + // mongoTemplate.getCollectionName(Page.class)); + // final String pageId = ((ObjectId) insertedPage.get("_id")).toHexString(); + // embeddedPages.add(Map.of( + // "_id", pageId, + // "isDefault", isDefault + // )); + // + // final Map<String, String> actionIdsByName = new HashMap<>(); + // for (final Map<String, Object> action : actions) { + // final Map<String, Object> datasource = (Map) action.get("datasource"); + // datasource.put("pluginId", plugins.get(datasource.remove("$pluginPackageName"))); + // datasource.put(FieldName.ORGANIZATION_ID, organizationId); + // if (FALSE.equals(datasource.remove("$isEmbedded"))) { + // datasource.put("_id", new ObjectId(datasourceIdsByName.get(datasource.get("name")))); + // } + // action.put(FieldName.ORGANIZATION_ID, organizationId); + // action.put("pageId", pageId); + // action.put("pluginId", plugins.get(action.remove("$pluginPackageName"))); + // action.put(FieldName.CREATED_AT, Instant.now()); + // final Map<String, Object> insertedAction = mongoTemplate.insert(action, + // mongoTemplate.getCollectionName(Action.class)); + // actionIdsByName.put((String) action.get("name"), ((ObjectId) + // insertedAction.get("_id")).toHexString()); + // } + // + // final List<Map<String, Object>> layouts1 = (List) insertedPage.get("layouts"); + // for (Map<String, Object> layout : layouts1) { + // final List<List<Map<String, Object>>> onLoadActions = (List) + // layout.getOrDefault("layoutOnLoadActions", Collections.emptyList()); + // for (final List<Map<String, Object>> actionSet : onLoadActions) { + // for (final Map<String, Object> action : actionSet) { + // action.put("_id", new ObjectId(actionIdsByName.get(action.get("name")))); + // } + // } + // final List<List<Map<String, Object>>> onLoadActions2 = (List) + // layout.getOrDefault("publishedLayoutOnLoadActions", Collections.emptyList()); + // for (final List<Map<String, Object>> actionSet : onLoadActions2) { + // for (final Map<String, Object> action : actionSet) { + // action.put("_id", new ObjectId(actionIdsByName.get(action.get("name")))); + // } + // } + // } + // mongoTemplate.updateFirst( + // query(where("_id").is(pageId)), + // update("layouts", layouts1), + // Page.class + // ); + // } + // + // application.put("pages", embeddedPages); + // mongoTemplate.updateFirst( + // query(where("_id").is(applicationId)), + // update("pages", embeddedPages), + // Application.class + // ); + // } + // + // Config config = new Config(); + // config.setName("template-organization"); + // config.setConfig(new JSONObject(Map.of("organizationId", organizationId))); + // mongoTemplate.insert(config); + // } + // + // @ChangeSet(order = "023", id = "set-example-apps-in-config", author = "") + // public void setExampleAppsInConfig(MongoTemplate mongoTemplate) { + // + // + // final org.springframework.data.mongodb.core.query.Query configQuery = + // query(where("name").is("template-organization")); + // + // final Config config = mongoTemplate.findOne( + // configQuery, + // Config.class + // ); + // + // if (config == null) { + // // No template organization configured. Nothing to migrate. + // return; + // } + // + // final String organizationId = config.getConfig().getAsString("organizationId"); + // + // final List<Application> applications = mongoTemplate.find( + // query(where(fieldName(QApplication.application.organizationId)).is(organizationId)), + // Application.class + // ); + // + // final List<String> applicationIds = new ArrayList<>(); + // for (final Application application : applications) { + // applicationIds.add(application.getId()); + // } + // + // mongoTemplate.updateFirst( + // configQuery, + // update("config.applicationIds", applicationIds), + // Config.class + // ); + // } + // + // @ChangeSet(order = "024", id = "update-erroneous-action-ids", author = "") + // public void updateErroneousActionIdsInPage(MongoTemplate mongoTemplate) { + // final org.springframework.data.mongodb.core.query.Query configQuery = + // query(where("name").is("template-organization")); + // + // final Config config = mongoTemplate.findOne( + // configQuery, + // Config.class + // ); + // + // if (config == null) { + // // No template organization configured. Nothing to migrate. + // return; + // } + // + // final String organizationId = config.getConfig().getAsString("organizationId"); + // + // final org.springframework.data.mongodb.core.query.Query query = + // query(where(FieldName.ORGANIZATION_ID).is(organizationId)); + // query.fields().include("_id"); + // + // // Get IDs of applications in the template org. + // final List<String> applicationIds = mongoTemplate + // .find(query, Application.class) + // .stream() + // .map(BaseDomain::getId) + // .collect(Collectors.toList()); + // + // // Get IDs of actions in the template org. + // final List<String> actionIds = mongoTemplate + // .find(query, Action.class) + // .stream() + // .map(BaseDomain::getId) + // .collect(Collectors.toList()); + // + // // Get pages that are not in applications in the template org, and have template org's action IDs in their + // // layoutOnload lists. + // final Criteria incorrectActionIdCriteria = new Criteria().orOperator( + // where("layouts.layoutOnLoadActions").elemMatch(new + // Criteria().elemMatch(where("_id").in(actionIds))), + // where("layouts.publishedLayoutOnLoadActions").elemMatch(new + // Criteria().elemMatch(where("_id").in(actionIds))) + // ); + // final List<Page> pagesToFix = mongoTemplate.find( + // query(where(FieldName.APPLICATION_ID).not().in(applicationIds)) + // .addCriteria(incorrectActionIdCriteria), + // Page.class + // ); + // + // + // for (Page page : pagesToFix) { + // for (Layout layout : page.getLayouts()) { + // final ArrayList<Set<DslActionDTO>> layoutOnLoadActions = new ArrayList<>(); + // if (layout.getLayoutOnLoadActions() != null) { + // layoutOnLoadActions.addAll(layout.getLayoutOnLoadActions()); + // } + // if (layout.getPublishedLayoutOnLoadActions() != null) { + // layoutOnLoadActions.addAll(layout.getPublishedLayoutOnLoadActions()); + // } + // for (Set<DslActionDTO> actionSet : layoutOnLoadActions) { + // for (DslActionDTO actionDTO : actionSet) { + // final String actionName = actionDTO.getName(); + // final Action action = mongoTemplate.findOne( + // query(where(FieldName.PAGE_ID).is(page.getId())) + // .addCriteria(where(FieldName.NAME).is(actionName)), + // Action.class + // ); + // if (action != null) { + // // Update the erroneous action id (template action id) to the cloned action id + // actionDTO.setId(action.getId()); + // } + // } + // } + // } + // + // mongoTemplate.save(page); + // } + // + // final long unfixablePagesCount = mongoTemplate.count( + // query(where(FieldName.APPLICATION_ID).not().in(applicationIds)) + // .addCriteria(where("layouts.layoutOnLoadActions").elemMatch(new + // Criteria().elemMatch(where("_id").in(actionIds)))), + // Page.class + // ); + // + // if (unfixablePagesCount > 0) { + // log.info("Not all pages' onLoad actions could be fixed. Some old applications might not auto-run + // actions."); + // + // } + // } @ChangeSet(order = "025", id = "generate-unique-id-for-instance", author = "") public void generateUniqueIdForInstance(MongoTemplate mongoTemplate) { - mongoTemplate.insert(new Config( - new JSONObject(Map.of("value", new ObjectId().toHexString())), - "instance-id" - )); + mongoTemplate.insert(new Config(new JSONObject(Map.of("value", new ObjectId().toHexString())), "instance-id")); } @ChangeSet(order = "026", id = "fix-password-reset-token-expiration", author = "") @@ -1029,11 +1040,11 @@ public void fixTokenExpiration(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, PasswordResetToken.class, FieldName.CREATED_AT); dropIndexIfExists(mongoTemplate, PasswordResetToken.class, FieldName.EMAIL); - ensureIndexes(mongoTemplate, PasswordResetToken.class, - makeIndex(FieldName.CREATED_AT) - .expire(2, TimeUnit.DAYS), - makeIndex(FieldName.EMAIL).unique() - ); + ensureIndexes( + mongoTemplate, + PasswordResetToken.class, + makeIndex(FieldName.CREATED_AT).expire(2, TimeUnit.DAYS), + makeIndex(FieldName.EMAIL).unique()); } @ChangeSet(order = "027", id = "add-elastic-search-plugin", author = "") @@ -1080,10 +1091,10 @@ public void addDynamoPlugin(MongoTemplate mongoTemplate) { public void usePngLogos(MongoTemplate mongoTemplate) { mongoTemplate.updateFirst( query(where(fieldName(QPlugin.plugin.packageName)).is("elasticsearch-plugin")), - update(fieldName(QPlugin.plugin.iconLocation), + update( + fieldName(QPlugin.plugin.iconLocation), "https://s3.us-east-2.amazonaws.com/assets.appsmith.com/ElasticSearch.png"), - Plugin.class - ); + Plugin.class); } @ChangeSet(order = "030", id = "add-redis-plugin", author = "") @@ -1134,9 +1145,7 @@ public void addNewPageIndexAfterDroppingNewPage(MongoTemplate mongoTemplate) { mongoTemplate.dropCollection(NewPage.class); // Now add an index - ensureIndexes(mongoTemplate, NewPage.class, - createdAtIndex - ); + ensureIndexes(mongoTemplate, NewPage.class, createdAtIndex); } @ChangeSet(order = "038", id = "createNewActionIndexAfterDroppingNewAction", author = "") @@ -1147,17 +1156,12 @@ public void addNewActionIndexAfterDroppingNewAction(MongoTemplate mongoTemplate) mongoTemplate.dropCollection(NewAction.class); // Now add an index - ensureIndexes(mongoTemplate, NewAction.class, - createdAtIndex - ); + ensureIndexes(mongoTemplate, NewAction.class, createdAtIndex); } @ChangeSet(order = "039", id = "migrate-page-and-actions", author = "") public void migratePage(MongoTemplate mongoTemplate) { - final List<Page> pages = mongoTemplate.find( - query(where("deletedAt").is(null)), - Page.class - ); + final List<Page> pages = mongoTemplate.find(query(where("deletedAt").is(null)), Page.class); List<NewPage> toBeInsertedPages = new ArrayList<>(); @@ -1197,7 +1201,7 @@ public void migratePage(MongoTemplate mongoTemplate) { newPage.setPublishedPage(publishedPage); newPage.setUnpublishedPage(unpublishedPage); - //Set the base domain fields + // Set the base domain fields newPage.setId(oldPage.getId()); newPage.setCreatedAt(oldPage.getCreatedAt()); newPage.setUpdatedAt(oldPage.getUpdatedAt()); @@ -1209,14 +1213,10 @@ public void migratePage(MongoTemplate mongoTemplate) { // Migrate Actions now - Map<String, String> pageIdApplicationIdMap = pages - .stream() - .collect(Collectors.toMap(Page::getId, Page::getApplicationId)); + Map<String, String> pageIdApplicationIdMap = + pages.stream().collect(Collectors.toMap(Page::getId, Page::getApplicationId)); - final List<Action> actions = mongoTemplate.find( - query(where("deletedAt").is(null)), - Action.class - ); + final List<Action> actions = mongoTemplate.find(query(where("deletedAt").is(null)), Action.class); List<NewAction> toBeInsertedActions = new ArrayList<>(); @@ -1250,7 +1250,7 @@ public void migratePage(MongoTemplate mongoTemplate) { newAction.setPluginId(oldAction.getDatasource().getPluginId()); } - //Set the base domain fields + // Set the base domain fields newAction.setId(oldAction.getId()); newAction.setCreatedAt(oldAction.getCreatedAt()); newAction.setUpdatedAt(oldAction.getUpdatedAt()); @@ -1260,7 +1260,6 @@ public void migratePage(MongoTemplate mongoTemplate) { } mongoTemplate.insertAll(toBeInsertedActions); - } @ChangeSet(order = "040", id = "new-page-new-action-add-indexes", author = "") @@ -1268,44 +1267,37 @@ public void addNewPageAndNewActionNewIndexes(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, NewAction.class, "createdAt"); - ensureIndexes(mongoTemplate, NewAction.class, + ensureIndexes( + mongoTemplate, + NewAction.class, makeIndex("applicationId", "deleted", "createdAt") - .named("applicationId_deleted_createdAt_compound_index") - ); + .named("applicationId_deleted_createdAt_compound_index")); dropIndexIfExists(mongoTemplate, NewPage.class, "createdAt"); - ensureIndexes(mongoTemplate, NewPage.class, - makeIndex("applicationId", "deleted") - .named("applicationId_deleted_compound_index") - ); - + ensureIndexes( + mongoTemplate, + NewPage.class, + makeIndex("applicationId", "deleted").named("applicationId_deleted_compound_index")); } @ChangeSet(order = "041", id = "new-action-add-index-pageId", author = "") public void addNewActionIndexForPageId(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, NewAction.class, "applicationId_deleted_createdAt_compound_index"); - } @ChangeSet(order = "042", id = "update-action-index-to-single-multiple-indices", author = "") public void updateActionIndexToSingleMultipleIndices(MongoTemplate mongoTemplate) { - ensureIndexes(mongoTemplate, NewAction.class, - makeIndex("applicationId") - .named("applicationId") - ); + ensureIndexes(mongoTemplate, NewAction.class, makeIndex("applicationId").named("applicationId")); - ensureIndexes(mongoTemplate, NewAction.class, - makeIndex("unpublishedAction.pageId") - .named("unpublishedAction_pageId") - ); + ensureIndexes( + mongoTemplate, + NewAction.class, + makeIndex("unpublishedAction.pageId").named("unpublishedAction_pageId")); - ensureIndexes(mongoTemplate, NewAction.class, - makeIndex("deleted") - .named("deleted") - ); + ensureIndexes(mongoTemplate, NewAction.class, makeIndex("deleted").named("deleted")); } @ChangeSet(order = "043", id = "add-firestore-plugin", author = "") @@ -1333,10 +1325,10 @@ public void ensureAppIconsAndColors(MongoTemplate mongoTemplate) { final String iconFieldName = fieldName(QApplication.application.icon); final String colorFieldName = fieldName(QApplication.application.color); - final org.springframework.data.mongodb.core.query.Query query = query(new Criteria().orOperator( - where(iconFieldName).exists(false), - where(colorFieldName).exists(false) - )); + final org.springframework.data.mongodb.core.query.Query query = query(new Criteria() + .orOperator( + where(iconFieldName).exists(false), + where(colorFieldName).exists(false))); // We are only getting the icon and color fields, rest will be null (or default values) in the // resulting Application objects. @@ -1422,26 +1414,10 @@ public void ensureAppIconsAndColors(MongoTemplate mongoTemplate) { "uk-pounds", "website", "yen", - "airplane" - ); + "airplane"); final List<String> colorPool = List.of( - "#6C4CF1", - "#4F70FD", - "#F56AF4", - "#B94CF1", - "#54A9FB", - "#5ED3DA", - "#5EDA82", - "#A8D76C", - "#E9C951", - "#FE9F44", - "#ED86A1", - "#EA6179", - "#C03C3C", - "#BC6DB2", - "#6C9DD0", - "#6CD0CF" - ); + "#6C4CF1", "#4F70FD", "#F56AF4", "#B94CF1", "#54A9FB", "#5ED3DA", "#5EDA82", "#A8D76C", "#E9C951", + "#FE9F44", "#ED86A1", "#EA6179", "#C03C3C", "#BC6DB2", "#6C9DD0", "#6CD0CF"); final Random iconRands = new Random(); final Random colorRands = new Random(); @@ -1454,16 +1430,14 @@ public void ensureAppIconsAndColors(MongoTemplate mongoTemplate) { mongoTemplate.updateFirst( query(where(fieldName(QApplication.application.id)).is(app.getId())), update(iconFieldName, iconPool.get(iconRands.nextInt(iconPoolSize))), - Application.class - ); + Application.class); } if (app.getColor() == null) { mongoTemplate.updateFirst( query(where(fieldName(QApplication.application.id)).is(app.getId())), update(colorFieldName, colorPool.get(colorRands.nextInt(colorPoolSize))), - Application.class - ); + Application.class); } } } @@ -1472,17 +1446,19 @@ public void ensureAppIconsAndColors(MongoTemplate mongoTemplate) { public void updateAuthenticationTypes(MongoTemplate mongoTemplate) { mongoTemplate.execute("datasource", new CollectionCallback<String>() { @Override - public String doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { + public String doInCollection(MongoCollection<Document> collection) + throws MongoException, DataAccessException { // Only update _class for authentication objects that exist - MongoCursor cursor = collection.find(Filters.exists("datasourceConfiguration.authentication")).cursor(); + MongoCursor cursor = collection + .find(Filters.exists("datasourceConfiguration.authentication")) + .cursor(); while (cursor.hasNext()) { Document current = (Document) cursor.next(); Document old = Document.parse(current.toJson()); // Extra precaution to only update _class for authentication objects that don't already have this // Is this condition required? What does production datasource look like? - ((Document) ((Document) current.get("datasourceConfiguration")) - .get("authentication")) + ((Document) ((Document) current.get("datasourceConfiguration")).get("authentication")) .putIfAbsent("_class", "dbAuth"); // Replace old document with the new one @@ -1494,23 +1470,24 @@ public String doInCollection(MongoCollection<Document> collection) throws MongoE mongoTemplate.execute("newAction", new CollectionCallback<String>() { @Override - public String doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { + public String doInCollection(MongoCollection<Document> collection) + throws MongoException, DataAccessException { // Only update _class for authentication objects that exist MongoCursor cursor = collection .find(Filters.and( Filters.exists("unpublishedAction.datasource"), Filters.exists("unpublishedAction.datasource.datasourceConfiguration"), - Filters.exists("unpublishedAction.datasource.datasourceConfiguration.authentication"))).cursor(); + Filters.exists("unpublishedAction.datasource.datasourceConfiguration.authentication"))) + .cursor(); while (cursor.hasNext()) { Document current = (Document) cursor.next(); Document old = Document.parse(current.toJson()); // Extra precaution to only update _class for authentication objects that don't already have this // Is this condition required? What does production datasource look like? - ((Document) ((Document) ((Document) ((Document) current.get("unpublishedAction")) - .get("datasource")) - .get("datasourceConfiguration")) - .get("authentication")) + ((Document) ((Document) ((Document) ((Document) current.get("unpublishedAction")).get("datasource")) + .get("datasourceConfiguration")) + .get("authentication")) .putIfAbsent("_class", "dbAuth"); // Replace old document with the new one @@ -1522,23 +1499,24 @@ public String doInCollection(MongoCollection<Document> collection) throws MongoE mongoTemplate.execute("newAction", new CollectionCallback<String>() { @Override - public String doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { + public String doInCollection(MongoCollection<Document> collection) + throws MongoException, DataAccessException { // Only update _class for authentication objects that exist MongoCursor cursor = collection .find(Filters.and( Filters.exists("publishedAction.datasource"), Filters.exists("publishedAction.datasource.datasourceConfiguration"), - Filters.exists("publishedAction.datasource.datasourceConfiguration.authentication"))).cursor(); + Filters.exists("publishedAction.datasource.datasourceConfiguration.authentication"))) + .cursor(); while (cursor.hasNext()) { Document current = (Document) cursor.next(); Document old = Document.parse(current.toJson()); // Extra precaution to only update _class for authentication objects that don't already have this // Is this condition required? What does production datasource look like? - ((Document) ((Document) ((Document) ((Document) current.get("publishedAction")) - .get("datasource")) - .get("datasourceConfiguration")) - .get("authentication")) + ((Document) ((Document) ((Document) ((Document) current.get("publishedAction")).get("datasource")) + .get("datasourceConfiguration")) + .get("authentication")) .putIfAbsent("_class", "dbAuth"); // Replace old document with the new one @@ -1554,12 +1532,10 @@ public void addIsSendSessionEnabledPropertyInDatasources(MongoTemplate mongoTemp String keyName = "isSendSessionEnabled"; - Plugin restApiPlugin = mongoTemplate.findOne( - query(where("packageName").is("restapi-plugin")), - Plugin.class - ); + Plugin restApiPlugin = mongoTemplate.findOne(query(where("packageName").is("restapi-plugin")), Plugin.class); - final org.springframework.data.mongodb.core.query.Query query = query(where("pluginId").is(restApiPlugin.getId())); + final org.springframework.data.mongodb.core.query.Query query = + query(where("pluginId").is(restApiPlugin.getId())); for (Datasource datasource : mongoTemplate.find(query, Datasource.class)) { // Find if the datasource should be updated with the new key @@ -1572,9 +1548,9 @@ public void addIsSendSessionEnabledPropertyInDatasources(MongoTemplate mongoTemp updateRequired = true; datasource.getDatasourceConfiguration().setProperties(new ArrayList<>()); } else { - List<Property> properties = datasource.getDatasourceConfiguration().getProperties(); - Optional<Property> isSendSessionEnabledOptional = properties - .stream() + List<Property> properties = + datasource.getDatasourceConfiguration().getProperties(); + Optional<Property> isSendSessionEnabledOptional = properties.stream() .filter(property -> keyName.equals(property.getKey())) .findFirst(); @@ -1591,7 +1567,6 @@ public void addIsSendSessionEnabledPropertyInDatasources(MongoTemplate mongoTemp datasource.getDatasourceConfiguration().getProperties().add(newProperty); mongoTemplate.save(datasource); } - } } @@ -1625,31 +1600,40 @@ public void updateDatabaseDocumentationLinks_v1_2_1(MongoTemplate mongoTemplate) for (Plugin plugin : mongoTemplate.findAll(Plugin.class)) { switch (plugin.getPackageName()) { case "postgres-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-postgres"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-postgres"); break; case "mongo-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-mongodb"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-mongodb"); break; case "elasticsearch-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-elasticsearch"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-elasticsearch"); break; case "dynamo-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-dynamodb"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-dynamodb"); break; case "redis-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-redis"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-redis"); break; case "mssql-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-mssql"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-mssql"); break; case "firestore-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-firestore"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-firestore"); break; case "redshift-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-redshift"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-redshift"); break; case "mysql-plugin": - plugin.setDocumentationLink("https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-mysql"); + plugin.setDocumentationLink( + "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-mysql"); break; default: continue; @@ -1682,11 +1666,10 @@ public void addAmazonS3Plugin(MongoTemplate mongoTemplate) { @ChangeSet(order = "052", id = "add-app-viewer-invite-policy", author = "") public void addAppViewerInvitePolicy(MongoTemplate mongoTemplate) { final List<Organization> organizations = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QOrganization.organization.userRoles) + ".role").is(AppsmithRole.ORGANIZATION_VIEWER.name()) - )), - Organization.class - ); + query(new Criteria() + .andOperator(where(fieldName(QOrganization.organization.userRoles) + ".role") + .is(AppsmithRole.ORGANIZATION_VIEWER.name()))), + Organization.class); for (final Organization org : organizations) { final Set<String> viewers = org.getUserRoles().stream() @@ -1694,15 +1677,15 @@ public void addAppViewerInvitePolicy(MongoTemplate mongoTemplate) { .map(UserRole::getUsername) .collect(Collectors.toSet()); mongoTemplate.updateFirst( - query(new Criteria().andOperator( - where(fieldName(QOrganization.organization.id)).is(org.getId()), - where(fieldName(QOrganization.organization.policies) + ".permission").is(WORKSPACE_INVITE_USERS.getValue()) - )), + query(new Criteria() + .andOperator( + where(fieldName(QOrganization.organization.id)) + .is(org.getId()), + where(fieldName(QOrganization.organization.policies) + ".permission") + .is(WORKSPACE_INVITE_USERS.getValue()))), new Update().addToSet("policies.$.users").each(viewers.toArray()), - Organization.class - ); + Organization.class); } - } @ChangeSet(order = "053", id = "update-plugin-datasource-form-components", author = "") @@ -1755,9 +1738,9 @@ public void updateEncodeParamsToggle(MongoTemplate mongoTemplate) { public void updatePostgresActionsSetPreparedStatementConfiguration(MongoTemplate mongoTemplate) { List<Plugin> plugins = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QPlugin.plugin.packageName)).is("postgres-plugin") - )), + query(new Criteria() + .andOperator( + where(fieldName(QPlugin.plugin.packageName)).is("postgres-plugin"))), Plugin.class); if (plugins.size() < 1) { @@ -1768,11 +1751,10 @@ public void updatePostgresActionsSetPreparedStatementConfiguration(MongoTemplate // Fetch all the actions built on top of a postgres database List<NewAction> postgresActions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(postgresPlugin.getId()) - )), - NewAction.class - ); + query(new Criteria() + .andOperator( + where(fieldName(QNewAction.newAction.pluginId)).is(postgresPlugin.getId()))), + NewAction.class); for (NewAction action : postgresActions) { List<Property> pluginSpecifiedTemplates = new ArrayList<>(); @@ -1780,11 +1762,16 @@ public void updatePostgresActionsSetPreparedStatementConfiguration(MongoTemplate // We have found an action of postgres plugin type if (action.getUnpublishedAction().getActionConfiguration() != null) { - action.getUnpublishedAction().getActionConfiguration().setPluginSpecifiedTemplates(pluginSpecifiedTemplates); + action.getUnpublishedAction() + .getActionConfiguration() + .setPluginSpecifiedTemplates(pluginSpecifiedTemplates); } - if (action.getPublishedAction() != null && action.getPublishedAction().getActionConfiguration() != null) { - action.getPublishedAction().getActionConfiguration().setPluginSpecifiedTemplates(pluginSpecifiedTemplates); + if (action.getPublishedAction() != null + && action.getPublishedAction().getActionConfiguration() != null) { + action.getPublishedAction() + .getActionConfiguration() + .setPluginSpecifiedTemplates(pluginSpecifiedTemplates); } mongoTemplate.save(action); @@ -1801,8 +1788,7 @@ public void fixDynamicBindingPathListForExistingActions(MongoTemplate mongoTempl // Only investigate actions which have atleast one dynamic binding path list if (action.getUnpublishedAction().getActionConfiguration() != null && !isNullOrEmpty(dynamicBindingPaths)) { - List<String> dynamicBindingPathNames = dynamicBindingPaths - .stream() + List<String> dynamicBindingPathNames = dynamicBindingPaths.stream() .map(property -> property.getKey()) .collect(Collectors.toList()); @@ -1810,21 +1796,22 @@ public void fixDynamicBindingPathListForExistingActions(MongoTemplate mongoTempl List<String> finalDynamicBindingPathList = new ArrayList<>(); finalDynamicBindingPathList.addAll(dynamicBindingPathNames); - Set<String> pathsToRemove = getInvalidDynamicBindingPathsInAction(objectMapper, action, dynamicBindingPathNames); + Set<String> pathsToRemove = + getInvalidDynamicBindingPathsInAction(objectMapper, action, dynamicBindingPathNames); Boolean actionEdited = pathsToRemove.size() > 0 ? TRUE : FALSE; // Only update the action if required if (actionEdited) { - // We have walked all the dynamic binding paths which either dont exist or they exist but don't contain any mustache bindings + // We have walked all the dynamic binding paths which either dont exist or they exist but don't + // contain any mustache bindings for (String path : dynamicBindingPathNames) { if (pathsToRemove.contains(path)) { finalDynamicBindingPathList.remove(path); } } - List<Property> updatedDynamicBindingPathList = finalDynamicBindingPathList - .stream() + List<Property> updatedDynamicBindingPathList = finalDynamicBindingPathList.stream() .map(path -> { Property property = new Property(); property.setKey(path); @@ -1836,11 +1823,11 @@ public void fixDynamicBindingPathListForExistingActions(MongoTemplate mongoTempl mongoTemplate.save(action); } } - } } - private static Set<String> getInvalidDynamicBindingPathsInAction(ObjectMapper mapper, NewAction action, List<String> dynamicBindingPathNames) { + private static Set<String> getInvalidDynamicBindingPathsInAction( + ObjectMapper mapper, NewAction action, List<String> dynamicBindingPathNames) { Set<String> pathsToRemove = new HashSet<>(); for (String path : dynamicBindingPathNames) { @@ -1849,9 +1836,12 @@ private static Set<String> getInvalidDynamicBindingPathsInAction(ObjectMapper ma String[] fields = path.split("[].\\[]"); // Convert actionConfiguration into JSON Object and then walk till we reach the path specified. - Map<String, Object> actionConfigurationMap = mapper.convertValue(action.getUnpublishedAction().getActionConfiguration(), Map.class); + Map<String, Object> actionConfigurationMap = + mapper.convertValue(action.getUnpublishedAction().getActionConfiguration(), Map.class); Object parent = new JSONObject(actionConfigurationMap); - Iterator<String> fieldsIterator = Arrays.stream(fields).filter(fieldToken -> !fieldToken.isBlank()).iterator(); + Iterator<String> fieldsIterator = Arrays.stream(fields) + .filter(fieldToken -> !fieldToken.isBlank()) + .iterator(); Boolean isLeafNode = false; while (fieldsIterator.hasNext()) { @@ -1886,15 +1876,17 @@ private static Set<String> getInvalidDynamicBindingPathsInAction(ObjectMapper ma } // Only extract mustache keys from leaf nodes if (parent != null && isLeafNode) { - Set<String> mustacheKeysFromFields = MustacheHelper.extractMustacheKeysFromFields(parent).stream().map(token -> token.getValue()).collect(Collectors.toSet()); + Set<String> mustacheKeysFromFields = MustacheHelper.extractMustacheKeysFromFields(parent).stream() + .map(token -> token.getValue()) + .collect(Collectors.toSet()); - // We found the path. But if the path does not have any mustache bindings, remove it from the path list + // We found the path. But if the path does not have any mustache bindings, remove it from the path + // list if (mustacheKeysFromFields.isEmpty()) { pathsToRemove.add(path); } } } - } return pathsToRemove; } @@ -1930,33 +1922,26 @@ public void updateActionConfigurationTimeout(MongoTemplate mongoTemplate) { @ChangeSet(order = "058", id = "update-s3-datasource-configuration-and-label", author = "") public void updateS3DatasourceConfigurationAndLabel(MongoTemplate mongoTemplate) { Plugin s3Plugin = mongoTemplate - .find(query(where("name").is("Amazon S3")), Plugin.class).get(0); + .find(query(where("name").is("Amazon S3")), Plugin.class) + .get(0); s3Plugin.setName("S3"); mongoTemplate.save(s3Plugin); - List<Datasource> s3Datasources = mongoTemplate - .find(query(where("pluginId").is(s3Plugin.getId())), Datasource.class); + List<Datasource> s3Datasources = + mongoTemplate.find(query(where("pluginId").is(s3Plugin.getId())), Datasource.class); - s3Datasources - .stream() - .forEach(datasource -> { - datasource - .getDatasourceConfiguration() - .getProperties() - .add(new Property("s3Provider", "amazon-s3")); + s3Datasources.stream().forEach(datasource -> { + datasource.getDatasourceConfiguration().getProperties().add(new Property("s3Provider", "amazon-s3")); - mongoTemplate.save(datasource); - }); + mongoTemplate.save(datasource); + }); } @ChangeSet(order = "059", id = "change-applayout-type-definition", author = "") public void changeAppLayoutTypeDefinition(MongoOperations mongoOperations) { // Unset an old version of this field, that is no longer used. mongoOperations.updateMulti( - query(where("appLayout").exists(true)), - new Update().unset("appLayout"), - Application.class - ); + query(where("appLayout").exists(true)), new Update().unset("appLayout"), Application.class); // For the published and unpublished app layouts, migrate the old way of specifying the device width to the new // way of doing it. Table of migrations: @@ -1964,10 +1949,12 @@ public void changeAppLayoutTypeDefinition(MongoOperations mongoOperations) { // Tablet L: Old - NA, New 960 - 1080 // Tablet: Old - 1024, New 650 - 800 // Mobile: Old - 720, New 350 - 450 - final Criteria criteria = new Criteria().orOperator( - where(fieldName(QApplication.application.unpublishedAppLayout)).exists(true), - where(fieldName(QApplication.application.publishedAppLayout)).exists(true) - ); + final Criteria criteria = new Criteria() + .orOperator( + where(fieldName(QApplication.application.unpublishedAppLayout)) + .exists(true), + where(fieldName(QApplication.application.publishedAppLayout)) + .exists(true)); final Query query = query(criteria); query.fields() @@ -1977,9 +1964,14 @@ public void changeAppLayoutTypeDefinition(MongoOperations mongoOperations) { List<Application> apps = mongoOperations.find(query, Application.class); for (final Application app : apps) { - final Integer unpublishedWidth = app.getUnpublishedAppLayout() == null ? null : app.getUnpublishedAppLayout().getWidth(); - final Integer publishedWidth = app.getPublishedAppLayout() == null ? null : app.getPublishedAppLayout().getWidth(); - final Update update = new Update().unset("unpublishedAppLayout.width").unset("publishedAppLayout.width"); + final Integer unpublishedWidth = app.getUnpublishedAppLayout() == null + ? null + : app.getUnpublishedAppLayout().getWidth(); + final Integer publishedWidth = app.getPublishedAppLayout() == null + ? null + : app.getPublishedAppLayout().getWidth(); + final Update update = + new Update().unset("unpublishedAppLayout.width").unset("publishedAppLayout.width"); if (unpublishedWidth != null) { final String typeField = "unpublishedAppLayout.type"; @@ -2014,97 +2006,95 @@ public void changeAppLayoutTypeDefinition(MongoOperations mongoOperations) { } mongoOperations.updateFirst( - query(where(fieldName(QApplication.application.id)).is(app.getId())), - update, - Application.class - ); - + query(where(fieldName(QApplication.application.id)).is(app.getId())), update, Application.class); } } // Commenting out Example workspace related migrations since example workspaces are not used anymore -// @ChangeSet(order = "060", id = "clear-example-apps", author = "") -// public void clearExampleApps(MongoTemplate mongoTemplate) { -// mongoTemplate.updateFirst( -// query(where(fieldName(QConfig.config1.name)).is("template-organization")), -// update("config.applicationIds", Collections.emptyList()).set("config.organizationId", null), -// Config.class -// ); -// } + // @ChangeSet(order = "060", id = "clear-example-apps", author = "") + // public void clearExampleApps(MongoTemplate mongoTemplate) { + // mongoTemplate.updateFirst( + // query(where(fieldName(QConfig.config1.name)).is("template-organization")), + // update("config.applicationIds", Collections.emptyList()).set("config.organizationId", null), + // Config.class + // ); + // } @ChangeSet(order = "061", id = "update-mysql-postgres-mongo-ssl-mode", author = "") public void updateMysqlPostgresMongoSslMode(MongoTemplate mongoTemplate) { - Plugin mysqlPlugin = mongoTemplate - .findOne(query(where("packageName").is("mysql-plugin")), Plugin.class); + Plugin mysqlPlugin = mongoTemplate.findOne(query(where("packageName").is("mysql-plugin")), Plugin.class); - Plugin mongoPlugin = mongoTemplate - .findOne(query(where("packageName").is("mongo-plugin")), Plugin.class); + Plugin mongoPlugin = mongoTemplate.findOne(query(where("packageName").is("mongo-plugin")), Plugin.class); - List<Datasource> mysqlAndMongoDatasources = mongoTemplate - .find( - query(new Criteria() - .orOperator( - where("pluginId").is(mysqlPlugin.getId()), - where("pluginId").is(mongoPlugin.getId()) - ) - ), - Datasource.class); + List<Datasource> mysqlAndMongoDatasources = mongoTemplate.find( + query(new Criteria() + .orOperator( + where("pluginId").is(mysqlPlugin.getId()), + where("pluginId").is(mongoPlugin.getId()))), + Datasource.class); /* * - Set SSL mode to DEFAULT for all mysql and mongodb datasources. */ - mysqlAndMongoDatasources - .stream() - .forEach(datasource -> { - if (datasource.getDatasourceConfiguration() != null) { - if (datasource.getDatasourceConfiguration().getConnection() == null) { - datasource.getDatasourceConfiguration().setConnection(new Connection()); - } + mysqlAndMongoDatasources.stream().forEach(datasource -> { + if (datasource.getDatasourceConfiguration() != null) { + if (datasource.getDatasourceConfiguration().getConnection() == null) { + datasource.getDatasourceConfiguration().setConnection(new Connection()); + } - if (datasource.getDatasourceConfiguration().getConnection().getSsl() == null) { - datasource.getDatasourceConfiguration().getConnection().setSsl(new SSLDetails()); - } + if (datasource.getDatasourceConfiguration().getConnection().getSsl() == null) { + datasource.getDatasourceConfiguration().getConnection().setSsl(new SSLDetails()); + } - datasource.getDatasourceConfiguration().getConnection().getSsl().setAuthType(SSLDetails.AuthType.DEFAULT); - mongoTemplate.save(datasource); - } - }); + datasource + .getDatasourceConfiguration() + .getConnection() + .getSsl() + .setAuthType(SSLDetails.AuthType.DEFAULT); + mongoTemplate.save(datasource); + } + }); - Plugin postgresPlugin = mongoTemplate - .findOne(query(where("packageName").is("postgres-plugin")), Plugin.class); + Plugin postgresPlugin = mongoTemplate.findOne(query(where("packageName").is("postgres-plugin")), Plugin.class); - List<Datasource> postgresDatasources = mongoTemplate - .find(query(where("pluginId").is(postgresPlugin.getId())), Datasource.class); + List<Datasource> postgresDatasources = + mongoTemplate.find(query(where("pluginId").is(postgresPlugin.getId())), Datasource.class); /* * - Set SSL mode to DEFAULT only for those postgres datasources where: * - SSL mode config doesn't exist. * - SSL mode config cannot be supported - NO_SSL, VERIFY_CA, VERIFY_FULL */ - postgresDatasources - .stream() - .forEach(datasource -> { - if (datasource.getDatasourceConfiguration() != null) { - if (datasource.getDatasourceConfiguration().getConnection() == null) { - datasource.getDatasourceConfiguration().setConnection(new Connection()); - } + postgresDatasources.stream().forEach(datasource -> { + if (datasource.getDatasourceConfiguration() != null) { + if (datasource.getDatasourceConfiguration().getConnection() == null) { + datasource.getDatasourceConfiguration().setConnection(new Connection()); + } - if (datasource.getDatasourceConfiguration().getConnection().getSsl() == null) { - datasource.getDatasourceConfiguration().getConnection().setSsl(new SSLDetails()); - } + if (datasource.getDatasourceConfiguration().getConnection().getSsl() == null) { + datasource.getDatasourceConfiguration().getConnection().setSsl(new SSLDetails()); + } - SSLDetails.AuthType authType = datasource.getDatasourceConfiguration().getConnection().getSsl().getAuthType(); - if (authType == null - || (!SSLDetails.AuthType.ALLOW.equals(authType) + SSLDetails.AuthType authType = datasource + .getDatasourceConfiguration() + .getConnection() + .getSsl() + .getAuthType(); + if (authType == null + || (!SSLDetails.AuthType.ALLOW.equals(authType) && !SSLDetails.AuthType.PREFER.equals(authType) && !SSLDetails.AuthType.REQUIRE.equals(authType) && !SSLDetails.AuthType.DISABLE.equals(authType))) { - datasource.getDatasourceConfiguration().getConnection().getSsl().setAuthType(SSLDetails.AuthType.DEFAULT); - } + datasource + .getDatasourceConfiguration() + .getConnection() + .getSsl() + .setAuthType(SSLDetails.AuthType.DEFAULT); + } - mongoTemplate.save(datasource); - } - }); + mongoTemplate.save(datasource); + } + }); } @ChangeSet(order = "062", id = "add-commenting-permissions", author = "") @@ -2112,8 +2102,7 @@ public void addCommentingPermissions(MongoTemplate mongoTemplate) { final List<Application> applications = mongoTemplate.findAll(Application.class); for (final Application application : applications) { - application.getPolicies() - .stream() + application.getPolicies().stream() .filter(policy -> AclPermission.READ_APPLICATIONS.getValue().equals(policy.getPermission())) .findFirst() .ifPresent(readAppPolicy -> { @@ -2123,10 +2112,10 @@ public void addCommentingPermissions(MongoTemplate mongoTemplate) { .groups(readAppPolicy.getGroups()) .build(); mongoTemplate.updateFirst( - query(where(fieldName(QApplication.application.id)).is(application.getId())), + query(where(fieldName(QApplication.application.id)) + .is(application.getId())), new Update().push(fieldName(QApplication.application.policies), newPolicy), - Application.class - ); + Application.class); }); } } @@ -2154,10 +2143,7 @@ public void addGoogleSheetsPlugin(MongoTemplate mongoTemplate) { @ChangeSet(order = "063", id = "mark-instance-unregistered", author = "") public void markInstanceAsUnregistered(MongoTemplate mongoTemplate) { - mongoTemplate.insert(new Config( - new JSONObject(Map.of("value", false)), - Appsmith.APPSMITH_REGISTERED - )); + mongoTemplate.insert(new Config(new JSONObject(Map.of("value", false)), Appsmith.APPSMITH_REGISTERED)); } @ChangeSet(order = "065", id = "create-entry-in-sequence-per-organization-for-datasource", author = "") @@ -2168,7 +2154,10 @@ public void createEntryInSequencePerOrganizationForDatasource(MongoTemplate mong .find(query(where("name").regex("^Untitled datasource \\d+$")), Datasource.class) .forEach(datasource -> { long count = 1; - String datasourceCnt = datasource.getName().substring("Untitled datasource ".length()).trim(); + String datasourceCnt = datasource + .getName() + .substring("Untitled datasource ".length()) + .trim(); if (!datasourceCnt.isEmpty()) { count = Long.parseLong(datasourceCnt); } @@ -2200,14 +2189,12 @@ public void migrateSmartSubstitutionDataTypeBoolean(MongoTemplate mongoTemplate, pluginPackages.add("mongo-plugin"); pluginPackages.add("mssql-plugin"); - Set<String> smartSubPlugins = mongoTemplate - .find(query(where("packageName").in(pluginPackages)), Plugin.class) - .stream() - .map(plugin -> plugin.getId()) - .collect(Collectors.toSet()); + Set<String> smartSubPlugins = + mongoTemplate.find(query(where("packageName").in(pluginPackages)), Plugin.class).stream() + .map(plugin -> plugin.getId()) + .collect(Collectors.toSet()); - List<NewAction> actions = mongoTemplate - .find(query(where("pluginId").in(smartSubPlugins)), NewAction.class); + List<NewAction> actions = mongoTemplate.find(query(where("pluginId").in(smartSubPlugins)), NewAction.class); // Find all the action ids where the data migration needs to happen. for (NewAction action : actions) { @@ -2234,7 +2221,8 @@ public void migrateSmartSubstitutionDataTypeBoolean(MongoTemplate mongoTemplate, } } } else if (pluginSpecifiedTemplates == null) { - // No pluginSpecifiedTemplates array exists. This is possible when an action was created before + // No pluginSpecifiedTemplates array exists. This is possible when an action was created + // before // the smart substitution feature was available noSmartSubConfig.add(action.getId()); } @@ -2247,15 +2235,13 @@ public void migrateSmartSubstitutionDataTypeBoolean(MongoTemplate mongoTemplate, mongoOperations.updateMulti( query(where("_id").in(smartSubTurnedOn)), new Update().set("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.0.value", true), - NewAction.class - ); + NewAction.class); // Migrate actions where smart substitution is turned off mongoOperations.updateMulti( query(where("_id").in(smartSubTurnedOff)), new Update().set("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.0.value", false), - NewAction.class - ); + NewAction.class); Property property = new Property(); property.setValue(false); @@ -2263,24 +2249,22 @@ public void migrateSmartSubstitutionDataTypeBoolean(MongoTemplate mongoTemplate, mongoOperations.updateMulti( query(where("_id").in(noSmartSubConfig)), new Update().addToSet("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates", property), - NewAction.class - ); + NewAction.class); } @ChangeSet(order = "067", id = "update-mongo-import-from-srv-field", author = "") public void updateMongoImportFromSrvField(MongoTemplate mongoTemplate) { - Plugin mongoPlugin = mongoTemplate - .findOne(query(where("packageName").is("mongo-plugin")), Plugin.class); + Plugin mongoPlugin = mongoTemplate.findOne(query(where("packageName").is("mongo-plugin")), Plugin.class); - List<Datasource> mongoDatasources = mongoTemplate - .find(query(where("pluginId").is(mongoPlugin.getId())), Datasource.class); + List<Datasource> mongoDatasources = + mongoTemplate.find(query(where("pluginId").is(mongoPlugin.getId())), Datasource.class); - mongoDatasources.stream() - .forEach(datasource -> { - datasource.getDatasourceConfiguration().setProperties(List.of(new Property("Use Mongo Connection " + - "String URI", "No"))); - mongoTemplate.save(datasource); - }); + mongoDatasources.stream().forEach(datasource -> { + datasource + .getDatasourceConfiguration() + .setProperties(List.of(new Property("Use Mongo Connection " + "String URI", "No"))); + mongoTemplate.save(datasource); + }); } @ChangeSet(order = "068", id = "delete-mongo-datasource-structures", author = "") @@ -2291,10 +2275,10 @@ public void deleteMongoDatasourceStructures(MongoTemplate mongoTemplate, MongoOp // made for these datasources, the server would re-compute the structure. Plugin mongoPlugin = mongoTemplate.findOne(query(where("packageName").is("mongo-plugin")), Plugin.class); - Query query = query(new Criteria().andOperator( - where(fieldName(QDatasource.datasource.pluginId)).is(mongoPlugin.getId()), - where("structure").exists(true) - )); + Query query = query(new Criteria() + .andOperator( + where(fieldName(QDatasource.datasource.pluginId)).is(mongoPlugin.getId()), + where("structure").exists(true))); Update update = new Update().set("structure", null); @@ -2302,7 +2286,6 @@ public void deleteMongoDatasourceStructures(MongoTemplate mongoTemplate, MongoOp mongoOperations.updateMulti(query, update, Datasource.class); } - @ChangeSet(order = "069", id = "set-mongo-actions-type-to-raw", author = "") public void setMongoActionInputToRaw(MongoTemplate mongoTemplate) { @@ -2313,23 +2296,29 @@ public void setMongoActionInputToRaw(MongoTemplate mongoTemplate) { // Fetch all the actions built on top of a mongo database, not having any value set for input type assert mongoPlugin != null; - List<NewAction> rawMongoActions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(mongoPlugin.getId()))), - NewAction.class - ) + List<NewAction> rawMongoActions = mongoTemplate + .find( + query(new Criteria() + .andOperator(where(fieldName(QNewAction.newAction.pluginId)) + .is(mongoPlugin.getId()))), + NewAction.class) .stream() .filter(mongoAction -> { - if (mongoAction.getUnpublishedAction() == null || mongoAction.getUnpublishedAction().getActionConfiguration() == null) { + if (mongoAction.getUnpublishedAction() == null + || mongoAction.getUnpublishedAction().getActionConfiguration() == null) { return false; } - final List<Property> pluginSpecifiedTemplates = mongoAction.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + final List<Property> pluginSpecifiedTemplates = mongoAction + .getUnpublishedAction() + .getActionConfiguration() + .getPluginSpecifiedTemplates(); return pluginSpecifiedTemplates != null && pluginSpecifiedTemplates.size() == 1; }) .collect(Collectors.toList()); for (NewAction action : rawMongoActions) { - List<Property> pluginSpecifiedTemplates = action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + List<Property> pluginSpecifiedTemplates = + action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); pluginSpecifiedTemplates.add(new Property(null, "RAW")); mongoTemplate.save(action); @@ -2345,102 +2334,114 @@ public void setMongoActionInputToRaw(MongoTemplate mongoTemplate) { */ @ChangeSet(order = "070", id = "update-firestore-where-conditions-data", author = "") public void updateFirestoreWhereConditionsData(MongoTemplate mongoTemplate) { - Plugin firestorePlugin = mongoTemplate - .findOne(query(where("packageName").is("firestore-plugin")), Plugin.class); - - Query query = query(new Criteria().andOperator( - where("pluginId").is(firestorePlugin.getId()), - new Criteria().orOperator( - where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.3").exists(true), - where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.4").exists(true), - where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.5").exists(true), - where("publishedAction.actionConfiguration.pluginSpecifiedTemplates.3").exists(true), - where("publishedAction.actionConfiguration.pluginSpecifiedTemplates.4").exists(true), - where("publishedAction.actionConfiguration.pluginSpecifiedTemplates.5").exists(true) - ))); + Plugin firestorePlugin = + mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), Plugin.class); + + Query query = query(new Criteria() + .andOperator( + where("pluginId").is(firestorePlugin.getId()), + new Criteria() + .orOperator( + where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.3") + .exists(true), + where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.4") + .exists(true), + where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.5") + .exists(true), + where("publishedAction.actionConfiguration.pluginSpecifiedTemplates.3") + .exists(true), + where("publishedAction.actionConfiguration.pluginSpecifiedTemplates.4") + .exists(true), + where("publishedAction.actionConfiguration.pluginSpecifiedTemplates.5") + .exists(true)))); List<NewAction> firestoreActionQueries = mongoTemplate.find(query, NewAction.class); - firestoreActionQueries.stream() - .forEach(action -> { - // For unpublished action - if (action.getUnpublishedAction() != null - && action.getUnpublishedAction().getActionConfiguration() != null - && action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates() != null - && action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates().size() > 3) { - - String path = null; - String op = null; - String value = null; - List<Property> properties = action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); - if (properties.size() > 3 && properties.get(3) != null) { - path = (String) properties.get(3).getValue(); - } - if (properties.size() > 4 && properties.get(4) != null) { - op = (String) properties.get(4).getValue(); - properties.set(4, null); // Index 4 does not map to any value in the new query format - } - if (properties.size() > 5 && properties.get(5) != null) { - value = (String) properties.get(5).getValue(); - properties.set(5, null); // Index 5 does not map to any value in the new query format - } + firestoreActionQueries.stream().forEach(action -> { + // For unpublished action + if (action.getUnpublishedAction() != null + && action.getUnpublishedAction().getActionConfiguration() != null + && action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates() != null + && action.getUnpublishedAction() + .getActionConfiguration() + .getPluginSpecifiedTemplates() + .size() + > 3) { + + String path = null; + String op = null; + String value = null; + List<Property> properties = + action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + if (properties.size() > 3 && properties.get(3) != null) { + path = (String) properties.get(3).getValue(); + } + if (properties.size() > 4 && properties.get(4) != null) { + op = (String) properties.get(4).getValue(); + properties.set(4, null); // Index 4 does not map to any value in the new query format + } + if (properties.size() > 5 && properties.get(5) != null) { + value = (String) properties.get(5).getValue(); + properties.set(5, null); // Index 5 does not map to any value in the new query format + } - Map newFormat = new HashMap(); - newFormat.put("path", path); - newFormat.put("operator", op); - newFormat.put("value", value); - properties.set(3, new Property("whereConditionTuples", List.of(newFormat))); - } + Map newFormat = new HashMap(); + newFormat.put("path", path); + newFormat.put("operator", op); + newFormat.put("value", value); + properties.set(3, new Property("whereConditionTuples", List.of(newFormat))); + } - // For published action - if (action.getPublishedAction() != null - && action.getPublishedAction().getActionConfiguration() != null - && action.getPublishedAction().getActionConfiguration().getPluginSpecifiedTemplates() != null - && action.getPublishedAction().getActionConfiguration().getPluginSpecifiedTemplates().size() > 3) { - - String path = null; - String op = null; - String value = null; - List<Property> properties = action.getPublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); - if (properties.size() > 3 && properties.get(3) != null) { - path = (String) properties.get(3).getValue(); - } - if (properties.size() > 4 && properties.get(4) != null) { - op = (String) properties.get(4).getValue(); - properties.set(4, null); // Index 4 does not map to any value in the new query format - } - if (properties.size() > 5 && properties.get(5) != null) { - value = (String) properties.get(5).getValue(); - properties.set(5, null); // Index 5 does not map to any value in the new query format - } + // For published action + if (action.getPublishedAction() != null + && action.getPublishedAction().getActionConfiguration() != null + && action.getPublishedAction().getActionConfiguration().getPluginSpecifiedTemplates() != null + && action.getPublishedAction() + .getActionConfiguration() + .getPluginSpecifiedTemplates() + .size() + > 3) { + + String path = null; + String op = null; + String value = null; + List<Property> properties = + action.getPublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + if (properties.size() > 3 && properties.get(3) != null) { + path = (String) properties.get(3).getValue(); + } + if (properties.size() > 4 && properties.get(4) != null) { + op = (String) properties.get(4).getValue(); + properties.set(4, null); // Index 4 does not map to any value in the new query format + } + if (properties.size() > 5 && properties.get(5) != null) { + value = (String) properties.get(5).getValue(); + properties.set(5, null); // Index 5 does not map to any value in the new query format + } - HashMap newFormat = new HashMap(); - newFormat.put("path", path); - newFormat.put("operator", op); - newFormat.put("value", value); - properties.set(3, new Property("whereConditionTuples", List.of(newFormat))); - } - }); + HashMap newFormat = new HashMap(); + newFormat.put("path", path); + newFormat.put("operator", op); + newFormat.put("value", value); + properties.set(3, new Property("whereConditionTuples", List.of(newFormat))); + } + }); /** * - Save changes only after all the processing is done so that in case any data manipulation fails, no data * write occurs. * - Write data back to db only if all data manipulations done above have succeeded. */ - firestoreActionQueries.stream() - .forEach(action -> mongoTemplate.save(action)); + firestoreActionQueries.stream().forEach(action -> mongoTemplate.save(action)); } @ChangeSet(order = "071", id = "add-application-export-permissions", author = "") public void addApplicationExportPermissions(MongoTemplate mongoTemplate) { - final List<Organization> organizations = mongoTemplate.find( - query(where("userRoles").exists(true)), - Organization.class - ); + final List<Organization> organizations = + mongoTemplate.find(query(where("userRoles").exists(true)), Organization.class); for (final Organization organization : organizations) { - Set<String> adminUsernames = organization.getUserRoles() - .stream() + Set<String> adminUsernames = organization.getUserRoles().stream() .filter(role -> (role.getRole().equals(AppsmithRole.ORGANIZATION_ADMIN))) .map(role -> role.getUsername()) .collect(Collectors.toSet()); @@ -2458,15 +2459,18 @@ public void addApplicationExportPermissions(MongoTemplate mongoTemplate) { } Optional<Policy> exportAppOrgLevelOptional = policies.stream() - .filter(policy -> policy.getPermission().equals(WORKSPACE_EXPORT_APPLICATIONS.getValue())).findFirst(); + .filter(policy -> policy.getPermission().equals(WORKSPACE_EXPORT_APPLICATIONS.getValue())) + .findFirst(); if (exportAppOrgLevelOptional.isPresent()) { Policy exportApplicationPolicy = exportAppOrgLevelOptional.get(); exportApplicationPolicy.getUsers().addAll(exportApplicationPermissionUsernames); } else { // this policy doesnt exist. create and add this to the policy set - Policy inviteUserPolicy = Policy.builder().permission(WORKSPACE_EXPORT_APPLICATIONS.getValue()) - .users(exportApplicationPermissionUsernames).build(); + Policy inviteUserPolicy = Policy.builder() + .permission(WORKSPACE_EXPORT_APPLICATIONS.getValue()) + .users(exportApplicationPermissionUsernames) + .build(); organization.getPolicies().add(inviteUserPolicy); } @@ -2474,9 +2478,9 @@ public void addApplicationExportPermissions(MongoTemplate mongoTemplate) { // Update the applications with export applications policy for all administrators of the organization List<Application> orgApplications = mongoTemplate.find( - query(where(fieldName(QApplication.application.organizationId)).is(organization.getId())), - Application.class - ); + query(where(fieldName(QApplication.application.organizationId)) + .is(organization.getId())), + Application.class); for (final Application application : orgApplications) { Set<Policy> applicationPolicies = application.getPolicies(); @@ -2485,15 +2489,18 @@ public void addApplicationExportPermissions(MongoTemplate mongoTemplate) { } Optional<Policy> exportAppOptional = applicationPolicies.stream() - .filter(policy -> policy.getPermission().equals(EXPORT_APPLICATIONS.getValue())).findFirst(); + .filter(policy -> policy.getPermission().equals(EXPORT_APPLICATIONS.getValue())) + .findFirst(); if (exportAppOptional.isPresent()) { Policy exportAppPolicy = exportAppOptional.get(); exportAppPolicy.getUsers().addAll(adminUsernames); } else { // this policy doesn't exist, create and add this to the policy set - Policy newExportAppPolicy = Policy.builder().permission(EXPORT_APPLICATIONS.getValue()) - .users(adminUsernames).build(); + Policy newExportAppPolicy = Policy.builder() + .permission(EXPORT_APPLICATIONS.getValue()) + .users(adminUsernames) + .build(); application.getPolicies().add(newExportAppPolicy); } @@ -2543,17 +2550,22 @@ public void migrateUpdateOneToUpdateManyMongoFormCommand(MongoTemplate mongoTemp // Fetch all the actions built on top of a mongo database with command type update_one or update_many assert mongoPlugin != null; - List<NewAction> updateMongoActions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(mongoPlugin.getId()))), - NewAction.class - ) + List<NewAction> updateMongoActions = mongoTemplate + .find( + query(new Criteria() + .andOperator(where(fieldName(QNewAction.newAction.pluginId)) + .is(mongoPlugin.getId()))), + NewAction.class) .stream() .filter(mongoAction -> { - if (mongoAction.getUnpublishedAction() == null || mongoAction.getUnpublishedAction().getActionConfiguration() == null) { + if (mongoAction.getUnpublishedAction() == null + || mongoAction.getUnpublishedAction().getActionConfiguration() == null) { return false; } - final List<Property> pluginSpecifiedTemplates = mongoAction.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + final List<Property> pluginSpecifiedTemplates = mongoAction + .getUnpublishedAction() + .getActionConfiguration() + .getPluginSpecifiedTemplates(); // Filter out all the actions which are of either of the two update command type if (pluginSpecifiedTemplates != null && pluginSpecifiedTemplates.size() == 21) { @@ -2571,7 +2583,8 @@ public void migrateUpdateOneToUpdateManyMongoFormCommand(MongoTemplate mongoTemp .collect(Collectors.toList()); for (NewAction action : updateMongoActions) { - List<Property> pluginSpecifiedTemplates = action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + List<Property> pluginSpecifiedTemplates = + action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); String command = (String) pluginSpecifiedTemplates.get(2).getValue(); // In case of update one, migrate the query and update configurations. @@ -2609,7 +2622,6 @@ public void migrateUpdateOneToUpdateManyMongoFormCommand(MongoTemplate mongoTemp List<Property> updatedTemplates = generateMongoFormConfigTemplates(configMap); action.getUnpublishedAction().getActionConfiguration().setPluginSpecifiedTemplates(updatedTemplates); - } } @@ -2619,23 +2631,18 @@ public void migrateUpdateOneToUpdateManyMongoFormCommand(MongoTemplate mongoTemp } } - @ChangeSet(order = "074", id = "ensure-user-created-and-updated-at-fields", author = "") public void ensureUserCreatedAndUpdatedAt(MongoTemplate mongoTemplate) { - final List<User> missingCreatedAt = mongoTemplate.find( - query(where("createdAt").exists(false)), - User.class - ); + final List<User> missingCreatedAt = + mongoTemplate.find(query(where("createdAt").exists(false)), User.class); for (User user : missingCreatedAt) { user.setCreatedAt(Instant.parse("2019-01-07T00:00:00.00Z")); mongoTemplate.save(user); } - final List<User> missingUpdatedAt = mongoTemplate.find( - query(where("updatedAt").exists(false)), - User.class - ); + final List<User> missingUpdatedAt = + mongoTemplate.find(query(where("updatedAt").exists(false)), User.class); for (User user : missingUpdatedAt) { user.setUpdatedAt(Instant.now()); @@ -2654,7 +2661,7 @@ public void ensureUserCreatedAndUpdatedAt(MongoTemplate mongoTemplate) { @ChangeSet(order = "075", id = "add-and-update-order-for-all-pages", author = "") public void addOrderToAllPagesOfApplication(MongoTemplate mongoTemplate) { for (Application application : mongoTemplate.findAll(Application.class)) { - //Commenting out this piece code as we have decided to remove the order field from ApplicationPages + // Commenting out this piece code as we have decided to remove the order field from ApplicationPages /*if(application.getPages() != null) { int i = 0; for (ApplicationPage page : application.getPages()) { @@ -2680,19 +2687,24 @@ public void migrateRawInputTypeToRawCommand(MongoTemplate mongoTemplate) { // Fetch all the actions built on top of a mongo database with input type set to raw. assert mongoPlugin != null; - List<NewAction> rawMongoQueryActions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(mongoPlugin.getId()))), - NewAction.class - ) + List<NewAction> rawMongoQueryActions = mongoTemplate + .find( + query(new Criteria() + .andOperator(where(fieldName(QNewAction.newAction.pluginId)) + .is(mongoPlugin.getId()))), + NewAction.class) .stream() .filter(mongoAction -> { boolean result = false; - if (mongoAction.getUnpublishedAction() == null || mongoAction.getUnpublishedAction().getActionConfiguration() == null) { + if (mongoAction.getUnpublishedAction() == null + || mongoAction.getUnpublishedAction().getActionConfiguration() == null) { return false; } - List<Property> pluginSpecifiedTemplates = mongoAction.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + List<Property> pluginSpecifiedTemplates = mongoAction + .getUnpublishedAction() + .getActionConfiguration() + .getPluginSpecifiedTemplates(); // Filter out all the unpublished actions which have the input type raw configured. if (pluginSpecifiedTemplates != null && pluginSpecifiedTemplates.size() >= 2) { @@ -2707,7 +2719,8 @@ public void migrateRawInputTypeToRawCommand(MongoTemplate mongoTemplate) { ActionDTO publishedAction = mongoAction.getPublishedAction(); if (publishedAction != null && publishedAction.getActionConfiguration() != null) { - pluginSpecifiedTemplates = publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); + pluginSpecifiedTemplates = + publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); // Filter out all the published actions which have the input type raw configured. if (pluginSpecifiedTemplates != null && pluginSpecifiedTemplates.size() >= 2) { @@ -2732,7 +2745,8 @@ public void migrateRawInputTypeToRawCommand(MongoTemplate mongoTemplate) { List<Property> updatedTemplates; // Migrate the unpublished actions - List<Property> pluginSpecifiedTemplates = action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + List<Property> pluginSpecifiedTemplates = + action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); if (pluginSpecifiedTemplates != null) { smartSubProperty = pluginSpecifiedTemplates.get(0); if (smartSubProperty != null) { @@ -2752,11 +2766,11 @@ public void migrateRawInputTypeToRawCommand(MongoTemplate mongoTemplate) { action.getUnpublishedAction().getActionConfiguration().setPluginSpecifiedTemplates(updatedTemplates); } - // Now migrate the published actions ActionDTO publishedAction = action.getPublishedAction(); if (publishedAction != null && publishedAction.getActionConfiguration() != null) { - pluginSpecifiedTemplates = publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); + pluginSpecifiedTemplates = + publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); if (pluginSpecifiedTemplates != null) { smartSub = true; @@ -2859,7 +2873,8 @@ public void removePageOrderFieldFromApplicationPages(MongoTemplate mongoTemplate public void createPluginReferenceForGenerateCRUDPage(MongoTemplate mongoTemplate) { final String templatePageNameForSQLDatasource = "SQL"; - final Set<String> sqlPackageNames = Set.of("mysql-plugin", "mssql-plugin", "redshift-plugin", "snowflake-plugin"); + final Set<String> sqlPackageNames = + Set.of("mysql-plugin", "mssql-plugin", "redshift-plugin", "snowflake-plugin"); Set<String> validPackageNames = new HashSet<>(sqlPackageNames); validPackageNames.add("mongo-plugin"); validPackageNames.add("postgres-plugin"); @@ -2920,15 +2935,12 @@ private void encryptPathValueIfExists(Document document, String path, Encryption * e.g. 'base64Content' in "datasourceConfiguration.connection.ssl.keyFile.base64Content" */ parentDocument.computeIfPresent( - pathKeys[pathKeys.length - 1], - (k, v) -> encryptionService.encryptString((String) v) - ); + pathKeys[pathKeys.length - 1], (k, v) -> encryptionService.encryptString((String) v)); } } private void encryptRawValues(Document document, List<String> pathList, EncryptionService encryptionService) { - pathList.stream() - .forEach(path -> encryptPathValueIfExists(document, path, encryptionService)); + pathList.stream().forEach(path -> encryptPathValueIfExists(document, path, encryptionService)); } @ChangeSet(order = "081", id = "encrypt-certificate", author = "") @@ -2950,17 +2962,16 @@ public void encryptCertificateAndPassword(MongoTemplate mongoTemplate, Encryptio mongoTemplate.execute("datasource", new CollectionCallback<String>() { @Override public String doInCollection(MongoCollection<Document> collection) { - MongoCursor cursor = collection.find( - Filters.or( + MongoCursor cursor = collection + .find(Filters.or( Filters.exists(pathList.get(0)), Filters.exists(pathList.get(1)), Filters.exists(pathList.get(2)), Filters.exists(pathList.get(3)), Filters.exists(pathList.get(4)), Filters.exists(pathList.get(5)), - Filters.exists(pathList.get(6)) - ) - ).cursor(); + Filters.exists(pathList.get(6)))) + .cursor(); List<Pair<Document, Document>> documentPairList = new ArrayList<>(); while (cursor.hasNext()) { @@ -3003,7 +3014,6 @@ public void createPluginReferenceForS3AndGSheetGenerateCRUDPage(MongoTemplate mo public void addApplicationGitMetadataFieldAndIndex(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, Application.class, "organization_application_compound_index"); dropIndexIfExists(mongoTemplate, Application.class, "organization_application_deleted_compound_index"); - } @ChangeSet(order = "084", id = "add-js-plugin", author = "") @@ -3030,9 +3040,9 @@ public void addJSPlugin(MongoTemplate mongoTemplate) { public void updateGoogleSheetActionsSetSmartSubstitutionConfiguration(MongoTemplate mongoTemplate) { Plugin googleSheetPlugin = mongoTemplate.findOne( - query(new Criteria().andOperator( - where(fieldName(QPlugin.plugin.packageName)).is("google-sheets-plugin") - )), + query(new Criteria() + .andOperator( + where(fieldName(QPlugin.plugin.packageName)).is("google-sheets-plugin"))), Plugin.class); if (googleSheetPlugin == null) { @@ -3041,11 +3051,10 @@ public void updateGoogleSheetActionsSetSmartSubstitutionConfiguration(MongoTempl // Fetch all the actions built on top of a google sheet plugin List<NewAction> googleSheetActions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(googleSheetPlugin.getId()) - )), - NewAction.class - ); + query(new Criteria() + .andOperator( + where(fieldName(QNewAction.newAction.pluginId)).is(googleSheetPlugin.getId()))), + NewAction.class); Set<String> toMigrateUnPublishedActions = new HashSet<>(); Set<String> toMigratePublishedActions = new HashSet<>(); @@ -3055,7 +3064,8 @@ public void updateGoogleSheetActionsSetSmartSubstitutionConfiguration(MongoTempl toMigrateUnPublishedActions.add(action.getId()); } - if (action.getPublishedAction() != null && action.getPublishedAction().getActionConfiguration() != null) { + if (action.getPublishedAction() != null + && action.getPublishedAction().getActionConfiguration() != null) { toMigratePublishedActions.add(action.getId()); } } @@ -3066,24 +3076,20 @@ public void updateGoogleSheetActionsSetSmartSubstitutionConfiguration(MongoTempl mongoTemplate.updateMulti( query(where("_id").in(toMigrateUnPublishedActions)), new Update().set("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.13", smartSubProperty), - NewAction.class - ); + NewAction.class); // Migrate published actions mongoTemplate.updateMulti( query(where("_id").in(toMigratePublishedActions)), new Update().set("publishedAction.actionConfiguration.pluginSpecifiedTemplates.13", smartSubProperty), - NewAction.class - ); + NewAction.class); } @ChangeSet(order = "086", id = "uninstall-mongo-uqi-plugin", author = "") public void uninstallMongoUqiPluginAndRemoveAllActions(MongoTemplate mongoTemplate) { - Plugin mongoUqiPlugin = mongoTemplate.findAndRemove( - query(where("packageName").is("mongo-uqi-plugin")), - Plugin.class - ); + Plugin mongoUqiPlugin = + mongoTemplate.findAndRemove(query(where("packageName").is("mongo-uqi-plugin")), Plugin.class); if (mongoUqiPlugin == null) { // If there's no installed plugin for the same, don't go any further. @@ -3096,16 +3102,14 @@ public void uninstallMongoUqiPluginAndRemoveAllActions(MongoTemplate mongoTempla // do nothing } - final Set<String> installedPlugins = organization - .getPlugins() - .stream() + final Set<String> installedPlugins = organization.getPlugins().stream() .map(WorkspacePlugin::getPluginId) .collect(Collectors.toSet()); if (installedPlugins.contains(mongoUqiPlugin.getId())) { - WorkspacePlugin mongoUqiOrganizationPlugin = organization.getPlugins() - .stream() - .filter(organizationPlugin -> organizationPlugin.getPluginId().equals(mongoUqiPlugin.getId())) + WorkspacePlugin mongoUqiOrganizationPlugin = organization.getPlugins().stream() + .filter(organizationPlugin -> + organizationPlugin.getPluginId().equals(mongoUqiPlugin.getId())) .findFirst() .get(); @@ -3115,22 +3119,18 @@ public void uninstallMongoUqiPluginAndRemoveAllActions(MongoTemplate mongoTempla } // Delete all mongo uqi datasources - List<Datasource> removedDatasources = mongoTemplate.findAllAndRemove( - query(where("pluginId").is(mongoUqiPlugin.getId())), - Datasource.class - ); + List<Datasource> removedDatasources = + mongoTemplate.findAllAndRemove(query(where("pluginId").is(mongoUqiPlugin.getId())), Datasource.class); // Now delete all the actions created on top of mongo uqi datasources for (Datasource deletedDatasource : removedDatasources) { mongoTemplate.findAllAndRemove( - query(where("unpublishedAction.datasource.id").is(deletedDatasource.getId())), - NewAction.class - ); + query(where("unpublishedAction.datasource.id").is(deletedDatasource.getId())), NewAction.class); } } - public final static Map<Integer, String> mongoMigrationMap = Map.ofEntries( - Map.entry(0, "smartSubstitution"), //SMART_BSON_SUBSTITUTION + public static final Map<Integer, String> mongoMigrationMap = Map.ofEntries( + Map.entry(0, "smartSubstitution"), // SMART_BSON_SUBSTITUTION Map.entry(2, "command"), // COMMAND Map.entry(19, "collection"), // COLLECTION Map.entry(3, "find.query"), // FIND_QUERY @@ -3148,7 +3148,7 @@ public void uninstallMongoUqiPluginAndRemoveAllActions(MongoTemplate mongoTempla Map.entry(16, "distinct.key"), // DISTINCT_KEY Map.entry(17, "aggregate.arrayPipelines"), // AGGREGATE_PIPELINE Map.entry(18, "insert.documents") // INSERT_DOCUMENT - ); + ); private void updateFormData(int index, Object value, Map formData, Map<Integer, String> migrationMap) { if (migrationMap.containsKey(index)) { @@ -3157,7 +3157,8 @@ private void updateFormData(int index, Object value, Map formData, Map<Integer, } } - public Map iteratePluginSpecifiedTemplatesAndCreateFormData(List<Property> pluginSpecifiedTemplates, Map<Integer, String> migrationMap) { + public Map iteratePluginSpecifiedTemplatesAndCreateFormData( + List<Property> pluginSpecifiedTemplates, Map<Integer, String> migrationMap) { if (pluginSpecifiedTemplates != null && !pluginSpecifiedTemplates.isEmpty()) { Map<String, Object> formData = new HashMap<>(); @@ -3177,41 +3178,44 @@ public Map iteratePluginSpecifiedTemplatesAndCreateFormData(List<Property> plugi public void migrateMongoPluginToUqi(MongoTemplate mongoTemplate) { // First update the UI component for the mongo plugin to UQI - Plugin mongoPlugin = mongoTemplate.findOne( - query(where("packageName").is("mongo-plugin")), - Plugin.class - ); + Plugin mongoPlugin = mongoTemplate.findOne(query(where("packageName").is("mongo-plugin")), Plugin.class); mongoPlugin.setUiComponent("UQIDbEditorForm"); mongoTemplate.save(mongoPlugin); // Now migrate all the existing actions to the new UQI structure. List<NewAction> mongoActions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(mongoPlugin.getId()))), - NewAction.class - ); + query(new Criteria() + .andOperator( + where(fieldName(QNewAction.newAction.pluginId)).is(mongoPlugin.getId()))), + NewAction.class); for (NewAction mongoAction : mongoActions) { - if (mongoAction.getUnpublishedAction() == null || mongoAction.getUnpublishedAction().getActionConfiguration() == null) { + if (mongoAction.getUnpublishedAction() == null + || mongoAction.getUnpublishedAction().getActionConfiguration() == null) { // No migrations required continue; } - List<Property> pluginSpecifiedTemplates = mongoAction.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + List<Property> pluginSpecifiedTemplates = + mongoAction.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); - mongoAction.getUnpublishedAction().getActionConfiguration().setFormData( - iteratePluginSpecifiedTemplatesAndCreateFormData(pluginSpecifiedTemplates, mongoMigrationMap) - ); + mongoAction + .getUnpublishedAction() + .getActionConfiguration() + .setFormData(iteratePluginSpecifiedTemplatesAndCreateFormData( + pluginSpecifiedTemplates, mongoMigrationMap)); mongoAction.getUnpublishedAction().getActionConfiguration().setPluginSpecifiedTemplates(null); ActionDTO publishedAction = mongoAction.getPublishedAction(); - if (publishedAction.getActionConfiguration() != null && - publishedAction.getActionConfiguration().getPluginSpecifiedTemplates() != null) { - pluginSpecifiedTemplates = publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); - publishedAction.getActionConfiguration().setFormData( - iteratePluginSpecifiedTemplatesAndCreateFormData(pluginSpecifiedTemplates, mongoMigrationMap) - ); + if (publishedAction.getActionConfiguration() != null + && publishedAction.getActionConfiguration().getPluginSpecifiedTemplates() != null) { + pluginSpecifiedTemplates = + publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); + publishedAction + .getActionConfiguration() + .setFormData(iteratePluginSpecifiedTemplatesAndCreateFormData( + pluginSpecifiedTemplates, mongoMigrationMap)); publishedAction.getActionConfiguration().setPluginSpecifiedTemplates(null); } @@ -3222,28 +3226,28 @@ public void migrateMongoPluginToUqi(MongoTemplate mongoTemplate) { @ChangeSet(order = "088", id = "migrate-mongo-uqi-dynamicBindingPathList", author = "") public void migrateMongoPluginDynamicBindingListUqi(MongoTemplate mongoTemplate) { - Plugin mongoPlugin = mongoTemplate.findOne( - query(where("packageName").is("mongo-plugin")), - Plugin.class - ); + Plugin mongoPlugin = mongoTemplate.findOne(query(where("packageName").is("mongo-plugin")), Plugin.class); // Now migrate all the existing actions dynamicBindingList to the new UQI structure. List<NewAction> mongoActions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(mongoPlugin.getId()) - )), - NewAction.class - ); + query(new Criteria() + .andOperator( + where(fieldName(QNewAction.newAction.pluginId)).is(mongoPlugin.getId()))), + NewAction.class); for (NewAction mongoAction : mongoActions) { - if (mongoAction.getUnpublishedAction() == null || - mongoAction.getUnpublishedAction().getDynamicBindingPathList() == null || - mongoAction.getUnpublishedAction().getDynamicBindingPathList().isEmpty()) { + if (mongoAction.getUnpublishedAction() == null + || mongoAction.getUnpublishedAction().getDynamicBindingPathList() == null + || mongoAction + .getUnpublishedAction() + .getDynamicBindingPathList() + .isEmpty()) { // No migrations required continue; } - List<Property> dynamicBindingPathList = mongoAction.getUnpublishedAction().getDynamicBindingPathList(); + List<Property> dynamicBindingPathList = + mongoAction.getUnpublishedAction().getDynamicBindingPathList(); List<Property> newDynamicBindingPathList = new ArrayList<>(); for (Property path : dynamicBindingPathList) { @@ -3274,13 +3278,15 @@ public void migrateMongoPluginDynamicBindingListUqi(MongoTemplate mongoTemplate) @ChangeSet(order = "089", id = "update-plugin-package-name-index", author = "") public void updatePluginPackageNameIndexToPluginNamePackageNameAndVersion(MongoTemplate mongoTemplate) { -// MongoTemplate mongoTemplate = mongoTemplate.getImpl(); + // MongoTemplate mongoTemplate = mongoTemplate.getImpl(); dropIndexIfExists(mongoTemplate, Plugin.class, "packageName"); - ensureIndexes(mongoTemplate, Plugin.class, + ensureIndexes( + mongoTemplate, + Plugin.class, makeIndex("pluginName", "packageName", "version") - .unique().named("plugin_name_package_name_version_index") - ); + .unique() + .named("plugin_name_package_name_version_index")); } @ChangeSet(order = "090", id = "delete-orphan-actions", author = "") @@ -3289,7 +3295,8 @@ public void deleteOrphanActions(MongoTemplate mongoTemplate) { deletionUpdates.set(fieldName(QNewAction.newAction.deleted), true); deletionUpdates.set(fieldName(QNewAction.newAction.deletedAt), Instant.now()); - final Query actionQuery = query(where(fieldName(QNewAction.newAction.deleted)).ne(true)); + final Query actionQuery = + query(where(fieldName(QNewAction.newAction.deleted)).ne(true)); actionQuery.fields().include(fieldName(QNewAction.newAction.applicationId)); final List<NewAction> actions = mongoTemplate.find(actionQuery, NewAction.class); @@ -3297,20 +3304,19 @@ public void deleteOrphanActions(MongoTemplate mongoTemplate) { for (final NewAction action : actions) { final String applicationId = action.getApplicationId(); - final boolean shouldDelete = StringUtils.isEmpty(applicationId) || mongoTemplate.exists( - query( - where(fieldName(QApplication.application.id)).is(applicationId) - .and(fieldName(QApplication.application.deleted)).is(true) - ), - Application.class - ); + final boolean shouldDelete = StringUtils.isEmpty(applicationId) + || mongoTemplate.exists( + query(where(fieldName(QApplication.application.id)) + .is(applicationId) + .and(fieldName(QApplication.application.deleted)) + .is(true)), + Application.class); if (shouldDelete) { mongoTemplate.updateFirst( query(where(fieldName(QNewAction.newAction.id)).is(action.getId())), deletionUpdates, - NewAction.class - ); + NewAction.class); } } } @@ -3318,16 +3324,16 @@ public void deleteOrphanActions(MongoTemplate mongoTemplate) { @ChangeSet(order = "091", id = "migrate-old-app-color-to-new-colors", author = "") public void migrateOldAppColorsToNewColors(MongoTemplate mongoTemplate) { String[] oldColors = { - "#FF6786", "#FFAD5E", "#FCD43E", "#B0E968", "#5CE7EF", "#69B5FF", "#9177FF", "#FF76FE", - "#61DF48", "#FF597B", "#6698FF", "#F8C356", "#6C4CF1", "#C5CD90", "#6272C8", "#4F70FD", - "#6CD0CF", "#A8D76C", "#5EDA82", "#6C9DD0", "#F56AF4", "#5ED3DA", "#B94CF1", "#BC6DB2", - "#EA6179", "#FE9F44", "#E9C951", "#ED86A1", "#54A9FB", "#F36380", "#C03C3C" + "#FF6786", "#FFAD5E", "#FCD43E", "#B0E968", "#5CE7EF", "#69B5FF", "#9177FF", "#FF76FE", + "#61DF48", "#FF597B", "#6698FF", "#F8C356", "#6C4CF1", "#C5CD90", "#6272C8", "#4F70FD", + "#6CD0CF", "#A8D76C", "#5EDA82", "#6C9DD0", "#F56AF4", "#5ED3DA", "#B94CF1", "#BC6DB2", + "#EA6179", "#FE9F44", "#E9C951", "#ED86A1", "#54A9FB", "#F36380", "#C03C3C" }; String[] newColors = { - "#FFDEDE", "#FFEFDB", "#F3F1C7", "#F4FFDE", "#C7F3F0", "#D9E7FF", "#E3DEFF", "#F1DEFF", - "#C7F3E3", "#F5D1D1", "#ECECEC", "#FBF4ED", "#D6D1F2", "#FFEBFB", "#EAEDFB", "#D6D1F2", - "#C7F3F0", "#F4FFDE", "#C7F3E3", "#D9E7FF", "#F1DEFF", "#C7F3F0", "#D6D1F2", "#F1DEFF", - "#F5D1D1", "#FFEFDB", "#F3F1C7", "#FFEBFB", "#D9E7FF", "#FFDEDE", "#F5D1D1" + "#FFDEDE", "#FFEFDB", "#F3F1C7", "#F4FFDE", "#C7F3F0", "#D9E7FF", "#E3DEFF", "#F1DEFF", + "#C7F3E3", "#F5D1D1", "#ECECEC", "#FBF4ED", "#D6D1F2", "#FFEBFB", "#EAEDFB", "#D6D1F2", + "#C7F3F0", "#F4FFDE", "#C7F3E3", "#D9E7FF", "#F1DEFF", "#C7F3F0", "#D6D1F2", "#F1DEFF", + "#F5D1D1", "#FFEFDB", "#F3F1C7", "#FFEBFB", "#D9E7FF", "#FFDEDE", "#F5D1D1" }; for (int i = 0; i < oldColors.length; i++) { @@ -3336,10 +3342,12 @@ public void migrateOldAppColorsToNewColors(MongoTemplate mongoTemplate) { // Migrate old color to new color String colorFieldName = fieldName(QApplication.application.color); mongoTemplate.updateMulti( - query(where(colorFieldName).is(oldColor).and(fieldName(QApplication.application.deleted)).is(false)), + query(where(colorFieldName) + .is(oldColor) + .and(fieldName(QApplication.application.deleted)) + .is(false)), new Update().set(colorFieldName, newColor), - Application.class - ); + Application.class); } } @@ -3354,10 +3362,7 @@ public void migrateOldAppColorsToNewColors(MongoTemplate mongoTemplate) { */ @ChangeSet(order = "092", id = "update-s3-permanent-url-toggle-default-value", author = "") public void updateS3PermanentUrlToggleDefaultValue(MongoTemplate mongoTemplate) { - Plugin s3Plugin = mongoTemplate.findOne( - query(where("packageName").is("amazons3-plugin")), - Plugin.class - ); + Plugin s3Plugin = mongoTemplate.findOne(query(where("packageName").is("amazons3-plugin")), Plugin.class); /** * Query to find all S3 actions such that: @@ -3365,33 +3370,37 @@ public void updateS3PermanentUrlToggleDefaultValue(MongoTemplate mongoTemplate) * o permanent url property either does not exist or the property is null or the property's value is null - * indicating that the property has not been set. */ - Query missingToggleQuery = query(new Criteria().andOperator( - where("pluginId").is(s3Plugin.getId()), - where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.0.value").is("LIST"), - new Criteria().orOperator( - where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.8").exists(false), - where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.8").is(null), - where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.8.value").is(null) - ) - )); + Query missingToggleQuery = query(new Criteria() + .andOperator( + where("pluginId").is(s3Plugin.getId()), + where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.0.value") + .is("LIST"), + new Criteria() + .orOperator( + where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.8") + .exists(false), + where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.8") + .is(null), + where("unpublishedAction.actionConfiguration.pluginSpecifiedTemplates.8.value") + .is(null)))); List<NewAction> s3ListActionObjectsWithNoToggleValue = mongoTemplate.find(missingToggleQuery, NewAction.class); // Replace old pluginSpecifiedTemplates with updated pluginSpecifiedTemplates. - s3ListActionObjectsWithNoToggleValue.stream() - .forEach(action -> { - List<Property> oldPluginSpecifiedTemplates = - action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); - List<Property> newPluginSpecifiedTemplates = setS3ListActionDefaults(oldPluginSpecifiedTemplates); - action.getUnpublishedAction().getActionConfiguration().setPluginSpecifiedTemplates(newPluginSpecifiedTemplates); - }); + s3ListActionObjectsWithNoToggleValue.stream().forEach(action -> { + List<Property> oldPluginSpecifiedTemplates = + action.getUnpublishedAction().getActionConfiguration().getPluginSpecifiedTemplates(); + List<Property> newPluginSpecifiedTemplates = setS3ListActionDefaults(oldPluginSpecifiedTemplates); + action.getUnpublishedAction() + .getActionConfiguration() + .setPluginSpecifiedTemplates(newPluginSpecifiedTemplates); + }); /** * Save changes only after all the processing is done so that in case any data manipulation fails, no data * write occurs. * Write data back to db only if all data manipulations done above have succeeded. */ - s3ListActionObjectsWithNoToggleValue.stream() - .forEach(action -> mongoTemplate.save(action)); + s3ListActionObjectsWithNoToggleValue.stream().forEach(action -> mongoTemplate.save(action)); } /** @@ -3447,13 +3456,20 @@ public void updateGitApplicationMetadataIndex(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, Application.class, "organization_application_compound_index"); dropIndexIfExists(mongoTemplate, Application.class, "organization_application_deleted_compound_index"); - ensureIndexes(mongoTemplate, Application.class, - makeIndex("organizationId", "name", "deletedAt", "gitApplicationMetadata.remoteUrl", "gitApplicationMetadata.branchName") - .unique().named("organization_name_deleted_gitApplicationMetadata") - ); + ensureIndexes( + mongoTemplate, + Application.class, + makeIndex( + "organizationId", + "name", + "deletedAt", + "gitApplicationMetadata.remoteUrl", + "gitApplicationMetadata.branchName") + .unique() + .named("organization_name_deleted_gitApplicationMetadata")); } - public final static Map<Integer, List<String>> s3MigrationMap = Map.ofEntries( + public static final Map<Integer, List<String>> s3MigrationMap = Map.ofEntries( Map.entry(0, List.of("command")), Map.entry(1, List.of("bucket")), Map.entry(2, List.of("list.signedUrl")), @@ -3462,8 +3478,7 @@ public void updateGitApplicationMetadataIndex(MongoTemplate mongoTemplate) { Map.entry(5, List.of("read.usingBase64Encoding")), Map.entry(6, List.of("create.dataType", "read.dataType")), Map.entry(7, List.of("create.expiry", "read.expiry", "delete.expiry")), - Map.entry(8, List.of("list.unSignedUrl")) - ); + Map.entry(8, List.of("list.unSignedUrl"))); /** * This class is meant to hold any method that is required to transform data before migrating the data to UQI @@ -3488,7 +3503,7 @@ public Object transformData(String pluginName, String transformationName, Object } switch (pluginName) { - /* Data transformations for Firestore plugin are defined in this case. */ + /* Data transformations for Firestore plugin are defined in this case. */ case FIRESTORE_PLUGIN_NAME: /** * This case takes care of transforming Firestore's where clause data to UQI's where @@ -3508,17 +3523,16 @@ public Object transformData(String pluginName, String transformationName, Object oldListOfConditions = new ArrayList<>(); } - oldListOfConditions.stream() - .forEachOrdered(oldCondition -> { - /* Map old values to keys in the new UQI format. */ - Map<String, Object> uqiCondition = new HashMap<>(); - uqiCondition.put(CONDITION_KEY, oldCondition.get(OPERATOR_KEY)); - uqiCondition.put(KEY, oldCondition.get(PATH_KEY)); - uqiCondition.put(VALUE_KEY, oldCondition.get(VALUE_KEY)); + oldListOfConditions.stream().forEachOrdered(oldCondition -> { + /* Map old values to keys in the new UQI format. */ + Map<String, Object> uqiCondition = new HashMap<>(); + uqiCondition.put(CONDITION_KEY, oldCondition.get(OPERATOR_KEY)); + uqiCondition.put(KEY, oldCondition.get(PATH_KEY)); + uqiCondition.put(VALUE_KEY, oldCondition.get(VALUE_KEY)); - /* Add condition to the UQI where clause. */ - ((List) uqiWhereMap.get(CHILDREN_KEY)).add(uqiCondition); - }); + /* Add condition to the UQI where clause. */ + ((List) uqiWhereMap.get(CHILDREN_KEY)).add(uqiCondition); + }); return uqiWhereMap; } @@ -3527,33 +3541,37 @@ public Object transformData(String pluginName, String transformationName, Object * Throw error since no handler could be found for the pluginName and transformationName * combination. */ - String transformationKeyNotFoundErrorMessage = "Data transformer failed to find any " + - "matching case for plugin: " + pluginName + " and key: " + transformationName + ". Please " + - "contact Appsmith customer support to resolve this."; + String transformationKeyNotFoundErrorMessage = + "Data transformer failed to find any " + "matching case for plugin: " + + pluginName + " and key: " + transformationName + ". Please " + + "contact Appsmith customer support to resolve this."; assert false : transformationKeyNotFoundErrorMessage; break; default: /* Throw error since no handler could be found for the plugin matching pluginName */ - String noPluginHandlerFoundErrorMessage = "Data transformer failed to find any matching case for " + - "plugin: " + pluginName + ". Please contact Appsmith customer support to resolve this."; + String noPluginHandlerFoundErrorMessage = "Data transformer failed to find any matching case for " + + "plugin: " + pluginName + ". Please contact Appsmith customer support to resolve this."; assert false : noPluginHandlerFoundErrorMessage; } /* Execution flow is never expected to reach here. */ - String badExecutionFlowErrorMessage = "Execution flow is never supposed to reach here. Please contact " + - "Appsmith customer support to resolve this."; + String badExecutionFlowErrorMessage = "Execution flow is never supposed to reach here. Please contact " + + "Appsmith customer support to resolve this."; assert false : badExecutionFlowErrorMessage; return value; } } - private void updateFormDataMultipleOptions(int index, Object value, Map formData, - Map<Integer, List<String>> migrationMap, - Map<Integer, String> uqiDataTransformationMap, - UQIMigrationDataTransformer dataTransformer, - String pluginName) { + private void updateFormDataMultipleOptions( + int index, + Object value, + Map formData, + Map<Integer, List<String>> migrationMap, + Map<Integer, String> uqiDataTransformationMap, + UQIMigrationDataTransformer dataTransformer, + String pluginName) { if (migrationMap.containsKey(index)) { if (dataTransformer != null && uqiDataTransformationMap.containsKey(index)) { String transformationKey = uqiDataTransformationMap.get(index); @@ -3566,17 +3584,26 @@ private void updateFormDataMultipleOptions(int index, Object value, Map formData } } - public Map iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions(List<Property> pluginSpecifiedTemplates, - Map<Integer, List<String>> migrationMap, Map<Integer, String> uqiDataTransformationMap, - UQIMigrationDataTransformer dataTransformer, String pluginName) { + public Map iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions( + List<Property> pluginSpecifiedTemplates, + Map<Integer, List<String>> migrationMap, + Map<Integer, String> uqiDataTransformationMap, + UQIMigrationDataTransformer dataTransformer, + String pluginName) { if (pluginSpecifiedTemplates != null && !pluginSpecifiedTemplates.isEmpty()) { Map<String, Object> formData = new HashMap<>(); for (int i = 0; i < pluginSpecifiedTemplates.size(); i++) { Property template = pluginSpecifiedTemplates.get(i); if (template != null) { - updateFormDataMultipleOptions(i, template.getValue(), formData, migrationMap, - uqiDataTransformationMap, dataTransformer, pluginName); + updateFormDataMultipleOptions( + i, + template.getValue(), + formData, + migrationMap, + uqiDataTransformationMap, + dataTransformer, + pluginName); } } @@ -3589,20 +3616,16 @@ public Map iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions(List< @ChangeSet(order = "094", id = "migrate-s3-to-uqi", author = "") public void migrateS3PluginToUqi(MongoTemplate mongoTemplate) { // First update the UI component for the s3 plugin to UQI - Plugin s3Plugin = mongoTemplate.findOne( - query(where("packageName").is("amazons3-plugin")), - Plugin.class - ); + Plugin s3Plugin = mongoTemplate.findOne(query(where("packageName").is("amazons3-plugin")), Plugin.class); s3Plugin.setUiComponent("UQIDbEditorForm"); - // Now migrate all the existing actions to the new UQI structure. List<NewAction> s3Actions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(s3Plugin.getId()))), - NewAction.class - ); + query(new Criteria() + .andOperator( + where(fieldName(QNewAction.newAction.pluginId)).is(s3Plugin.getId()))), + NewAction.class); List<NewAction> actionsToSave = new ArrayList<>(); @@ -3615,29 +3638,32 @@ public void migrateS3PluginToUqi(MongoTemplate mongoTemplate) { continue; } - List<Property> pluginSpecifiedTemplates = unpublishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); + List<Property> pluginSpecifiedTemplates = + unpublishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); - unpublishedAction.getActionConfiguration().setFormData( - iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions(pluginSpecifiedTemplates, - s3MigrationMap, null, null, null) - ); + unpublishedAction + .getActionConfiguration() + .setFormData(iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions( + pluginSpecifiedTemplates, s3MigrationMap, null, null, null)); unpublishedAction.getActionConfiguration().setPluginSpecifiedTemplates(null); ActionDTO publishedAction = s3Action.getPublishedAction(); - if (publishedAction != null && publishedAction.getActionConfiguration() != null && - publishedAction.getActionConfiguration().getPluginSpecifiedTemplates() != null) { - pluginSpecifiedTemplates = publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); - publishedAction.getActionConfiguration().setFormData( - iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions(pluginSpecifiedTemplates, - s3MigrationMap, null, null, null) - ); + if (publishedAction != null + && publishedAction.getActionConfiguration() != null + && publishedAction.getActionConfiguration().getPluginSpecifiedTemplates() != null) { + pluginSpecifiedTemplates = + publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); + publishedAction + .getActionConfiguration() + .setFormData(iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions( + pluginSpecifiedTemplates, s3MigrationMap, null, null, null)); publishedAction.getActionConfiguration().setPluginSpecifiedTemplates(null); } // Migrate the dynamic binding path list for unpublished action List<Property> dynamicBindingPathList = unpublishedAction.getDynamicBindingPathList(); - List<Property> newDynamicBindingPathList = getUpdatedDynamicBindingPathList(dynamicBindingPathList, - objectMapper, s3Action, s3MigrationMap); + List<Property> newDynamicBindingPathList = + getUpdatedDynamicBindingPathList(dynamicBindingPathList, objectMapper, s3Action, s3MigrationMap); unpublishedAction.setDynamicBindingPathList(newDynamicBindingPathList); actionsToSave.add(s3Action); @@ -3661,9 +3687,11 @@ public void migrateS3PluginToUqi(MongoTemplate mongoTemplate) { * reference, please check out the `s3MigrationMap` defined above. * @return : updated dynamicBindingPathList - ported to UQI model. */ - static List<Property> getUpdatedDynamicBindingPathList(List<Property> dynamicBindingPathList, - ObjectMapper objectMapper, NewAction action, - Map<Integer, List<String>> migrationMap) { + static List<Property> getUpdatedDynamicBindingPathList( + List<Property> dynamicBindingPathList, + ObjectMapper objectMapper, + NewAction action, + Map<Integer, List<String>> migrationMap) { // Return if empty. if (CollectionUtils.isEmpty(dynamicBindingPathList)) { return dynamicBindingPathList; @@ -3692,12 +3720,12 @@ static List<Property> getUpdatedDynamicBindingPathList(List<Property> dynamicBin } // We may have an invalid dynamic binding. Trim the same - List<String> dynamicBindingPathNames = newDynamicBindingPathList - .stream() + List<String> dynamicBindingPathNames = newDynamicBindingPathList.stream() .map(property -> property.getKey()) .collect(Collectors.toList()); - Set<String> pathsToRemove = getInvalidDynamicBindingPathsInAction(objectMapper, action, dynamicBindingPathNames); + Set<String> pathsToRemove = + getInvalidDynamicBindingPathsInAction(objectMapper, action, dynamicBindingPathNames); // We have found atleast 1 invalid dynamic binding path. if (!pathsToRemove.isEmpty()) { @@ -3705,8 +3733,7 @@ static List<Property> getUpdatedDynamicBindingPathList(List<Property> dynamicBin dynamicBindingPathNames.removeAll(pathsToRemove); // Transform the set of paths to Property as it is stored in the db. - List<Property> updatedDynamicBindingPathList = dynamicBindingPathNames - .stream() + List<Property> updatedDynamicBindingPathList = dynamicBindingPathNames.stream() .map(dynamicBindingPath -> { Property property = new Property(); property.setKey(dynamicBindingPath); @@ -3726,50 +3753,49 @@ static List<Property> getUpdatedDynamicBindingPathList(List<Property> dynamicBin public void setSlugToApplicationAndPage(MongoTemplate mongoTemplate) { // update applications final Query applicationQuery = query(where("deletedAt").is(null)); - applicationQuery.fields() - .include(fieldName(QApplication.application.name)); + applicationQuery.fields().include(fieldName(QApplication.application.name)); List<Application> applications = mongoTemplate.find(applicationQuery, Application.class); for (Application application : applications) { mongoTemplate.updateFirst( query(where(fieldName(QApplication.application.id)).is(application.getId())), - new Update().set(fieldName(QApplication.application.slug), TextUtils.makeSlug(application.getName())), - Application.class - ); + new Update() + .set(fieldName(QApplication.application.slug), TextUtils.makeSlug(application.getName())), + Application.class); } // update pages final Query pageQuery = query(where("deletedAt").is(null)); - pageQuery.fields() - .include(String.format("%s.%s", - fieldName(QNewPage.newPage.unpublishedPage), fieldName(QNewPage.newPage.unpublishedPage.name) - )) - .include(String.format("%s.%s", - fieldName(QNewPage.newPage.publishedPage), fieldName(QNewPage.newPage.publishedPage.name) - )); + pageQuery + .fields() + .include(String.format( + "%s.%s", + fieldName(QNewPage.newPage.unpublishedPage), fieldName(QNewPage.newPage.unpublishedPage.name))) + .include(String.format( + "%s.%s", + fieldName(QNewPage.newPage.publishedPage), fieldName(QNewPage.newPage.publishedPage.name))); List<NewPage> pages = mongoTemplate.find(pageQuery, NewPage.class); for (NewPage page : pages) { Update update = new Update(); if (page.getUnpublishedPage() != null) { - String fieldName = String.format("%s.%s", - fieldName(QNewPage.newPage.unpublishedPage), fieldName(QNewPage.newPage.unpublishedPage.slug) - ); - update = update.set(fieldName, TextUtils.makeSlug(page.getUnpublishedPage().getName())); + String fieldName = String.format( + "%s.%s", + fieldName(QNewPage.newPage.unpublishedPage), fieldName(QNewPage.newPage.unpublishedPage.slug)); + update = update.set( + fieldName, TextUtils.makeSlug(page.getUnpublishedPage().getName())); } if (page.getPublishedPage() != null) { - String fieldName = String.format("%s.%s", - fieldName(QNewPage.newPage.publishedPage), fieldName(QNewPage.newPage.publishedPage.slug) - ); - update = update.set(fieldName, TextUtils.makeSlug(page.getPublishedPage().getName())); + String fieldName = String.format( + "%s.%s", + fieldName(QNewPage.newPage.publishedPage), fieldName(QNewPage.newPage.publishedPage.slug)); + update = update.set( + fieldName, TextUtils.makeSlug(page.getPublishedPage().getName())); } mongoTemplate.updateFirst( - query(where(fieldName(QNewPage.newPage.id)).is(page.getId())), - update, - NewPage.class - ); + query(where(fieldName(QNewPage.newPage.id)).is(page.getId())), update, NewPage.class); } } @@ -3799,9 +3825,12 @@ private DslUpdateDto updateListWidgetTriggerPaths(DslUpdateDto dslUpdateDto) { String[] fields = fieldPath.split("[].\\[]"); // For nested fields, the parent dsl to search in would shift by one level every iteration Object parent = dsl; - Iterator<String> fieldsIterator = Arrays.stream(fields).filter(fieldToken -> !fieldToken.isBlank()).iterator(); + Iterator<String> fieldsIterator = Arrays.stream(fields) + .filter(fieldToken -> !fieldToken.isBlank()) + .iterator(); boolean isLeafNode = false; - // This loop will end at either a leaf node, or the last identified JSON field (by throwing an exception) + // This loop will end at either a leaf node, or the last identified JSON field (by throwing an + // exception) // Valid forms of the fieldPath for this search could be: // root.field.list[index].childField.anotherList.indexWithDotOperator.multidimensionalList[index1][index2] while (fieldsIterator.hasNext()) { @@ -3844,8 +3873,10 @@ private DslUpdateDto updateListWidgetTriggerPaths(DslUpdateDto dslUpdateDto) { } } - // Check if the newly computed trigger paths are different from the existing ones and if true, set it in the dsl - if (dynamicTriggerPaths.size() != newTriggerPaths.size() || !newTriggerPaths.containsAll(dynamicTriggerPaths)) { + // Check if the newly computed trigger paths are different from the existing ones and if true, set it in + // the dsl + if (dynamicTriggerPaths.size() != newTriggerPaths.size() + || !newTriggerPaths.containsAll(dynamicTriggerPaths)) { updated = Boolean.TRUE; List<Object> finalTriggerPaths = new ArrayList<>(); for (String triggerPath : newTriggerPaths) { @@ -3882,30 +3913,23 @@ private DslUpdateDto updateListWidgetTriggerPaths(DslUpdateDto dslUpdateDto) { @ChangeSet(order = "095", id = "update-list-widget-trigger-paths", author = "") public void removeUnusedTriggerPathsListWidget(MongoTemplate mongoTemplate) { - // Find all the pages which haven't been deleted - final Criteria possibleCandidatePagesCriteria = new Criteria().andOperator( - where("deletedAt").is(null), - where("unpublishedPage.layouts.0.dsl").exists(true) - ); + final Criteria possibleCandidatePagesCriteria = new Criteria() + .andOperator( + where("deletedAt").is(null), + where("unpublishedPage.layouts.0.dsl").exists(true)); Query pageQuery = query(possibleCandidatePagesCriteria); - pageQuery.fields() - .include(fieldName(QNewPage.newPage.id)); + pageQuery.fields().include(fieldName(QNewPage.newPage.id)); - final List<NewPage> pages = mongoTemplate.find( - pageQuery, - NewPage.class - ); + final List<NewPage> pages = mongoTemplate.find(pageQuery, NewPage.class); for (NewPage onlyIdPage : pages) { // Fetch one action at a time to avoid OOM. NewPage page = mongoTemplate.findOne( - query(where(fieldName(QNewPage.newPage.id)).is(onlyIdPage.getId())), - NewPage.class - ); + query(where(fieldName(QNewPage.newPage.id)).is(onlyIdPage.getId())), NewPage.class); List<Layout> layouts = page.getUnpublishedPage().getLayouts(); @@ -3919,7 +3943,8 @@ public void removeUnusedTriggerPathsListWidget(MongoTemplate mongoTemplate) { if (!CollectionUtils.isEmpty(layouts)) { layout = layouts.get(0); // update the dsl - dslUpdateDto = updateListWidgetTriggerPaths(new DslUpdateDto(layout.getDsl(), dslUpdateDto.getUpdated())); + dslUpdateDto = + updateListWidgetTriggerPaths(new DslUpdateDto(layout.getDsl(), dslUpdateDto.getUpdated())); layout.setDsl(dslUpdateDto.getDsl()); } } @@ -3940,17 +3965,14 @@ public void removeUnusedTriggerPathsListWidget(MongoTemplate mongoTemplate) { */ @ChangeSet(order = "096", id = "update-s3-action-configuration-for-type", author = "") public void updateS3ActionConfigurationBodyForContentTypeSupport(MongoTemplate mongoTemplate) { - Plugin s3Plugin = mongoTemplate.findOne( - query(where("packageName").is("amazons3-plugin")), - Plugin.class - ); + Plugin s3Plugin = mongoTemplate.findOne(query(where("packageName").is("amazons3-plugin")), Plugin.class); // Find all S3 actions List<NewAction> s3Actions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(s3Plugin.getId()))), - NewAction.class - ); + query(new Criteria() + .andOperator( + where(fieldName(QNewAction.newAction.pluginId)).is(s3Plugin.getId()))), + NewAction.class); List<NewAction> actionsToSave = new ArrayList<>(); @@ -3962,13 +3984,15 @@ public void updateS3ActionConfigurationBodyForContentTypeSupport(MongoTemplate m continue; } - final String oldUnpublishedBody = unpublishedAction.getActionConfiguration().getBody(); + final String oldUnpublishedBody = + unpublishedAction.getActionConfiguration().getBody(); final String newUnpublishedBody = "{\n\t\"data\": \"" + oldUnpublishedBody + "\"\n}"; unpublishedAction.getActionConfiguration().setBody(newUnpublishedBody); ActionDTO publishedAction = s3Action.getPublishedAction(); if (publishedAction != null && publishedAction.getActionConfiguration() != null) { - final String oldPublishedBody = publishedAction.getActionConfiguration().getBody(); + final String oldPublishedBody = + publishedAction.getActionConfiguration().getBody(); final String newPublishedBody = "{\n\t\"data\": \"" + oldPublishedBody + "\"\n}"; publishedAction.getActionConfiguration().setBody(newPublishedBody); } @@ -3991,30 +4015,27 @@ public void updateS3ActionConfigurationBodyForContentTypeSupport(MongoTemplate m */ @ChangeSet(order = "097", id = "fix-ispublic-is-false-for-public-apps", author = "") public void fixIsPublicIsSetFalseWhenAppIsPublic(MongoTemplate mongoTemplate) { - Query query = query( - where("isPublic").is(false) - .and("deleted").is(false) - .and("policies").elemMatch( - where("permission").is("read:applications").and("users").is("anonymousUser") - ) - ); + Query query = query(where("isPublic") + .is(false) + .and("deleted") + .is(false) + .and("policies") + .elemMatch( + where("permission").is("read:applications").and("users").is("anonymousUser"))); Update update = new Update().set("isPublic", true); mongoTemplate.updateMulti(query, update, Application.class); } @ChangeSet(order = "098", id = "update-js-action-client-side-execution", author = "") public void updateJsActionsClientSideExecution(MongoTemplate mongoTemplate) { - Plugin jsPlugin = mongoTemplate.findOne( - query(where("packageName").is("js-plugin")), - Plugin.class - ); + Plugin jsPlugin = mongoTemplate.findOne(query(where("packageName").is("js-plugin")), Plugin.class); // Find all JS actions List<NewAction> jsActions = mongoTemplate.find( - query(new Criteria().andOperator( - where(fieldName(QNewAction.newAction.pluginId)).is(jsPlugin.getId()))), - NewAction.class - ); + query(new Criteria() + .andOperator( + where(fieldName(QNewAction.newAction.pluginId)).is(jsPlugin.getId()))), + NewAction.class); List<NewAction> actionsToSave = new ArrayList<>(); @@ -4064,18 +4085,16 @@ public void addSmtpPluginPlugin(MongoTemplate mongoTemplate) { @ChangeSet(order = "100", id = "update-mockdb-endpoint", author = "") public void updateMockdbEndpoint(MongoTemplate mongoTemplate) { mongoTemplate.updateMulti( - query(where("datasourceConfiguration.endpoints.host").is("fake-api.cvuydmurdlas.us-east-1.rds.amazonaws.com")), + query(where("datasourceConfiguration.endpoints.host") + .is("fake-api.cvuydmurdlas.us-east-1.rds.amazonaws.com")), update("datasourceConfiguration.endpoints.$.host", "mockdb.internal.appsmith.com"), - Datasource.class - ); + Datasource.class); } @ChangeSet(order = "101", id = "add-google-sheets-plugin-name", author = "") public void addPluginNameForGoogleSheets(MongoTemplate mongoTemplate) { - Plugin googleSheetsPlugin = mongoTemplate.findOne( - query(where("packageName").is("google-sheets-plugin")), - Plugin.class - ); + Plugin googleSheetsPlugin = + mongoTemplate.findOne(query(where("packageName").is("google-sheets-plugin")), Plugin.class); assert googleSheetsPlugin != null; googleSheetsPlugin.setPluginName("google-sheets-plugin"); @@ -4087,9 +4106,11 @@ public void addPluginNameForGoogleSheets(MongoTemplate mongoTemplate) { public void insertDefaultResources(MongoTemplate mongoTemplate) { // Update datasources - final Query datasourceQuery = query(where(fieldName(QDatasource.datasource.deleted)).ne(true)); + final Query datasourceQuery = + query(where(fieldName(QDatasource.datasource.deleted)).ne(true)); - datasourceQuery.fields() + datasourceQuery + .fields() .include(fieldName(QDatasource.datasource.id)) .include(fieldName(QDatasource.datasource.organizationId)); @@ -4101,12 +4122,12 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { mongoTemplate.updateFirst( query(where(fieldName(QDatasource.datasource.id)).is(datasource.getId())), update, - Datasource.class - ); + Datasource.class); } // Update default page Ids in pages and publishedPages for all existing applications - final Query applicationQuery = query(where(fieldName(QApplication.application.deleted)).ne(true)) + final Query applicationQuery = query( + where(fieldName(QApplication.application.deleted)).ne(true)) .addCriteria(where(fieldName(QApplication.application.pages)).exists(true)); List<Application> applications = mongoTemplate.find(applicationQuery, Application.class); @@ -4125,8 +4146,7 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { // Update pages for defaultIds (applicationId, pageId) along-with the defaultActionIds for onPageLoadActions final Query pageQuery = query(where(fieldName(QNewPage.newPage.deleted)).ne(true)); - pageQuery.fields() - .include(fieldName(QNewPage.newPage.id)); + pageQuery.fields().include(fieldName(QNewPage.newPage.id)); List<NewPage> pages = mongoTemplate.find(pageQuery, NewPage.class); @@ -4134,9 +4154,7 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { // Fetch one page at a time to avoid OOM. NewPage page = mongoTemplate.findOne( - query(where(fieldName(QNewPage.newPage.id)).is(onlyIdPage.getId())), - NewPage.class - ); + query(where(fieldName(QNewPage.newPage.id)).is(onlyIdPage.getId())), NewPage.class); String applicationId = page.getApplicationId(); final Update defaultResourceUpdates = new Update(); @@ -4151,51 +4169,52 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { defaultResourceUpdates.set(fieldName(QNewPage.newPage.gitSyncId), gitSyncId); if (!CollectionUtils.isEmpty(page.getUnpublishedPage().getLayouts())) { - page.getUnpublishedPage() - .getLayouts() - .stream() + page.getUnpublishedPage().getLayouts().stream() .filter(layout -> !CollectionUtils.isEmpty(layout.getLayoutOnLoadActions())) .forEach(layout -> layout.getLayoutOnLoadActions() - .forEach(dslActionDTOS -> dslActionDTOS.forEach(actionDTO -> actionDTO.setDefaultActionId(actionDTO.getId())))); + .forEach(dslActionDTOS -> dslActionDTOS.forEach( + actionDTO -> actionDTO.setDefaultActionId(actionDTO.getId())))); } - defaultResourceUpdates.set(fieldName(QNewPage.newPage.unpublishedPage) + "." + "layouts", page.getUnpublishedPage().getLayouts()); + defaultResourceUpdates.set( + fieldName(QNewPage.newPage.unpublishedPage) + "." + "layouts", + page.getUnpublishedPage().getLayouts()); - if (page.getPublishedPage() != null && !CollectionUtils.isEmpty(page.getPublishedPage().getLayouts())) { - page.getPublishedPage() - .getLayouts() - .stream() + if (page.getPublishedPage() != null + && !CollectionUtils.isEmpty(page.getPublishedPage().getLayouts())) { + page.getPublishedPage().getLayouts().stream() .filter(layout -> !CollectionUtils.isEmpty(layout.getLayoutOnLoadActions())) .forEach(layout -> layout.getLayoutOnLoadActions() - .forEach(dslActionDTOS -> dslActionDTOS.forEach(actionDTO -> actionDTO.setDefaultActionId(actionDTO.getId())))); + .forEach(dslActionDTOS -> dslActionDTOS.forEach( + actionDTO -> actionDTO.setDefaultActionId(actionDTO.getId())))); - defaultResourceUpdates.set(fieldName(QNewPage.newPage.publishedPage) + "." + "layouts", page.getPublishedPage().getLayouts()); + defaultResourceUpdates.set( + fieldName(QNewPage.newPage.publishedPage) + "." + "layouts", + page.getPublishedPage().getLayouts()); } if (!StringUtils.isEmpty(applicationId)) { mongoTemplate.updateFirst( query(where(fieldName(QNewPage.newPage.id)).is(page.getId())), defaultResourceUpdates, - NewPage.class - ); + NewPage.class); } } // Update actions - final Query actionQuery = query(where(fieldName(QNewAction.newAction.deleted)).ne(true)) - .addCriteria(where(fieldName(QNewAction.newAction.applicationId)).exists(true)); + final Query actionQuery = query( + where(fieldName(QNewAction.newAction.deleted)).ne(true)) + .addCriteria( + where(fieldName(QNewAction.newAction.applicationId)).exists(true)); - actionQuery.fields() - .include(fieldName(QNewAction.newAction.id)); + actionQuery.fields().include(fieldName(QNewAction.newAction.id)); List<NewAction> actions = mongoTemplate.find(actionQuery, NewAction.class); for (NewAction actionIdOnly : actions) { // Fetch one action at a time to avoid OOM. final NewAction action = mongoTemplate.findOne( - query(where(fieldName(QNewAction.newAction.id)).is(actionIdOnly.getId())), - NewAction.class - ); + query(where(fieldName(QNewAction.newAction.id)).is(actionIdOnly.getId())), NewAction.class); String applicationId = action.getApplicationId(); if (StringUtils.isEmpty(applicationId)) { @@ -4214,9 +4233,9 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { unpublishedActionDTODefaults.setPageId(unpublishedAction.getPageId()); unpublishedActionDTODefaults.setCollectionId(unpublishedAction.getCollectionId()); defaultResourceUpdates.set( - fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.defaultResources), - unpublishedActionDTODefaults - ); + fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.defaultResources), + unpublishedActionDTODefaults); } ActionDTO publishedAction = action.getPublishedAction(); @@ -4225,36 +4244,42 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { publishedActionDTODefaults.setPageId(publishedAction.getPageId()); publishedActionDTODefaults.setCollectionId(publishedAction.getCollectionId()); defaultResourceUpdates.set( - fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.defaultResources), - publishedActionDTODefaults - ); + fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.defaultResources), + publishedActionDTODefaults); } // Update gitSyncId final String gitSyncId = applicationId + "_" + new ObjectId(); defaultResourceUpdates.set(fieldName(QNewAction.newAction.gitSyncId), gitSyncId); - mongoTemplate.updateFirst( query(where(fieldName(QNewAction.newAction.id)).is(action.getId())), defaultResourceUpdates, - NewAction.class - ); + NewAction.class); } // Update JS collection - final Query actionCollectionQuery = query(where(fieldName(QActionCollection.actionCollection.deleted)).ne(true)) - .addCriteria(where(fieldName(QActionCollection.actionCollection.applicationId)).exists(true)); + final Query actionCollectionQuery = query(where(fieldName(QActionCollection.actionCollection.deleted)) + .ne(true)) + .addCriteria(where(fieldName(QActionCollection.actionCollection.applicationId)) + .exists(true)); - actionCollectionQuery.fields() + actionCollectionQuery + .fields() .include(fieldName(QActionCollection.actionCollection.applicationId)) - .include(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId)) - .include(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.pageId)) - .include(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.actionIds)) - .include(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.archivedActionIds)) - .include(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.actionIds)) - .include(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.archivedActionIds)); - + .include(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId)) + .include(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName(QActionCollection.actionCollection.publishedCollection.pageId)) + .include(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.actionIds)) + .include(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.archivedActionIds)) + .include(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName(QActionCollection.actionCollection.publishedCollection.actionIds)) + .include(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName(QActionCollection.actionCollection.publishedCollection.archivedActionIds)); List<ActionCollection> collections = mongoTemplate.find(actionCollectionQuery, ActionCollection.class); @@ -4275,34 +4300,43 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { Map<String, String> defaultIdMap = new HashMap<>(); unpublishedCollection.getActionIds().forEach(actionId -> defaultIdMap.put(actionId, actionId)); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.defaultToBranchedActionIdsMap), - defaultIdMap - ); + fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName( + QActionCollection.actionCollection + .unpublishedCollection + .defaultToBranchedActionIdsMap), + defaultIdMap); // Remove actionIds from set as this will now be deprecated defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.actionIds), - null - ); + fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.actionIds), + null); } if (!CollectionUtils.isEmpty(unpublishedCollection.getArchivedActionIds())) { Map<String, String> defaultArchiveIdMap = new HashMap<>(); - unpublishedCollection.getArchivedActionIds().forEach(actionId -> defaultArchiveIdMap.put(actionId, actionId)); + unpublishedCollection + .getArchivedActionIds() + .forEach(actionId -> defaultArchiveIdMap.put(actionId, actionId)); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.defaultToBranchedArchivedActionIdsMap), - defaultArchiveIdMap - ); + fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName( + QActionCollection.actionCollection + .unpublishedCollection + .defaultToBranchedArchivedActionIdsMap), + defaultArchiveIdMap); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.archivedActionIds), - null - ); + fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName( + QActionCollection.actionCollection.unpublishedCollection.archivedActionIds), + null); } DefaultResources unpubDefaults = new DefaultResources(); unpubDefaults.setPageId(unpublishedCollection.getPageId()); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + FieldName.DEFAULT_RESOURCES, - unpubDefaults - ); + fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + FieldName.DEFAULT_RESOURCES, + unpubDefaults); } ActionCollectionDTO publishedCollection = collection.getPublishedCollection(); @@ -4312,36 +4346,45 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { publishedCollection.getActionIds().forEach(actionId -> defaultIdMap.put(actionId, actionId)); publishedCollection.setDefaultToBranchedActionIdsMap(defaultIdMap); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.defaultToBranchedActionIdsMap), - defaultIdMap - ); + fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName( + QActionCollection.actionCollection + .publishedCollection + .defaultToBranchedActionIdsMap), + defaultIdMap); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.actionIds), - null - ); + fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName(QActionCollection.actionCollection.publishedCollection.actionIds), + null); } if (!CollectionUtils.isEmpty(publishedCollection.getArchivedActions())) { Map<String, String> defaultArchiveIdMap = new HashMap<>(); - publishedCollection.getArchivedActionIds().forEach(actionId -> defaultArchiveIdMap.put(actionId, actionId)); + publishedCollection + .getArchivedActionIds() + .forEach(actionId -> defaultArchiveIdMap.put(actionId, actionId)); publishedCollection.setDefaultToBranchedArchivedActionIdsMap(defaultArchiveIdMap); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.defaultToBranchedArchivedActionIdsMap), - defaultArchiveIdMap - ); + fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName( + QActionCollection.actionCollection + .publishedCollection + .defaultToBranchedArchivedActionIdsMap), + defaultArchiveIdMap); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.archivedActionIds), - null - ); + fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName( + QActionCollection.actionCollection.publishedCollection.archivedActionIds), + null); } DefaultResources pubDefaults = new DefaultResources(); pubDefaults.setPageId(publishedCollection.getPageId()); defaultResourceUpdates.set( - fieldName(QActionCollection.actionCollection.publishedCollection) + "." + FieldName.DEFAULT_RESOURCES, - pubDefaults - ); + fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + FieldName.DEFAULT_RESOURCES, + pubDefaults); } // Update gitSyncId @@ -4350,10 +4393,10 @@ public void insertDefaultResources(MongoTemplate mongoTemplate) { if (!StringUtils.isEmpty(applicationId)) { mongoTemplate.updateFirst( - query(where(fieldName(QActionCollection.actionCollection.id)).is(collection.getId())), + query(where(fieldName(QActionCollection.actionCollection.id)) + .is(collection.getId())), defaultResourceUpdates, - ActionCollection.class - ); + ActionCollection.class); } } } @@ -4364,17 +4407,15 @@ public void clearRedisCache(ReactiveRedisOperations<String, String> reactiveRedi } protected static void doClearRedisKeys(ReactiveRedisOperations<String, String> reactiveRedisOperations) { - final String script = - "for _,k in ipairs(redis.call('keys','spring:session:sessions:*'))" + - " do redis.call('del',k) " + - "end"; + final String script = "for _,k in ipairs(redis.call('keys','spring:session:sessions:*'))" + + " do redis.call('del',k) " + "end"; final Flux<Object> flushdb = reactiveRedisOperations.execute(RedisScript.of(script)); flushdb.blockLast(); } /* Map values from pluginSpecifiedTemplates to formData (UQI) */ - public final static Map<Integer, List<String>> firestoreMigrationMap = Map.ofEntries( + public static final Map<Integer, List<String>> firestoreMigrationMap = Map.ofEntries( Map.entry(0, List.of("command")), Map.entry(1, List.of("orderBy")), Map.entry(2, List.of("limitDocuments")), @@ -4384,8 +4425,7 @@ protected static void doClearRedisKeys(ReactiveRedisOperations<String, String> r Map.entry(6, List.of("startAfter")), Map.entry(7, List.of("endBefore")), Map.entry(8, List.of("timestampValuePath")), - Map.entry(9, List.of("deleteKeyPath")) - ); + Map.entry(9, List.of("deleteKeyPath"))); /** * This map indicates which fields in pluginSpecifiedTemplates require a transformation before their data can be @@ -4395,32 +4435,27 @@ protected static void doClearRedisKeys(ReactiveRedisOperations<String, String> r * pluginSpecifiedTemplates needs to be migrated by the rules identified by the string "where-clause-migration". * The rules are defined in the class UQIMigrationDataTransformer. */ - public static final Map<Integer, String> firestoreUQIDataTransformationMap = Map.ofEntries( - Map.entry(3, "where-clause-migration") - ); + public static final Map<Integer, String> firestoreUQIDataTransformationMap = + Map.ofEntries(Map.entry(3, "where-clause-migration")); @ChangeSet(order = "103", id = "migrate-firestore-to-uqi", author = "") public void migrateFirestorePluginToUqi(MongoTemplate mongoTemplate) { // Update Firestore plugin to indicate use of UQI schema - Plugin firestorePlugin = mongoTemplate.findOne( - query(where("packageName").is("firestore-plugin")), - Plugin.class - ); + Plugin firestorePlugin = + mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), Plugin.class); firestorePlugin.setUiComponent("UQIDbEditorForm"); // Find all Firestore actions final Query firestoreActionQuery = query( - where(fieldName(QNewAction.newAction.pluginId)).is(firestorePlugin.getId()) - .and(fieldName(QNewAction.newAction.deleted)).is(true) // Update: Should have been .ne(true) - ); - firestoreActionQuery.fields() - .include(fieldName(QNewAction.newAction.id)); + where(fieldName(QNewAction.newAction.pluginId)) + .is(firestorePlugin.getId()) + .and(fieldName(QNewAction.newAction.deleted)) + .is(true) // Update: Should have been .ne(true) + ); + firestoreActionQuery.fields().include(fieldName(QNewAction.newAction.id)); - List<NewAction> firestoreActions = mongoTemplate.find( - firestoreActionQuery, - NewAction.class - ); + List<NewAction> firestoreActions = mongoTemplate.find(firestoreActionQuery, NewAction.class); migrateFirestoreToUQI(mongoTemplate, firestoreActions); @@ -4433,9 +4468,7 @@ private void migrateFirestoreToUQI(MongoTemplate mongoTemplate, List<NewAction> // Fetch one page at a time to avoid OOM. final NewAction firestoreAction = mongoTemplate.findOne( - query(where(fieldName(QNewAction.newAction.id)).is(firestoreActionId.getId())), - NewAction.class - ); + query(where(fieldName(QNewAction.newAction.id)).is(firestoreActionId.getId())), NewAction.class); ActionDTO unpublishedAction = firestoreAction.getUnpublishedAction(); @@ -4445,22 +4478,27 @@ private void migrateFirestoreToUQI(MongoTemplate mongoTemplate, List<NewAction> } /* It means that earlier migration had succeeded on this action, hence current migration can be skipped. */ - if (!CollectionUtils.isEmpty(unpublishedAction.getActionConfiguration().getFormData())) { + if (!CollectionUtils.isEmpty( + unpublishedAction.getActionConfiguration().getFormData())) { continue; } - List<Property> pluginSpecifiedTemplates = unpublishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); + List<Property> pluginSpecifiedTemplates = + unpublishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); UQIMigrationDataTransformer uqiMigrationDataTransformer = new UQIMigrationDataTransformer(); /** * Migrate unpublished action configuration data. * Create `formData` used in UQI schema from the `pluginSpecifiedTemplates` used earlier. */ - unpublishedAction.getActionConfiguration().setFormData( - iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions(pluginSpecifiedTemplates, - firestoreMigrationMap, firestoreUQIDataTransformationMap, uqiMigrationDataTransformer, - "firestore-plugin") - ); + unpublishedAction + .getActionConfiguration() + .setFormData(iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions( + pluginSpecifiedTemplates, + firestoreMigrationMap, + firestoreUQIDataTransformationMap, + uqiMigrationDataTransformer, + "firestore-plugin")); /* `pluginSpecifiedTemplates` is no longer required since `formData` will be used in UQI schema. */ unpublishedAction.getActionConfiguration().setPluginSpecifiedTemplates(null); @@ -4470,14 +4508,19 @@ private void migrateFirestoreToUQI(MongoTemplate mongoTemplate, List<NewAction> * Create `formData` used in UQI schema from the `pluginSpecifiedTemplates` used earlier. */ ActionDTO publishedAction = firestoreAction.getPublishedAction(); - if (publishedAction != null && publishedAction.getActionConfiguration() != null && - publishedAction.getActionConfiguration().getPluginSpecifiedTemplates() != null) { - pluginSpecifiedTemplates = publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); - publishedAction.getActionConfiguration().setFormData( - iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions(pluginSpecifiedTemplates, - firestoreMigrationMap, firestoreUQIDataTransformationMap, uqiMigrationDataTransformer - , "firestore-plugin") - ); + if (publishedAction != null + && publishedAction.getActionConfiguration() != null + && publishedAction.getActionConfiguration().getPluginSpecifiedTemplates() != null) { + pluginSpecifiedTemplates = + publishedAction.getActionConfiguration().getPluginSpecifiedTemplates(); + publishedAction + .getActionConfiguration() + .setFormData(iteratePluginSpecifiedTemplatesAndCreateFormDataMultipleOptions( + pluginSpecifiedTemplates, + firestoreMigrationMap, + firestoreUQIDataTransformationMap, + uqiMigrationDataTransformer, + "firestore-plugin")); /* `pluginSpecifiedTemplates` is no longer required since `formData` will be used in UQI schema. */ publishedAction.getActionConfiguration().setPluginSpecifiedTemplates(null); @@ -4490,8 +4533,8 @@ private void migrateFirestoreToUQI(MongoTemplate mongoTemplate, List<NewAction> * on unpublished actions data and copied over for the view mode. */ List<Property> dynamicBindingPathList = unpublishedAction.getDynamicBindingPathList(); - List<Property> newDynamicBindingPathList = getUpdatedDynamicBindingPathList(dynamicBindingPathList, - objectMapper, firestoreAction, firestoreMigrationMap); + List<Property> newDynamicBindingPathList = getUpdatedDynamicBindingPathList( + dynamicBindingPathList, objectMapper, firestoreAction, firestoreMigrationMap); unpublishedAction.setDynamicBindingPathList(newDynamicBindingPathList); mongoTemplate.save(firestoreAction); @@ -4506,55 +4549,42 @@ private void migrateFirestoreToUQI(MongoTemplate mongoTemplate, List<NewAction> public void migrateFirestorePluginToUqi2(MongoTemplate mongoTemplate) { // Update Firestore plugin to indicate use of UQI schema - Plugin firestorePlugin = mongoTemplate.findOne( - query(where("packageName").is("firestore-plugin")), - Plugin.class - ); + Plugin firestorePlugin = + mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), Plugin.class); // Find all Firestore actions - final Query firestoreActionQuery = query( - where(fieldName(QNewAction.newAction.pluginId)).is(firestorePlugin.getId()) - .and(fieldName(QNewAction.newAction.deleted)).ne(true)); // setting `deleted` != `true` - firestoreActionQuery.fields() - .include(fieldName(QNewAction.newAction.id)); + final Query firestoreActionQuery = query(where(fieldName(QNewAction.newAction.pluginId)) + .is(firestorePlugin.getId()) + .and(fieldName(QNewAction.newAction.deleted)) + .ne(true)); // setting `deleted` != `true` + firestoreActionQuery.fields().include(fieldName(QNewAction.newAction.id)); - List<NewAction> firestoreActions = mongoTemplate.find( - firestoreActionQuery, - NewAction.class - ); + List<NewAction> firestoreActions = mongoTemplate.find(firestoreActionQuery, NewAction.class); migrateFirestoreToUQI(mongoTemplate, firestoreActions); } @ChangeSet(order = "105", id = "migrate-firestore-pagination-data", author = "") public void migrateFirestorePaginationData(MongoTemplate mongoTemplate) { - Plugin firestorePlugin = mongoTemplate.findOne( - query(where("packageName").is("firestore-plugin")), - Plugin.class - ); + Plugin firestorePlugin = + mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), Plugin.class); // Query to get action id from all Firestore actions - Query queryToGetActionIds = query( - where(fieldName(QNewAction.newAction.pluginId)).is(firestorePlugin.getId()) - .and(fieldName(QNewAction.newAction.deleted)).ne(true) - ); - queryToGetActionIds.fields() - .include(fieldName(QNewAction.newAction.id)); + Query queryToGetActionIds = query(where(fieldName(QNewAction.newAction.pluginId)) + .is(firestorePlugin.getId()) + .and(fieldName(QNewAction.newAction.deleted)) + .ne(true)); + queryToGetActionIds.fields().include(fieldName(QNewAction.newAction.id)); // Get list of Firestore action ids - List<NewAction> firestoreActionIds = mongoTemplate.find( - queryToGetActionIds, - NewAction.class - ); + List<NewAction> firestoreActionIds = mongoTemplate.find(queryToGetActionIds, NewAction.class); // Iterate over each action id and operate on each action one by one. for (NewAction firestoreActionId : firestoreActionIds) { // Fetch one action at a time to avoid OOM. final NewAction firestoreAction = mongoTemplate.findOne( - query(where(fieldName(QNewAction.newAction.id)).is(firestoreActionId.getId())), - NewAction.class - ); + query(where(fieldName(QNewAction.newAction.id)).is(firestoreActionId.getId())), NewAction.class); ActionDTO unpublishedAction = firestoreAction.getUnpublishedAction(); @@ -4565,7 +4595,8 @@ public void migrateFirestorePaginationData(MongoTemplate mongoTemplate) { // Migrate unpublished action config data if (unpublishedAction.getActionConfiguration().getFormData() != null) { - Map<String, Object> formData = unpublishedAction.getActionConfiguration().getFormData(); + Map<String, Object> formData = + unpublishedAction.getActionConfiguration().getFormData(); Object startAfter = PluginUtils.getValueSafelyFromFormData(formData, START_AFTER); if (startAfter == null) { @@ -4582,11 +4613,14 @@ public void migrateFirestorePaginationData(MongoTemplate mongoTemplate) { // Migrate published action config data. ActionDTO publishedAction = firestoreAction.getPublishedAction(); - if (publishedAction != null && publishedAction.getActionConfiguration() != null && - publishedAction.getActionConfiguration().getFormData() != null) { - Map<String, Object> formData = publishedAction.getActionConfiguration().getFormData(); - - String startAfter = PluginUtils.getDataValueSafelyFromFormData(formData, START_AFTER, STRING_TYPE, "{}"); + if (publishedAction != null + && publishedAction.getActionConfiguration() != null + && publishedAction.getActionConfiguration().getFormData() != null) { + Map<String, Object> formData = + publishedAction.getActionConfiguration().getFormData(); + + String startAfter = + PluginUtils.getDataValueSafelyFromFormData(formData, START_AFTER, STRING_TYPE, "{}"); publishedAction.getActionConfiguration().setNext(startAfter); String endBefore = PluginUtils.getDataValueSafelyFromFormData(formData, END_BEFORE, STRING_TYPE, "{}"); @@ -4602,13 +4636,14 @@ public void updateMongoMockdbEndpoint(MongoTemplate mongoTemplate) { mongoTemplate.updateMulti( query(where("datasourceConfiguration.endpoints.host").is("mockdb.swrsq.mongodb.net")), update("datasourceConfiguration.endpoints.$.host", "mockdb.kce5o.mongodb.net"), - Datasource.class - ); + Datasource.class); mongoTemplate.updateMulti( - query(where("datasourceConfiguration.properties.value").is("mongodb+srv://mockdb_super:****@mockdb.swrsq.mongodb.net/movies")), - update("datasourceConfiguration.properties.$.value", "mongodb+srv://mockdb_super:****@mockdb.kce5o.mongodb.net/movies"), - Datasource.class - ); + query(where("datasourceConfiguration.properties.value") + .is("mongodb+srv://mockdb_super:****@mockdb.swrsq.mongodb.net/movies")), + update( + "datasourceConfiguration.properties.$.value", + "mongodb+srv://mockdb_super:****@mockdb.kce5o.mongodb.net/movies"), + Datasource.class); } /** @@ -4618,23 +4653,18 @@ public void updateMongoMockdbEndpoint(MongoTemplate mongoTemplate) { @ChangeSet(order = "107", id = "migrate-firestore-to-uqi-3", author = "") public void migrateFirestorePluginToUqi3(MongoTemplate mongoTemplate) { // Update Firestore plugin to indicate use of UQI schema - Plugin firestorePlugin = mongoTemplate.findOne( - query(where("packageName").is("firestore-plugin")), - Plugin.class - ); + Plugin firestorePlugin = + mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), Plugin.class); firestorePlugin.setUiComponent("UQIDbEditorForm"); // Find all Firestore actions - final Query firestoreActionQuery = query( - where(fieldName(QNewAction.newAction.pluginId)).is(firestorePlugin.getId()) - .and(fieldName(QNewAction.newAction.deleted)).ne(true)); // setting `deleted` != `true` - firestoreActionQuery.fields() - .include(fieldName(QNewAction.newAction.id)); + final Query firestoreActionQuery = query(where(fieldName(QNewAction.newAction.pluginId)) + .is(firestorePlugin.getId()) + .and(fieldName(QNewAction.newAction.deleted)) + .ne(true)); // setting `deleted` != `true` + firestoreActionQuery.fields().include(fieldName(QNewAction.newAction.id)); - List<NewAction> firestoreActions = mongoTemplate.find( - firestoreActionQuery, - NewAction.class - ); + List<NewAction> firestoreActions = mongoTemplate.find(firestoreActionQuery, NewAction.class); migrateFirestoreToUQI(mongoTemplate, firestoreActions); @@ -4656,14 +4686,18 @@ private void updateLimitFieldForEachAction(List<NewAction> mongoActions, MongoTe .filter(this::hasUnpublishedActionConfiguration) .forEachOrdered(mongoAction -> { /* set key for unpublished action */ - Map<String, Object> unpublishedFormData = - mongoAction.getUnpublishedAction().getActionConfiguration().getFormData(); + Map<String, Object> unpublishedFormData = mongoAction + .getUnpublishedAction() + .getActionConfiguration() + .getFormData(); setValueSafelyInFormData(unpublishedFormData, AGGREGATE_LIMIT, DEFAULT_BATCH_SIZE); /* set key for published action */ if (hasPublishedActionConfiguration(mongoAction)) { - Map<String, Object> publishedFormData = - mongoAction.getPublishedAction().getActionConfiguration().getFormData(); + Map<String, Object> publishedFormData = mongoAction + .getPublishedAction() + .getActionConfiguration() + .getFormData(); setValueSafelyInFormData(publishedFormData, AGGREGATE_LIMIT, DEFAULT_BATCH_SIZE); } @@ -4740,8 +4774,8 @@ public boolean hasUnpublishedActionConfiguration(NewAction action) { * @return action */ public static NewAction fetchActionUsingId(String actionId, MongoTemplate mongoTemplate) { - final NewAction action = - mongoTemplate.findOne(query(where(fieldName(QNewAction.newAction.id)).is(actionId)), NewAction.class); + final NewAction action = mongoTemplate.findOne( + query(where(fieldName(QNewAction.newAction.id)).is(actionId)), NewAction.class); return action; } @@ -4767,25 +4801,29 @@ public void updateGitIndexes(MongoTemplate mongoTemplate) { // We can't set unique indexes for following as these requires the _id of the resource to be filled in for // defaultResourceId if the app is not connected to git. This results in handling the _id creation for resources // on our end instead of asking mongo driver to perform this operation - ensureIndexes(mongoTemplate, NewAction.class, + ensureIndexes( + mongoTemplate, + NewAction.class, makeIndex("defaultResources.actionId", "defaultResources.branchName", "deleted") - .named("defaultActionId_branchName_deleted_compound_index") - ); + .named("defaultActionId_branchName_deleted_compound_index")); - ensureIndexes(mongoTemplate, ActionCollection.class, + ensureIndexes( + mongoTemplate, + ActionCollection.class, makeIndex("defaultResources.collectionId", "defaultResources.branchName", "deleted") - .named("defaultCollectionId_branchName_deleted") - ); + .named("defaultCollectionId_branchName_deleted")); - ensureIndexes(mongoTemplate, NewPage.class, + ensureIndexes( + mongoTemplate, + NewPage.class, makeIndex("defaultResources.pageId", "defaultResources.branchName", "deleted") - .named("defaultPageId_branchName_deleted_compound_index") - ); + .named("defaultPageId_branchName_deleted_compound_index")); - ensureIndexes(mongoTemplate, Application.class, + ensureIndexes( + mongoTemplate, + Application.class, makeIndex("gitApplicationMetadata.defaultApplicationId", "gitApplicationMetadata.branchName", "deleted") - .named("defaultApplicationId_branchName_deleted") - ); + .named("defaultApplicationId_branchName_deleted")); } @ChangeSet(order = "111", id = "update-mockdb-endpoint-2", author = "") @@ -4818,13 +4856,13 @@ public void useAssetsCDNForPluginIcons(MongoTemplate mongoTemplate) { query.fields().include(fieldName(QPlugin.plugin.iconLocation)); List<Plugin> plugins = mongoTemplate.find(query, Plugin.class); for (final Plugin plugin : plugins) { - if (plugin.getIconLocation() != null && plugin.getIconLocation().startsWith("https://s3.us-east-2.amazonaws.com/assets.appsmith.com")) { + if (plugin.getIconLocation() != null + && plugin.getIconLocation().startsWith("https://s3.us-east-2.amazonaws.com/assets.appsmith.com")) { final String cdnUrl = plugin.getIconLocation().replace("s3.us-east-2.amazonaws.com/", ""); mongoTemplate.updateFirst( query(where(fieldName(QPlugin.plugin.id)).is(plugin.getId())), update(fieldName(QPlugin.plugin.iconLocation), cdnUrl), - Plugin.class - ); + Plugin.class); } } } @@ -4835,32 +4873,34 @@ public void useAssetsCDNForPluginIcons(MongoTemplate mongoTemplate) { @ChangeSet(order = "114", id = "update-index-for-newAction-actionCollection-userData", author = "") public void updateNewActionActionCollectionAndUserDataIndexes(MongoTemplate mongoTemplate) { - ensureIndexes(mongoTemplate, ActionCollection.class, - makeIndex(FieldName.APPLICATION_ID) - .named("applicationId") - ); + ensureIndexes( + mongoTemplate, + ActionCollection.class, + makeIndex(FieldName.APPLICATION_ID).named("applicationId")); - ensureIndexes(mongoTemplate, ActionCollection.class, + ensureIndexes( + mongoTemplate, + ActionCollection.class, makeIndex(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + FieldName.PAGE_ID) - .named("unpublishedCollection_pageId") - ); + .named("unpublishedCollection_pageId")); String defaultResources = fieldName(QBranchAwareDomain.branchAwareDomain.defaultResources); - ensureIndexes(mongoTemplate, ActionCollection.class, + ensureIndexes( + mongoTemplate, + ActionCollection.class, makeIndex(defaultResources + "." + FieldName.APPLICATION_ID, FieldName.GIT_SYNC_ID) - .named("defaultApplicationId_gitSyncId_compound_index") - ); + .named("defaultApplicationId_gitSyncId_compound_index")); - ensureIndexes(mongoTemplate, NewAction.class, + ensureIndexes( + mongoTemplate, + NewAction.class, makeIndex(defaultResources + "." + FieldName.APPLICATION_ID, FieldName.GIT_SYNC_ID) - .named("defaultApplicationId_gitSyncId_compound_index") - ); + .named("defaultApplicationId_gitSyncId_compound_index")); - ensureIndexes(mongoTemplate, UserData.class, - makeIndex(fieldName(QUserData.userData.userId)) - .unique() - .named("userId") - ); + ensureIndexes( + mongoTemplate, + UserData.class, + makeIndex(fieldName(QUserData.userData.userId)).unique().named("userId")); } @ChangeSet(order = "115", id = "mark-mssql-crud-unavailable", author = "") @@ -4880,27 +4920,39 @@ public void updateNewActionActionCollectionIndexes(MongoTemplate mongoTemplate) dropIndexIfExists(mongoTemplate, NewAction.class, "unpublishedAction_pageId"); - ensureIndexes(mongoTemplate, NewAction.class, - makeIndex(fieldName(QNewAction.newAction.unpublishedAction) + "." + FieldName.PAGE_ID, FieldName.DELETED) - .named("unpublishedActionPageId_deleted_compound_index") - ); - - ensureIndexes(mongoTemplate, NewAction.class, + ensureIndexes( + mongoTemplate, + NewAction.class, + makeIndex( + fieldName(QNewAction.newAction.unpublishedAction) + "." + FieldName.PAGE_ID, + FieldName.DELETED) + .named("unpublishedActionPageId_deleted_compound_index")); + + ensureIndexes( + mongoTemplate, + NewAction.class, makeIndex(fieldName(QNewAction.newAction.publishedAction) + "." + FieldName.PAGE_ID, FieldName.DELETED) - .named("publishedActionPageId_deleted_compound_index") - ); + .named("publishedActionPageId_deleted_compound_index")); dropIndexIfExists(mongoTemplate, ActionCollection.class, "unpublishedCollection_pageId"); - ensureIndexes(mongoTemplate, ActionCollection.class, - makeIndex(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + FieldName.PAGE_ID, FieldName.DELETED) - .named("unpublishedCollectionPageId_deleted") - ); - - ensureIndexes(mongoTemplate, ActionCollection.class, - makeIndex(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + FieldName.PAGE_ID, FieldName.DELETED) - .named("publishedCollectionPageId_deleted") - ); + ensureIndexes( + mongoTemplate, + ActionCollection.class, + makeIndex( + fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + FieldName.PAGE_ID, + FieldName.DELETED) + .named("unpublishedCollectionPageId_deleted")); + + ensureIndexes( + mongoTemplate, + ActionCollection.class, + makeIndex( + fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + FieldName.PAGE_ID, + FieldName.DELETED) + .named("publishedCollectionPageId_deleted")); } /** @@ -4913,78 +4965,81 @@ public void updateNewActionActionCollectionIndexes(MongoTemplate mongoTemplate) @ChangeSet(order = "117", id = "create-system-themes-v2", author = "", runAlways = false) public void createSystemThemes2(MongoTemplate mongoTemplate) throws IOException { -// Commenting this out to ensure that system themes get added only once the baseline object creations are complete -// This runs as part of `createSystemThemes3` - -// Index systemThemeIndex = new Index() -// .on(fieldName(QTheme.theme.isSystemTheme), Sort.Direction.ASC) -// .named("system_theme_index") -// .background(); -// -// Index applicationIdIndex = new Index() -// .on(fieldName(QTheme.theme.applicationId), Sort.Direction.ASC) -// .on(fieldName(QTheme.theme.deleted), Sort.Direction.ASC) -// .named("application_id_index") -// .background(); -// -// dropIndexIfExists(mongoTemplate, Theme.class, "system_theme_index"); -// dropIndexIfExists(mongoTemplate, Theme.class, "application_id_index"); -// ensureIndexes(mongoTemplate, Theme.class, systemThemeIndex, applicationIdIndex); -// -// final String themesJson = StreamUtils.copyToString( -// new DefaultResourceLoader().getResource("system-themes.json").getInputStream(), -// Charset.defaultCharset() -// ); -// Theme[] themes = new Gson().fromJson(themesJson, Theme[].class); -// -// Theme legacyTheme = null; -// boolean themeExists = false; -// -// Policy policyWithCurrentPermission = Policy.builder().permission(READ_THEMES.getValue()) -// .users(Set.of(FieldName.ANONYMOUS_USER)).build(); -// -// for (Theme theme : themes) { -// theme.setSystemTheme(true); -// theme.setCreatedAt(Instant.now()); -// theme.setPolicies(Set.of(policyWithCurrentPermission)); -// Query query = new Query(Criteria.where(fieldName(QTheme.theme.name)).is(theme.getName()) -// .and(fieldName(QTheme.theme.isSystemTheme)).is(true)); -// -// Theme savedTheme = mongoTemplate.findOne(query, Theme.class); -// if(savedTheme == null) { // this theme does not exist, create it -// savedTheme = mongoTemplate.save(theme); -// } else { // theme already found, update -// themeExists = true; -// savedTheme.setDisplayName(theme.getDisplayName()); -// savedTheme.setPolicies(theme.getPolicies()); -// savedTheme.setConfig(theme.getConfig()); -// savedTheme.setProperties(theme.getProperties()); -// savedTheme.setStylesheet(theme.getStylesheet()); -// if(savedTheme.getCreatedAt() == null) { -// savedTheme.setCreatedAt(Instant.now()); -// } -// mongoTemplate.save(savedTheme); -// } -// -// if(theme.getName().equalsIgnoreCase(Theme.LEGACY_THEME_NAME)) { -// legacyTheme = savedTheme; -// } -// } -// -// if(!themeExists) { // this is the first time we're running the migration -// // migrate all applications and set legacy theme to them in both mode -// Update update = new Update().set(fieldName(QApplication.application.publishedModeThemeId), legacyTheme.getId()) -// .set(fieldName(QApplication.application.editModeThemeId), legacyTheme.getId()); -// mongoTemplate.updateMulti( -// new Query(where(fieldName(QApplication.application.deleted)).is(false)), update, Application.class -// ); -// } + // Commenting this out to ensure that system themes get added only once the baseline object creations are + // complete + // This runs as part of `createSystemThemes3` + + // Index systemThemeIndex = new Index() + // .on(fieldName(QTheme.theme.isSystemTheme), Sort.Direction.ASC) + // .named("system_theme_index") + // .background(); + // + // Index applicationIdIndex = new Index() + // .on(fieldName(QTheme.theme.applicationId), Sort.Direction.ASC) + // .on(fieldName(QTheme.theme.deleted), Sort.Direction.ASC) + // .named("application_id_index") + // .background(); + // + // dropIndexIfExists(mongoTemplate, Theme.class, "system_theme_index"); + // dropIndexIfExists(mongoTemplate, Theme.class, "application_id_index"); + // ensureIndexes(mongoTemplate, Theme.class, systemThemeIndex, applicationIdIndex); + // + // final String themesJson = StreamUtils.copyToString( + // new DefaultResourceLoader().getResource("system-themes.json").getInputStream(), + // Charset.defaultCharset() + // ); + // Theme[] themes = new Gson().fromJson(themesJson, Theme[].class); + // + // Theme legacyTheme = null; + // boolean themeExists = false; + // + // Policy policyWithCurrentPermission = Policy.builder().permission(READ_THEMES.getValue()) + // .users(Set.of(FieldName.ANONYMOUS_USER)).build(); + // + // for (Theme theme : themes) { + // theme.setSystemTheme(true); + // theme.setCreatedAt(Instant.now()); + // theme.setPolicies(Set.of(policyWithCurrentPermission)); + // Query query = new Query(Criteria.where(fieldName(QTheme.theme.name)).is(theme.getName()) + // .and(fieldName(QTheme.theme.isSystemTheme)).is(true)); + // + // Theme savedTheme = mongoTemplate.findOne(query, Theme.class); + // if(savedTheme == null) { // this theme does not exist, create it + // savedTheme = mongoTemplate.save(theme); + // } else { // theme already found, update + // themeExists = true; + // savedTheme.setDisplayName(theme.getDisplayName()); + // savedTheme.setPolicies(theme.getPolicies()); + // savedTheme.setConfig(theme.getConfig()); + // savedTheme.setProperties(theme.getProperties()); + // savedTheme.setStylesheet(theme.getStylesheet()); + // if(savedTheme.getCreatedAt() == null) { + // savedTheme.setCreatedAt(Instant.now()); + // } + // mongoTemplate.save(savedTheme); + // } + // + // if(theme.getName().equalsIgnoreCase(Theme.LEGACY_THEME_NAME)) { + // legacyTheme = savedTheme; + // } + // } + // + // if(!themeExists) { // this is the first time we're running the migration + // // migrate all applications and set legacy theme to them in both mode + // Update update = new Update().set(fieldName(QApplication.application.publishedModeThemeId), + // legacyTheme.getId()) + // .set(fieldName(QApplication.application.editModeThemeId), legacyTheme.getId()); + // mongoTemplate.updateMulti( + // new Query(where(fieldName(QApplication.application.deleted)).is(false)), update, + // Application.class + // ); + // } } @ChangeSet(order = "118", id = "set-firestore-smart-substitution-to-false-for-old-cmds", author = "") public void setFirestoreSmartSubstitutionToFalseForOldCommands(MongoTemplate mongoTemplate) { - Plugin firestorePlugin = mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), - Plugin.class); + Plugin firestorePlugin = + mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), Plugin.class); /* Query to get all Mongo actions which are not deleted */ Query queryToGetActions = getQueryToFetchAllPluginActionsWhichAreNotDeleted(firestorePlugin); @@ -4999,22 +5054,25 @@ public void setFirestoreSmartSubstitutionToFalseForOldCommands(MongoTemplate mon setSmartSubstitutionFieldForEachAction(firestoreActions, mongoTemplate); } - private void setSmartSubstitutionFieldForEachAction(List<NewAction> firestoreActions, - MongoTemplate mongoTemplate) { + private void setSmartSubstitutionFieldForEachAction(List<NewAction> firestoreActions, MongoTemplate mongoTemplate) { firestoreActions.stream() .map(NewAction::getId) /* iterate over one action id at a time */ .map(actionId -> fetchActionUsingId(actionId, mongoTemplate)) /* fetch action using id */ .filter(this::hasUnpublishedActionConfiguration) .forEachOrdered(firestoreAction -> { /* set key for unpublished action */ - Map<String, Object> unpublishedFormData = - firestoreAction.getUnpublishedAction().getActionConfiguration().getFormData(); + Map<String, Object> unpublishedFormData = firestoreAction + .getUnpublishedAction() + .getActionConfiguration() + .getFormData(); setValueSafelyInFormData(unpublishedFormData, SMART_SUBSTITUTION, FALSE.toString()); /* set key for published action */ if (hasPublishedActionConfiguration(firestoreAction)) { - Map<String, Object> publishedFormData = - firestoreAction.getPublishedAction().getActionConfiguration().getFormData(); + Map<String, Object> publishedFormData = firestoreAction + .getPublishedAction() + .getActionConfiguration() + .getFormData(); setValueSafelyInFormData(publishedFormData, SMART_SUBSTITUTION, FALSE.toString()); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java index 8a4737e57e79..7c9c0403f377 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java @@ -52,12 +52,12 @@ import com.appsmith.server.dtos.Permission; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.helpers.TextUtils; import com.appsmith.server.repositories.CacheableRepositoryHelper; import com.appsmith.server.repositories.NewPageRepository; import com.appsmith.server.repositories.UserRepository; import com.appsmith.server.services.WorkspaceService; +import com.appsmith.server.solutions.PolicySolution; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.cloudyrock.mongock.ChangeLog; import com.github.cloudyrock.mongock.ChangeSet; @@ -130,14 +130,14 @@ import static org.springframework.data.mongodb.core.query.Query.query; import static org.springframework.data.mongodb.core.query.Update.update; - @Slf4j @ChangeLog(order = "002") public class DatabaseChangelog2 { private static final ObjectMapper objectMapper = new ObjectMapper(); - private static final Pattern sheetRangePattern = Pattern.compile("https://docs.google.com/spreadsheets/d/([^/]+)/?[^\"]*"); + private static final Pattern sheetRangePattern = + Pattern.compile("https://docs.google.com/spreadsheets/d/([^/]+)/?[^\"]*"); @ChangeSet(order = "001", id = "fix-plugin-title-casing", author = "") public void fixPluginTitleCasing(MongoTemplate mongoTemplate) { @@ -160,11 +160,14 @@ public void fixPluginTitleCasing(MongoTemplate mongoTemplate) { @ChangeSet(order = "002", id = "deprecate-archivedAt-in-action", author = "") public void deprecateArchivedAtForNewAction(MongoTemplate mongoTemplate) { // Update actions - final Query actionQuery = query(where(fieldName(QNewAction.newAction.applicationId)).exists(true)) + final Query actionQuery = query( + where(fieldName(QNewAction.newAction.applicationId)).exists(true)) .addCriteria(where(fieldName(QNewAction.newAction.unpublishedAction) + "." - + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)).exists(true)); + + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)) + .exists(true)); - actionQuery.fields() + actionQuery + .fields() .include(fieldName(QNewAction.newAction.id)) .include(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)); @@ -186,9 +189,7 @@ public void deprecateArchivedAtForNewAction(MongoTemplate mongoTemplate) { + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)); } mongoTemplate.updateFirst( - query(where(fieldName(QNewAction.newAction.id)).is(action.getId())), - update, - NewAction.class); + query(where(fieldName(QNewAction.newAction.id)).is(action.getId())), update, NewAction.class); } } @@ -207,32 +208,28 @@ public void updateActionFormDataPath(MongoTemplate mongoTemplate) { // Get all plugin references to Mongo, S3 and Firestore actions List<Plugin> uqiPlugins = mongoTemplate.find( - query(where("packageName").in("mongo-plugin", "amazons3-plugin", "firestore-plugin")), - Plugin.class); + query(where("packageName").in("mongo-plugin", "amazons3-plugin", "firestore-plugin")), Plugin.class); - final Map<String, String> pluginMap = uqiPlugins.stream() - .collect(Collectors.toMap(Plugin::getId, Plugin::getPackageName)); + final Map<String, String> pluginMap = + uqiPlugins.stream().collect(Collectors.toMap(Plugin::getId, Plugin::getPackageName)); final Set<String> pluginIds = pluginMap.keySet(); // Find all relevant actions - final Query actionQuery = query( - where(fieldName(QNewAction.newAction.pluginId)).in(pluginIds) - .and(fieldName(QNewAction.newAction.deleted)).ne(true)); // setting `deleted` != `true` - actionQuery.fields() - .include(fieldName(QNewAction.newAction.id)); + final Query actionQuery = query(where(fieldName(QNewAction.newAction.pluginId)) + .in(pluginIds) + .and(fieldName(QNewAction.newAction.deleted)) + .ne(true)); // setting `deleted` != `true` + actionQuery.fields().include(fieldName(QNewAction.newAction.id)); - List<NewAction> uqiActions = mongoTemplate.find( - actionQuery, - NewAction.class); + List<NewAction> uqiActions = mongoTemplate.find(actionQuery, NewAction.class); // Retrieve the formData path for all actions for (NewAction uqiActionWithId : uqiActions) { // Fetch one action at a time to avoid OOM. final NewAction uqiAction = mongoTemplate.findOne( - query(where(fieldName(QNewAction.newAction.id)).is(uqiActionWithId.getId())), - NewAction.class); + query(where(fieldName(QNewAction.newAction.id)).is(uqiActionWithId.getId())), NewAction.class); assert uqiAction != null; ActionDTO unpublishedAction = uqiAction.getUnpublishedAction(); @@ -265,7 +262,8 @@ public static void migrateFirestoreActionsFormData(NewAction uqiAction) { /** * Migrate unpublished action configuration data. */ - final Map<String, Object> unpublishedFormData = unpublishedAction.getActionConfiguration().getFormData(); + final Map<String, Object> unpublishedFormData = + unpublishedAction.getActionConfiguration().getFormData(); if (unpublishedFormData != null) { final Object command = unpublishedFormData.get("command"); @@ -274,41 +272,41 @@ public static void migrateFirestoreActionsFormData(NewAction uqiAction) { throw new AppsmithException(AppsmithError.MIGRATION_ERROR); } - unpublishedFormData - .keySet() - .stream() - .forEach(k -> { - if (k != null) { - final Object oldValue = unpublishedFormData.get(k); - final HashMap<String, Object> map = new HashMap<>(); - map.put("data", oldValue); - map.put("componentData", oldValue); - map.put("viewType", "component"); - unpublishedFormData.put(k, map); - } - }); - + unpublishedFormData.keySet().stream().forEach(k -> { + if (k != null) { + final Object oldValue = unpublishedFormData.get(k); + final HashMap<String, Object> map = new HashMap<>(); + map.put("data", oldValue); + map.put("componentData", oldValue); + map.put("viewType", "component"); + unpublishedFormData.put(k, map); + } + }); } - final String unpublishedBody = unpublishedAction.getActionConfiguration().getBody(); + final String unpublishedBody = + unpublishedAction.getActionConfiguration().getBody(); if (StringUtils.hasLength(unpublishedBody)) { convertToFormDataObject(unpublishedFormData, "body", unpublishedBody); unpublishedAction.getActionConfiguration().setBody(null); } - final String unpublishedPath = unpublishedAction.getActionConfiguration().getPath(); + final String unpublishedPath = + unpublishedAction.getActionConfiguration().getPath(); if (StringUtils.hasLength(unpublishedPath)) { convertToFormDataObject(unpublishedFormData, "path", unpublishedPath); unpublishedAction.getActionConfiguration().setPath(null); } - final String unpublishedNext = unpublishedAction.getActionConfiguration().getNext(); + final String unpublishedNext = + unpublishedAction.getActionConfiguration().getNext(); if (StringUtils.hasLength(unpublishedNext)) { convertToFormDataObject(unpublishedFormData, "next", unpublishedNext); unpublishedAction.getActionConfiguration().setNext(null); } - final String unpublishedPrev = unpublishedAction.getActionConfiguration().getPrev(); + final String unpublishedPrev = + unpublishedAction.getActionConfiguration().getPrev(); if (StringUtils.hasLength(unpublishedPrev)) { convertToFormDataObject(unpublishedFormData, "prev", unpublishedPrev); unpublishedAction.getActionConfiguration().setPrev(null); @@ -318,9 +316,11 @@ public static void migrateFirestoreActionsFormData(NewAction uqiAction) { * Migrate published action configuration data. */ ActionDTO publishedAction = uqiAction.getPublishedAction(); - if (publishedAction != null && publishedAction.getActionConfiguration() != null && - publishedAction.getActionConfiguration().getFormData() != null) { - final Map<String, Object> publishedFormData = publishedAction.getActionConfiguration().getFormData(); + if (publishedAction != null + && publishedAction.getActionConfiguration() != null + && publishedAction.getActionConfiguration().getFormData() != null) { + final Map<String, Object> publishedFormData = + publishedAction.getActionConfiguration().getFormData(); final Object command = publishedFormData.get("command"); @@ -328,39 +328,40 @@ public static void migrateFirestoreActionsFormData(NewAction uqiAction) { throw new AppsmithException(AppsmithError.MIGRATION_ERROR); } - publishedFormData - .keySet() - .stream() - .forEach(k -> { - if (k != null) { - final Object oldValue = publishedFormData.get(k); - final HashMap<String, Object> map = new HashMap<>(); - map.put("data", oldValue); - map.put("componentData", oldValue); - map.put("viewType", "component"); - publishedFormData.put(k, map); - } - }); + publishedFormData.keySet().stream().forEach(k -> { + if (k != null) { + final Object oldValue = publishedFormData.get(k); + final HashMap<String, Object> map = new HashMap<>(); + map.put("data", oldValue); + map.put("componentData", oldValue); + map.put("viewType", "component"); + publishedFormData.put(k, map); + } + }); - final String publishedBody = publishedAction.getActionConfiguration().getBody(); + final String publishedBody = + publishedAction.getActionConfiguration().getBody(); if (StringUtils.hasLength(publishedBody)) { convertToFormDataObject(publishedFormData, "body", publishedBody); publishedAction.getActionConfiguration().setBody(null); } - final String publishedPath = publishedAction.getActionConfiguration().getPath(); + final String publishedPath = + publishedAction.getActionConfiguration().getPath(); if (StringUtils.hasLength(publishedPath)) { convertToFormDataObject(publishedFormData, "path", publishedPath); publishedAction.getActionConfiguration().setPath(null); } - final String publishedNext = publishedAction.getActionConfiguration().getNext(); + final String publishedNext = + publishedAction.getActionConfiguration().getNext(); if (StringUtils.hasLength(publishedNext)) { convertToFormDataObject(publishedFormData, "next", publishedNext); publishedAction.getActionConfiguration().setNext(null); } - final String publishedPrev = publishedAction.getActionConfiguration().getPrev(); + final String publishedPrev = + publishedAction.getActionConfiguration().getPrev(); if (StringUtils.hasLength(publishedPrev)) { convertToFormDataObject(publishedFormData, "prev", publishedPrev); publishedAction.getActionConfiguration().setPrev(null); @@ -377,35 +378,33 @@ public static void migrateFirestoreActionsFormData(NewAction uqiAction) { */ List<Property> dynamicBindingPathList = unpublishedAction.getDynamicBindingPathList(); if (dynamicBindingPathList != null && !dynamicBindingPathList.isEmpty()) { - dynamicBindingPathList - .stream() - .forEach(dynamicBindingPath -> { - if (dynamicBindingPath.getKey().contains("formData")) { - final String oldKey = dynamicBindingPath.getKey(); - final Pattern pattern = Pattern.compile("formData\\.([^.]*)(\\..*)?"); + dynamicBindingPathList.stream().forEach(dynamicBindingPath -> { + if (dynamicBindingPath.getKey().contains("formData")) { + final String oldKey = dynamicBindingPath.getKey(); + final Pattern pattern = Pattern.compile("formData\\.([^.]*)(\\..*)?"); - Matcher matcher = pattern.matcher(oldKey); + Matcher matcher = pattern.matcher(oldKey); - while (matcher.find()) { - final String fieldName = matcher.group(1); - final String remainderPath = matcher.group(2) == null ? "" : matcher.group(2); + while (matcher.find()) { + final String fieldName = matcher.group(1); + final String remainderPath = matcher.group(2) == null ? "" : matcher.group(2); - dynamicBindingPath.setKey("formData." + fieldName + ".data" + remainderPath); - } - } else { - final String oldKey = dynamicBindingPath.getKey(); - final Pattern pattern = Pattern.compile("^(body|next|prev|path)(\\..*)?"); + dynamicBindingPath.setKey("formData." + fieldName + ".data" + remainderPath); + } + } else { + final String oldKey = dynamicBindingPath.getKey(); + final Pattern pattern = Pattern.compile("^(body|next|prev|path)(\\..*)?"); - Matcher matcher = pattern.matcher(oldKey); + Matcher matcher = pattern.matcher(oldKey); - while (matcher.find()) { - final String fieldName = matcher.group(1); - final String remainderPath = matcher.group(2) == null ? "" : matcher.group(2); + while (matcher.find()) { + final String fieldName = matcher.group(1); + final String remainderPath = matcher.group(2) == null ? "" : matcher.group(2); - dynamicBindingPath.setKey("formData." + fieldName + ".data" + remainderPath); - } - } - }); + dynamicBindingPath.setKey("formData." + fieldName + ".data" + remainderPath); + } + } + }); } } @@ -413,7 +412,8 @@ private static void convertToFormDataObject(Map<String, Object> formDataMap, Str convertToFormDataObject(formDataMap, key, value, false); } - private static void convertToFormDataObject(Map<String, Object> formDataMap, String key, Object value, boolean hasBinding) { + private static void convertToFormDataObject( + Map<String, Object> formDataMap, String key, Object value, boolean hasBinding) { if (value == null) { return; } @@ -464,8 +464,8 @@ private static void mapS3ToNewFormData(ActionDTO action, Map<String, Object> f) convertToFormDataObject(f, "bucket", formData.get("bucket")); convertToFormDataObject(f, "smartSubstitution", formData.get("smartSubstitution")); switch ((String) command) { - // No case for delete single and multiple since they only had bucket that needed - // migration + // No case for delete single and multiple since they only had bucket that needed + // migration case "LIST": final Map listMap = (Map) formData.get("list"); if (listMap == null) { @@ -551,17 +551,16 @@ public static void migrateAmazonS3ActionsFormData(NewAction uqiAction) { dynamicBindingMapper.put("formData.smartSubstitution", "formData.smartSubstitution.data"); dynamicBindingMapper.put("body", "formData.body.data"); dynamicBindingMapper.put("path", "formData.path.data"); - dynamicBindingPathList - .stream() - .forEach(dynamicBindingPath -> { - final String currentBinding = dynamicBindingPath.getKey(); - final Optional<String> matchingBinding = dynamicBindingMapper.keySet().stream() - .filter(currentBinding::startsWith).findFirst(); - if (matchingBinding.isPresent()) { - final String newBindingPrefix = dynamicBindingMapper.get(matchingBinding.get()); - dynamicBindingPath.setKey(currentBinding.replace(matchingBinding.get(), newBindingPrefix)); - } - }); + dynamicBindingPathList.stream().forEach(dynamicBindingPath -> { + final String currentBinding = dynamicBindingPath.getKey(); + final Optional<String> matchingBinding = dynamicBindingMapper.keySet().stream() + .filter(currentBinding::startsWith) + .findFirst(); + if (matchingBinding.isPresent()) { + final String newBindingPrefix = dynamicBindingMapper.get(matchingBinding.get()); + dynamicBindingPath.setKey(currentBinding.replace(matchingBinding.get(), newBindingPrefix)); + } + }); } } @@ -715,17 +714,16 @@ public static void migrateMongoActionsFormData(NewAction uqiAction) { dynamicBindingMapper.put("formData.updateMany.limit", "formData.updateMany.limit.data"); dynamicBindingMapper.put("formData.smartSubstitution", "formData.smartSubstitution.data"); dynamicBindingMapper.put("body", "formData.body.data"); - dynamicBindingPathList - .stream() - .forEach(dynamicBindingPath -> { - final String currentBinding = dynamicBindingPath.getKey(); - final Optional<String> matchingBinding = dynamicBindingMapper.keySet().stream() - .filter(currentBinding::startsWith).findFirst(); - if (matchingBinding.isPresent()) { - final String newBindingPrefix = dynamicBindingMapper.get(matchingBinding.get()); - dynamicBindingPath.setKey(currentBinding.replace(matchingBinding.get(), newBindingPrefix)); - } - }); + dynamicBindingPathList.stream().forEach(dynamicBindingPath -> { + final String currentBinding = dynamicBindingPath.getKey(); + final Optional<String> matchingBinding = dynamicBindingMapper.keySet().stream() + .filter(currentBinding::startsWith) + .findFirst(); + if (matchingBinding.isPresent()) { + final String newBindingPrefix = dynamicBindingMapper.get(matchingBinding.get()); + dynamicBindingPath.setKey(currentBinding.replace(matchingBinding.get(), newBindingPrefix)); + } + }); } } @@ -738,10 +736,10 @@ public static void migrateMongoActionsFormData(NewAction uqiAction) { */ @ChangeSet(order = "004", id = "add-isConfigured-flag-for-all-datasources", author = "") public void updateIsConfiguredFlagForAllTheExistingDatasources(MongoTemplate mongoTemplate) { - final Query datasourceQuery = query(where(fieldName(QDatasource.datasource.deleted)).ne(true)) + final Query datasourceQuery = query( + where(fieldName(QDatasource.datasource.deleted)).ne(true)) .addCriteria(where(fieldName(QDatasource.datasource.invalids)).size(0)); - datasourceQuery.fields() - .include(fieldName(QDatasource.datasource.id)); + datasourceQuery.fields().include(fieldName(QDatasource.datasource.id)); List<Datasource> datasources = mongoTemplate.find(datasourceQuery, Datasource.class); for (Datasource datasource : datasources) { @@ -758,15 +756,15 @@ public void updateIsConfiguredFlagForAllTheExistingDatasources(MongoTemplate mon public void setDefaultApplicationVersion(MongoTemplate mongoTemplate) { mongoTemplate.updateMulti( Query.query(where(fieldName(QApplication.application.deleted)).is(false)), - update(fieldName(QApplication.application.applicationVersion), - ApplicationVersion.EARLIEST_VERSION), + update(fieldName(QApplication.application.applicationVersion), ApplicationVersion.EARLIEST_VERSION), Application.class); } @ChangeSet(order = "006", id = "delete-orphan-pages", author = "") public void deleteOrphanPages(MongoTemplate mongoTemplate) { - final Query validPagesQuery = query(where(fieldName(QApplication.application.deleted)).ne(true)); + final Query validPagesQuery = + query(where(fieldName(QApplication.application.deleted)).ne(true)); validPagesQuery.fields().include(fieldName(QApplication.application.pages)); validPagesQuery.fields().include(fieldName(QApplication.application.publishedPages)); @@ -789,8 +787,10 @@ public void deleteOrphanPages(MongoTemplate mongoTemplate) { validPageIds.add(applicationPublishedPage.getId()); } } - final Query pageQuery = query(where(fieldName(QNewPage.newPage.deleted)).ne(true)); - pageQuery.addCriteria(where(fieldName(QNewPage.newPage.applicationId)).is(application.getId())); + final Query pageQuery = + query(where(fieldName(QNewPage.newPage.deleted)).ne(true)); + pageQuery.addCriteria( + where(fieldName(QNewPage.newPage.applicationId)).is(application.getId())); pageQuery.fields().include(fieldName(QNewPage.newPage.applicationId)); final List<NewPage> pages = mongoTemplate.find(pageQuery, NewPage.class); @@ -799,8 +799,7 @@ public void deleteOrphanPages(MongoTemplate mongoTemplate) { mongoTemplate.updateFirst( query(where(fieldName(QNewPage.newPage.id)).is(newPage.getId())), deletionUpdates, - NewPage.class - ); + NewPage.class); } } } @@ -821,35 +820,34 @@ public static void doAddIndexesForGit(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, ActionCollection.class, "defaultApplicationId_gitSyncId_compound_index"); String defaultResources = fieldName(QBranchAwareDomain.branchAwareDomain.defaultResources); - ensureIndexes(mongoTemplate, ActionCollection.class, + ensureIndexes( + mongoTemplate, + ActionCollection.class, makeIndex( - defaultResources + "." + FieldName.APPLICATION_ID, - fieldName(QBaseDomain.baseDomain.gitSyncId), - fieldName(QBaseDomain.baseDomain.deleted) - ) - .named("defaultApplicationId_gitSyncId_deleted") - ); - - ensureIndexes(mongoTemplate, NewAction.class, + defaultResources + "." + FieldName.APPLICATION_ID, + fieldName(QBaseDomain.baseDomain.gitSyncId), + fieldName(QBaseDomain.baseDomain.deleted)) + .named("defaultApplicationId_gitSyncId_deleted")); + + ensureIndexes( + mongoTemplate, + NewAction.class, makeIndex( - defaultResources + "." + FieldName.APPLICATION_ID, - fieldName(QBaseDomain.baseDomain.gitSyncId), - fieldName(QBaseDomain.baseDomain.deleted) - ) - .named("defaultApplicationId_gitSyncId_deleted") - ); - - ensureIndexes(mongoTemplate, NewPage.class, + defaultResources + "." + FieldName.APPLICATION_ID, + fieldName(QBaseDomain.baseDomain.gitSyncId), + fieldName(QBaseDomain.baseDomain.deleted)) + .named("defaultApplicationId_gitSyncId_deleted")); + + ensureIndexes( + mongoTemplate, + NewPage.class, makeIndex( - defaultResources + "." + FieldName.APPLICATION_ID, - fieldName(QBaseDomain.baseDomain.gitSyncId), - fieldName(QBaseDomain.baseDomain.deleted) - ) - .named("defaultApplicationId_gitSyncId_deleted") - ); + defaultResources + "." + FieldName.APPLICATION_ID, + fieldName(QBaseDomain.baseDomain.gitSyncId), + fieldName(QBaseDomain.baseDomain.deleted)) + .named("defaultApplicationId_gitSyncId_deleted")); } - /** * We'll remove the unique index on organization slugs. We'll also regenerate the slugs for all organizations as * most of them are outdated @@ -862,17 +860,18 @@ public void updateOrganizationSlugs(MongoTemplate mongoTemplate) { // update organizations final Query getAllOrganizationsQuery = query(where("deletedAt").is(null)); - getAllOrganizationsQuery.fields() - .include(fieldName(QOrganization.organization.name)); + getAllOrganizationsQuery.fields().include(fieldName(QOrganization.organization.name)); List<Organization> organizations = mongoTemplate.find(getAllOrganizationsQuery, Organization.class); for (Organization organization : organizations) { mongoTemplate.updateFirst( query(where(fieldName(QOrganization.organization.id)).is(organization.getId())), - new Update().set(fieldName(QOrganization.organization.slug), TextUtils.makeSlug(organization.getName())), - Organization.class - ); + new Update() + .set( + fieldName(QOrganization.organization.slug), + TextUtils.makeSlug(organization.getName())), + Organization.class); } } @@ -881,11 +880,12 @@ public void copyOrganizationToWorkspaces(MongoTemplate mongoTemplate) { // Drop the workspace collection in case it has been partially run, otherwise it has no effect mongoTemplate.dropCollection(Workspace.class); Gson gson = new Gson(); - //Memory optimization note: - //Call stream instead of findAll to avoid out of memory if the collection is big - //stream implementation lazy loads the data using underlying cursor open on the collection - //the data is loaded as and when needed by the pipeline - try (Stream<Organization> stream = mongoTemplate.stream(new Query().cursorBatchSize(10000), Organization.class)) { + // Memory optimization note: + // Call stream instead of findAll to avoid out of memory if the collection is big + // stream implementation lazy loads the data using underlying cursor open on the collection + // the data is loaded as and when needed by the pipeline + try (Stream<Organization> stream = + mongoTemplate.stream(new Query().cursorBatchSize(10000), Organization.class)) { stream.forEach((organization) -> { Workspace workspace = gson.fromJson(gson.toJson(organization), Workspace.class); mongoTemplate.insert(workspace); @@ -900,22 +900,18 @@ public void copyOrganizationToWorkspaces(MongoTemplate mongoTemplate) { */ @ChangeSet(order = "010", id = "add-workspace-indexes", author = "") public void addWorkspaceIndexes(MongoTemplate mongoTemplate) { - ensureIndexes(mongoTemplate, Workspace.class, - makeIndex("createdAt") - ); + ensureIndexes(mongoTemplate, Workspace.class, makeIndex("createdAt")); } @ChangeSet(order = "011", id = "update-sequence-names-from-organization-to-workspace", author = "") public void updateSequenceNamesFromOrganizationToWorkspace(MongoTemplate mongoTemplate) { for (Sequence sequence : mongoTemplate.findAll(Sequence.class)) { String oldName = sequence.getName(); - String newName = oldName.replaceAll("(.*) for organization with _id : (.*)", "$1 for workspace with _id : $2"); + String newName = + oldName.replaceAll("(.*) for organization with _id : (.*)", "$1 for workspace with _id : $2"); if (!newName.equals(oldName)) { - //Using strings in the field names instead of QSequence becauce Sequence is not a AppsmithDomain - mongoTemplate.updateFirst(query(where("name").is(oldName)), - update("name", newName), - Sequence.class - ); + // Using strings in the field names instead of QSequence becauce Sequence is not a AppsmithDomain + mongoTemplate.updateFirst(query(where("name").is(oldName)), update("name", newName), Sequence.class); } } } @@ -938,7 +934,6 @@ public void addDefaultTenant(MongoTemplate mongoTemplate) { defaultTenant.setPricingPlan(PricingPlan.FREE); mongoTemplate.save(defaultTenant); - } @ChangeSet(order = "013", id = "add-tenant-to-all-workspaces", author = "") @@ -950,16 +945,12 @@ public void addTenantToWorkspaces(MongoTemplate mongoTemplate) { assert (defaultTenant != null); // Set all the workspaces to be under the default tenant - mongoTemplate.updateMulti( - new Query(), - new Update().set("tenantId", defaultTenant.getId()), - Workspace.class - ); - + mongoTemplate.updateMulti(new Query(), new Update().set("tenantId", defaultTenant.getId()), Workspace.class); } @ChangeSet(order = "014", id = "add-tenant-to-all-users-and-flush-redis", author = "") - public void addTenantToUsersAndFlushRedis(MongoTemplate mongoTemplate, ReactiveRedisOperations<String, String> reactiveRedisOperations) { + public void addTenantToUsersAndFlushRedis( + MongoTemplate mongoTemplate, ReactiveRedisOperations<String, String> reactiveRedisOperations) { Query tenantQuery = new Query(); tenantQuery.addCriteria(where(fieldName(QTenant.tenant.slug)).is("default")); @@ -967,30 +958,28 @@ public void addTenantToUsersAndFlushRedis(MongoTemplate mongoTemplate, ReactiveR assert (defaultTenant != null); // Set all the users to be under the default tenant - mongoTemplate.updateMulti( - new Query(), - new Update().set("tenantId", defaultTenant.getId()), - User.class - ); + mongoTemplate.updateMulti(new Query(), new Update().set("tenantId", defaultTenant.getId()), User.class); // Now sign out all the existing users since this change impacts the user object. - final String script = - "for _,k in ipairs(redis.call('keys','spring:session:sessions:*'))" + - " do redis.call('del',k) " + - "end"; + final String script = "for _,k in ipairs(redis.call('keys','spring:session:sessions:*'))" + + " do redis.call('del',k) " + "end"; final Flux<Object> flushdb = reactiveRedisOperations.execute(RedisScript.of(script)); flushdb.subscribe(); } @ChangeSet(order = "015", id = "migrate-organizationId-to-workspaceId-in-domain-objects", author = "") - public void migrateOrganizationIdToWorkspaceIdInDomainObjects(MongoTemplate mongoTemplate, ReactiveRedisOperations<String, String> reactiveRedisOperations) { + public void migrateOrganizationIdToWorkspaceIdInDomainObjects( + MongoTemplate mongoTemplate, ReactiveRedisOperations<String, String> reactiveRedisOperations) { // Datasource if (mongoTemplate.findOne(new Query(), Datasource.class) == null) { System.out.println("No datasource to migrate."); } else { - mongoTemplate.updateMulti(new Query(), - AggregationUpdate.update().set(fieldName(QDatasource.datasource.workspaceId)).toValueOf(Fields.field(fieldName(QDatasource.datasource.organizationId))), + mongoTemplate.updateMulti( + new Query(), + AggregationUpdate.update() + .set(fieldName(QDatasource.datasource.workspaceId)) + .toValueOf(Fields.field(fieldName(QDatasource.datasource.organizationId))), Datasource.class); } @@ -998,8 +987,11 @@ public void migrateOrganizationIdToWorkspaceIdInDomainObjects(MongoTemplate mong if (mongoTemplate.findOne(new Query(), ActionCollection.class) == null) { System.out.println("No actionCollection to migrate."); } else { - mongoTemplate.updateMulti(new Query(), - AggregationUpdate.update().set(fieldName(QActionCollection.actionCollection.workspaceId)).toValueOf(Fields.field(fieldName(QActionCollection.actionCollection.organizationId))), + mongoTemplate.updateMulti( + new Query(), + AggregationUpdate.update() + .set(fieldName(QActionCollection.actionCollection.workspaceId)) + .toValueOf(Fields.field(fieldName(QActionCollection.actionCollection.organizationId))), ActionCollection.class); } @@ -1007,8 +999,11 @@ public void migrateOrganizationIdToWorkspaceIdInDomainObjects(MongoTemplate mong if (mongoTemplate.findOne(new Query(), Application.class) == null) { System.out.println("No application to migrate."); } else { - mongoTemplate.updateMulti(new Query(), - AggregationUpdate.update().set(fieldName(QApplication.application.workspaceId)).toValueOf(Fields.field(fieldName(QApplication.application.organizationId))), + mongoTemplate.updateMulti( + new Query(), + AggregationUpdate.update() + .set(fieldName(QApplication.application.workspaceId)) + .toValueOf(Fields.field(fieldName(QApplication.application.organizationId))), Application.class); } @@ -1016,8 +1011,11 @@ public void migrateOrganizationIdToWorkspaceIdInDomainObjects(MongoTemplate mong if (mongoTemplate.findOne(new Query(), NewAction.class) == null) { System.out.println("No newAction to migrate."); } else { - mongoTemplate.updateMulti(new Query(), - AggregationUpdate.update().set(fieldName(QNewAction.newAction.workspaceId)).toValueOf(Fields.field(fieldName(QNewAction.newAction.organizationId))), + mongoTemplate.updateMulti( + new Query(), + AggregationUpdate.update() + .set(fieldName(QNewAction.newAction.workspaceId)) + .toValueOf(Fields.field(fieldName(QNewAction.newAction.organizationId))), NewAction.class); } @@ -1025,8 +1023,11 @@ public void migrateOrganizationIdToWorkspaceIdInDomainObjects(MongoTemplate mong if (mongoTemplate.findOne(new Query(), Theme.class) == null) { System.out.println("No theme to migrate."); } else { - mongoTemplate.updateMulti(new Query(), - AggregationUpdate.update().set(fieldName(QTheme.theme.workspaceId)).toValueOf(Fields.field(fieldName(QTheme.theme.organizationId))), + mongoTemplate.updateMulti( + new Query(), + AggregationUpdate.update() + .set(fieldName(QTheme.theme.workspaceId)) + .toValueOf(Fields.field(fieldName(QTheme.theme.organizationId))), Theme.class); } @@ -1034,8 +1035,11 @@ public void migrateOrganizationIdToWorkspaceIdInDomainObjects(MongoTemplate mong if (mongoTemplate.findOne(new Query(), UserData.class) == null) { System.out.println("No userData to migrate."); } else { - mongoTemplate.updateMulti(new Query(), - AggregationUpdate.update().set(fieldName(QUserData.userData.recentlyUsedWorkspaceIds)).toValueOf(Fields.field(fieldName(QUserData.userData.recentlyUsedOrgIds))), + mongoTemplate.updateMulti( + new Query(), + AggregationUpdate.update() + .set(fieldName(QUserData.userData.recentlyUsedWorkspaceIds)) + .toValueOf(Fields.field(fieldName(QUserData.userData.recentlyUsedOrgIds))), UserData.class); } @@ -1043,8 +1047,11 @@ public void migrateOrganizationIdToWorkspaceIdInDomainObjects(MongoTemplate mong if (mongoTemplate.findOne(new Query(), Workspace.class) == null) { System.out.println("No workspace to migrate."); } else { - mongoTemplate.updateMulti(new Query(), - AggregationUpdate.update().set(fieldName(QWorkspace.workspace.isAutoGeneratedWorkspace)).toValueOf(Fields.field(fieldName(QWorkspace.workspace.isAutoGeneratedOrganization))), + mongoTemplate.updateMulti( + new Query(), + AggregationUpdate.update() + .set(fieldName(QWorkspace.workspace.isAutoGeneratedWorkspace)) + .toValueOf(Fields.field(fieldName(QWorkspace.workspace.isAutoGeneratedOrganization))), Workspace.class); } @@ -1052,19 +1059,21 @@ public void migrateOrganizationIdToWorkspaceIdInDomainObjects(MongoTemplate mong if (mongoTemplate.findOne(new Query(), User.class) == null) { System.out.println("No user to migrate."); } else { - mongoTemplate.updateMulti(new Query(), + mongoTemplate.updateMulti( + new Query(), AggregationUpdate.update() - .set(fieldName(QUser.user.workspaceIds)).toValueOf(Fields.field(fieldName(QUser.user.organizationIds))) - .set(fieldName(QUser.user.currentWorkspaceId)).toValueOf(Fields.field(fieldName(QUser.user.currentOrganizationId))) - .set(fieldName(QUser.user.examplesWorkspaceId)).toValueOf(Fields.field(fieldName(QUser.user.examplesOrganizationId))), + .set(fieldName(QUser.user.workspaceIds)) + .toValueOf(Fields.field(fieldName(QUser.user.organizationIds))) + .set(fieldName(QUser.user.currentWorkspaceId)) + .toValueOf(Fields.field(fieldName(QUser.user.currentOrganizationId))) + .set(fieldName(QUser.user.examplesWorkspaceId)) + .toValueOf(Fields.field(fieldName(QUser.user.examplesOrganizationId))), User.class); } // Now sign out all the existing users since this change impacts the user object. - final String script = - "for _,k in ipairs(redis.call('keys','spring:session:sessions:*'))" + - " do redis.call('del',k) " + - "end"; + final String script = "for _,k in ipairs(redis.call('keys','spring:session:sessions:*'))" + + " do redis.call('del',k) " + "end"; final Flux<Object> flushdb = reactiveRedisOperations.execute(RedisScript.of(script)); flushdb.subscribe(); @@ -1075,25 +1084,30 @@ public void organizationToWorkspaceIndexesRecreate(MongoTemplate mongoTemplate) dropIndexIfExists(mongoTemplate, Application.class, "organization_name_deleted_gitApplicationMetadata"); dropIndexIfExists(mongoTemplate, Datasource.class, "organization_datasource_deleted_compound_index"); - //If this migration is re-run + // If this migration is re-run dropIndexIfExists(mongoTemplate, Application.class, "workspace_app_deleted_gitApplicationMetadata"); dropIndexIfExists(mongoTemplate, Datasource.class, "workspace_datasource_deleted_compound_index"); - ensureIndexes(mongoTemplate, Application.class, + ensureIndexes( + mongoTemplate, + Application.class, makeIndex( - fieldName(QApplication.application.workspaceId), - fieldName(QApplication.application.name), - fieldName(QApplication.application.deletedAt), - "gitApplicationMetadata.remoteUrl", - "gitApplicationMetadata.branchName") - .unique().named("workspace_app_deleted_gitApplicationMetadata") - ); - ensureIndexes(mongoTemplate, Datasource.class, - makeIndex(fieldName(QDatasource.datasource.workspaceId), - fieldName(QDatasource.datasource.name), - fieldName(QDatasource.datasource.deletedAt)) - .unique().named("workspace_datasource_deleted_compound_index") - ); + fieldName(QApplication.application.workspaceId), + fieldName(QApplication.application.name), + fieldName(QApplication.application.deletedAt), + "gitApplicationMetadata.remoteUrl", + "gitApplicationMetadata.branchName") + .unique() + .named("workspace_app_deleted_gitApplicationMetadata")); + ensureIndexes( + mongoTemplate, + Datasource.class, + makeIndex( + fieldName(QDatasource.datasource.workspaceId), + fieldName(QDatasource.datasource.name), + fieldName(QDatasource.datasource.deletedAt)) + .unique() + .named("workspace_datasource_deleted_compound_index")); } @ChangeSet(order = "017", id = "migrate-permission-in-user", author = "") @@ -1145,16 +1159,25 @@ public void migratePermissionsInWorkspace(MongoTemplate mongoTemplate) { } @ChangeSet(order = "019", id = "migrate-organizationId-to-workspaceId-in-newaction-datasource", author = "") - public void migrateOrganizationIdToWorkspaceIdInNewActionDatasource(MongoTemplate mongoTemplate, ReactiveRedisOperations<String, String> reactiveRedisOperations) { + public void migrateOrganizationIdToWorkspaceIdInNewActionDatasource( + MongoTemplate mongoTemplate, ReactiveRedisOperations<String, String> reactiveRedisOperations) { if (mongoTemplate.findOne(new Query(), NewAction.class) == null) { System.out.println("No newAction to migrate."); return; } - mongoTemplate.updateMulti(new Query(Criteria.where("unpublishedAction.datasource.organizationId").exists(true)), - AggregationUpdate.update().set("unpublishedAction.datasource.workspaceId").toValueOf(Fields.field("unpublishedAction.datasource.organizationId")), + mongoTemplate.updateMulti( + new Query(Criteria.where("unpublishedAction.datasource.organizationId") + .exists(true)), + AggregationUpdate.update() + .set("unpublishedAction.datasource.workspaceId") + .toValueOf(Fields.field("unpublishedAction.datasource.organizationId")), NewAction.class); - mongoTemplate.updateMulti(new Query(Criteria.where("publishedAction.datasource.organizationId").exists(true)), - AggregationUpdate.update().set("publishedAction.datasource.workspaceId").toValueOf(Fields.field("publishedAction.datasource.organizationId")), + mongoTemplate.updateMulti( + new Query(Criteria.where("publishedAction.datasource.organizationId") + .exists(true)), + AggregationUpdate.update() + .set("publishedAction.datasource.workspaceId") + .toValueOf(Fields.field("publishedAction.datasource.organizationId")), NewAction.class); } @@ -1162,10 +1185,7 @@ public void migrateOrganizationIdToWorkspaceIdInNewActionDatasource(MongoTemplat public void migrateGoogleSheetsToUqi(MongoTemplate mongoTemplate) { // Get plugin references to Google Sheets actions - Plugin uqiPlugin = mongoTemplate.findOne( - query(where("packageName").in("google-sheets-plugin")), - Plugin.class - ); + Plugin uqiPlugin = mongoTemplate.findOne(query(where("packageName").in("google-sheets-plugin")), Plugin.class); assert uqiPlugin != null; uqiPlugin.setUiComponent("UQIDbEditorForm"); @@ -1174,25 +1194,20 @@ public void migrateGoogleSheetsToUqi(MongoTemplate mongoTemplate) { final String pluginId = uqiPlugin.getId(); // Find all relevant actions - final Query actionQuery = query( - where(fieldName(QNewAction.newAction.pluginId)).is(pluginId) - .and(fieldName(QNewAction.newAction.deleted)).ne(true)); // setting `deleted` != `true` - actionQuery.fields() - .include(fieldName(QNewAction.newAction.id)); + final Query actionQuery = query(where(fieldName(QNewAction.newAction.pluginId)) + .is(pluginId) + .and(fieldName(QNewAction.newAction.deleted)) + .ne(true)); // setting `deleted` != `true` + actionQuery.fields().include(fieldName(QNewAction.newAction.id)); - List<NewAction> uqiActions = mongoTemplate.find( - actionQuery, - NewAction.class - ); + List<NewAction> uqiActions = mongoTemplate.find(actionQuery, NewAction.class); // Retrieve the formData path for all actions for (NewAction uqiActionWithId : uqiActions) { // Fetch one action at a time to avoid OOM. final NewAction uqiAction = mongoTemplate.findOne( - query(where(fieldName(QNewAction.newAction.id)).is(uqiActionWithId.getId())), - NewAction.class - ); + query(where(fieldName(QNewAction.newAction.id)).is(uqiActionWithId.getId())), NewAction.class); assert uqiAction != null; ActionDTO unpublishedAction = uqiAction.getUnpublishedAction(); @@ -1231,9 +1246,7 @@ public static void migrateGoogleSheetsToUqi(NewAction uqiAction) { Map.entry(11, List.of("rowIndex.data")), Map.entry(12, List.of("")), // We do not expect deleteFormat to have been dynamically bound at all Map.entry(13, List.of("smartSubstitution.data")), - Map.entry(14, List.of("where.data")) - - ); + Map.entry(14, List.of("where.data"))); ActionDTO unpublishedAction = uqiAction.getUnpublishedAction(); /** @@ -1254,8 +1267,8 @@ public static void migrateGoogleSheetsToUqi(NewAction uqiAction) { } List<Property> dynamicBindingPathList = unpublishedAction.getDynamicBindingPathList(); - List<Property> newDynamicBindingPathList = getUpdatedDynamicBindingPathList(dynamicBindingPathList, - objectMapper, uqiAction, googleSheetsMigrationMap); + List<Property> newDynamicBindingPathList = getUpdatedDynamicBindingPathList( + dynamicBindingPathList, objectMapper, uqiAction, googleSheetsMigrationMap); unpublishedAction.setDynamicBindingPathList(newDynamicBindingPathList); } @@ -1267,7 +1280,8 @@ private static void mapGoogleSheetsToNewFormData(ActionDTO action, Map<String, O throw new AppsmithException(AppsmithError.MIGRATION_ERROR); } - final List<Property> pluginSpecifiedTemplates = action.getActionConfiguration().getPluginSpecifiedTemplates(); + final List<Property> pluginSpecifiedTemplates = + action.getActionConfiguration().getPluginSpecifiedTemplates(); if (pluginSpecifiedTemplates == null || pluginSpecifiedTemplates.isEmpty()) { // Nothing to do with this action, it is already incorrectly configured @@ -1323,35 +1337,56 @@ private static void mapGoogleSheetsToNewFormData(ActionDTO action, Map<String, O switch (pluginSpecifiedTemplatesSize) { case 15: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(14)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(14).getValue())) { - convertToFormDataObject(f, "where", updateWhereClauseFormat(pluginSpecifiedTemplates.get(14).getValue())); + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(14)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(14).getValue())) { + convertToFormDataObject( + f, + "where", + updateWhereClauseFormat( + pluginSpecifiedTemplates.get(14).getValue())); } case 14: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(13)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(13).getValue())) { - convertToFormDataObject(f, "smartSubstitution", pluginSpecifiedTemplates.get(13).getValue()); + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(13)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(13).getValue())) { + convertToFormDataObject( + f, + "smartSubstitution", + pluginSpecifiedTemplates.get(13).getValue()); } case 13: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(12)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(12).getValue()) && "DELETE".equals(oldCommand)) { - convertToFormDataObject(f, "entityType", pluginSpecifiedTemplates.get(12).getValue()); + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(12)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(12).getValue()) + && "DELETE".equals(oldCommand)) { + convertToFormDataObject( + f, "entityType", pluginSpecifiedTemplates.get(12).getValue()); } case 12: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(11)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(11).getValue())) { - convertToFormDataObject(f, "rowIndex", pluginSpecifiedTemplates.get(11).getValue()); + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(11)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(11).getValue())) { + convertToFormDataObject( + f, "rowIndex", pluginSpecifiedTemplates.get(11).getValue()); } case 11: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(10)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(10).getValue())) { + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(10)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(10).getValue())) { if (List.of("BULK_APPEND", "BULK_UPDATE", "CREATE").contains(oldCommand)) { - convertToFormDataObject(f, "rowObjects", pluginSpecifiedTemplates.get(10).getValue()); + convertToFormDataObject( + f, + "rowObjects", + pluginSpecifiedTemplates.get(10).getValue()); } } case 10: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(9)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(9).getValue())) { + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(9)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(9).getValue())) { if (List.of("APPEND", "UPDATE").contains(oldCommand)) { - convertToFormDataObject(f, "rowObjects", pluginSpecifiedTemplates.get(9).getValue()); + convertToFormDataObject( + f, "rowObjects", pluginSpecifiedTemplates.get(9).getValue()); } } case 9: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(8)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(8).getValue())) { + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(8)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(8).getValue())) { if (!f.containsKey("pagination")) { final HashMap<String, Object> map = new HashMap<>(); map.put("offset", pluginSpecifiedTemplates.get(8).getValue()); @@ -1361,11 +1396,13 @@ private static void mapGoogleSheetsToNewFormData(ActionDTO action, Map<String, O final Map<String, Object> data = (Map<String, Object>) pagination.get("data"); final Map<String, Object> componentData = (Map<String, Object>) pagination.get("componentData"); data.put("offset", pluginSpecifiedTemplates.get(8).getValue()); - componentData.put("offset", pluginSpecifiedTemplates.get(8).getValue()); + componentData.put( + "offset", pluginSpecifiedTemplates.get(8).getValue()); } } case 8: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(7)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(7).getValue())) { + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(7)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(7).getValue())) { // Sheet name will now have a dropdown component that is selected from a pre-populated list. // Bindings would need to be placed in the JS mode boolean hasBinding = false; @@ -1374,10 +1411,12 @@ private static void mapGoogleSheetsToNewFormData(ActionDTO action, Map<String, O return dynamicBindingPath.getKey().contains("pluginSpecifiedTemplates[7]"); }); } - convertToFormDataObject(f, "sheetName", pluginSpecifiedTemplates.get(7).getValue(), hasBinding); + convertToFormDataObject( + f, "sheetName", pluginSpecifiedTemplates.get(7).getValue(), hasBinding); } case 7: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(6)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(6).getValue())) { + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(6)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(6).getValue())) { if (!f.containsKey("pagination")) { final HashMap<String, Object> map = new HashMap<>(); map.put("limit", pluginSpecifiedTemplates.get(6).getValue()); @@ -1387,27 +1426,41 @@ private static void mapGoogleSheetsToNewFormData(ActionDTO action, Map<String, O final Map<String, Object> data = (Map<String, Object>) pagination.get("data"); final Map<String, Object> componentData = (Map<String, Object>) pagination.get("componentData"); data.put("limit", pluginSpecifiedTemplates.get(6).getValue()); - componentData.put("limit", pluginSpecifiedTemplates.get(6).getValue()); + componentData.put( + "limit", pluginSpecifiedTemplates.get(6).getValue()); } } case 6: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(5)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(5).getValue())) { - convertToFormDataObject(f, "queryFormat", pluginSpecifiedTemplates.get(5).getValue()); + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(5)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(5).getValue())) { + convertToFormDataObject( + f, "queryFormat", pluginSpecifiedTemplates.get(5).getValue()); } case 5: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(4)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(4).getValue())) { - convertToFormDataObject(f, "tableHeaderIndex", pluginSpecifiedTemplates.get(4).getValue()); + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(4)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(4).getValue())) { + convertToFormDataObject( + f, + "tableHeaderIndex", + pluginSpecifiedTemplates.get(4).getValue()); } case 4: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(3)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(3).getValue())) { - convertToFormDataObject(f, "spreadsheetName", pluginSpecifiedTemplates.get(3).getValue()); + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(3)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(3).getValue())) { + convertToFormDataObject( + f, + "spreadsheetName", + pluginSpecifiedTemplates.get(3).getValue()); } case 3: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(2)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(2).getValue())) { - convertToFormDataObject(f, "range", pluginSpecifiedTemplates.get(2).getValue()); + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(2)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(2).getValue())) { + convertToFormDataObject( + f, "range", pluginSpecifiedTemplates.get(2).getValue()); } case 2: - if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(1)) && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(1).getValue())) { + if (!ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(1)) + && !ObjectUtils.isEmpty(pluginSpecifiedTemplates.get(1).getValue())) { // Sheet URL will now have a dropdown component that is selected from a pre-populated list. // Bindings would need to be placed in the JS mode boolean hasBinding = false; @@ -1416,18 +1469,19 @@ private static void mapGoogleSheetsToNewFormData(ActionDTO action, Map<String, O return dynamicBindingPath.getKey().contains("pluginSpecifiedTemplates[1]"); }); } - final String spreadsheetUrl = (String) pluginSpecifiedTemplates.get(1).getValue(); + final String spreadsheetUrl = + (String) pluginSpecifiedTemplates.get(1).getValue(); final Matcher matcher = sheetRangePattern.matcher(spreadsheetUrl); if (matcher.find()) { - final String newSpreadsheetUrl = matcher.replaceAll("https://docs.google.com/spreadsheets/d/" + matcher.group(1) + "/edit"); + final String newSpreadsheetUrl = matcher.replaceAll( + "https://docs.google.com/spreadsheets/d/" + matcher.group(1) + "/edit"); convertToFormDataObject(f, "sheetUrl", newSpreadsheetUrl, hasBinding); } else { convertToFormDataObject(f, "sheetUrl", spreadsheetUrl, hasBinding); } } } - } private static Map<String, Object> updateWhereClauseFormat(Object oldWhereClauseArray) { @@ -1435,31 +1489,28 @@ private static Map<String, Object> updateWhereClauseFormat(Object oldWhereClause newWhereClause.put("condition", "AND"); final List<Object> convertedConditionArray = new ArrayList<>(); - if (oldWhereClauseArray instanceof List) { - ((ArrayList) oldWhereClauseArray) - .stream() - .forEach(oldWhereClauseCondition -> { - if (oldWhereClauseCondition != null) { - Map<String, Object> newWhereClauseCondition = new HashMap<>(); - final Map clauseCondition = (Map) oldWhereClauseCondition; - if (clauseCondition.isEmpty()) { - return; - } - if (clauseCondition.containsKey("path")) { - newWhereClauseCondition.put("key", clauseCondition.get("path")); - } - if (clauseCondition.containsKey("operator")) { - newWhereClauseCondition.put("condition", clauseCondition.get("operator")); - } else { - newWhereClauseCondition.put("condition", "LT"); - } - if (clauseCondition.containsKey("value")) { - newWhereClauseCondition.put("value", clauseCondition.get("value")); - } - convertedConditionArray.add(newWhereClauseCondition); - } - }); + ((ArrayList) oldWhereClauseArray).stream().forEach(oldWhereClauseCondition -> { + if (oldWhereClauseCondition != null) { + Map<String, Object> newWhereClauseCondition = new HashMap<>(); + final Map clauseCondition = (Map) oldWhereClauseCondition; + if (clauseCondition.isEmpty()) { + return; + } + if (clauseCondition.containsKey("path")) { + newWhereClauseCondition.put("key", clauseCondition.get("path")); + } + if (clauseCondition.containsKey("operator")) { + newWhereClauseCondition.put("condition", clauseCondition.get("operator")); + } else { + newWhereClauseCondition.put("condition", "LT"); + } + if (clauseCondition.containsKey("value")) { + newWhereClauseCondition.put("value", clauseCondition.get("value")); + } + convertedConditionArray.add(newWhereClauseCondition); + } + }); } if (!convertedConditionArray.isEmpty()) { @@ -1474,15 +1525,19 @@ public void clearRedisCache2(ReactiveRedisOperations<String, String> reactiveRed DatabaseChangelog1.doClearRedisKeys(reactiveRedisOperations); } - private List<String> getCustomizedThemeIds(String fieldName, Function<Application, String> getThemeIdMethod, List<String> systemThemeIds, MongoTemplate mongoTemplate) { + private List<String> getCustomizedThemeIds( + String fieldName, + Function<Application, String> getThemeIdMethod, + List<String> systemThemeIds, + MongoTemplate mongoTemplate) { // query to get application having a customized theme in the provided fieldName - Query getAppsWithCustomTheme = new Query( - Criteria.where(fieldName(QApplication.application.gitApplicationMetadata)).exists(true) - .and(fieldName(QApplication.application.deleted)).is(false) - .andOperator( - where(fieldName).nin(systemThemeIds), where(fieldName).exists(true) - ) - ); + Query getAppsWithCustomTheme = new Query(Criteria.where( + fieldName(QApplication.application.gitApplicationMetadata)) + .exists(true) + .and(fieldName(QApplication.application.deleted)) + .is(false) + .andOperator( + where(fieldName).nin(systemThemeIds), where(fieldName).exists(true))); // we need the provided field "fieldName" only getAppsWithCustomTheme.fields().include(fieldName); @@ -1493,35 +1548,46 @@ private List<String> getCustomizedThemeIds(String fieldName, Function<Applicatio @ChangeSet(order = "022", id = "fix-deleted-themes-when-git-branch-deleted", author = "") public void fixDeletedThemesWhenGitBranchDeleted(MongoTemplate mongoTemplate) { - Query getSystemThemesQuery = new Query(Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(TRUE)); + Query getSystemThemesQuery = + new Query(Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(TRUE)); getSystemThemesQuery.fields().include(fieldName(QTheme.theme.id)); List<Theme> systemThemes = mongoTemplate.find(getSystemThemesQuery, Theme.class); - List<String> systemThemeIds = systemThemes.stream().map(BaseDomain::getId).collect(Collectors.toList()); + List<String> systemThemeIds = + systemThemes.stream().map(BaseDomain::getId).collect(Collectors.toList()); List<String> customizedEditModeThemeIds = getCustomizedThemeIds( - fieldName(QApplication.application.editModeThemeId), Application::getEditModeThemeId, systemThemeIds, mongoTemplate - ); + fieldName(QApplication.application.editModeThemeId), + Application::getEditModeThemeId, + systemThemeIds, + mongoTemplate); List<String> customizedPublishedModeThemeIds = getCustomizedThemeIds( - fieldName(QApplication.application.publishedModeThemeId), Application::getPublishedModeThemeId, systemThemeIds, mongoTemplate - ); + fieldName(QApplication.application.publishedModeThemeId), + Application::getPublishedModeThemeId, + systemThemeIds, + mongoTemplate); // combine the theme ids Set<String> set = new HashSet<>(); set.addAll(customizedEditModeThemeIds); set.addAll(customizedPublishedModeThemeIds); - Update update = new Update().set(fieldName(QTheme.theme.deleted), false) - .unset(fieldName(QTheme.theme.deletedAt)); - Criteria deletedCustomThemes = Criteria.where(fieldName(QTheme.theme.id)).in(set) - .and(fieldName(QTheme.theme.deleted)).is(true); + Update update = + new Update().set(fieldName(QTheme.theme.deleted), false).unset(fieldName(QTheme.theme.deletedAt)); + Criteria deletedCustomThemes = Criteria.where(fieldName(QTheme.theme.id)) + .in(set) + .and(fieldName(QTheme.theme.deleted)) + .is(true); mongoTemplate.updateMulti(new Query(deletedCustomThemes), update, Theme.class); for (String editModeThemeId : customizedEditModeThemeIds) { - Query query = new Query(Criteria.where(fieldName(QApplication.application.editModeThemeId)).is(editModeThemeId)) - .addCriteria(where(fieldName(QApplication.application.deleted)).is(false)) - .addCriteria(where(fieldName(QApplication.application.gitApplicationMetadata)).exists(true)); + Query query = new Query(Criteria.where(fieldName(QApplication.application.editModeThemeId)) + .is(editModeThemeId)) + .addCriteria( + where(fieldName(QApplication.application.deleted)).is(false)) + .addCriteria(where(fieldName(QApplication.application.gitApplicationMetadata)) + .exists(true)); query.fields().include(fieldName(QApplication.application.id)); List<Application> applicationList = mongoTemplate.find(query, Application.class); @@ -1530,7 +1596,8 @@ public void fixDeletedThemesWhenGitBranchDeleted(MongoTemplate mongoTemplate) { applicationList.remove(applicationList.size() - 1); // clone the custom theme for each of these applications - Query themeQuery = new Query(Criteria.where(fieldName(QTheme.theme.id)).is(editModeThemeId)) + Query themeQuery = new Query( + Criteria.where(fieldName(QTheme.theme.id)).is(editModeThemeId)) .addCriteria(where(fieldName(QTheme.theme.deleted)).is(false)); Theme theme = mongoTemplate.findOne(themeQuery, Theme.class); for (Application application : applicationList) { @@ -1540,10 +1607,10 @@ public void fixDeletedThemesWhenGitBranchDeleted(MongoTemplate mongoTemplate) { newTheme.setSystemTheme(false); newTheme = mongoTemplate.insert(newTheme); mongoTemplate.updateFirst( - new Query(Criteria.where(fieldName(QApplication.application.id)).is(application.getId())), + new Query(Criteria.where(fieldName(QApplication.application.id)) + .is(application.getId())), new Update().set(fieldName(QApplication.application.editModeThemeId), newTheme.getId()), - Application.class - ); + Application.class); } } } @@ -1556,7 +1623,8 @@ public void addAnonymousUser(MongoTemplate mongoTemplate) { Tenant tenant = mongoTemplate.findOne(tenantQuery, Tenant.class); Query userQuery = new Query(); - userQuery.addCriteria(where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER)) + userQuery + .addCriteria(where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER)) .addCriteria(where(fieldName(QUser.user.tenantId)).is(tenant.getId())); User anonymousUser = mongoTemplate.findOne(userQuery, User.class); @@ -1577,7 +1645,8 @@ private String getDefaultNameForGroupInWorkspace(String prefix, String workspace return prefix + " - " + workspaceName; } - private Set<PermissionGroup> generateDefaultPermissionGroupsWithoutPermissions(MongoTemplate mongoTemplate, Workspace workspace) { + private Set<PermissionGroup> generateDefaultPermissionGroupsWithoutPermissions( + MongoTemplate mongoTemplate, Workspace workspace) { String workspaceName = workspace.getName(); String workspaceId = workspace.getId(); Set<Permission> permissions = new HashSet<>(); @@ -1601,7 +1670,8 @@ private Set<PermissionGroup> generateDefaultPermissionGroupsWithoutPermissions(M developerPermissionGroup.setDescription(FieldName.WORKSPACE_DEVELOPER_DESCRIPTION); developerPermissionGroup = mongoTemplate.save(developerPermissionGroup); // This ensures that a user can leave a permission group - permissions = Set.of(new Permission(developerPermissionGroup.getId(), AclPermission.UNASSIGN_PERMISSION_GROUPS)); + permissions = + Set.of(new Permission(developerPermissionGroup.getId(), AclPermission.UNASSIGN_PERMISSION_GROUPS)); developerPermissionGroup.setPermissions(permissions); developerPermissionGroup = mongoTemplate.save(developerPermissionGroup); @@ -1620,36 +1690,44 @@ private Set<PermissionGroup> generateDefaultPermissionGroupsWithoutPermissions(M return Set.of(adminPermissionGroup, developerPermissionGroup, viewerPermissionGroup); } - private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups(MongoTemplate mongoTemplate, PolicySolution policySolution, Set<PermissionGroup> permissionGroups, Workspace workspace, Map<String, String> userIdForEmail, Set<String> validUserIds) { + private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups( + MongoTemplate mongoTemplate, + PolicySolution policySolution, + Set<PermissionGroup> permissionGroups, + Workspace workspace, + Map<String, String> userIdForEmail, + Set<String> validUserIds) { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) - .findFirst().get(); + .findFirst() + .get(); // Administrator permissions - Set<Permission> workspacePermissions = AppsmithRole.ORGANIZATION_ADMIN - .getPermissions() - .stream() + Set<Permission> workspacePermissions = AppsmithRole.ORGANIZATION_ADMIN.getPermissions().stream() .filter(aclPermission -> aclPermission.getEntity().equals(Workspace.class)) .map(aclPermission -> new Permission(workspace.getId(), aclPermission)) .collect(Collectors.toSet()); Set<Permission> readPermissionGroupPermissions = permissionGroups.stream() - .map(permissionGroup -> new Permission(permissionGroup.getId(), AclPermission.READ_PERMISSION_GROUP_MEMBERS)) + .map(permissionGroup -> + new Permission(permissionGroup.getId(), AclPermission.READ_PERMISSION_GROUP_MEMBERS)) .collect(Collectors.toSet()); Set<Permission> unassignPermissionGroupPermissions = permissionGroups.stream() - .map(permissionGroup -> new Permission(permissionGroup.getId(), AclPermission.UNASSIGN_PERMISSION_GROUPS)) + .map(permissionGroup -> + new Permission(permissionGroup.getId(), AclPermission.UNASSIGN_PERMISSION_GROUPS)) .collect(Collectors.toSet()); Set<Permission> assignPermissionGroupPermissions = permissionGroups.stream() .map(permissionGroup -> new Permission(permissionGroup.getId(), AclPermission.ASSIGN_PERMISSION_GROUPS)) .collect(Collectors.toSet()); - List<UserRole> userRoles = workspace.getUserRoles() - .stream() + List<UserRole> userRoles = workspace.getUserRoles().stream() .map(userRole -> { // If userId is not valid populate it with the userId mapped to the email // This happens if user is deleted manually from database and re-added again @@ -1663,9 +1741,9 @@ private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups(Mongo } return userRole; }) - //filter out the users who are still not valid + // filter out the users who are still not valid .filter(userRole -> userRole.getUserId() != null) - //collect the user roles into a list + // collect the user roles into a list .collect(Collectors.toList()); Set<Permission> permissions = new HashSet<>(adminPermissionGroup.getPermissions()); @@ -1676,8 +1754,7 @@ private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups(Mongo adminPermissionGroup.setPermissions(permissions); // Assign admin user ids to the administrator permission group - Set<String> adminUserIds = userRoles - .stream() + Set<String> adminUserIds = userRoles.stream() .filter(userRole -> userRole.getRole().equals(AppsmithRole.ORGANIZATION_ADMIN)) .map(UserRole::getUserId) .collect(Collectors.toSet()); @@ -1685,9 +1762,7 @@ private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups(Mongo adminPermissionGroup.setAssignedToUserIds(adminUserIds); // Developer Permissions - workspacePermissions = AppsmithRole.ORGANIZATION_DEVELOPER - .getPermissions() - .stream() + workspacePermissions = AppsmithRole.ORGANIZATION_DEVELOPER.getPermissions().stream() .filter(aclPermission -> aclPermission.getEntity().equals(Workspace.class)) .map(aclPermission -> new Permission(workspace.getId(), aclPermission)) .collect(Collectors.toSet()); @@ -1702,8 +1777,7 @@ private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups(Mongo developerPermissionGroup.setPermissions(permissions); // Assign developer user ids to the developer permission group - Set<String> developerUserIds = userRoles - .stream() + Set<String> developerUserIds = userRoles.stream() .filter(userRole -> userRole.getRole().equals(AppsmithRole.ORGANIZATION_DEVELOPER)) .map(UserRole::getUserId) .collect(Collectors.toSet()); @@ -1711,9 +1785,7 @@ private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups(Mongo developerPermissionGroup.setAssignedToUserIds(developerUserIds); // App Viewer Permissions - workspacePermissions = AppsmithRole.ORGANIZATION_VIEWER - .getPermissions() - .stream() + workspacePermissions = AppsmithRole.ORGANIZATION_VIEWER.getPermissions().stream() .filter(aclPermission -> aclPermission.getEntity().equals(Workspace.class)) .map(aclPermission -> new Permission(workspace.getId(), aclPermission)) .collect(Collectors.toSet()); @@ -1728,20 +1800,21 @@ private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups(Mongo viewerPermissionGroup.setPermissions(permissions); // Assign viewer user ids to the viewer permission group - Set<String> viewerUserIds = userRoles - .stream() + Set<String> viewerUserIds = userRoles.stream() .filter(userRole -> userRole.getRole().equals(AppsmithRole.ORGANIZATION_VIEWER)) .map(UserRole::getUserId) .collect(Collectors.toSet()); viewerPermissionGroup.setAssignedToUserIds(viewerUserIds); - Set<PermissionGroup> savedPermissionGroups = Set.of(adminPermissionGroup, developerPermissionGroup, viewerPermissionGroup); + Set<PermissionGroup> savedPermissionGroups = + Set.of(adminPermissionGroup, developerPermissionGroup, viewerPermissionGroup); // Apply the permissions to the permission groups for (PermissionGroup permissionGroup : savedPermissionGroups) { for (PermissionGroup nestedPermissionGroup : savedPermissionGroups) { - Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject(permissionGroup, nestedPermissionGroup.getId()); + Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject( + permissionGroup, nestedPermissionGroup.getId()); policySolution.addPoliciesToExistingObject(policyMap, nestedPermissionGroup); } } @@ -1756,13 +1829,19 @@ private Set<PermissionGroup> generatePermissionsForDefaultPermissionGroups(Mongo private void rollbackAddDefaultPermissionGroups(MongoTemplate mongoTemplate, Workspace workspace) { // Delete the permission groups - mongoTemplate.remove(PermissionGroup.class) - .matching(new Query(Criteria.where(fieldName(QPermissionGroup.permissionGroup.defaultWorkspaceId)).is(workspace.getId()))) + mongoTemplate + .remove(PermissionGroup.class) + .matching(new Query(Criteria.where(fieldName(QPermissionGroup.permissionGroup.defaultWorkspaceId)) + .is(workspace.getId()))) .all(); } @ChangeSet(order = "024", id = "add-default-permission-groups", author = "") - public void addDefaultPermissionGroups(MongoTemplate mongoTemplate, WorkspaceService workspaceService, @NonLockGuarded PolicySolution policySolution, UserRepository userRepository) { + public void addDefaultPermissionGroups( + MongoTemplate mongoTemplate, + WorkspaceService workspaceService, + @NonLockGuarded PolicySolution policySolution, + UserRepository userRepository) { // Create a map of emails to userIds Map<String, String> userIdForEmail = mongoTemplate.stream(new Query(), User.class) @@ -1776,19 +1855,24 @@ public void addDefaultPermissionGroups(MongoTemplate mongoTemplate, WorkspaceSer .forEach(workspace -> { rollbackAddDefaultPermissionGroups(mongoTemplate, workspace); // unlock the workspace - mongoTemplate.update(Workspace.class) + mongoTemplate + .update(Workspace.class) .matching(new Criteria("_id").is(new ObjectId(workspace.getId()))) .apply(new Update().unset("locked")) .first(); }); // Stream workspaces which does not have default permission groups - mongoTemplate.stream(new Query(Criteria.where(fieldName(QWorkspace.workspace.defaultPermissionGroups)).is(null)), Workspace.class) + mongoTemplate.stream( + new Query(Criteria.where(fieldName(QWorkspace.workspace.defaultPermissionGroups)) + .is(null)), + Workspace.class) .forEach(workspace -> { if (workspace.getUserRoles() != null) { - //lock the workspace - mongoTemplate.update(Workspace.class) + // lock the workspace + mongoTemplate + .update(Workspace.class) .matching(new Criteria("_id").is(new ObjectId(workspace.getId()))) .apply(new Update().set("locked", true)) .first(); @@ -1798,22 +1882,33 @@ public void addDefaultPermissionGroups(MongoTemplate mongoTemplate, WorkspaceSer workspace.getPolicies().forEach(policy -> { policy.setPermissionGroups(new HashSet<>()); }); - Set<PermissionGroup> permissionGroups = generateDefaultPermissionGroupsWithoutPermissions(mongoTemplate, workspace); + Set<PermissionGroup> permissionGroups = + generateDefaultPermissionGroupsWithoutPermissions(mongoTemplate, workspace); // Set default permission groups - workspace.setDefaultPermissionGroups(permissionGroups.stream().map(PermissionGroup::getId).collect(Collectors.toSet())); + workspace.setDefaultPermissionGroups(permissionGroups.stream() + .map(PermissionGroup::getId) + .collect(Collectors.toSet())); // Generate permissions and policies for the default permission groups - permissionGroups = generatePermissionsForDefaultPermissionGroups(mongoTemplate, policySolution, permissionGroups, workspace, userIdForEmail, validUserIds); + permissionGroups = generatePermissionsForDefaultPermissionGroups( + mongoTemplate, + policySolution, + permissionGroups, + workspace, + userIdForEmail, + validUserIds); // Apply the permissions to the workspace for (PermissionGroup permissionGroup : permissionGroups) { // Apply the permissions to the workspace - Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject(permissionGroup, workspace.getId()); + Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject( + permissionGroup, workspace.getId()); workspace = policySolution.addPoliciesToExistingObject(policyMap, workspace); } // Save the workspace mongoTemplate.save(workspace); // unlock the workspace - mongoTemplate.update(Workspace.class) + mongoTemplate + .update(Workspace.class) .matching(new Criteria("_id").is(new ObjectId(workspace.getId()))) .apply(new Update().unset("locked")) .first(); @@ -1823,69 +1918,106 @@ public void addDefaultPermissionGroups(MongoTemplate mongoTemplate, WorkspaceSer @ChangeSet(order = "025", id = "mark-public-apps", author = "") public void markPublicApps(MongoTemplate mongoTemplate) { - //Temporarily mark public applications - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where("policies").elemMatch(Criteria.where("permission").is(AclPermission.READ_APPLICATIONS.getValue()).and("users").is("anonymousUser"))), + // Temporarily mark public applications + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where("policies") + .elemMatch(Criteria.where("permission") + .is(AclPermission.READ_APPLICATIONS.getValue()) + .and("users") + .is("anonymousUser"))), new Update().set("makePublic", true), Application.class); } @ChangeSet(order = "026", id = "mark-workspaces-for-inheritance", author = "") public void markWorkspacesForInheritance(MongoTemplate mongoTemplate) { - //Temporarily mark all workspaces for processing of permissions inheritance - mongoTemplate.updateMulti(new Query(), - new Update().set("inheritPermissions", true), - Workspace.class); + // Temporarily mark all workspaces for processing of permissions inheritance + mongoTemplate.updateMulti(new Query(), new Update().set("inheritPermissions", true), Workspace.class); } @ChangeSet(order = "027", id = "inherit-policies-to-every-child-object", author = "") - public void inheritPoliciesToEveryChildObject(MongoTemplate mongoTemplate, @NonLockGuarded PolicyGenerator policyGenerator) { + public void inheritPoliciesToEveryChildObject( + MongoTemplate mongoTemplate, @NonLockGuarded PolicyGenerator policyGenerator) { mongoTemplate.stream(new Query(Criteria.where("inheritPermissions").is(true)), Workspace.class) .forEach(workspace -> { // Process applications - Set<Policy> applicationPolicies = policyGenerator.getAllChildPolicies(workspace.getPolicies(), Workspace.class, Application.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QApplication.application.workspaceId)).is(workspace.getId())), + Set<Policy> applicationPolicies = policyGenerator.getAllChildPolicies( + workspace.getPolicies(), Workspace.class, Application.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QApplication.application.workspaceId)) + .is(workspace.getId())), new Update().set("policies", applicationPolicies), Application.class); // Process datasources - Set<Policy> datasourcePolicies = policyGenerator.getAllChildPolicies(workspace.getPolicies(), Workspace.class, Datasource.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QDatasource.datasource.workspaceId)).is(workspace.getId())), + Set<Policy> datasourcePolicies = policyGenerator.getAllChildPolicies( + workspace.getPolicies(), Workspace.class, Datasource.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QDatasource.datasource.workspaceId)) + .is(workspace.getId())), new Update().set("policies", datasourcePolicies), Datasource.class); // Get application ids - Set<String> applicationIds = mongoTemplate.stream(new Query().addCriteria(Criteria.where(fieldName(QApplication.application.workspaceId)).is(workspace.getId())), Application.class) + Set<String> applicationIds = mongoTemplate.stream( + new Query() + .addCriteria(Criteria.where(fieldName(QApplication.application.workspaceId)) + .is(workspace.getId())), + Application.class) .map(Application::getId) .collect(Collectors.toSet()); // Update pages - Set<Policy> pagePolicies = policyGenerator.getAllChildPolicies(applicationPolicies, Application.class, Page.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QNewPage.newPage.applicationId)).in(applicationIds)), + Set<Policy> pagePolicies = + policyGenerator.getAllChildPolicies(applicationPolicies, Application.class, Page.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QNewPage.newPage.applicationId)) + .in(applicationIds)), new Update().set("policies", pagePolicies), NewPage.class); // Update NewActions - Set<Policy> actionPolicies = policyGenerator.getAllChildPolicies(pagePolicies, Page.class, Action.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QNewAction.newAction.applicationId)).in(applicationIds)), + Set<Policy> actionPolicies = + policyGenerator.getAllChildPolicies(pagePolicies, Page.class, Action.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QNewAction.newAction.applicationId)) + .in(applicationIds)), new Update().set("policies", actionPolicies), NewAction.class); // Update ActionCollections - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QActionCollection.actionCollection.applicationId)).in(applicationIds)), + mongoTemplate.updateMulti( + new Query() + .addCriteria( + Criteria.where(fieldName(QActionCollection.actionCollection.applicationId)) + .in(applicationIds)), new Update().set("policies", actionPolicies), ActionCollection.class); // Update Themes // First update all the named themes with the new policies - Set<Policy> themePolicies = policyGenerator.getAllChildPolicies(applicationPolicies, Application.class, Theme.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QTheme.theme.applicationId)).in(applicationIds)), + Set<Policy> themePolicies = + policyGenerator.getAllChildPolicies(applicationPolicies, Application.class, Theme.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QTheme.theme.applicationId)) + .in(applicationIds)), new Update().set("policies", themePolicies), Theme.class); // Also update the non-named themes. // Get the theme ids to update - Set<String> themeIdSet = mongoTemplate.stream(new Query().addCriteria(Criteria.where(fieldName(QApplication.application.workspaceId)).is(workspace.getId())), Application.class) + Set<String> themeIdSet = mongoTemplate.stream( + new Query() + .addCriteria(Criteria.where(fieldName(QApplication.application.workspaceId)) + .is(workspace.getId())), + Application.class) .flatMap(application -> { Set<String> themeIds = new HashSet<>(); if (application.getEditModeThemeId() != null) { @@ -1898,26 +2030,34 @@ public void inheritPoliciesToEveryChildObject(MongoTemplate mongoTemplate, @NonL }) .collect(Collectors.toSet()); - Criteria nonSystemThemeCriteria = Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(false); - Criteria idCriteria = Criteria.where(fieldName(QTheme.theme.id)).in(themeIdSet); + Criteria nonSystemThemeCriteria = Criteria.where(fieldName(QTheme.theme.isSystemTheme)) + .is(false); + Criteria idCriteria = + Criteria.where(fieldName(QTheme.theme.id)).in(themeIdSet); Criteria queryCriteria = new Criteria().andOperator(nonSystemThemeCriteria, idCriteria); // Add the policies to the un-named themes as well. mongoTemplate.updateMulti( - new Query(queryCriteria), - new Update().set("policies", themePolicies), - Theme.class); + new Query(queryCriteria), new Update().set("policies", themePolicies), Theme.class); // Processed, remove temporary flag - mongoTemplate.update(Workspace.class) + mongoTemplate + .update(Workspace.class) .matching(new Criteria("_id").is(new ObjectId(workspace.getId()))) .apply(new Update().unset("inheritPermissions")) .first(); }); } - private void makeApplicationPublic(PolicySolution policySolution, PolicyGenerator policyGenerator, NewPageRepository newPageRepository, Application application, Workspace workspace, MongoTemplate mongoTemplate, User anonymousUser) { + private void makeApplicationPublic( + PolicySolution policySolution, + PolicyGenerator policyGenerator, + NewPageRepository newPageRepository, + Application application, + Workspace workspace, + MongoTemplate mongoTemplate, + User anonymousUser) { PermissionGroup publicPermissionGroup = new PermissionGroup(); publicPermissionGroup.setName(application.getName() + " Public"); publicPermissionGroup.setTenantId(workspace.getTenantId()); @@ -1931,13 +2071,15 @@ private void makeApplicationPublic(PolicySolution policySolution, PolicyGenerato .findFirst() .get(); - // Let this newly created permission group be assignable by everyone who has permission for make public application + // Let this newly created permission group be assignable by everyone who has permission for make public + // application Policy assignPermissionGroup = Policy.builder() .permission(AclPermission.ASSIGN_PERMISSION_GROUPS.getValue()) .permissionGroups(makePublicPolicy.getPermissionGroups()) .build(); - // Let this newly created permission group be assignable by everyone who has permission for make public application + // Let this newly created permission group be assignable by everyone who has permission for make public + // application Policy unassignPermissionGroup = Policy.builder() .permission(AclPermission.UNASSIGN_PERMISSION_GROUPS.getValue()) .permissionGroups(makePublicPolicy.getPermissionGroups()) @@ -1951,26 +2093,30 @@ private void makeApplicationPublic(PolicySolution policySolution, PolicyGenerato String permissionGroupId = publicPermissionGroup.getId(); - Map<String, Policy> applicationPolicyMap = policySolution - .generatePolicyFromPermissionWithPermissionGroup(AclPermission.READ_APPLICATIONS, permissionGroupId); - Map<String, Policy> datasourcePolicyMap = policySolution - .generatePolicyFromPermissionWithPermissionGroup(AclPermission.EXECUTE_DATASOURCES, permissionGroupId); + Map<String, Policy> applicationPolicyMap = policySolution.generatePolicyFromPermissionWithPermissionGroup( + AclPermission.READ_APPLICATIONS, permissionGroupId); + Map<String, Policy> datasourcePolicyMap = policySolution.generatePolicyFromPermissionWithPermissionGroup( + AclPermission.EXECUTE_DATASOURCES, permissionGroupId); Set<String> datasourceIds = new HashSet<>(); - mongoTemplate.stream(new Query().addCriteria(Criteria.where(fieldName(QNewAction.newAction.applicationId)).is(application.getId())), NewAction.class) + mongoTemplate.stream( + new Query() + .addCriteria(Criteria.where(fieldName(QNewAction.newAction.applicationId)) + .is(application.getId())), + NewAction.class) .forEach(newAction -> { ActionDTO unpublishedAction = newAction.getUnpublishedAction(); ActionDTO publishedAction = newAction.getPublishedAction(); - if (unpublishedAction.getDatasource() != null && - unpublishedAction.getDatasource().getId() != null) { + if (unpublishedAction.getDatasource() != null + && unpublishedAction.getDatasource().getId() != null) { datasourceIds.add(unpublishedAction.getDatasource().getId()); } - if (publishedAction != null && - publishedAction.getDatasource() != null && - publishedAction.getDatasource().getId() != null) { + if (publishedAction != null + && publishedAction.getDatasource() != null + && publishedAction.getDatasource().getId() != null) { datasourceIds.add(publishedAction.getDatasource().getId()); } }); @@ -1981,116 +2127,168 @@ private void makeApplicationPublic(PolicySolution policySolution, PolicyGenerato applicationPolicies = application.getPolicies(); // Update datasources - mongoTemplate.stream(new Query().addCriteria(Criteria.where(fieldName(QDatasource.datasource.id)).in(datasourceIds)), Datasource.class) + mongoTemplate.stream( + new Query() + .addCriteria(Criteria.where(fieldName(QDatasource.datasource.id)) + .in(datasourceIds)), + Datasource.class) .forEach(datasource -> { datasource = policySolution.addPoliciesToExistingObject(datasourcePolicyMap, datasource); mongoTemplate.save(datasource); }); // Update pages - Set<Policy> pagePolicies = policyGenerator.getAllChildPolicies(applicationPolicies, Application.class, Page.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QNewPage.newPage.applicationId)).is(application.getId())), + Set<Policy> pagePolicies = + policyGenerator.getAllChildPolicies(applicationPolicies, Application.class, Page.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QNewPage.newPage.applicationId)) + .is(application.getId())), new Update().set("policies", pagePolicies), NewPage.class); // Update NewActions Set<Policy> actionPolicies = policyGenerator.getAllChildPolicies(pagePolicies, Page.class, Action.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QNewAction.newAction.applicationId)).is(application.getId())), + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QNewAction.newAction.applicationId)) + .is(application.getId())), new Update().set("policies", actionPolicies), NewAction.class); // Update ActionCollections - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QActionCollection.actionCollection.applicationId)).is(application.getId())), + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QActionCollection.actionCollection.applicationId)) + .is(application.getId())), new Update().set("policies", actionPolicies), ActionCollection.class); // Update Themes - Set<Policy> themePolicies = policyGenerator.getAllChildPolicies(applicationPolicies, Application.class, Theme.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QTheme.theme.applicationId)).is(application.getId())), + Set<Policy> themePolicies = + policyGenerator.getAllChildPolicies(applicationPolicies, Application.class, Theme.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QTheme.theme.applicationId)) + .is(application.getId())), new Update().set("policies", themePolicies), Theme.class); } private void rollbackMakeApplicationsPublic(Application application, MongoTemplate mongoTemplate) { - PermissionGroup publicPermissionGroup = mongoTemplate - .stream(new Query().addCriteria(Criteria.where(fieldName(QPermissionGroup.permissionGroup.defaultWorkspaceId)).is(application.getId())), PermissionGroup.class) + PermissionGroup publicPermissionGroup = mongoTemplate.stream( + new Query() + .addCriteria( + Criteria.where(fieldName(QPermissionGroup.permissionGroup.defaultWorkspaceId)) + .is(application.getId())), + PermissionGroup.class) .findFirst() .orElse(null); if (publicPermissionGroup != null) { // Remove permission group from application policies - application.getPolicies().forEach(permissionGroup -> - permissionGroup.getPermissionGroups().remove(publicPermissionGroup.getId()) - ); + application.getPolicies().forEach(permissionGroup -> permissionGroup + .getPermissionGroups() + .remove(publicPermissionGroup.getId())); mongoTemplate.save(application); Set<String> datasourceIds = new HashSet<>(); - mongoTemplate.stream(new Query().addCriteria(Criteria.where(fieldName(QNewAction.newAction.applicationId)).is(application.getId())), NewAction.class) + mongoTemplate.stream( + new Query() + .addCriteria(Criteria.where(fieldName(QNewAction.newAction.applicationId)) + .is(application.getId())), + NewAction.class) .forEach(newAction -> { - ActionDTO unpublishedAction = newAction.getUnpublishedAction(); ActionDTO publishedAction = newAction.getPublishedAction(); - if (unpublishedAction.getDatasource() != null && - unpublishedAction.getDatasource().getId() != null) { + if (unpublishedAction.getDatasource() != null + && unpublishedAction.getDatasource().getId() != null) { datasourceIds.add(unpublishedAction.getDatasource().getId()); } - if (publishedAction != null && - publishedAction.getDatasource() != null && - publishedAction.getDatasource().getId() != null) { + if (publishedAction != null + && publishedAction.getDatasource() != null + && publishedAction.getDatasource().getId() != null) { datasourceIds.add(publishedAction.getDatasource().getId()); } }); // Remove permission group from datasources policies - mongoTemplate.stream(new Query().addCriteria(Criteria.where(fieldName(QDatasource.datasource.id)).in(datasourceIds)), Datasource.class) + mongoTemplate.stream( + new Query() + .addCriteria(Criteria.where(fieldName(QDatasource.datasource.id)) + .in(datasourceIds)), + Datasource.class) .forEach(datasource -> { - datasource.getPolicies().forEach(permissionGroup -> - permissionGroup.getPermissionGroups().remove(publicPermissionGroup.getId()) - ); + datasource.getPolicies().forEach(permissionGroup -> permissionGroup + .getPermissionGroups() + .remove(publicPermissionGroup.getId())); mongoTemplate.save(datasource); }); - //remove permission group + // remove permission group mongoTemplate.remove(publicPermissionGroup); } } @ChangeSet(order = "028", id = "make-applications-public", author = "") - public void makeApplicationsPublic(MongoTemplate mongoTemplate, @NonLockGuarded PolicySolution policySolution, @NonLockGuarded PolicyGenerator policyGenerator, NewPageRepository newPageRepository) { - User anonymousUser = mongoTemplate.findOne(new Query().addCriteria(Criteria.where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER)), User.class); + public void makeApplicationsPublic( + MongoTemplate mongoTemplate, + @NonLockGuarded PolicySolution policySolution, + @NonLockGuarded PolicyGenerator policyGenerator, + NewPageRepository newPageRepository) { + User anonymousUser = mongoTemplate.findOne( + new Query() + .addCriteria(Criteria.where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER)), + User.class); // Rollback permission groups created on locked workspaces mongoTemplate.stream(new Query(Criteria.where("locked").is(true)), Application.class) .forEach(application -> { rollbackMakeApplicationsPublic(application, mongoTemplate); // unlock the workspace - mongoTemplate.update(Application.class) + mongoTemplate + .update(Application.class) .matching(new Criteria("_id").is(new ObjectId(application.getId()))) .apply(new Update().unset("locked")) .first(); }); // Make all marked applications public - mongoTemplate.stream(new Query().addCriteria(Criteria.where("makePublic").is(true)), Application.class) + mongoTemplate.stream( + new Query().addCriteria(Criteria.where("makePublic").is(true)), Application.class) .forEach(application -> { // lock the application - mongoTemplate.update(Application.class) + mongoTemplate + .update(Application.class) .matching(new Criteria("_id").is(new ObjectId(application.getId()))) .apply(new Update().set("locked", true)) .first(); - Workspace workspace = mongoTemplate.findOne(new Query().addCriteria(Criteria.where(fieldName(QBaseDomain.baseDomain.id)).is(application.getWorkspaceId())), Workspace.class); - makeApplicationPublic(policySolution, policyGenerator, newPageRepository, application, workspace, mongoTemplate, anonymousUser); + Workspace workspace = mongoTemplate.findOne( + new Query() + .addCriteria(Criteria.where(fieldName(QBaseDomain.baseDomain.id)) + .is(application.getWorkspaceId())), + Workspace.class); + makeApplicationPublic( + policySolution, + policyGenerator, + newPageRepository, + application, + workspace, + mongoTemplate, + anonymousUser); // Remove makePublic flag from application - mongoTemplate.updateFirst(new Query().addCriteria(Criteria.where("_id").is(new ObjectId(application.getId()))), + mongoTemplate.updateFirst( + new Query().addCriteria(Criteria.where("_id").is(new ObjectId(application.getId()))), new Update().unset("makePublic"), Application.class); // unlock the application - mongoTemplate.update(Application.class) + mongoTemplate + .update(Application.class) .matching(new Criteria("_id").is(new ObjectId(application.getId()))) .apply(new Update().unset("locked")) .first(); @@ -2100,7 +2298,8 @@ public void makeApplicationsPublic(MongoTemplate mongoTemplate, @NonLockGuarded @ChangeSet(order = "029", id = "add-instance-config-object", author = "") public void addInstanceConfigurationPlaceHolder(MongoTemplate mongoTemplate) { Query instanceConfigurationQuery = new Query(); - instanceConfigurationQuery.addCriteria(where(fieldName(QConfig.config1.name)).is(FieldName.INSTANCE_CONFIG)); + instanceConfigurationQuery.addCriteria( + where(fieldName(QConfig.config1.name)).is(FieldName.INSTANCE_CONFIG)); Config instanceAdminConfiguration = mongoTemplate.findOne(instanceConfigurationQuery, Config.class); if (instanceAdminConfiguration != null) { @@ -2115,10 +2314,7 @@ public void addInstanceConfigurationPlaceHolder(MongoTemplate mongoTemplate) { PermissionGroup instanceManagerPermissionGroup = new PermissionGroup(); instanceManagerPermissionGroup.setName(FieldName.INSTANCE_ADMIN_ROLE); instanceManagerPermissionGroup.setPermissions( - Set.of( - new Permission(savedInstanceConfig.getId(), MANAGE_INSTANCE_CONFIGURATION) - ) - ); + Set.of(new Permission(savedInstanceConfig.getId(), MANAGE_INSTANCE_CONFIGURATION))); Query adminUserQuery = new Query(); adminUserQuery.addCriteria(where(fieldName(QBaseDomain.baseDomain.policies)) @@ -2126,18 +2322,19 @@ public void addInstanceConfigurationPlaceHolder(MongoTemplate mongoTemplate) { List<User> adminUsers = mongoTemplate.find(adminUserQuery, User.class); instanceManagerPermissionGroup.setAssignedToUserIds( - adminUsers.stream().map(User::getId).collect(Collectors.toSet()) - ); + adminUsers.stream().map(User::getId).collect(Collectors.toSet())); PermissionGroup savedPermissionGroup = mongoTemplate.save(instanceManagerPermissionGroup); // Update the instance config with the permission group id savedInstanceConfig.setConfig(new JSONObject(Map.of(DEFAULT_PERMISSION_GROUP, savedPermissionGroup.getId()))); - Policy editConfigPolicy = Policy.builder().permission(MANAGE_INSTANCE_CONFIGURATION.getValue()) + Policy editConfigPolicy = Policy.builder() + .permission(MANAGE_INSTANCE_CONFIGURATION.getValue()) .permissionGroups(Set.of(savedPermissionGroup.getId())) .build(); - Policy readConfigPolicy = Policy.builder().permission(READ_INSTANCE_CONFIGURATION.getValue()) + Policy readConfigPolicy = Policy.builder() + .permission(READ_INSTANCE_CONFIGURATION.getValue()) .permissionGroups(Set.of(savedPermissionGroup.getId())) .build(); @@ -2146,28 +2343,29 @@ public void addInstanceConfigurationPlaceHolder(MongoTemplate mongoTemplate) { mongoTemplate.save(savedInstanceConfig); // Also give the permission group permission to unassign & assign & read to itself - Policy updatePermissionGroupPolicy = Policy.builder().permission(AclPermission.UNASSIGN_PERMISSION_GROUPS.getValue()) + Policy updatePermissionGroupPolicy = Policy.builder() + .permission(AclPermission.UNASSIGN_PERMISSION_GROUPS.getValue()) .permissionGroups(Set.of(savedPermissionGroup.getId())) .build(); - Policy assignPermissionGroupPolicy = Policy.builder().permission(ASSIGN_PERMISSION_GROUPS.getValue()) + Policy assignPermissionGroupPolicy = Policy.builder() + .permission(ASSIGN_PERMISSION_GROUPS.getValue()) .permissionGroups(Set.of(savedPermissionGroup.getId())) .build(); - Policy readPermissionGroupPolicy = Policy.builder().permission(READ_PERMISSION_GROUP_MEMBERS.getValue()) + Policy readPermissionGroupPolicy = Policy.builder() + .permission(READ_PERMISSION_GROUP_MEMBERS.getValue()) .permissionGroups(Set.of(savedPermissionGroup.getId())) .build(); - savedPermissionGroup.setPolicies(new HashSet<>(Set.of(updatePermissionGroupPolicy, assignPermissionGroupPolicy))); + savedPermissionGroup.setPolicies( + new HashSet<>(Set.of(updatePermissionGroupPolicy, assignPermissionGroupPolicy))); Set<Permission> permissions = new HashSet<>(savedPermissionGroup.getPermissions()); - permissions.addAll( - Set.of( - new Permission(savedPermissionGroup.getId(), AclPermission.UNASSIGN_PERMISSION_GROUPS), - new Permission(savedPermissionGroup.getId(), ASSIGN_PERMISSION_GROUPS), - new Permission(savedPermissionGroup.getId(), READ_PERMISSION_GROUP_MEMBERS) - ) - ); + permissions.addAll(Set.of( + new Permission(savedPermissionGroup.getId(), AclPermission.UNASSIGN_PERMISSION_GROUPS), + new Permission(savedPermissionGroup.getId(), ASSIGN_PERMISSION_GROUPS), + new Permission(savedPermissionGroup.getId(), READ_PERMISSION_GROUP_MEMBERS))); savedPermissionGroup.setPermissions(permissions); mongoTemplate.save(savedPermissionGroup); @@ -2176,7 +2374,8 @@ public void addInstanceConfigurationPlaceHolder(MongoTemplate mongoTemplate) { @ChangeSet(order = "030", id = "add-anonymous-user-permission-group", author = "") public void addAnonymousUserPermissionGroup(MongoTemplate mongoTemplate) { Query anonymousUserPermissionConfig = new Query(); - anonymousUserPermissionConfig.addCriteria(where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)); + anonymousUserPermissionConfig.addCriteria( + where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)); Config publicPermissionGroupConfig = mongoTemplate.findOne(anonymousUserPermissionConfig, Config.class); @@ -2193,11 +2392,11 @@ public void addAnonymousUserPermissionGroup(MongoTemplate mongoTemplate) { Tenant tenant = mongoTemplate.findOne(tenantQuery, Tenant.class); Query userQuery = new Query(); - userQuery.addCriteria(where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER)) + userQuery + .addCriteria(where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER)) .addCriteria(where(fieldName(QUser.user.tenantId)).is(tenant.getId())); User anonymousUser = mongoTemplate.findOne(userQuery, User.class); - // Give access to anonymous user to the permission group. publicPermissionGroup.setAssignedToUserIds(Set.of(anonymousUser.getId())); PermissionGroup savedPermissionGroup = mongoTemplate.save(publicPermissionGroup); @@ -2205,7 +2404,8 @@ public void addAnonymousUserPermissionGroup(MongoTemplate mongoTemplate) { publicPermissionGroupConfig = new Config(); publicPermissionGroupConfig.setName(FieldName.PUBLIC_PERMISSION_GROUP); - publicPermissionGroupConfig.setConfig(new JSONObject(Map.of(PERMISSION_GROUP_ID, savedPermissionGroup.getId()))); + publicPermissionGroupConfig.setConfig( + new JSONObject(Map.of(PERMISSION_GROUP_ID, savedPermissionGroup.getId()))); mongoTemplate.save(publicPermissionGroupConfig); return; @@ -2230,22 +2430,26 @@ public void createSystemThemes3(MongoTemplate mongoTemplate) throws IOException final String themesJson = StreamUtils.copyToString( new DefaultResourceLoader().getResource("system-themes.json").getInputStream(), - Charset.defaultCharset() - ); + Charset.defaultCharset()); - Theme[] themes = new GsonBuilder().registerTypeAdapter(Instant.class, new ISOStringToInstantConverter()).create().fromJson(themesJson, Theme[].class); + Theme[] themes = new GsonBuilder() + .registerTypeAdapter(Instant.class, new ISOStringToInstantConverter()) + .create() + .fromJson(themesJson, Theme[].class); Theme legacyTheme = null; boolean themeExists = false; // Make this theme accessible to anonymous users. Query anonymousUserPermissionConfig = new Query(); - anonymousUserPermissionConfig.addCriteria(where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)); + anonymousUserPermissionConfig.addCriteria( + where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)); Config publicPermissionGroupConfig = mongoTemplate.findOne(anonymousUserPermissionConfig, Config.class); String permissionGroupId = publicPermissionGroupConfig.getConfig().getAsString(PERMISSION_GROUP_ID); - PermissionGroup publicPermissionGroup = mongoTemplate.findOne(query(where("_id").is(permissionGroupId)), PermissionGroup.class); + PermissionGroup publicPermissionGroup = + mongoTemplate.findOne(query(where("_id").is(permissionGroupId)), PermissionGroup.class); // Initialize the permissions for the role HashSet<Permission> permissions = new HashSet<>(); @@ -2262,11 +2466,13 @@ public void createSystemThemes3(MongoTemplate mongoTemplate) throws IOException theme.setSystemTheme(true); theme.setCreatedAt(Instant.now()); theme.setPolicies(new HashSet<>(Set.of(policyWithCurrentPermission))); - Query query = new Query(Criteria.where(fieldName(QTheme.theme.name)).is(theme.getName()) - .and(fieldName(QTheme.theme.isSystemTheme)).is(true)); + Query query = new Query(Criteria.where(fieldName(QTheme.theme.name)) + .is(theme.getName()) + .and(fieldName(QTheme.theme.isSystemTheme)) + .is(true)); Theme savedTheme = mongoTemplate.findOne(query, Theme.class); - if (savedTheme == null) { // this theme does not exist, create it + if (savedTheme == null) { // this theme does not exist, create it savedTheme = mongoTemplate.save(theme); } else { // theme already found, update themeExists = true; @@ -2288,7 +2494,8 @@ public void createSystemThemes3(MongoTemplate mongoTemplate) throws IOException // Add the access to this theme to the public permission group Theme finalSavedTheme = savedTheme; boolean isThemePermissionPresent = permissions.stream() - .filter(p -> p.getAclPermission().equals(READ_THEMES) && p.getDocumentId().equals(finalSavedTheme.getId())) + .filter(p -> p.getAclPermission().equals(READ_THEMES) + && p.getDocumentId().equals(finalSavedTheme.getId())) .findFirst() .isPresent(); if (!isThemePermissionPresent) { @@ -2298,11 +2505,11 @@ public void createSystemThemes3(MongoTemplate mongoTemplate) throws IOException if (!themeExists) { // this is the first time we're running the migration // migrate all applications and set legacy theme to them in both mode - Update update = new Update().set(fieldName(QApplication.application.publishedModeThemeId), legacyTheme.getId()) + Update update = new Update() + .set(fieldName(QApplication.application.publishedModeThemeId), legacyTheme.getId()) .set(fieldName(QApplication.application.editModeThemeId), legacyTheme.getId()); mongoTemplate.updateMulti( - new Query(where(fieldName(QApplication.application.deleted)).is(false)), update, Application.class - ); + new Query(where(fieldName(QApplication.application.deleted)).is(false)), update, Application.class); } // Finally save the role which gives access to all the system themes to the anonymous user. @@ -2318,18 +2525,16 @@ public void addPermissionGroupIndex(MongoTemplate mongoTemplate) { public static void doAddPermissionGroupIndex(MongoTemplate mongoTemplate) { dropIndexIfExists(mongoTemplate, PermissionGroup.class, "permission_group_workspace_deleted_compound_index"); - dropIndexIfExists(mongoTemplate, PermissionGroup.class, "permission_group_assignedUserIds_deleted_compound_index"); + dropIndexIfExists( + mongoTemplate, PermissionGroup.class, "permission_group_assignedUserIds_deleted_compound_index"); dropIndexIfExists(mongoTemplate, PermissionGroup.class, "permission_group_assignedUserIds_deleted"); Index assignedToUserIds_deleted_compound_index = makeIndex( - fieldName(QPermissionGroup.permissionGroup.assignedToUserIds), - fieldName(QPermissionGroup.permissionGroup.deleted) - ) + fieldName(QPermissionGroup.permissionGroup.assignedToUserIds), + fieldName(QPermissionGroup.permissionGroup.deleted)) .named("permission_group_assignedUserIds_deleted"); - ensureIndexes(mongoTemplate, PermissionGroup.class, - assignedToUserIds_deleted_compound_index - ); + ensureIndexes(mongoTemplate, PermissionGroup.class, assignedToUserIds_deleted_compound_index); } /** @@ -2347,15 +2552,19 @@ public void updateSuperUsers(MongoTemplate mongoTemplate, CacheableRepositoryHel Set<String> adminEmails = TextUtils.csvToSet(adminEmailsStr); Query instanceConfigurationQuery = new Query(); - instanceConfigurationQuery.addCriteria(where(fieldName(QConfig.config1.name)).is(FieldName.INSTANCE_CONFIG)); + instanceConfigurationQuery.addCriteria( + where(fieldName(QConfig.config1.name)).is(FieldName.INSTANCE_CONFIG)); Config instanceAdminConfiguration = mongoTemplate.findOne(instanceConfigurationQuery, Config.class); - String instanceAdminPermissionGroupId = (String) instanceAdminConfiguration.getConfig().get(DEFAULT_PERMISSION_GROUP); + String instanceAdminPermissionGroupId = + (String) instanceAdminConfiguration.getConfig().get(DEFAULT_PERMISSION_GROUP); Query permissionGroupQuery = new Query(); permissionGroupQuery - .addCriteria(where(fieldName(QPermissionGroup.permissionGroup.id)).is(instanceAdminPermissionGroupId)) - .fields().include(fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)); + .addCriteria( + where(fieldName(QPermissionGroup.permissionGroup.id)).is(instanceAdminPermissionGroupId)) + .fields() + .include(fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)); PermissionGroup instanceAdminPG = mongoTemplate.findOne(permissionGroupQuery, PermissionGroup.class); Query tenantQuery = new Query(); @@ -2399,11 +2608,7 @@ private User createNewUser(String email, String tenantId, MongoTemplate mongoTem PermissionGroup userManagementPermissionGroup = new PermissionGroup(); userManagementPermissionGroup.setName(user.getUsername() + FieldName.SUFFIX_USER_MANAGEMENT_ROLE); // Add CRUD permissions for user to the group - userManagementPermissionGroup.setPermissions( - Set.of( - new Permission(user.getId(), MANAGE_USERS) - ) - ); + userManagementPermissionGroup.setPermissions(Set.of(new Permission(user.getId(), MANAGE_USERS))); // Assign the permission group to the user userManagementPermissionGroup.setAssignedToUserIds(Set.of(user.getId())); @@ -2429,68 +2634,76 @@ private User createNewUser(String email, String tenantId, MongoTemplate mongoTem } @ChangeSet(order = "034", id = "update-bad-theme-state", author = "") - public void updateBadThemeState(MongoTemplate mongoTemplate, @NonLockGuarded PolicyGenerator policyGenerator, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public void updateBadThemeState( + MongoTemplate mongoTemplate, + @NonLockGuarded PolicyGenerator policyGenerator, + CacheableRepositoryHelper cacheableRepositoryHelper) { Query query = new Query(); - query.addCriteria( - new Criteria().andOperator( + query.addCriteria(new Criteria() + .andOperator( new Criteria(fieldName(QTheme.theme.isSystemTheme)).is(false), - new Criteria(fieldName(QTheme.theme.deleted)).is(false) - ) - ); - - mongoTemplate.stream(query, Theme.class) - .forEach(theme -> { - Query applicationQuery = new Query(); - Criteria themeCriteria = new Criteria(fieldName(QApplication.application.editModeThemeId)).is(theme.getId()) - .orOperator(new Criteria(fieldName(QApplication.application.publishedModeThemeId)).is(theme.getId())); - - List<Application> applications = mongoTemplate.find(applicationQuery.addCriteria(themeCriteria), Application.class); - // This is an erroneous state where the theme is being used by multiple applications - if (applications != null && applications.size() > 1) { - // Create new themes for the rest of the applications which are copies of the original theme - for (int i = 0; i < applications.size(); i++) { - Application application = applications.get(i); - Set<Policy> themePolicies = policyGenerator.getAllChildPolicies(application.getPolicies(), Application.class, Theme.class); - - if (i == 0) { - // Don't create a new theme for the first application - // Just update the policies - theme.setPolicies(themePolicies); - mongoTemplate.save(theme); - } else { - - Theme newTheme = new Theme(); - newTheme.setSystemTheme(false); - newTheme.setName(theme.getName()); - newTheme.setDisplayName(theme.getDisplayName()); - newTheme.setConfig(theme.getConfig()); - newTheme.setStylesheet(theme.getStylesheet()); - newTheme.setProperties(theme.getProperties()); - newTheme.setCreatedAt(Instant.now()); - newTheme.setUpdatedAt(Instant.now()); - newTheme.setPolicies(themePolicies); - - newTheme = mongoTemplate.save(newTheme); - - if (application.getEditModeThemeId().equals(theme.getId())) { - application.setEditModeThemeId(newTheme.getId()); - } - if (application.getPublishedModeThemeId().equals(theme.getId())) { - application.setPublishedModeThemeId(newTheme.getId()); - } - mongoTemplate.save(application); - } + new Criteria(fieldName(QTheme.theme.deleted)).is(false))); + + mongoTemplate.stream(query, Theme.class).forEach(theme -> { + Query applicationQuery = new Query(); + Criteria themeCriteria = new Criteria(fieldName(QApplication.application.editModeThemeId)) + .is(theme.getId()) + .orOperator( + new Criteria(fieldName(QApplication.application.publishedModeThemeId)).is(theme.getId())); + + List<Application> applications = + mongoTemplate.find(applicationQuery.addCriteria(themeCriteria), Application.class); + // This is an erroneous state where the theme is being used by multiple applications + if (applications != null && applications.size() > 1) { + // Create new themes for the rest of the applications which are copies of the original theme + for (int i = 0; i < applications.size(); i++) { + Application application = applications.get(i); + Set<Policy> themePolicies = policyGenerator.getAllChildPolicies( + application.getPolicies(), Application.class, Theme.class); + + if (i == 0) { + // Don't create a new theme for the first application + // Just update the policies + theme.setPolicies(themePolicies); + mongoTemplate.save(theme); + } else { + + Theme newTheme = new Theme(); + newTheme.setSystemTheme(false); + newTheme.setName(theme.getName()); + newTheme.setDisplayName(theme.getDisplayName()); + newTheme.setConfig(theme.getConfig()); + newTheme.setStylesheet(theme.getStylesheet()); + newTheme.setProperties(theme.getProperties()); + newTheme.setCreatedAt(Instant.now()); + newTheme.setUpdatedAt(Instant.now()); + newTheme.setPolicies(themePolicies); + + newTheme = mongoTemplate.save(newTheme); + + if (application.getEditModeThemeId().equals(theme.getId())) { + application.setEditModeThemeId(newTheme.getId()); + } + if (application.getPublishedModeThemeId().equals(theme.getId())) { + application.setPublishedModeThemeId(newTheme.getId()); } + mongoTemplate.save(application); } - }); + } + } + }); } @ChangeSet(order = "035", id = "migrate-public-apps-single-pg", author = "") - public void migratePublicAppsSinglePg(MongoTemplate mongoTemplate, @NonLockGuarded PolicySolution policySolution, @NonLockGuarded PolicyGenerator policyGenerator, CacheableRepositoryHelper cacheableRepositoryHelper) { + public void migratePublicAppsSinglePg( + MongoTemplate mongoTemplate, + @NonLockGuarded PolicySolution policySolution, + @NonLockGuarded PolicyGenerator policyGenerator, + CacheableRepositoryHelper cacheableRepositoryHelper) { Query anonymousUserPermissionConfig = new Query(); - anonymousUserPermissionConfig.addCriteria(where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)); + anonymousUserPermissionConfig.addCriteria( + where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)); Config publicPermissionGroupConfig = mongoTemplate.findOne(anonymousUserPermissionConfig, Config.class); String permissionGroupId = publicPermissionGroupConfig.getConfig().getAsString(PERMISSION_GROUP_ID); @@ -2499,99 +2712,114 @@ public void migratePublicAppsSinglePg(MongoTemplate mongoTemplate, @NonLockGuard ConcurrentHashMap.KeySetView<Object, Boolean> oldPgIds = oldPermissionGroupMap.newKeySet(); // Find all public apps Query publicAppQuery = new Query(); - publicAppQuery.addCriteria(where(fieldName(QApplication.application.defaultPermissionGroup)).exists(true)); - - mongoTemplate.stream(publicAppQuery, Application.class) - .parallel() - .forEach(application -> { - String oldPermissionGroupId = application.getDefaultPermissionGroup(); - // Store the existing permission group providing view access to the app for cleanup - oldPgIds.add(oldPermissionGroupId); - application.setDefaultPermissionGroup(null); - - // Update the application policies to use the public permission group - application.getPolicies() - .stream() - .filter(policy -> policy.getPermissionGroups().contains(oldPermissionGroupId)) - .forEach(policy -> { - policy.getPermissionGroups().remove(oldPermissionGroupId); - policy.getPermissionGroups().add(permissionGroupId); - }); - mongoTemplate.save(application); - - Set<String> datasourceIds = new HashSet<>(); - Query applicationActionsQuery = new Query().addCriteria(where(fieldName(QNewAction.newAction.applicationId)).is(application.getId())); - // Only fetch the datasources that are used in the action - applicationActionsQuery.fields() - .include(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.datasource)) - .include(fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.datasource)); - - mongoTemplate.stream(applicationActionsQuery, NewAction.class) - .forEach(newAction -> { - ActionDTO unpublishedAction = newAction.getUnpublishedAction(); - ActionDTO publishedAction = newAction.getPublishedAction(); - - if (unpublishedAction.getDatasource() != null && - unpublishedAction.getDatasource().getId() != null) { - datasourceIds.add(unpublishedAction.getDatasource().getId()); - } + publicAppQuery.addCriteria(where(fieldName(QApplication.application.defaultPermissionGroup)) + .exists(true)); + + mongoTemplate.stream(publicAppQuery, Application.class).parallel().forEach(application -> { + String oldPermissionGroupId = application.getDefaultPermissionGroup(); + // Store the existing permission group providing view access to the app for cleanup + oldPgIds.add(oldPermissionGroupId); + application.setDefaultPermissionGroup(null); + + // Update the application policies to use the public permission group + application.getPolicies().stream() + .filter(policy -> policy.getPermissionGroups().contains(oldPermissionGroupId)) + .forEach(policy -> { + policy.getPermissionGroups().remove(oldPermissionGroupId); + policy.getPermissionGroups().add(permissionGroupId); + }); + mongoTemplate.save(application); - if (publishedAction != null && - publishedAction.getDatasource() != null && - publishedAction.getDatasource().getId() != null) { - datasourceIds.add(publishedAction.getDatasource().getId()); - } - }); + Set<String> datasourceIds = new HashSet<>(); + Query applicationActionsQuery = new Query() + .addCriteria( + where(fieldName(QNewAction.newAction.applicationId)).is(application.getId())); + // Only fetch the datasources that are used in the action + applicationActionsQuery + .fields() + .include(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.datasource)) + .include(fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.datasource)); + + mongoTemplate.stream(applicationActionsQuery, NewAction.class).forEach(newAction -> { + ActionDTO unpublishedAction = newAction.getUnpublishedAction(); + ActionDTO publishedAction = newAction.getPublishedAction(); + + if (unpublishedAction.getDatasource() != null + && unpublishedAction.getDatasource().getId() != null) { + datasourceIds.add(unpublishedAction.getDatasource().getId()); + } - // Update datasources - Query datasourceQuery = new Query().addCriteria(where(fieldName(QDatasource.datasource.id)).in(datasourceIds)); - mongoTemplate.stream(datasourceQuery, Datasource.class) - .parallel() - .forEach(datasource -> { - // Update the datasource policies. - datasource.getPolicies() - .stream() - .filter(policy -> policy.getPermissionGroups().contains(oldPermissionGroupId)) - .forEach(policy -> { - policy.getPermissionGroups().remove(oldPermissionGroupId); - policy.getPermissionGroups().add(permissionGroupId); - }); - mongoTemplate.save(datasource); - }); + if (publishedAction != null + && publishedAction.getDatasource() != null + && publishedAction.getDatasource().getId() != null) { + datasourceIds.add(publishedAction.getDatasource().getId()); + } + }); - // Update pages - Set<Policy> pagePolicies = policyGenerator.getAllChildPolicies(application.getPolicies(), Application.class, Page.class); - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QNewPage.newPage.applicationId)).is(application.getId())), - new Update().set(fieldName(QNewPage.newPage.policies), pagePolicies), - NewPage.class); + // Update datasources + Query datasourceQuery = new Query() + .addCriteria(where(fieldName(QDatasource.datasource.id)).in(datasourceIds)); + mongoTemplate.stream(datasourceQuery, Datasource.class).parallel().forEach(datasource -> { + // Update the datasource policies. + datasource.getPolicies().stream() + .filter(policy -> policy.getPermissionGroups().contains(oldPermissionGroupId)) + .forEach(policy -> { + policy.getPermissionGroups().remove(oldPermissionGroupId); + policy.getPermissionGroups().add(permissionGroupId); + }); + mongoTemplate.save(datasource); + }); - // Update actions - Set<Policy> actionPolicies = policyGenerator.getAllChildPolicies(pagePolicies, Page.class, Action.class); - mongoTemplate.updateMulti(new Query().addCriteria(where(fieldName(QNewAction.newAction.applicationId)).is(application.getId())), - new Update().set(fieldName(QNewAction.newAction.policies), actionPolicies), - NewAction.class); + // Update pages + Set<Policy> pagePolicies = + policyGenerator.getAllChildPolicies(application.getPolicies(), Application.class, Page.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QNewPage.newPage.applicationId)) + .is(application.getId())), + new Update().set(fieldName(QNewPage.newPage.policies), pagePolicies), + NewPage.class); + + // Update actions + Set<Policy> actionPolicies = policyGenerator.getAllChildPolicies(pagePolicies, Page.class, Action.class); + mongoTemplate.updateMulti( + new Query() + .addCriteria(where(fieldName(QNewAction.newAction.applicationId)) + .is(application.getId())), + new Update().set(fieldName(QNewAction.newAction.policies), actionPolicies), + NewAction.class); - // Update js objects - mongoTemplate.updateMulti(new Query().addCriteria(Criteria.where(fieldName(QActionCollection.actionCollection.applicationId)).is(application.getId())), - new Update().set(fieldName(QActionCollection.actionCollection.policies), actionPolicies), - ActionCollection.class); + // Update js objects + mongoTemplate.updateMulti( + new Query() + .addCriteria(Criteria.where(fieldName(QActionCollection.actionCollection.applicationId)) + .is(application.getId())), + new Update().set(fieldName(QActionCollection.actionCollection.policies), actionPolicies), + ActionCollection.class); - // Update application themes - Criteria nonSystemThemeCriteria = Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(false); - Criteria idCriteria = Criteria.where(fieldName(QTheme.theme.id)).in( - application.getEditModeThemeId(), - application.getPublishedModeThemeId() - ); - Criteria queryCriteria = new Criteria().andOperator(nonSystemThemeCriteria, idCriteria); - Set<Policy> themePolicies = policyGenerator.getAllChildPolicies(application.getPolicies(), Application.class, Theme.class); - mongoTemplate.updateMulti(new Query().addCriteria(queryCriteria), - new Update().set(fieldName(QTheme.theme.policies), themePolicies), - Theme.class); - }); + // Update application themes + Criteria nonSystemThemeCriteria = + Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(false); + Criteria idCriteria = Criteria.where(fieldName(QTheme.theme.id)) + .in(application.getEditModeThemeId(), application.getPublishedModeThemeId()); + Criteria queryCriteria = new Criteria().andOperator(nonSystemThemeCriteria, idCriteria); + Set<Policy> themePolicies = + policyGenerator.getAllChildPolicies(application.getPolicies(), Application.class, Theme.class); + mongoTemplate.updateMulti( + new Query().addCriteria(queryCriteria), + new Update().set(fieldName(QTheme.theme.policies), themePolicies), + Theme.class); + }); // All the applications have been migrated. // Clean up all the permission groups which were created to provide views to public apps - mongoTemplate.findAllAndRemove(new Query().addCriteria(Criteria.where(fieldName(QPermissionGroup.permissionGroup.id)).in(oldPgIds)), PermissionGroup.class); + mongoTemplate.findAllAndRemove( + new Query() + .addCriteria(Criteria.where(fieldName(QPermissionGroup.permissionGroup.id)) + .in(oldPgIds)), + PermissionGroup.class); // Finally evict the anonymous user cache entry so that it gets recomputed on next use. Query tenantQuery = new Query(); @@ -2599,7 +2827,8 @@ public void migratePublicAppsSinglePg(MongoTemplate mongoTemplate, @NonLockGuard Tenant tenant = mongoTemplate.findOne(tenantQuery, Tenant.class); Query userQuery = new Query(); - userQuery.addCriteria(where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER)) + userQuery + .addCriteria(where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER)) .addCriteria(where(fieldName(QUser.user.tenantId)).is(tenant.getId())); User anonymousUser = mongoTemplate.findOne(userQuery, User.class); evictPermissionCacheForUsers(Set.of(anonymousUser.getId()), mongoTemplate, cacheableRepositoryHelper); @@ -2634,8 +2863,7 @@ public void addGraphQLPlugin(MongoTemplate mongoTemplate) { */ @ChangeSet(order = "037", id = "install-graphql-plugin-to-remaining-workspaces", author = "") public void reInstallGraphQLPluginToWorkspaces(MongoTemplate mongoTemplate) { - Plugin graphQLPlugin = mongoTemplate - .findOne(query(where("packageName").is("graphql-plugin")), Plugin.class); + Plugin graphQLPlugin = mongoTemplate.findOne(query(where("packageName").is("graphql-plugin")), Plugin.class); installPluginToAllWorkspaces(mongoTemplate, graphQLPlugin.getId()); } @@ -2648,8 +2876,7 @@ public void softDeletePlugin(MongoTemplate mongoTemplate, Plugin plugin) { @ChangeSet(order = "038", id = "delete-rapid-api-plugin-related-items", author = "") public void deleteRapidApiPluginRelatedItems(MongoTemplate mongoTemplate) { - Plugin rapidApiPlugin = mongoTemplate.findOne(query(where("packageName").is("rapidapi-plugin")), - Plugin.class); + Plugin rapidApiPlugin = mongoTemplate.findOne(query(where("packageName").is("rapidapi-plugin")), Plugin.class); if (rapidApiPlugin == null) { return; @@ -2659,21 +2886,26 @@ public void deleteRapidApiPluginRelatedItems(MongoTemplate mongoTemplate) { } @ChangeSet(order = "035", id = "add-tenant-admin-permissions-instance-admin", author = "") - public void addTenantAdminPermissionsToInstanceAdmin(MongoTemplate mongoTemplate, @NonLockGuarded PolicySolution policySolution) { + public void addTenantAdminPermissionsToInstanceAdmin( + MongoTemplate mongoTemplate, @NonLockGuarded PolicySolution policySolution) { Query tenantQuery = new Query(); tenantQuery.addCriteria(where(fieldName(QTenant.tenant.slug)).is("default")); Tenant defaultTenant = mongoTemplate.findOne(tenantQuery, Tenant.class); Query instanceConfigurationQuery = new Query(); - instanceConfigurationQuery.addCriteria(where(fieldName(QConfig.config1.name)).is(FieldName.INSTANCE_CONFIG)); + instanceConfigurationQuery.addCriteria( + where(fieldName(QConfig.config1.name)).is(FieldName.INSTANCE_CONFIG)); Config instanceAdminConfiguration = mongoTemplate.findOne(instanceConfigurationQuery, Config.class); - String instanceAdminPermissionGroupId = (String) instanceAdminConfiguration.getConfig().get(DEFAULT_PERMISSION_GROUP); + String instanceAdminPermissionGroupId = + (String) instanceAdminConfiguration.getConfig().get(DEFAULT_PERMISSION_GROUP); Query permissionGroupQuery = new Query(); - permissionGroupQuery.addCriteria(where(fieldName(QPermissionGroup.permissionGroup.id)).is(instanceAdminPermissionGroupId)); + permissionGroupQuery.addCriteria( + where(fieldName(QPermissionGroup.permissionGroup.id)).is(instanceAdminPermissionGroupId)); - PermissionGroup instanceAdminPGBeforeChanges = mongoTemplate.findOne(permissionGroupQuery, PermissionGroup.class); + PermissionGroup instanceAdminPGBeforeChanges = + mongoTemplate.findOne(permissionGroupQuery, PermissionGroup.class); // Give read permission to instanceAdminPg to all the users who have been assigned this permission group Map<String, Policy> readPermissionGroupPolicyMap = Map.of( @@ -2681,9 +2913,9 @@ public void addTenantAdminPermissionsToInstanceAdmin(MongoTemplate mongoTemplate Policy.builder() .permission(READ_PERMISSION_GROUP_MEMBERS.getValue()) .permissionGroups(Set.of(instanceAdminPGBeforeChanges.getId())) - .build() - ); - PermissionGroup instanceAdminPG = policySolution.addPoliciesToExistingObject(readPermissionGroupPolicyMap, instanceAdminPGBeforeChanges); + .build()); + PermissionGroup instanceAdminPG = + policySolution.addPoliciesToExistingObject(readPermissionGroupPolicyMap, instanceAdminPGBeforeChanges); // Now add admin permissions to the tenant Set<Permission> tenantPermissions = TENANT_ADMIN.getPermissions().stream() @@ -2694,13 +2926,15 @@ public void addTenantAdminPermissionsToInstanceAdmin(MongoTemplate mongoTemplate instanceAdminPG.setPermissions(permissions); mongoTemplate.save(instanceAdminPG); - Map<String, Policy> tenantPolicy = policySolution.generatePolicyFromPermissionGroupForObject(instanceAdminPG, defaultTenant.getId()); + Map<String, Policy> tenantPolicy = + policySolution.generatePolicyFromPermissionGroupForObject(instanceAdminPG, defaultTenant.getId()); Tenant updatedTenant = policySolution.addPoliciesToExistingObject(tenantPolicy, defaultTenant); mongoTemplate.save(updatedTenant); } @ChangeSet(order = "039", id = "change-readPermissionGroup-to-readPermissionGroupMembers", author = "") - public void modifyReadPermissionGroupToReadPermissionGroupMembers(MongoTemplate mongoTemplate, @NonLockGuarded PolicySolution policySolution) { + public void modifyReadPermissionGroupToReadPermissionGroupMembers( + MongoTemplate mongoTemplate, @NonLockGuarded PolicySolution policySolution) { Query query = new Query(Criteria.where("policies.permission").is("read:permissionGroups")); Update update = new Update().set("policies.$.permission", "read:permissionGroupMembers"); @@ -2724,7 +2958,8 @@ private void softDeletePluginFromAllWorkspaces(Plugin plugin, MongoTemplate mong .forEachOrdered(workspace -> { workspace.getPlugins().stream() .filter(workspacePlugin -> workspacePlugin != null && workspacePlugin.getPluginId() != null) - .filter(workspacePlugin -> workspacePlugin.getPluginId().equals(plugin.getId())) + .filter(workspacePlugin -> + workspacePlugin.getPluginId().equals(plugin.getId())) .forEach(workspacePlugin -> { workspacePlugin.setDeleted(true); workspacePlugin.setDeletedAt(Instant.now()); @@ -2750,8 +2985,8 @@ private void softDeleteAllPluginDatasources(Plugin plugin, MongoTemplate mongoTe List<Datasource> datasources = mongoTemplate.find(queryToGetDatasources, Datasource.class); /* Mark each selected datasource as deleted */ - updateDeleteAndDeletedAtFieldsForEachDomainObject(datasources, mongoTemplate, - QDatasource.datasource.id, Datasource.class); + updateDeleteAndDeletedAtFieldsForEachDomainObject( + datasources, mongoTemplate, QDatasource.datasource.id, Datasource.class); } private void softDeleteAllPluginActions(Plugin plugin, MongoTemplate mongoTemplate) { @@ -2765,8 +3000,8 @@ private void softDeleteAllPluginActions(Plugin plugin, MongoTemplate mongoTempla List<NewAction> actions = mongoTemplate.find(queryToGetActions, NewAction.class); /* Mark each selected action as deleted */ - updateDeleteAndDeletedAtFieldsForEachDomainObject(actions, mongoTemplate, QNewAction.newAction.id, - NewAction.class); + updateDeleteAndDeletedAtFieldsForEachDomainObject( + actions, mongoTemplate, QNewAction.newAction.id, NewAction.class); } private Query getQueryToFetchAllDomainObjectsWhichAreNotDeletedUsingPluginId(Plugin plugin) { @@ -2775,9 +3010,8 @@ private Query getQueryToFetchAllDomainObjectsWhichAreNotDeletedUsingPluginId(Plu return query((new Criteria()).andOperator(pluginIdMatchesSuppliedPluginId, isNotDeleted)); } - private <T extends BaseDomain> void updateDeleteAndDeletedAtFieldsForEachDomainObject(List<? extends BaseDomain> domainObjects, - MongoTemplate mongoTemplate, Path path, - Class<T> type) { + private <T extends BaseDomain> void updateDeleteAndDeletedAtFieldsForEachDomainObject( + List<? extends BaseDomain> domainObjects, MongoTemplate mongoTemplate, Path path, Class<T> type) { domainObjects.stream() .map(BaseDomain::getId) // iterate over id one by one .map(id -> fetchDomainObjectUsingId(id, mongoTemplate, path, type)) // find object using id @@ -2794,9 +3028,10 @@ private <T extends BaseDomain> void updateDeleteAndDeletedAtFieldsForEachDomainO * `type` is a POJO class type that indicates which collection we are interested in. eg. path=QNewAction * .newAction.id, type=NewAction.class */ - private <T extends BaseDomain> T fetchDomainObjectUsingId(String id, MongoTemplate mongoTemplate, Path path, - Class<T> type) { - final T domainObject = mongoTemplate.findOne(query(where(fieldName(path)).is(id)), type); + private <T extends BaseDomain> T fetchDomainObjectUsingId( + String id, MongoTemplate mongoTemplate, Path path, Class<T> type) { + final T domainObject = + mongoTemplate.findOne(query(where(fieldName(path)).is(id)), type); return domainObject; } @@ -2809,13 +3044,13 @@ public void addIndicesRecommendedByMongoCloud(MongoTemplate mongoTemplate) { ensureIndexes(mongoTemplate, Application.class, makeIndex("deleted")); dropIndexIfExists(mongoTemplate, Workspace.class, "tenantId_deleted"); - ensureIndexes(mongoTemplate, Workspace.class, makeIndex("tenantId", "deleted").named("tenantId_deleted")); + ensureIndexes( + mongoTemplate, Workspace.class, makeIndex("tenantId", "deleted").named("tenantId_deleted")); } @ChangeSet(order = "038", id = "add-unique-index-for-uidstring", author = "") public void addUniqueIndexOnUidString(MongoTemplate mongoTemplate) { - Index uidStringUniqueness = makeIndex("uidString").unique() - .named("customjslibs_uidstring_index"); + Index uidStringUniqueness = makeIndex("uidString").unique().named("customjslibs_uidstring_index"); ensureIndexes(mongoTemplate, CustomJSLib.class, uidStringUniqueness); } @@ -2825,11 +3060,10 @@ public void addUniqueIndexOnUidString(MongoTemplate mongoTemplate) { */ @ChangeSet(order = "039", id = "remove-preferred-ssl-mode-from-mysql", author = "") public void changeSSLModeFromPreferredToDefaultForMySQLPlugin(MongoTemplate mongoTemplate) { - Plugin mySQLPlugin = mongoTemplate.findOne(query(where("packageName").is("mysql-plugin")), - Plugin.class); + Plugin mySQLPlugin = mongoTemplate.findOne(query(where("packageName").is("mysql-plugin")), Plugin.class); Query queryToGetDatasources = getQueryToFetchAllDomainObjectsWhichAreNotDeletedUsingPluginId(mySQLPlugin); - queryToGetDatasources.addCriteria(Criteria.where("datasourceConfiguration.connection.ssl.authType").is( - "PREFERRED")); + queryToGetDatasources.addCriteria(Criteria.where("datasourceConfiguration.connection.ssl.authType") + .is("PREFERRED")); Update update = new Update(); update.set("datasourceConfiguration.connection.ssl.authType", "DEFAULT"); @@ -2839,7 +3073,8 @@ public void changeSSLModeFromPreferredToDefaultForMySQLPlugin(MongoTemplate mong // Migration to drop usage pulse collection for Appsmith cloud as we will not be logging these pulses unless // multi-tenancy is introduced @ChangeSet(order = "040", id = "remove-usage-pulses-for-appsmith-cloud", author = "") - public void removeUsagePulsesForAppsmithCloud(MongoTemplate mongoTemplate, @NonLockGuarded CommonConfig commonConfig) { + public void removeUsagePulsesForAppsmithCloud( + MongoTemplate mongoTemplate, @NonLockGuarded CommonConfig commonConfig) { if (Boolean.TRUE.equals(commonConfig.isCloudHosting())) { mongoTemplate.dropCollection(UsagePulse.class); } @@ -2853,8 +3088,7 @@ public void removeUsagePulsesForAppsmithCloud(MongoTemplate mongoTemplate, @NonL */ @ChangeSet(order = "041", id = "add-ssl-mode-settings-for-existing-mssql-datasources", author = "") public void addSslModeSettingsForExistingMssqlDatasource(MongoTemplate mongoTemplate) { - Plugin mssqlPlugin = mongoTemplate.findOne(query(where("packageName").is("mssql-plugin")), - Plugin.class); + Plugin mssqlPlugin = mongoTemplate.findOne(query(where("packageName").is("mssql-plugin")), Plugin.class); Query queryToGetDatasources = getQueryToFetchAllDomainObjectsWhichAreNotDeletedUsingPluginId(mssqlPlugin); Update update = new Update(); @@ -2888,4 +3122,4 @@ public void updateOraclePluginName(MongoTemplate mongoTemplate) { oraclePlugin.setIconLocation("https://s3.us-east-2.amazonaws.com/assets.appsmith.com/oracle.svg"); mongoTemplate.save(oraclePlugin); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java index 6cf145b6db1a..d2b53919c861 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java @@ -13,8 +13,10 @@ private static boolean checkCompatibility(ApplicationJson applicationJson) { public static ApplicationJson migrateApplicationToLatestSchema(ApplicationJson applicationJson) { // Check if the schema versions are available and set to initial version if not present - Integer serverSchemaVersion = applicationJson.getServerSchemaVersion() == null ? 0 : applicationJson.getServerSchemaVersion(); - Integer clientSchemaVersion = applicationJson.getClientSchemaVersion() == null ? 0 : applicationJson.getClientSchemaVersion(); + Integer serverSchemaVersion = + applicationJson.getServerSchemaVersion() == null ? 0 : applicationJson.getServerSchemaVersion(); + Integer clientSchemaVersion = + applicationJson.getClientSchemaVersion() == null ? 0 : applicationJson.getClientSchemaVersion(); applicationJson.setClientSchemaVersion(clientSchemaVersion); applicationJson.setServerSchemaVersion(serverSchemaVersion); @@ -52,7 +54,8 @@ private static ApplicationJson migrateServerSchema(ApplicationJson applicationJs applicationJson.setServerSchemaVersion(4); case 4: // Remove unwanted fields from DTO and allow serialization for JsonIgnore fields - if (!CollectionUtils.isNullOrEmpty(applicationJson.getPageList()) && applicationJson.getExportedApplication() != null) { + if (!CollectionUtils.isNullOrEmpty(applicationJson.getPageList()) + && applicationJson.getExportedApplication() != null) { MigrationHelperMethods.arrangeApplicationPagesAsPerImportedPageOrder(applicationJson); MigrationHelperMethods.updateMongoEscapedWidget(applicationJson); } @@ -78,6 +81,4 @@ private static ApplicationJson migrateClientSchema(ApplicationJson applicationJs // supporting this on server side return applicationJson; } - - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java index 01c18b323fbf..7ce889a98f9c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java @@ -12,6 +12,6 @@ */ @Getter public class JsonSchemaVersions { - public final static Integer serverVersion = 6; - public final static Integer clientVersion = 1; + public static final Integer serverVersion = 6; + public static final Integer clientVersion = 1; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java index a1b1f34ba521..d68ff6ca424e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java @@ -43,18 +43,17 @@ public static void migrateActionFormDataToObject(ApplicationJson applicationJson final List<NewAction> actionList = applicationJson.getActionList(); if (!CollectionUtils.isNullOrEmpty(actionList)) { - actionList.parallelStream() - .forEach(newAction -> { - // determine plugin - final String pluginName = newAction.getPluginId(); - if ("mongo-plugin".equals(pluginName)) { - DatabaseChangelog2.migrateMongoActionsFormData(newAction); - } else if ("amazons3-plugin".equals(pluginName)) { - DatabaseChangelog2.migrateAmazonS3ActionsFormData(newAction); - } else if ("firestore-plugin".equals(pluginName)) { - DatabaseChangelog2.migrateFirestoreActionsFormData(newAction); - } - }); + actionList.parallelStream().forEach(newAction -> { + // determine plugin + final String pluginName = newAction.getPluginId(); + if ("mongo-plugin".equals(pluginName)) { + DatabaseChangelog2.migrateMongoActionsFormData(newAction); + } else if ("amazons3-plugin".equals(pluginName)) { + DatabaseChangelog2.migrateAmazonS3ActionsFormData(newAction); + } else if ("firestore-plugin".equals(pluginName)) { + DatabaseChangelog2.migrateFirestoreActionsFormData(newAction); + } + }); } } @@ -64,23 +63,23 @@ public static void arrangeApplicationPagesAsPerImportedPageOrder(ApplicationJson Map<ResourceModes, List<ApplicationPage>> applicationPages = Map.of( EDIT, new ArrayList<>(), - VIEW, new ArrayList<>() - ); + VIEW, new ArrayList<>()); // Reorder the pages based on edit mode page sequence List<String> pageOrderList; if (!CollectionUtils.isNullOrEmpty(applicationJson.getPageOrder())) { pageOrderList = applicationJson.getPageOrder(); } else { - pageOrderList = applicationJson.getPageList() - .parallelStream() - .filter(newPage -> newPage.getUnpublishedPage() != null && newPage.getUnpublishedPage().getDeletedAt() == null) + pageOrderList = applicationJson.getPageList().parallelStream() + .filter(newPage -> newPage.getUnpublishedPage() != null + && newPage.getUnpublishedPage().getDeletedAt() == null) .map(newPage -> newPage.getUnpublishedPage().getName()) .collect(Collectors.toList()); } for (String pageName : pageOrderList) { ApplicationPage unpublishedAppPage = new ApplicationPage(); unpublishedAppPage.setId(pageName); - unpublishedAppPage.setIsDefault(StringUtils.equals(pageName, applicationJson.getUnpublishedDefaultPageName())); + unpublishedAppPage.setIsDefault( + StringUtils.equals(pageName, applicationJson.getUnpublishedDefaultPageName())); applicationPages.get(EDIT).add(unpublishedAppPage); } @@ -89,9 +88,9 @@ public static void arrangeApplicationPagesAsPerImportedPageOrder(ApplicationJson if (!CollectionUtils.isNullOrEmpty(applicationJson.getPublishedPageOrder())) { pageOrderList = applicationJson.getPublishedPageOrder(); } else { - pageOrderList = applicationJson.getPageList() - .parallelStream() - .filter(newPage -> newPage.getPublishedPage() != null && !StringUtils.isEmpty(newPage.getPublishedPage().getName())) + pageOrderList = applicationJson.getPageList().parallelStream() + .filter(newPage -> newPage.getPublishedPage() != null + && !StringUtils.isEmpty(newPage.getPublishedPage().getName())) .map(newPage -> newPage.getPublishedPage().getName()) .collect(Collectors.toList()); } @@ -108,20 +107,22 @@ public static void arrangeApplicationPagesAsPerImportedPageOrder(ApplicationJson // Method to embed mongo escaped widgets in imported layouts as per modified serialization format where we are // serialising JsonIgnored fields to keep the relevant data with domain objects only public static void updateMongoEscapedWidget(ApplicationJson applicationJson) { - Map<String, Set<String>> unpublishedMongoEscapedWidget - = CollectionUtils.isNullOrEmpty(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()) - ? new HashMap<>() - : applicationJson.getUnpublishedLayoutmongoEscapedWidgets(); + Map<String, Set<String>> unpublishedMongoEscapedWidget = + CollectionUtils.isNullOrEmpty(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()) + ? new HashMap<>() + : applicationJson.getUnpublishedLayoutmongoEscapedWidgets(); - Map<String, Set<String>> publishedMongoEscapedWidget - = CollectionUtils.isNullOrEmpty(applicationJson.getPublishedLayoutmongoEscapedWidgets()) - ? new HashMap<>() - : applicationJson.getPublishedLayoutmongoEscapedWidgets(); + Map<String, Set<String>> publishedMongoEscapedWidget = + CollectionUtils.isNullOrEmpty(applicationJson.getPublishedLayoutmongoEscapedWidgets()) + ? new HashMap<>() + : applicationJson.getPublishedLayoutmongoEscapedWidgets(); applicationJson.getPageList().parallelStream().forEach(newPage -> { if (newPage.getUnpublishedPage() != null - && unpublishedMongoEscapedWidget.containsKey(newPage.getUnpublishedPage().getName()) - && !CollectionUtils.isNullOrEmpty(newPage.getUnpublishedPage().getLayouts())) { + && unpublishedMongoEscapedWidget.containsKey( + newPage.getUnpublishedPage().getName()) + && !CollectionUtils.isNullOrEmpty( + newPage.getUnpublishedPage().getLayouts())) { newPage.getUnpublishedPage().getLayouts().forEach(layout -> { layout.setMongoEscapedWidgetNames(unpublishedMongoEscapedWidget.get(layout.getId())); @@ -129,7 +130,8 @@ public static void updateMongoEscapedWidget(ApplicationJson applicationJson) { } if (newPage.getPublishedPage() != null - && publishedMongoEscapedWidget.containsKey(newPage.getPublishedPage().getName()) + && publishedMongoEscapedWidget.containsKey( + newPage.getPublishedPage().getName()) && !CollectionUtils.isNullOrEmpty(newPage.getPublishedPage().getLayouts())) { newPage.getPublishedPage().getLayouts().forEach(layout -> { @@ -146,12 +148,18 @@ public static void updateUserSetOnLoadAction(ApplicationJson applicationJson) { if (invisibleActionFieldsMap != null) { applicationJson.getActionList().parallelStream().forEach(newAction -> { if (newAction.getUnpublishedAction() != null) { - newAction.getUnpublishedAction() - .setUserSetOnLoad(invisibleActionFieldsMap.get(newAction.getId()).getUnpublishedUserSetOnLoad()); + newAction + .getUnpublishedAction() + .setUserSetOnLoad(invisibleActionFieldsMap + .get(newAction.getId()) + .getUnpublishedUserSetOnLoad()); } if (newAction.getPublishedAction() != null) { - newAction.getPublishedAction() - .setUserSetOnLoad(invisibleActionFieldsMap.get(newAction.getId()).getPublishedUserSetOnLoad()); + newAction + .getPublishedAction() + .setUserSetOnLoad(invisibleActionFieldsMap + .get(newAction.getId()) + .getPublishedUserSetOnLoad()); } }); } @@ -161,20 +169,18 @@ public static void migrateGoogleSheetsActionsToUqi(ApplicationJson applicationJs final List<NewAction> actionList = applicationJson.getActionList(); if (!CollectionUtils.isNullOrEmpty(actionList)) { - actionList.parallelStream() - .forEach(newAction -> { - // Determine plugin - final String pluginName = newAction.getPluginId(); - if ("google-sheets-plugin".equals(pluginName)) { - DatabaseChangelog2.migrateGoogleSheetsToUqi(newAction); - } - }); + actionList.parallelStream().forEach(newAction -> { + // Determine plugin + final String pluginName = newAction.getPluginId(); + if ("google-sheets-plugin".equals(pluginName)) { + DatabaseChangelog2.migrateGoogleSheetsToUqi(newAction); + } + }); } } - public static void evictPermissionCacheForUsers(Set<String> userIds, - MongoTemplate mongoTemplate, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public static void evictPermissionCacheForUsers( + Set<String> userIds, MongoTemplate mongoTemplate, CacheableRepositoryHelper cacheableRepositoryHelper) { if (userIds == null || userIds.isEmpty()) { // Nothing to do here. @@ -186,7 +192,8 @@ public static void evictPermissionCacheForUsers(Set<String> userIds, User user = mongoTemplate.findOne(query, User.class); if (user != null) { // blocking call for cache eviction to ensure its subscribed immediately before proceeding further. - cacheableRepositoryHelper.evictPermissionGroupsUser(user.getEmail(), user.getTenantId()) + cacheableRepositoryHelper + .evictPermissionGroupsUser(user.getEmail(), user.getTenantId()) .block(); } }); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration003AddInstanceNameToTenantConfiguration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration003AddInstanceNameToTenantConfiguration.java index 8054397aab56..977600fb2c22 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration003AddInstanceNameToTenantConfiguration.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration003AddInstanceNameToTenantConfiguration.java @@ -20,7 +20,7 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; @Slf4j -@ChangeUnit(order = "003", id="add-instance-name-env-variable-tenant-configuration") +@ChangeUnit(order = "003", id = "add-instance-name-env-variable-tenant-configuration") public class Migration003AddInstanceNameToTenantConfiguration { private final MongoTemplate mongoTemplate; @@ -29,8 +29,7 @@ public Migration003AddInstanceNameToTenantConfiguration(MongoTemplate mongoTempl } @RollbackExecution - public void executionRollback() { - } + public void executionRollback() {} @Execution public void addInstanceNameEnvVarToTenantConfiguration() { @@ -39,7 +38,8 @@ public void addInstanceNameEnvVarToTenantConfiguration() { Tenant defaultTenant = mongoTemplate.findOne(tenantQuery, Tenant.class); // Using default name as Appsmith here. - String instanceName = StringUtils.defaultIfEmpty(System.getenv(String.valueOf(APPSMITH_INSTANCE_NAME)), DEFAULT_INSTANCE_NAME); + String instanceName = StringUtils.defaultIfEmpty( + System.getenv(String.valueOf(APPSMITH_INSTANCE_NAME)), DEFAULT_INSTANCE_NAME); TenantConfiguration defaultTenantConfiguration = new TenantConfiguration(); if (Objects.nonNull(defaultTenant.getTenantConfiguration())) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration003PermissionGroupDefaultWorkspaceIdMigration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration003PermissionGroupDefaultWorkspaceIdMigration.java index 1aa96bb0a456..150e4f725dc8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration003PermissionGroupDefaultWorkspaceIdMigration.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration003PermissionGroupDefaultWorkspaceIdMigration.java @@ -16,8 +16,7 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; - -@ChangeUnit(order = "003", id="migrate-default-workspace-id-to-default-domain-id") +@ChangeUnit(order = "003", id = "migrate-default-workspace-id-to-default-domain-id") public class Migration003PermissionGroupDefaultWorkspaceIdMigration { private final MongoTemplate mongoTemplate; @@ -26,13 +25,13 @@ public Migration003PermissionGroupDefaultWorkspaceIdMigration(MongoTemplate mong } @RollbackExecution - public void demoRollbackExecution() { - } + public void demoRollbackExecution() {} @Execution public void defaultWorkspaceIdMigration() { - Query defaultWorkspaceIdExistsQuery = query(where( - fieldName(QPermissionGroup.permissionGroup.defaultWorkspaceId)).exists(true)); + Query defaultWorkspaceIdExistsQuery = + query(where(fieldName(QPermissionGroup.permissionGroup.defaultWorkspaceId)) + .exists(true)); if (mongoTemplate.findOne(defaultWorkspaceIdExistsQuery, PermissionGroup.class) == null) { System.out.println("No permissionGroup data to migrate."); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration004CreateIndexForApplicationSnapshotMigration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration004CreateIndexForApplicationSnapshotMigration.java index aad849732403..356cb1bc9f75 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration004CreateIndexForApplicationSnapshotMigration.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration004CreateIndexForApplicationSnapshotMigration.java @@ -12,7 +12,7 @@ import static com.appsmith.server.migrations.DatabaseChangelog1.makeIndex; import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.fieldName; -@ChangeUnit(order = "004", id="create-index-for-application-snapshot-collection") +@ChangeUnit(order = "004", id = "create-index-for-application-snapshot-collection") public class Migration004CreateIndexForApplicationSnapshotMigration { private final MongoTemplate mongoTemplate; @@ -21,15 +21,15 @@ public Migration004CreateIndexForApplicationSnapshotMigration(MongoTemplate mong } @RollbackExecution - public void demoRollbackExecution() { - } + public void demoRollbackExecution() {} @Execution public void addIndexOnApplicationIdAndChunkOrder() { Index applicationIdChunkOrderUniqueIndex = makeIndex( - fieldName(QApplicationSnapshot.applicationSnapshot.applicationId), - fieldName(QApplicationSnapshot.applicationSnapshot.chunkOrder) - ).named("applicationId_chunkOrder_unique_index").unique(); + fieldName(QApplicationSnapshot.applicationSnapshot.applicationId), + fieldName(QApplicationSnapshot.applicationSnapshot.chunkOrder)) + .named("applicationId_chunkOrder_unique_index") + .unique(); ensureIndexes(mongoTemplate, ApplicationSnapshot.class, applicationIdChunkOrderUniqueIndex); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration004ResetOnPageLoadEdgesInLayouts.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration004ResetOnPageLoadEdgesInLayouts.java index 20030e704846..1249fbf1bf4f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration004ResetOnPageLoadEdgesInLayouts.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration004ResetOnPageLoadEdgesInLayouts.java @@ -27,8 +27,7 @@ public Migration004ResetOnPageLoadEdgesInLayouts(MongoTemplate mongoTemplate) { } @RollbackExecution - public void demoRollbackExecution() { - } + public void demoRollbackExecution() {} @Execution public void executeMigration() { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration005OptOutUnsupportedPluginsForAirGap.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration005OptOutUnsupportedPluginsForAirGap.java index b1b38bef0306..b1f8012250d4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration005OptOutUnsupportedPluginsForAirGap.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration005OptOutUnsupportedPluginsForAirGap.java @@ -18,7 +18,7 @@ import static com.appsmith.external.constants.PluginConstants.PackageName.REDSHIFT_PLUGIN; import static com.appsmith.external.constants.PluginConstants.PackageName.SAAS_PLUGIN; -@ChangeUnit(order = "005", id="opt-out-unsupported-plugins-airgap-instance", author = " ") +@ChangeUnit(order = "005", id = "opt-out-unsupported-plugins-airgap-instance", author = " ") public class Migration005OptOutUnsupportedPluginsForAirGap { private final MongoTemplate mongoTemplate; @@ -28,8 +28,7 @@ public Migration005OptOutUnsupportedPluginsForAirGap(MongoTemplate mongoTemplate } @RollbackExecution - public void rollBackExecution() { - } + public void rollBackExecution() {} @Execution public void optOutUnsupportedPluginsForAirGapInstance() { @@ -38,9 +37,13 @@ public void optOutUnsupportedPluginsForAirGapInstance() { // Generally SaaS plugins and DBs which can't be self-hosted can be a candidate for opting out of air-gap as // these are dependent on external internet final Set<String> unsupportedPluginPackageNameInAirgap = Set.of( - SAAS_PLUGIN, RAPID_API_PLUGIN, FIRESTORE_PLUGIN, REDSHIFT_PLUGIN, DYNAMO_PLUGIN, - AMAZON_S3_PLUGIN, GOOGLE_SHEETS_PLUGIN - ); + SAAS_PLUGIN, + RAPID_API_PLUGIN, + FIRESTORE_PLUGIN, + REDSHIFT_PLUGIN, + DYNAMO_PLUGIN, + AMAZON_S3_PLUGIN, + GOOGLE_SHEETS_PLUGIN); final Set<PluginType> cloudServicesDependentPluginTypes = Set.of(PluginType.SAAS, PluginType.REMOTE); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration006SupportNonHostedPluginsForAirgap.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration006SupportNonHostedPluginsForAirgap.java index 815e35672380..d4d9f6cec6d6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration006SupportNonHostedPluginsForAirgap.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration006SupportNonHostedPluginsForAirgap.java @@ -18,7 +18,7 @@ import static com.appsmith.external.constants.PluginConstants.PackageName.FIRESTORE_PLUGIN; import static com.appsmith.external.constants.PluginConstants.PackageName.REDSHIFT_PLUGIN; -@ChangeUnit(order = "006", id="support-non-self-hosted-plugins-for-airgap", author = " ") +@ChangeUnit(order = "006", id = "support-non-self-hosted-plugins-for-airgap", author = " ") public class Migration006SupportNonHostedPluginsForAirgap { private final MongoTemplate mongoTemplate; @@ -27,8 +27,7 @@ public Migration006SupportNonHostedPluginsForAirgap(MongoTemplate mongoTemplate) } @RollbackExecution - public void rollBackExecution() { - } + public void rollBackExecution() {} @Execution public void supportNonHostedPluginsForAirgap() { @@ -36,9 +35,8 @@ public void supportNonHostedPluginsForAirgap() { // In earlier PR we opted out for plugins which can't be self-hosted for airgap thinking that as public internet // is not available. But we are seeing multiple level of airgapping is needed where customers still want the // support for few plugins like S3, Redshift, Firestore etc. which are offered by hosting providers. - final Set<String> supportedNonSelfHostedPluginPackageNameForAirgap = Set.of( - FIRESTORE_PLUGIN, REDSHIFT_PLUGIN, DYNAMO_PLUGIN, AMAZON_S3_PLUGIN - ); + final Set<String> supportedNonSelfHostedPluginPackageNameForAirgap = + Set.of(FIRESTORE_PLUGIN, REDSHIFT_PLUGIN, DYNAMO_PLUGIN, AMAZON_S3_PLUGIN); List<Plugin> plugins = mongoTemplate.findAll(Plugin.class); for (Plugin plugin : plugins) { @@ -46,10 +44,7 @@ public void supportNonHostedPluginsForAirgap() { Update update = new Update(); update.unset(FieldName.IS_SUPPORTED_FOR_AIR_GAP); mongoTemplate.updateFirst( - new Query().addCriteria(Criteria.where(FieldName.ID).is(plugin.getId())), - update, - Plugin.class - ); + new Query().addCriteria(Criteria.where(FieldName.ID).is(plugin.getId())), update, Plugin.class); } } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdateOracleLogoToSVG.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdateOracleLogoToSVG.java index 316fe8552ad8..1cce9894aac6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdateOracleLogoToSVG.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdateOracleLogoToSVG.java @@ -1,26 +1,15 @@ package com.appsmith.server.migrations.db.ce; -import com.appsmith.server.constants.FieldName; import com.appsmith.server.domains.Plugin; import io.mongock.api.annotations.ChangeUnit; import io.mongock.api.annotations.Execution; import io.mongock.api.annotations.RollbackExecution; import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.core.query.Criteria; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.data.mongodb.core.query.Update; -import java.util.List; -import java.util.Set; - -import static com.appsmith.external.constants.PluginConstants.PackageName.AMAZON_S3_PLUGIN; -import static com.appsmith.external.constants.PluginConstants.PackageName.DYNAMO_PLUGIN; -import static com.appsmith.external.constants.PluginConstants.PackageName.FIRESTORE_PLUGIN; -import static com.appsmith.external.constants.PluginConstants.PackageName.REDSHIFT_PLUGIN; import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; -@ChangeUnit(order = "007", id="update-oracle-logo-to-svg", author = " ") +@ChangeUnit(order = "007", id = "update-oracle-logo-to-svg", author = " ") public class Migration007UpdateOracleLogoToSVG { private final MongoTemplate mongoTemplate; @@ -29,8 +18,7 @@ public Migration007UpdateOracleLogoToSVG(MongoTemplate mongoTemplate) { } @RollbackExecution - public void rollBackExecution() { - } + public void rollBackExecution() {} @Execution public void updateOracleLogoToSVG() { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdatePluginDocsLink.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdatePluginDocsLink.java index e5e4dd83ae83..f8298976a05c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdatePluginDocsLink.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdatePluginDocsLink.java @@ -29,23 +29,28 @@ public void updatePluginDocumentationLinks() { final Map<String, String> newDocsLinkMap = new HashMap<>(); newDocsLinkMap.putAll(Map.of( "amazons3-plugin", "https://docs.appsmith.com/reference/datasources/querying-amazon-s3#list-files", - "postgres-plugin", "https://docs.appsmith.com/reference/datasources/querying-postgres#create-crud-queries", + "postgres-plugin", + "https://docs.appsmith.com/reference/datasources/querying-postgres#create-crud-queries", "mongo-plugin", "https://docs.appsmith.com/reference/datasources/querying-mongodb#create-queries", "mysql-plugin", "https://docs.appsmith.com/reference/datasources/querying-mysql#create-queries", - "elasticsearch-plugin", "https://docs.appsmith.com/reference/datasources/querying-elasticsearch#querying-elasticsearch", + "elasticsearch-plugin", + "https://docs.appsmith.com/reference/datasources/querying-elasticsearch#querying-elasticsearch", "dynamo-plugin", "https://docs.appsmith.com/reference/datasources/querying-dynamodb#create-queries", "redis-plugin", "https://docs.appsmith.com/reference/datasources/querying-redis#querying-redis", "mssql-plugin", "https://docs.appsmith.com/reference/datasources/querying-mssql#create-queries", - "firestore-plugin", "https://docs.appsmith.com/reference/datasources/querying-firestore#understanding-commands", - "redshift-plugin", "https://docs.appsmith.com/reference/datasources/querying-redshift#querying-redshift" - )); + "firestore-plugin", + "https://docs.appsmith.com/reference/datasources/querying-firestore#understanding-commands", + "redshift-plugin", + "https://docs.appsmith.com/reference/datasources/querying-redshift#querying-redshift")); newDocsLinkMap.putAll(Map.of( - "google-sheets-plugin", "https://docs.appsmith.com/reference/datasources/querying-google-sheets#create-queries", - "snowflake-plugin", "https://docs.appsmith.com/reference/datasources/querying-snowflake-db#querying-snowflake", - "arangodb-plugin", "https://docs.appsmith.com/reference/datasources/querying-arango-db#using-queries-in-applications", + "google-sheets-plugin", + "https://docs.appsmith.com/reference/datasources/querying-google-sheets#create-queries", + "snowflake-plugin", + "https://docs.appsmith.com/reference/datasources/querying-snowflake-db#querying-snowflake", + "arangodb-plugin", + "https://docs.appsmith.com/reference/datasources/querying-arango-db#using-queries-in-applications", "smtp-plugin", "https://docs.appsmith.com/reference/datasources/using-smtp", - "graphql-plugin", "https://docs.appsmith.com/reference/datasources/graphql#create-queries" - )); + "graphql-plugin", "https://docs.appsmith.com/reference/datasources/graphql#create-queries")); List<Plugin> plugins = mongoTemplate.findAll(Plugin.class); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDefaultWorkspaceId.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDefaultWorkspaceId.java index 4d563c54c80c..89cf0df358f5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDefaultWorkspaceId.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDefaultWorkspaceId.java @@ -1,6 +1,5 @@ package com.appsmith.server.migrations.db.ce; - import com.appsmith.server.domains.PermissionGroup; import com.appsmith.server.domains.QPermissionGroup; import io.mongock.api.annotations.ChangeUnit; @@ -20,29 +19,32 @@ public class Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDef private final MongoTemplate mongoTemplate; // An old index that's no longer present in the source. - private final static String oldPermissionGroupIndexNameDefaultWorkspaceIdDeleted = "permission_group_workspace_deleted_compound_index"; + private static final String oldPermissionGroupIndexNameDefaultWorkspaceIdDeleted = + "permission_group_workspace_deleted_compound_index"; - public final static String newPermissionGroupIndexNameDefaultDomainIdDefaultDomainType = "permission_group_domainId_domainType_deleted"; + public static final String newPermissionGroupIndexNameDefaultDomainIdDefaultDomainType = + "permission_group_domainId_domainType_deleted"; - public Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDefaultWorkspaceId(MongoTemplate mongoTemplate) { + public Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDefaultWorkspaceId( + MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } @RollbackExecution - public void rollBackExecution() { - } + public void rollBackExecution() {} @Execution public void createNewIndexDefaultDomainIdDefaultDomainTypeAndDropOldIndexDefaultWorkspaceId() { dropIndexIfExists(mongoTemplate, PermissionGroup.class, oldPermissionGroupIndexNameDefaultWorkspaceIdDeleted); - dropIndexIfExists(mongoTemplate, PermissionGroup.class, newPermissionGroupIndexNameDefaultDomainIdDefaultDomainType); + dropIndexIfExists( + mongoTemplate, PermissionGroup.class, newPermissionGroupIndexNameDefaultDomainIdDefaultDomainType); Index newIndexDefaultDomainIdDefaultDomainTypeDeletedDeletedAt = makeIndex( - fieldName(QPermissionGroup.permissionGroup.defaultDomainId), - fieldName(QPermissionGroup.permissionGroup.defaultDomainType), - fieldName(QPermissionGroup.permissionGroup.deleted), - fieldName(QPermissionGroup.permissionGroup.deletedAt) - ).named(newPermissionGroupIndexNameDefaultDomainIdDefaultDomainType); + fieldName(QPermissionGroup.permissionGroup.defaultDomainId), + fieldName(QPermissionGroup.permissionGroup.defaultDomainType), + fieldName(QPermissionGroup.permissionGroup.deleted), + fieldName(QPermissionGroup.permissionGroup.deletedAt)) + .named(newPermissionGroupIndexNameDefaultDomainIdDefaultDomainType); ensureIndexes(mongoTemplate, PermissionGroup.class, newIndexDefaultDomainIdDefaultDomainTypeDeletedDeletedAt); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration009RemoveStructureFromWithinDatasource.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration009RemoveStructureFromWithinDatasource.java index 7b4e594170c2..622cc42e8c73 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration009RemoveStructureFromWithinDatasource.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration009RemoveStructureFromWithinDatasource.java @@ -1,6 +1,5 @@ package com.appsmith.server.migrations.db.ce; - import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceStorageStructure; import com.appsmith.server.migrations.DatabaseChangelog1; @@ -22,8 +21,8 @@ public class Migration009RemoveStructureFromWithinDatasource { private final MongoTemplate mongoTemplate; - public Migration009RemoveStructureFromWithinDatasource(MongoOperations mongoOperations, - MongoTemplate mongoTemplate) { + public Migration009RemoveStructureFromWithinDatasource( + MongoOperations mongoOperations, MongoTemplate mongoTemplate) { this.mongoOperations = mongoOperations; this.mongoTemplate = mongoTemplate; } @@ -35,12 +34,15 @@ public void rollBackExecution() { @Execution public void executeMigration() { - DatabaseChangelog1.dropIndexIfExists(mongoTemplate, DatasourceStorageStructure.class, "dsConfigStructure_dsId_envId"); + DatabaseChangelog1.dropIndexIfExists( + mongoTemplate, DatasourceStorageStructure.class, "dsConfigStructure_dsId_envId"); - DatabaseChangelog1.ensureIndexes(mongoTemplate, DatasourceStorageStructure.class, + DatabaseChangelog1.ensureIndexes( + mongoTemplate, + DatasourceStorageStructure.class, DatabaseChangelog1.makeIndex("datasourceId", "environmentId") - .unique().named("dsConfigStructure_dsId_envId") - ); + .unique() + .named("dsConfigStructure_dsId_envId")); Query query = query(where("structure").exists(true)); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration010AddEmailBodyTypeToSMTPPlugin.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration010AddEmailBodyTypeToSMTPPlugin.java index a444e0bf6ff3..1b79c5050d33 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration010AddEmailBodyTypeToSMTPPlugin.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration010AddEmailBodyTypeToSMTPPlugin.java @@ -13,7 +13,7 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; -@ChangeUnit(order = "010", id="add-smtp-email-body-type", author = " ") +@ChangeUnit(order = "010", id = "add-smtp-email-body-type", author = " ") public class Migration010AddEmailBodyTypeToSMTPPlugin { private final MongoTemplate mongoTemplate; @@ -23,18 +23,18 @@ public Migration010AddEmailBodyTypeToSMTPPlugin(MongoTemplate mongoTemplate) { } @RollbackExecution - public void rollBackExecution() { - } + public void rollBackExecution() {} @Execution public void addSmtpEmailBodyType() { - Plugin smtpPlugin = mongoTemplate.findOne(query(where("packageName").is("smtp-plugin")), - Plugin.class); + Plugin smtpPlugin = mongoTemplate.findOne(query(where("packageName").is("smtp-plugin")), Plugin.class); /* Query to get all smtp plugin unpublished actions which are not deleted and doesn't have bodyType field */ Query unpublishedActionsQuery = getQueryToFetchAllDomainObjectsWhichAreNotDeletedUsingPluginId(smtpPlugin) - .addCriteria(where("unpublishedAction.actionConfiguration.formData.send").exists(true)) - .addCriteria(where("unpublishedAction.actionConfiguration.formData.send.bodyType").exists(false)); + .addCriteria(where("unpublishedAction.actionConfiguration.formData.send") + .exists(true)) + .addCriteria(where("unpublishedAction.actionConfiguration.formData.send.bodyType") + .exists(false)); /* Update the bodyType field to have "text/html" value by default */ Update updateUnpublishedActions = new Update(); @@ -42,11 +42,12 @@ public void addSmtpEmailBodyType() { mongoTemplate.updateMulti(unpublishedActionsQuery, updateUnpublishedActions, NewAction.class); - /* Query to get all smtp plugin published actions which are not deleted and doesn't have bodyType field */ Query publishedActionsQuery = getQueryToFetchAllDomainObjectsWhichAreNotDeletedUsingPluginId(smtpPlugin) - .addCriteria(where("publishedAction.actionConfiguration.formData.send").exists(true)) - .addCriteria(where("publishedAction.actionConfiguration.formData.send.bodyType").exists(false)); + .addCriteria(where("publishedAction.actionConfiguration.formData.send") + .exists(true)) + .addCriteria(where("publishedAction.actionConfiguration.formData.send.bodyType") + .exists(false)); /* Update the bodyType field to have "text/html" value by default */ Update updatePublishedActions = new Update(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration010AddIndexToDatasourceStorage.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration010AddIndexToDatasourceStorage.java index 4648123661a0..8e4ac5fe155c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration010AddIndexToDatasourceStorage.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration010AddIndexToDatasourceStorage.java @@ -26,7 +26,8 @@ public void rollbackExecution() { @Execution public void addingIndexToDatasourceStorage() { - Index datasourceIdAndEnvironmentId = makeIndex("datasourceId", "environmentId", "deletedAt").unique() + Index datasourceIdAndEnvironmentId = makeIndex("datasourceId", "environmentId", "deletedAt") + .unique() .named("datasource_storage_compound_index"); ensureIndexes(mongoTemplate, DatasourceStorage.class, datasourceIdAndEnvironmentId); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration011AddPluginTypeIndexToNewActionCollection.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration011AddPluginTypeIndexToNewActionCollection.java index f7198b192bd2..d5b34e6f375e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration011AddPluginTypeIndexToNewActionCollection.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration011AddPluginTypeIndexToNewActionCollection.java @@ -27,15 +27,12 @@ public void rollbackExecution() { @Execution public void addingIndexToNewAction() { - Index pluginTypeDeletedAtCompoundIndex = - makeIndex(fieldName(QNewAction.newAction.applicationId), + Index pluginTypeDeletedAtCompoundIndex = makeIndex( + fieldName(QNewAction.newAction.applicationId), fieldName(QNewAction.newAction.pluginType), fieldName(QNewAction.newAction.deletedAt)) - .named("applicationId_pluginType_deletedAt_compound_index"); + .named("applicationId_pluginType_deletedAt_compound_index"); ensureIndexes(mongoTemplate, NewAction.class, pluginTypeDeletedAtCompoundIndex); } - } - - diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration012RenameIndexesWithLongNames.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration012RenameIndexesWithLongNames.java index 10e6bfec99b9..e68060dfc717 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration012RenameIndexesWithLongNames.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration012RenameIndexesWithLongNames.java @@ -1,6 +1,5 @@ package com.appsmith.server.migrations.db.ce; - import com.appsmith.external.models.DatasourceStorageStructure; import com.appsmith.server.constants.FieldName; import com.appsmith.server.domains.ActionCollection; @@ -33,84 +32,111 @@ public class Migration012RenameIndexesWithLongNames { @RollbackExecution public void rollBackExecution() { - // Rollback behaviour is undefined. This migration is idempotent, and only does indexes, so should be fine going back. + // Rollback behaviour is undefined. This migration is idempotent, and only does indexes, so should be fine going + // back. } @Execution public void executeMigration() { // update-index-for-git - if (dropIndexIfExists(mongoTemplate, Application.class, "defaultCollectionId_branchName_deleted_compound_index")) { - ensureIndexes(mongoTemplate, ActionCollection.class, - makeIndex("defaultResources.collectionId", "defaultResources.branchName", "deleted") - .named("defaultCollectionId_branchName_deleted") - ); + if (dropIndexIfExists( + mongoTemplate, Application.class, "defaultCollectionId_branchName_deleted_compound_index")) { + ensureIndexes( + mongoTemplate, + ActionCollection.class, + makeIndex("defaultResources.collectionId", "defaultResources.branchName", "deleted") + .named("defaultCollectionId_branchName_deleted")); } // update-index-for-git - if (dropIndexIfExists(mongoTemplate, Application.class, "defaultApplicationId_branchName_deleted_compound_index")) { - ensureIndexes(mongoTemplate, Application.class, - makeIndex("gitApplicationMetadata.defaultApplicationId", "gitApplicationMetadata.branchName", "deleted") - .named("defaultApplicationId_branchName_deleted") - ); + if (dropIndexIfExists( + mongoTemplate, Application.class, "defaultApplicationId_branchName_deleted_compound_index")) { + ensureIndexes( + mongoTemplate, + Application.class, + makeIndex( + "gitApplicationMetadata.defaultApplicationId", + "gitApplicationMetadata.branchName", + "deleted") + .named("defaultApplicationId_branchName_deleted")); } // update-index-for-newAction-actionCollection - if (dropIndexIfExists(mongoTemplate, ActionCollection.class, "unpublishedCollectionPageId_deleted_compound_index")) { - ensureIndexes(mongoTemplate, ActionCollection.class, - makeIndex(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + FieldName.PAGE_ID, FieldName.DELETED) - .named("unpublishedCollectionPageId_deleted") - ); + if (dropIndexIfExists( + mongoTemplate, ActionCollection.class, "unpublishedCollectionPageId_deleted_compound_index")) { + ensureIndexes( + mongoTemplate, + ActionCollection.class, + makeIndex( + fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + FieldName.PAGE_ID, + FieldName.DELETED) + .named("unpublishedCollectionPageId_deleted")); } // update-index-for-newAction-actionCollection - if (dropIndexIfExists(mongoTemplate, ActionCollection.class, "publishedCollectionPageId_deleted_compound_index")) { - ensureIndexes(mongoTemplate, ActionCollection.class, - makeIndex(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + FieldName.PAGE_ID, FieldName.DELETED) - .named("publishedCollectionPageId_deleted") - ); + if (dropIndexIfExists( + mongoTemplate, ActionCollection.class, "publishedCollectionPageId_deleted_compound_index")) { + ensureIndexes( + mongoTemplate, + ActionCollection.class, + makeIndex( + fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + FieldName.PAGE_ID, + FieldName.DELETED) + .named("publishedCollectionPageId_deleted")); } // update-git-indexes - dropIndexIfExists(mongoTemplate, ActionCollection.class, "defaultApplicationId_gitSyncId_deleted_compound_index"); + dropIndexIfExists( + mongoTemplate, ActionCollection.class, "defaultApplicationId_gitSyncId_deleted_compound_index"); dropIndexIfExists(mongoTemplate, NewAction.class, "defaultApplicationId_gitSyncId_deleted_compound_index"); dropIndexIfExists(mongoTemplate, NewPage.class, "defaultApplicationId_gitSyncId_deleted_compound_index"); DatabaseChangelog2.doAddIndexesForGit(mongoTemplate); // organization-to-workspace-indexes-recreate - if (dropIndexIfExists(mongoTemplate, Application.class, "workspace_application_deleted_gitApplicationMetadata_compound_index")) { - ensureIndexes(mongoTemplate, Application.class, - makeIndex( - fieldName(QApplication.application.workspaceId), - fieldName(QApplication.application.name), - fieldName(QApplication.application.deletedAt), - "gitApplicationMetadata.remoteUrl", - "gitApplicationMetadata.branchName") - .unique().named("workspace_app_deleted_gitApplicationMetadata") - ); + if (dropIndexIfExists( + mongoTemplate, + Application.class, + "workspace_application_deleted_gitApplicationMetadata_compound_index")) { + ensureIndexes( + mongoTemplate, + Application.class, + makeIndex( + fieldName(QApplication.application.workspaceId), + fieldName(QApplication.application.name), + fieldName(QApplication.application.deletedAt), + "gitApplicationMetadata.remoteUrl", + "gitApplicationMetadata.branchName") + .unique() + .named("workspace_app_deleted_gitApplicationMetadata")); } DatabaseChangelog2.doAddPermissionGroupIndex(mongoTemplate); // Idempotent index-only migration, do it again. // create-index-default-domain-id-default-domain-type dropIndexIfExists( - mongoTemplate, - PermissionGroup.class, - "permission_group_domainId_domainType_deleted_deleted_compound_index" - ); + mongoTemplate, + PermissionGroup.class, + "permission_group_domainId_domainType_deleted_deleted_compound_index"); Index newIndexDefaultDomainIdDefaultDomainTypeDeletedDeletedAt = makeIndex( - fieldName(QPermissionGroup.permissionGroup.defaultDomainId), - fieldName(QPermissionGroup.permissionGroup.defaultDomainType), - fieldName(QPermissionGroup.permissionGroup.deleted), - fieldName(QPermissionGroup.permissionGroup.deletedAt) - ).named(Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDefaultWorkspaceId.newPermissionGroupIndexNameDefaultDomainIdDefaultDomainType); + fieldName(QPermissionGroup.permissionGroup.defaultDomainId), + fieldName(QPermissionGroup.permissionGroup.defaultDomainType), + fieldName(QPermissionGroup.permissionGroup.deleted), + fieldName(QPermissionGroup.permissionGroup.deletedAt)) + .named( + Migration008CreateIndexDefaultDomainIdDefaultDomainTypeDropIndexDefaultWorkspaceId + .newPermissionGroupIndexNameDefaultDomainIdDefaultDomainType); ensureIndexes(mongoTemplate, PermissionGroup.class, newIndexDefaultDomainIdDefaultDomainTypeDeletedDeletedAt); // remove-structure-from-within-datasource - dropIndexIfExists(mongoTemplate, DatasourceStorageStructure.class, "dsConfigStructure_datasourceId_envId_compound_index"); - DatabaseChangelog1.ensureIndexes(mongoTemplate, DatasourceStorageStructure.class, - DatabaseChangelog1.makeIndex("datasourceId", "environmentId") - .unique().named("dsConfigStructure_dsId_envId") - ); + dropIndexIfExists( + mongoTemplate, DatasourceStorageStructure.class, "dsConfigStructure_datasourceId_envId_compound_index"); + DatabaseChangelog1.ensureIndexes( + mongoTemplate, + DatasourceStorageStructure.class, + DatabaseChangelog1.makeIndex("datasourceId", "environmentId") + .unique() + .named("dsConfigStructure_dsId_envId")); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration013UnsetEncryptionVersion2Fields.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration013UnsetEncryptionVersion2Fields.java index 3e98a0e76b03..56d549b50177 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration013UnsetEncryptionVersion2Fields.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration013UnsetEncryptionVersion2Fields.java @@ -25,7 +25,6 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; - @Slf4j @ChangeUnit(order = "013", id = "unset-not-encrypted-encryption-version-2-fields", author = " ") public class Migration013UnsetEncryptionVersion2Fields { @@ -33,17 +32,25 @@ public class Migration013UnsetEncryptionVersion2Fields { private final MongoTemplate mongoTemplate; private static final int ENCRYPTION_VERSION = 2; private static final String ENCRYPTION_VERSION_FIELD_NAME = "encryptionVersion"; - private static final String DATASOURCE_CONFIGURATION_FIELD_NAME = fieldName(QDatasource.datasource.datasourceConfiguration); - private static final String AUTHENTICATION_FIELD_NAME = fieldName(QDatasourceConfiguration.datasourceConfiguration.authentication); + private static final String DATASOURCE_CONFIGURATION_FIELD_NAME = + fieldName(QDatasource.datasource.datasourceConfiguration); + private static final String AUTHENTICATION_FIELD_NAME = + fieldName(QDatasourceConfiguration.datasourceConfiguration.authentication); private static final String DELIMITER = "."; - private static final String AUTHENTICATION_QUALIFIED_NAME = DATASOURCE_CONFIGURATION_FIELD_NAME + DELIMITER + AUTHENTICATION_FIELD_NAME; - private static final String AUTHENTICATION_RESPONSE_QUALIFIED_NAME = AUTHENTICATION_QUALIFIED_NAME + DELIMITER + fieldName(QAuthenticationDTO.authenticationDTO.authenticationResponse); - private static final String PASSWORD_QUALIFIED_NAME = AUTHENTICATION_QUALIFIED_NAME + DELIMITER + PASSWORD; - private static final String CLIENT_SECRET_QUALIFIED_NAME = AUTHENTICATION_RESPONSE_QUALIFIED_NAME + DELIMITER + CLIENT_SECRET; + private static final String AUTHENTICATION_QUALIFIED_NAME = + DATASOURCE_CONFIGURATION_FIELD_NAME + DELIMITER + AUTHENTICATION_FIELD_NAME; + private static final String AUTHENTICATION_RESPONSE_QUALIFIED_NAME = AUTHENTICATION_QUALIFIED_NAME + + DELIMITER + + fieldName(QAuthenticationDTO.authenticationDTO.authenticationResponse); + private static final String PASSWORD_QUALIFIED_NAME = AUTHENTICATION_QUALIFIED_NAME + DELIMITER + PASSWORD; + private static final String CLIENT_SECRET_QUALIFIED_NAME = + AUTHENTICATION_RESPONSE_QUALIFIED_NAME + DELIMITER + CLIENT_SECRET; private static final String TOKEN_QUALIFIED_NAME = AUTHENTICATION_RESPONSE_QUALIFIED_NAME + DELIMITER + TOKEN; - private static final String REFRESH_TOKEN_QUALIFIED_NAME = AUTHENTICATION_RESPONSE_QUALIFIED_NAME + DELIMITER + REFRESH_TOKEN; - private static final String TOKEN_RESPONSE_QUALIFIED_NAME = AUTHENTICATION_RESPONSE_QUALIFIED_NAME + DELIMITER + TOKEN_RESPONSE; + private static final String REFRESH_TOKEN_QUALIFIED_NAME = + AUTHENTICATION_RESPONSE_QUALIFIED_NAME + DELIMITER + REFRESH_TOKEN; + private static final String TOKEN_RESPONSE_QUALIFIED_NAME = + AUTHENTICATION_RESPONSE_QUALIFIED_NAME + DELIMITER + TOKEN_RESPONSE; public Migration013UnsetEncryptionVersion2Fields(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; @@ -70,24 +77,23 @@ public void executeMigration(MongoOperations mongoOperations) { mongoOperations.updateMulti(datasourcesToUpdateQuery, updateQuery, Datasource.class); } - private Criteria findDatasourceToUnsetFieldsIn() { + private Criteria findDatasourceToUnsetFieldsIn() { - return new Criteria().andOperator( - //Older check for deleted - new Criteria().orOperator( - where(FieldName.DELETED).exists(false), - where(FieldName.DELETED).is(false) - ), - //New check for deleted - new Criteria().orOperator( - where(FieldName.DELETED_AT).exists(false), - where(FieldName.DELETED_AT).is(null) - ), - new Criteria().andOperator( - where(ENCRYPTION_VERSION_FIELD_NAME).exists(true), - where(ENCRYPTION_VERSION_FIELD_NAME).is(ENCRYPTION_VERSION) - ) - ); + return new Criteria() + .andOperator( + // Older check for deleted + new Criteria() + .orOperator( + where(FieldName.DELETED).exists(false), + where(FieldName.DELETED).is(false)), + // New check for deleted + new Criteria() + .orOperator( + where(FieldName.DELETED_AT).exists(false), + where(FieldName.DELETED_AT).is(null)), + new Criteria() + .andOperator( + where(ENCRYPTION_VERSION_FIELD_NAME).exists(true), + where(ENCRYPTION_VERSION_FIELD_NAME).is(ENCRYPTION_VERSION))); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration014UpdateOraclePluginDocumentationLink.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration014UpdateOraclePluginDocumentationLink.java index 4b85aa5c5661..c4583d833eb7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration014UpdateOraclePluginDocumentationLink.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration014UpdateOraclePluginDocumentationLink.java @@ -9,7 +9,7 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; -@ChangeUnit(order = "014", id="update-oracle-doc-link", author = " ") +@ChangeUnit(order = "014", id = "update-oracle-doc-link", author = " ") public class Migration014UpdateOraclePluginDocumentationLink { private final MongoTemplate mongoTemplate; @@ -18,13 +18,13 @@ public Migration014UpdateOraclePluginDocumentationLink(MongoTemplate mongoTempla } @RollbackExecution - public void rollBackExecution() { - } + public void rollBackExecution() {} @Execution public void updateOracleDocumentationLink() { Plugin oraclePlugin = mongoTemplate.findOne(query(where("packageName").is("oracle-plugin")), Plugin.class); - oraclePlugin.setDocumentationLink("https://docs.appsmith.com/reference/datasources/querying-oracle#create-queries"); + oraclePlugin.setDocumentationLink( + "https://docs.appsmith.com/reference/datasources/querying-oracle#create-queries"); mongoTemplate.save(oraclePlugin); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration015RemoveNullEnvIdDatasourceStrucutureDocuments.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration015RemoveNullEnvIdDatasourceStrucutureDocuments.java index 8124a3050cc8..09f380b57c6a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration015RemoveNullEnvIdDatasourceStrucutureDocuments.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration015RemoveNullEnvIdDatasourceStrucutureDocuments.java @@ -16,6 +16,7 @@ public class Migration015RemoveNullEnvIdDatasourceStrucutureDocuments { private final MongoTemplate mongoTemplate; private static final String environmentId = FieldName.ENVIRONMENT_ID; + public Migration015RemoveNullEnvIdDatasourceStrucutureDocuments(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } @@ -31,9 +32,9 @@ public void executeMigration() { } private Criteria nullEnvironmentIdCriterion() { - return new Criteria().orOperator( - Criteria.where(environmentId).is(null), - Criteria.where(environmentId).exists(false) - ); + return new Criteria() + .orOperator( + Criteria.where(environmentId).is(null), + Criteria.where(environmentId).exists(false)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration109TransferToDatasourceStorage.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration109TransferToDatasourceStorage.java index ffafca8f897a..c849a6c9b00c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration109TransferToDatasourceStorage.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration109TransferToDatasourceStorage.java @@ -30,14 +30,18 @@ */ @Slf4j @ChangeUnit(order = "109", id = "migrate-configurations-to-data-storage-v2", author = " ") -// Although this migration is common to CE and BE, the ordering of this change-unit needs to be specifically after 107-ee, -// as this migration has EE overrides for default environmentId, and for getting the environments on existing workspaces, 107-ee needs to run +// Although this migration is common to CE and BE, the ordering of this change-unit needs to be specifically after +// 107-ee, +// as this migration has EE overrides for default environmentId, and for getting the environments on existing +// workspaces, 107-ee needs to run public class Migration109TransferToDatasourceStorage { private final MongoTemplate mongoTemplate; private final String migrationFlag = "hasDatasourceStorage"; - private static final String datasourceConfigurationFieldName = fieldName(QDatasource.datasource.datasourceConfiguration); - private static final String authenticationFieldName = fieldName(QDatasourceConfiguration.datasourceConfiguration.authentication); + private static final String datasourceConfigurationFieldName = + fieldName(QDatasource.datasource.datasourceConfiguration); + private static final String authenticationFieldName = + fieldName(QDatasourceConfiguration.datasourceConfiguration.authentication); private static final String delimiter = "."; private final DatasourceStorageMigrationSolution solution = new DatasourceStorageMigrationSolution(); @@ -60,91 +64,94 @@ public void executeMigration() { // query to fetch all datasource that // do not have `hasDatasourceStorage` value set as true Query datasourcesToUpdateQuery = query(findDatasourceIdsToUpdate()).cursorBatchSize(1024); - datasourcesToUpdateQuery.fields().include( - fieldName(QDatasource.datasource.id), - fieldName(QDatasource.datasource.workspaceId), - fieldName(QDatasource.datasource.isConfigured), - fieldName(QDatasource.datasource.gitSyncId), - fieldName(QDatasource.datasource.invalids), - fieldName(QDatasource.datasource.hasDatasourceStorage), - fieldName(QDatasource.datasource.datasourceConfiguration) - ); - - final Query performanceOptimizedUpdateQuery = CompatibilityUtils - .optimizeQueryForNoCursorTimeout(mongoTemplate, datasourcesToUpdateQuery, Datasource.class); + datasourcesToUpdateQuery + .fields() + .include( + fieldName(QDatasource.datasource.id), + fieldName(QDatasource.datasource.workspaceId), + fieldName(QDatasource.datasource.isConfigured), + fieldName(QDatasource.datasource.gitSyncId), + fieldName(QDatasource.datasource.invalids), + fieldName(QDatasource.datasource.hasDatasourceStorage), + fieldName(QDatasource.datasource.datasourceConfiguration)); + + final Query performanceOptimizedUpdateQuery = CompatibilityUtils.optimizeQueryForNoCursorTimeout( + mongoTemplate, datasourcesToUpdateQuery, Datasource.class); // Now go back to streaming through each datasource that has // `hasDatasourceStorage` value set as true - mongoTemplate - .stream(performanceOptimizedUpdateQuery, Datasource.class) - .forEach(datasource -> { - // For each of these datasource, we want to build a new datasource storage - - // Fetch the correct environment id to use with this datasource storage - String environmentId = solution - .getEnvironmentIdForDatasource(environmentsMap, datasource.getWorkspaceId()); - - // If none exists, this is an error scenario, log the error and skip the datasource - if (environmentId == null) { - log.error("Could not find default environment id for workspace id: {}, skipping datasource id: {}", - datasource.getWorkspaceId(), datasource.getId()); - return; - } - - DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, environmentId); - - log.debug("Creating datasource storage for datasource id: {} with environment id: {}", - datasource.getId(), environmentId); - - // Insert the populated datasource storage into database - try { - mongoTemplate.insert(datasourceStorage); - } catch (DuplicateKeyException e) { - log.warn("Looks like the datasource storage already exists for datasource id: {}", - datasource.getId()); - log.warn("We will attempt to reset the datasource again."); - } - - // Once the datasource storage exists, delete the older config inside datasource - // And set `hasDatasourceStorage` value to true - mongoTemplate.updateFirst( - new Query() - .addCriteria(where(fieldName(QDatasource.datasource.id)).is(datasource.getId())), - new Update() - .set(migrationFlag, true) - .unset(fieldName(QDatasource.datasource.datasourceConfiguration)) - .unset(fieldName(QDatasource.datasource.invalids)) - .unset(fieldName(QDatasource.datasource.isConfigured)), - Datasource.class); - }); - + mongoTemplate.stream(performanceOptimizedUpdateQuery, Datasource.class).forEach(datasource -> { + // For each of these datasource, we want to build a new datasource storage + + // Fetch the correct environment id to use with this datasource storage + String environmentId = solution.getEnvironmentIdForDatasource(environmentsMap, datasource.getWorkspaceId()); + + // If none exists, this is an error scenario, log the error and skip the datasource + if (environmentId == null) { + log.error( + "Could not find default environment id for workspace id: {}, skipping datasource id: {}", + datasource.getWorkspaceId(), + datasource.getId()); + return; + } + + DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, environmentId); + + log.debug( + "Creating datasource storage for datasource id: {} with environment id: {}", + datasource.getId(), + environmentId); + + // Insert the populated datasource storage into database + try { + mongoTemplate.insert(datasourceStorage); + } catch (DuplicateKeyException e) { + log.warn("Looks like the datasource storage already exists for datasource id: {}", datasource.getId()); + log.warn("We will attempt to reset the datasource again."); + } + + // Once the datasource storage exists, delete the older config inside datasource + // And set `hasDatasourceStorage` value to true + mongoTemplate.updateFirst( + new Query() + .addCriteria( + where(fieldName(QDatasource.datasource.id)).is(datasource.getId())), + new Update() + .set(migrationFlag, true) + .unset(fieldName(QDatasource.datasource.datasourceConfiguration)) + .unset(fieldName(QDatasource.datasource.invalids)) + .unset(fieldName(QDatasource.datasource.isConfigured)), + Datasource.class); + }); } private Criteria findDatasourceIdsToUpdate() { - return new Criteria().andOperator( - // Check for migration flag - new Criteria().orOperator( - where(migrationFlag).exists(false), - where(migrationFlag).is(false) - ), - //Older check for deleted - new Criteria().orOperator( - where(FieldName.DELETED).exists(false), - where(FieldName.DELETED).is(false) - ), - //New check for deleted - new Criteria().orOperator( - where(FieldName.DELETED_AT).exists(false), - where(FieldName.DELETED_AT).is(null) - ), - // these checks are placed because we are getting values which are empty and while decrypting - // those values, we are getting ArrayOutOfBoundException because password is set to "" - where(fieldName(QDatasource.datasource.workspaceId)).exists(true), - where(fieldName(QDatasource.datasource.workspaceId)).ne(null), - where(datasourceConfigurationFieldName + delimiter + authenticationFieldName + delimiter + PASSWORD).ne("") - ); + return new Criteria() + .andOperator( + // Check for migration flag + new Criteria() + .orOperator( + where(migrationFlag).exists(false), + where(migrationFlag).is(false)), + // Older check for deleted + new Criteria() + .orOperator( + where(FieldName.DELETED).exists(false), + where(FieldName.DELETED).is(false)), + // New check for deleted + new Criteria() + .orOperator( + where(FieldName.DELETED_AT).exists(false), + where(FieldName.DELETED_AT).is(null)), + // these checks are placed because we are getting values which are empty and while decrypting + // those values, we are getting ArrayOutOfBoundException because password is set to "" + where(fieldName(QDatasource.datasource.workspaceId)).exists(true), + where(fieldName(QDatasource.datasource.workspaceId)).ne(null), + where(datasourceConfigurationFieldName + + delimiter + + authenticationFieldName + + delimiter + + PASSWORD) + .ne("")); } - } - - diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/solutions/DatasourceStorageMigrationSolution.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/solutions/DatasourceStorageMigrationSolution.java index b9d3090e9c95..821290a29d19 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/solutions/DatasourceStorageMigrationSolution.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/solutions/DatasourceStorageMigrationSolution.java @@ -4,6 +4,4 @@ import lombok.NoArgsConstructor; @NoArgsConstructor -public class DatasourceStorageMigrationSolution extends DatasourceStorageMigrationSolutionCE { - -} +public class DatasourceStorageMigrationSolution extends DatasourceStorageMigrationSolutionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/solutions/ce/DatasourceStorageMigrationSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/solutions/ce/DatasourceStorageMigrationSolutionCE.java index 6e3f3381c3b0..a4fd410a7368 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/solutions/ce/DatasourceStorageMigrationSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/solutions/ce/DatasourceStorageMigrationSolutionCE.java @@ -11,8 +11,7 @@ public Map<String, String> getDefaultEnvironmentsMap(MongoTemplate mongoTemplate return Map.of(); } - public String getEnvironmentIdForDatasource(Map<String, String> wsIdToEnvIdMap, - String workspaceId) { + public String getEnvironmentIdForDatasource(Map<String, String> wsIdToEnvIdMap, String workspaceId) { return FieldName.UNUSED_ENVIRONMENT_ID; } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/utils/CompatibilityUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/utils/CompatibilityUtils.java index 09559f509cc5..e31957abddcd 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/utils/CompatibilityUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/utils/CompatibilityUtils.java @@ -19,12 +19,13 @@ public class CompatibilityUtils { * @param <T> The BaseDomain type this collection maps to * @return A query that is guaranteed to run on this instance, with or without optimization */ - public static <T extends BaseDomain> Query optimizeQueryForNoCursorTimeout - (MongoTemplate mongoTemplate, Query originalQuery, Class<T> clazz) { + public static <T extends BaseDomain> Query optimizeQueryForNoCursorTimeout( + MongoTemplate mongoTemplate, Query originalQuery, Class<T> clazz) { try { log.debug("Check if performant query can be used."); Query queryBatchedPerformant = Query.of(originalQuery).noCursorTimeout(); - Query queryBatchedPerformantLimit1 = Query.of(queryBatchedPerformant).limit(1); + Query queryBatchedPerformantLimit1 = + Query.of(queryBatchedPerformant).limit(1); mongoTemplate.stream(queryBatchedPerformantLimit1, clazz) .forEach(domain -> log.debug("{} Id: {}", clazz.getName(), domain.getId())); log.debug("Using performant query."); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/notifications/EmailSender.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/notifications/EmailSender.java index 5e39fe866623..485392479d73 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/notifications/EmailSender.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/notifications/EmailSender.java @@ -42,7 +42,8 @@ public Mono<Boolean> sendMail(String to, String subject, String text, Map<String return sendMail(to, subject, text, params, null); } - public Mono<Boolean> sendMail(String to, String subject, String text, Map<String, ? extends Object> params, String replyTo) { + public Mono<Boolean> sendMail( + String to, String subject, String text, Map<String, ? extends Object> params, String replyTo) { /** * Creating a publisher which sends email in a blocking fashion, subscribing on the bounded elastic @@ -108,7 +109,11 @@ private void sendMailSync(String to, String subject, String text, String replyTo log.debug("Email sent successfully to {} with subject {}", to, subject); } catch (MessagingException e) { - log.error("Unable to create the mime message while sending an email to {} with subject: {}. Cause: ", to, subject, e); + log.error( + "Unable to create the mime message while sending an email to {} with subject: {}. Cause: ", + to, + subject, + e); } catch (MailException e) { log.error("Unable to send email. Cause: ", e); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ActionCollectionRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ActionCollectionRepository.java index f2c1f8517b51..217446df7ae6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ActionCollectionRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ActionCollectionRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface ActionCollectionRepository extends CustomActionCollectionRepository, ActionCollectionRepositoryCE { - -} +public interface ActionCollectionRepository extends CustomActionCollectionRepository, ActionCollectionRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ActionRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ActionRepository.java index 67cc5bc5b376..59fbd69bdb62 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ActionRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ActionRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface ActionRepository extends ActionRepositoryCE, CustomActionRepository { - -} +public interface ActionRepository extends ActionRepositoryCE, CustomActionRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApiTemplateRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApiTemplateRepository.java index 26c10026f466..cc589ae8cae4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApiTemplateRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApiTemplateRepository.java @@ -2,5 +2,4 @@ import com.appsmith.server.repositories.ce.ApiTemplateRepositoryCE; -public interface ApiTemplateRepository extends ApiTemplateRepositoryCE, CustomApiTemplateRepository { -} +public interface ApiTemplateRepository extends ApiTemplateRepositoryCE, CustomApiTemplateRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApplicationRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApplicationRepository.java index f0fbeb6b5633..718b248b5feb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApplicationRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApplicationRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface ApplicationRepository extends ApplicationRepositoryCE, CustomApplicationRepository { - -} +public interface ApplicationRepository extends ApplicationRepositoryCE, CustomApplicationRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApplicationSnapshotRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApplicationSnapshotRepository.java index 6f8b55a1fde0..d6f71adb9a15 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApplicationSnapshotRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ApplicationSnapshotRepository.java @@ -4,6 +4,5 @@ import org.springframework.stereotype.Repository; @Repository -public interface ApplicationSnapshotRepository extends ApplicationSnapshotRepositoryCE, CustomApplicationSnapshotRepository { - -} +public interface ApplicationSnapshotRepository + extends ApplicationSnapshotRepositoryCE, CustomApplicationSnapshotRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/AssetRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/AssetRepository.java index f6410205235f..bd6b5ff294b1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/AssetRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/AssetRepository.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface AssetRepository extends AssetRepositoryCE { -} +public interface AssetRepository extends AssetRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseAppsmithRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseAppsmithRepositoryImpl.java index c3f7a3a5f294..f76d565d025f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseAppsmithRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseAppsmithRepositoryImpl.java @@ -9,10 +9,11 @@ @Slf4j public abstract class BaseAppsmithRepositoryImpl<T extends BaseDomain> extends BaseAppsmithRepositoryCEImpl<T> { - public BaseAppsmithRepositoryImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public BaseAppsmithRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseRepository.java index fe638386cfbc..0500e7d6b440 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseRepository.java @@ -1,7 +1,7 @@ package com.appsmith.server.repositories; -import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import com.mongodb.client.result.UpdateResult; +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import org.springframework.data.repository.NoRepositoryBean; import reactor.core.publisher.Mono; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseRepositoryImpl.java index 7c5bff043d6b..0bed0d582b50 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseRepositoryImpl.java @@ -59,30 +59,31 @@ * Ref: https://theappsmith.slack.com/archives/CPQNLFHTN/p1669100205502599?thread_ts=1668753437.497369&cid=CPQNLFHTN */ @Slf4j -public class BaseRepositoryImpl<T extends BaseDomain, ID extends Serializable> extends SimpleReactiveMongoRepository<T, ID> - implements BaseRepository<T, ID> { +public class BaseRepositoryImpl<T extends BaseDomain, ID extends Serializable> + extends SimpleReactiveMongoRepository<T, ID> implements BaseRepository<T, ID> { protected final MongoEntityInformation<T, ID> entityInformation; protected final ReactiveMongoOperations mongoOperations; - public BaseRepositoryImpl(@NonNull MongoEntityInformation<T, ID> entityInformation, - @NonNull ReactiveMongoOperations mongoOperations) { + public BaseRepositoryImpl( + @NonNull MongoEntityInformation<T, ID> entityInformation, + @NonNull ReactiveMongoOperations mongoOperations) { super(entityInformation, mongoOperations); this.entityInformation = entityInformation; this.mongoOperations = mongoOperations; } private Criteria notDeleted() { - return new Criteria().andOperator( - new Criteria().orOperator( - where(FieldName.DELETED).exists(false), - where(FieldName.DELETED).is(false) - ), - new Criteria().orOperator( - where(FieldName.DELETED_AT).exists(false), - where(FieldName.DELETED_AT).is(null) - ) - ); + return new Criteria() + .andOperator( + new Criteria() + .orOperator( + where(FieldName.DELETED).exists(false), + where(FieldName.DELETED).is(false)), + new Criteria() + .orOperator( + where(FieldName.DELETED_AT).exists(false), + where(FieldName.DELETED_AT).is(null))); } private Criteria getIdCriteria(Object id) { @@ -111,7 +112,8 @@ public Mono<T> findByIdAndFieldNames(ID id, List<String> fieldNames) { }); } - return mongoOperations.query(entityInformation.getJavaType()) + return mongoOperations + .query(entityInformation.getJavaType()) .inCollection(entityInformation.getCollectionName()) .matching(query) .one(); @@ -157,7 +159,8 @@ public Flux<T> findAll() { .map(auth -> auth.getPrincipal()) .flatMapMany(principal -> { Query query = new Query(notDeleted()); - return mongoOperations.find(query, entityInformation.getJavaType(), entityInformation.getCollectionName()); + return mongoOperations.find( + query, entityInformation.getJavaType(), entityInformation.getCollectionName()); }); } @@ -170,21 +173,20 @@ public Flux<T> findAll(Example example, Sort sort) { .map(ctx -> ctx.getAuthentication()) .map(auth -> auth.getPrincipal()) .flatMapMany(principal -> { - - Criteria criteria = new Criteria().andOperator( - //Older check for deleted - new Criteria().orOperator( - where(FieldName.DELETED).exists(false), - where(FieldName.DELETED).is(false) - ), - //New check for deleted - new Criteria().orOperator( - where(FieldName.DELETED_AT).exists(false), - where(FieldName.DELETED_AT).is(null) - ), - // Set the criteria as the example - new Criteria().alike(example) - ); + Criteria criteria = new Criteria() + .andOperator( + // Older check for deleted + new Criteria() + .orOperator( + where(FieldName.DELETED).exists(false), + where(FieldName.DELETED).is(false)), + // New check for deleted + new Criteria() + .orOperator( + where(FieldName.DELETED_AT).exists(false), + where(FieldName.DELETED_AT).is(null)), + // Set the criteria as the example + new Criteria().alike(example)); Query query = new Query(criteria) .collation(entityInformation.getCollation()) // @@ -229,7 +231,8 @@ public Mono<Boolean> archiveById(ID id) { Update update = new Update(); update.set(FieldName.DELETED, true); update.set(FieldName.DELETED_AT, Instant.now()); - return mongoOperations.updateFirst(query, update, entityInformation.getJavaType()) + return mongoOperations + .updateFirst(query, update, entityInformation.getJavaType()) .map(result -> result.getModifiedCount() > 0 ? true : false); }); } @@ -250,7 +253,8 @@ public Mono<Boolean> archiveAllById(List<ID> ids) { Update update = new Update(); update.set(FieldName.DELETED, true); update.set(FieldName.DELETED_AT, Instant.now()); - return mongoOperations.updateMulti(query, update, entityInformation.getJavaType()) + return mongoOperations + .updateMulti(query, update, entityInformation.getJavaType()) .map(result -> result.getModifiedCount() > 0 ? true : false); }); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CacheableRepositoryHelper.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CacheableRepositoryHelper.java index 3ba3e0c324c9..6d4a45d5cd1c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CacheableRepositoryHelper.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CacheableRepositoryHelper.java @@ -2,5 +2,4 @@ import com.appsmith.server.repositories.ce.CacheableRepositoryHelperCE; -public interface CacheableRepositoryHelper extends CacheableRepositoryHelperCE { -} +public interface CacheableRepositoryHelper extends CacheableRepositoryHelperCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CacheableRepositoryHelperImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CacheableRepositoryHelperImpl.java index 22e2db74abc6..9bbb4787b1f9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CacheableRepositoryHelperImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CacheableRepositoryHelperImpl.java @@ -5,7 +5,8 @@ import org.springframework.stereotype.Component; @Component -public class CacheableRepositoryHelperImpl extends CacheableRepositoryHelperCEImpl implements CacheableRepositoryHelper{ +public class CacheableRepositoryHelperImpl extends CacheableRepositoryHelperCEImpl + implements CacheableRepositoryHelper { public CacheableRepositoryHelperImpl(ReactiveMongoOperations mongoOperations) { super(mongoOperations); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CollectionRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CollectionRepository.java index 92a4fc7611b9..f56b886f0ce3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CollectionRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CollectionRepository.java @@ -1,11 +1,7 @@ package com.appsmith.server.repositories; -import com.appsmith.server.domains.Collection; import com.appsmith.server.repositories.ce.CollectionRepositoryCE; import org.springframework.stereotype.Repository; -import reactor.core.publisher.Mono; @Repository -public interface CollectionRepository extends CollectionRepositoryCE, CustomCollectionRepository { - -} +public interface CollectionRepository extends CollectionRepositoryCE, CustomCollectionRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ConfigRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ConfigRepository.java index 94308aff9b88..b3b1cb09dfce 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ConfigRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ConfigRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface ConfigRepository extends ConfigRepositoryCE, CustomConfigRepository { - -} +public interface ConfigRepository extends ConfigRepositoryCE, CustomConfigRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionCollectionRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionCollectionRepository.java index 2c8c80237c34..d18d7dd2091e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionCollectionRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionCollectionRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomActionCollectionRepositoryCE; -public interface CustomActionCollectionRepository extends CustomActionCollectionRepositoryCE { - -} +public interface CustomActionCollectionRepository extends CustomActionCollectionRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionCollectionRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionCollectionRepositoryImpl.java index 8502e3d43fc7..6e95f7f5098a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionCollectionRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionCollectionRepositoryImpl.java @@ -6,10 +6,13 @@ import org.springframework.stereotype.Component; @Component -public class CustomActionCollectionRepositoryImpl extends CustomActionCollectionRepositoryCEImpl implements CustomActionCollectionRepository { +public class CustomActionCollectionRepositoryImpl extends CustomActionCollectionRepositoryCEImpl + implements CustomActionCollectionRepository { - public CustomActionCollectionRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomActionCollectionRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionRepository.java index 253961fcb18a..aa1dea274dc7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomActionRepositoryCE; -public interface CustomActionRepository extends CustomActionRepositoryCE { - -} +public interface CustomActionRepository extends CustomActionRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionRepositoryImpl.java index 65926bc30067..690f6bfa6280 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomActionRepositoryImpl.java @@ -8,8 +8,10 @@ @Component public class CustomActionRepositoryImpl extends CustomActionRepositoryCEImpl implements CustomActionRepository { - public CustomActionRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomActionRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApiTemplateRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApiTemplateRepository.java index a862c79941bd..82bd2c4dfcc4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApiTemplateRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApiTemplateRepository.java @@ -2,5 +2,4 @@ import com.appsmith.server.repositories.ce.CustomApiTemplateRepositoryCE; -public interface CustomApiTemplateRepository extends CustomApiTemplateRepositoryCE { -} +public interface CustomApiTemplateRepository extends CustomApiTemplateRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApiTemplateRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApiTemplateRepositoryImpl.java index 041d08cf2615..366c74ac7176 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApiTemplateRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApiTemplateRepositoryImpl.java @@ -9,7 +9,10 @@ public class CustomApiTemplateRepositoryImpl extends CustomApiTemplateRepositoryCEImpl implements CustomApiTemplateRepository { - public CustomApiTemplateRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomApiTemplateRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationRepository.java index 0e248c3bdb82..0a741d7cc265 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomApplicationRepositoryCE; -public interface CustomApplicationRepository extends CustomApplicationRepositoryCE { - -} +public interface CustomApplicationRepository extends CustomApplicationRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationRepositoryImpl.java index a9a75a8b4634..8f632ae47655 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationRepositoryImpl.java @@ -15,11 +15,11 @@ public class CustomApplicationRepositoryImpl extends CustomApplicationRepository implements CustomApplicationRepository { @Autowired - public CustomApplicationRepositoryImpl(@NonNull ReactiveMongoOperations mongoOperations, - @NonNull MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper, - ApplicationPermission applicationPermission) { + public CustomApplicationRepositoryImpl( + @NonNull ReactiveMongoOperations mongoOperations, + @NonNull MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper, + ApplicationPermission applicationPermission) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper, applicationPermission); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationSnapshotRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationSnapshotRepository.java index 7b965a469202..fee25b5e1484 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationSnapshotRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationSnapshotRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomApplicationSnapshotRepositoryCE; -public interface CustomApplicationSnapshotRepository extends CustomApplicationSnapshotRepositoryCE { - -} +public interface CustomApplicationSnapshotRepository extends CustomApplicationSnapshotRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationSnapshotRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationSnapshotRepositoryImpl.java index d0fd60ccaed8..75b436568afc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationSnapshotRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomApplicationSnapshotRepositoryImpl.java @@ -6,8 +6,12 @@ import org.springframework.stereotype.Component; @Component -public class CustomApplicationSnapshotRepositoryImpl extends CustomApplicationSnapshotRepositoryCEImpl implements CustomApplicationSnapshotRepository { - public CustomApplicationSnapshotRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { +public class CustomApplicationSnapshotRepositoryImpl extends CustomApplicationSnapshotRepositoryCEImpl + implements CustomApplicationSnapshotRepository { + public CustomApplicationSnapshotRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCollectionRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCollectionRepository.java index 8e41902f1ab8..966d8c6d49af 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCollectionRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCollectionRepository.java @@ -2,5 +2,4 @@ import com.appsmith.server.repositories.ce.CustomCollectionRepositoryCE; -public interface CustomCollectionRepository extends CustomCollectionRepositoryCE { -} +public interface CustomCollectionRepository extends CustomCollectionRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCollectionRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCollectionRepositoryImpl.java index bea286b66040..8b011fa7ae58 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCollectionRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCollectionRepositoryImpl.java @@ -7,10 +7,14 @@ import org.springframework.stereotype.Component; @Component -public class CustomCollectionRepositoryImpl extends CustomCollectionRepositoryCEImpl implements CustomCollectionRepository { +public class CustomCollectionRepositoryImpl extends CustomCollectionRepositoryCEImpl + implements CustomCollectionRepository { @Autowired - public CustomCollectionRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomCollectionRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomConfigRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomConfigRepository.java index 28c8d027b22c..b54bbee0e60b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomConfigRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomConfigRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomConfigRepositoryCE; -public interface CustomConfigRepository extends CustomConfigRepositoryCE { - -} +public interface CustomConfigRepository extends CustomConfigRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomConfigRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomConfigRepositoryImpl.java index 0afad2dc681a..cd53e776d202 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomConfigRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomConfigRepositoryImpl.java @@ -8,7 +8,10 @@ @Component public class CustomConfigRepositoryImpl extends CustomConfigRepositoryCEImpl implements CustomConfigRepository { - public CustomConfigRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomConfigRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceRepository.java index 1498cc8e95bf..44d097b0f534 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomDatasourceRepositoryCE; -public interface CustomDatasourceRepository extends CustomDatasourceRepositoryCE { - -} +public interface CustomDatasourceRepository extends CustomDatasourceRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceRepositoryImpl.java index cadc6b687539..63a510fad17d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceRepositoryImpl.java @@ -6,10 +6,13 @@ import org.springframework.stereotype.Component; @Component -public class CustomDatasourceRepositoryImpl extends CustomDatasourceRepositoryCEImpl implements CustomDatasourceRepository { +public class CustomDatasourceRepositoryImpl extends CustomDatasourceRepositoryCEImpl + implements CustomDatasourceRepository { - public CustomDatasourceRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomDatasourceRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStorageRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStorageRepository.java index 2f630df294fd..b90e90414964 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStorageRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStorageRepository.java @@ -2,5 +2,4 @@ import com.appsmith.server.repositories.ce.CustomDatasourceStorageRepositoryCE; -public interface CustomDatasourceStorageRepository extends CustomDatasourceStorageRepositoryCE { -} +public interface CustomDatasourceStorageRepository extends CustomDatasourceStorageRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStorageRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStorageRepositoryImpl.java index 3fe4748649eb..9155963238c1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStorageRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStorageRepositoryImpl.java @@ -11,9 +11,10 @@ public class CustomDatasourceStorageRepositoryImpl extends CustomDatasourceStorageRepositoryCEImpl implements CustomDatasourceStorageRepository { - public CustomDatasourceStorageRepositoryImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomDatasourceStorageRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStructureRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStructureRepository.java index 642e6310574a..3712d11da2f7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStructureRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStructureRepository.java @@ -2,5 +2,4 @@ import com.appsmith.server.repositories.ce.CustomDatasourceStructureRepositoryCE; -public interface CustomDatasourceStructureRepository extends CustomDatasourceStructureRepositoryCE { -} +public interface CustomDatasourceStructureRepository extends CustomDatasourceStructureRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStructureRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStructureRepositoryImpl.java index 3a940733649d..e06cbdf33463 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStructureRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomDatasourceStructureRepositoryImpl.java @@ -4,12 +4,12 @@ import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.data.mongodb.core.convert.MongoConverter; -public class CustomDatasourceStructureRepositoryImpl - extends CustomDatasourceStructureRepositoryCEImpl +public class CustomDatasourceStructureRepositoryImpl extends CustomDatasourceStructureRepositoryCEImpl implements CustomDatasourceStructureRepository { - public CustomDatasourceStructureRepositoryImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomDatasourceStructureRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomGroupRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomGroupRepository.java index 5e4f6d405cf5..edf5c4311853 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomGroupRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomGroupRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomGroupRepositoryCE; -public interface CustomGroupRepository extends CustomGroupRepositoryCE { - -} +public interface CustomGroupRepository extends CustomGroupRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomGroupRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomGroupRepositoryImpl.java index 6a304f1e1b20..34a581a1de23 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomGroupRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomGroupRepositoryImpl.java @@ -8,11 +8,12 @@ @Component @Slf4j -public class CustomGroupRepositoryImpl extends CustomGroupRepositoryCEImpl - implements CustomGroupRepository { +public class CustomGroupRepositoryImpl extends CustomGroupRepositoryCEImpl implements CustomGroupRepository { - public CustomGroupRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomGroupRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomJSLibRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomJSLibRepository.java index 17b80d48563c..9cd5aed49b19 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomJSLibRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomJSLibRepository.java @@ -2,9 +2,7 @@ import com.appsmith.server.domains.CustomJSLib; import com.appsmith.server.repositories.ce.CustomJSLibRepositoryCE; -import org.springframework.data.repository.NoRepositoryBean; import org.springframework.stereotype.Repository; @Repository -public interface CustomJSLibRepository extends CustomJSLibRepositoryCE, BaseRepository<CustomJSLib, String> { -} +public interface CustomJSLibRepository extends CustomJSLibRepositoryCE, BaseRepository<CustomJSLib, String> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomJSLibRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomJSLibRepositoryImpl.java index 7b767ff392da..ab0c185ce691 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomJSLibRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomJSLibRepositoryImpl.java @@ -6,8 +6,10 @@ import org.springframework.data.mongodb.core.convert.MongoConverter; public class CustomJSLibRepositoryImpl extends CustomJSLibRepositoryCEImpl implements CustomJSLibRepositoryCE { - public CustomJSLibRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomJSLibRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewActionRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewActionRepository.java index 6f855777863f..501506ee3a3a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewActionRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewActionRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomNewActionRepositoryCE; -public interface CustomNewActionRepository extends CustomNewActionRepositoryCE { - -} +public interface CustomNewActionRepository extends CustomNewActionRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewActionRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewActionRepositoryImpl.java index cb0203883901..e45c7fd224f9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewActionRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewActionRepositoryImpl.java @@ -11,9 +11,10 @@ public class CustomNewActionRepositoryImpl extends CustomNewActionRepositoryCEImpl implements CustomNewActionRepository { - public CustomNewActionRepositoryImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomNewActionRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewPageRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewPageRepository.java index d9dcdf3ba4f3..7436898c4151 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewPageRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewPageRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomNewPageRepositoryCE; -public interface CustomNewPageRepository extends CustomNewPageRepositoryCE { - -} +public interface CustomNewPageRepository extends CustomNewPageRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewPageRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewPageRepositoryImpl.java index 1a54ae2b26af..370e5202b216 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewPageRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNewPageRepositoryImpl.java @@ -8,11 +8,12 @@ @Component @Slf4j -public class CustomNewPageRepositoryImpl extends CustomNewPageRepositoryCEImpl - implements CustomNewPageRepository { +public class CustomNewPageRepositoryImpl extends CustomNewPageRepositoryCEImpl implements CustomNewPageRepository { - public CustomNewPageRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomNewPageRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNotificationRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNotificationRepository.java index 6abc97b3f1e4..138b2c696d3f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNotificationRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNotificationRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomNotificationRepositoryCE; -public interface CustomNotificationRepository extends CustomNotificationRepositoryCE { - -} +public interface CustomNotificationRepository extends CustomNotificationRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNotificationRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNotificationRepositoryImpl.java index 113949db5655..8ed54cfea885 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNotificationRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomNotificationRepositoryImpl.java @@ -9,8 +9,10 @@ public class CustomNotificationRepositoryImpl extends CustomNotificationRepositoryCEImpl implements CustomNotificationRepository { - public CustomNotificationRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomNotificationRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPageRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPageRepository.java index 3f60e3b58211..f4862d20c085 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPageRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPageRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomPageRepositoryCE; -public interface CustomPageRepository extends CustomPageRepositoryCE { - -} +public interface CustomPageRepository extends CustomPageRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPageRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPageRepositoryImpl.java index 565a2a08fa51..fc884e5b44b8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPageRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPageRepositoryImpl.java @@ -6,11 +6,12 @@ import org.springframework.stereotype.Component; @Component -public class CustomPageRepositoryImpl extends CustomPageRepositoryCEImpl - implements CustomPageRepository { +public class CustomPageRepositoryImpl extends CustomPageRepositoryCEImpl implements CustomPageRepository { - public CustomPageRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomPageRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPermissionGroupRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPermissionGroupRepository.java index e1e08a91db94..877a0dd274ce 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPermissionGroupRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPermissionGroupRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomPermissionGroupRepositoryCE; -public interface CustomPermissionGroupRepository extends CustomPermissionGroupRepositoryCE { - -} +public interface CustomPermissionGroupRepository extends CustomPermissionGroupRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPermissionGroupRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPermissionGroupRepositoryImpl.java index e61da3a09dc9..84073cf7c631 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPermissionGroupRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPermissionGroupRepositoryImpl.java @@ -9,7 +9,10 @@ public class CustomPermissionGroupRepositoryImpl extends CustomPermissionGroupRepositoryCEImpl implements CustomPermissionGroupRepository { - public CustomPermissionGroupRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomPermissionGroupRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPluginRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPluginRepository.java index 5bc7345a83ca..84cf3820b8e0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPluginRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPluginRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomPluginRepositoryCE; -public interface CustomPluginRepository extends CustomPluginRepositoryCE { - -} +public interface CustomPluginRepository extends CustomPluginRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPluginRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPluginRepositoryImpl.java index dedf0902749e..4ae1f6a9afca 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPluginRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomPluginRepositoryImpl.java @@ -8,7 +8,10 @@ @Component public class CustomPluginRepositoryImpl extends CustomPluginRepositoryCEImpl implements CustomPluginRepository { - public CustomPluginRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomPluginRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomProviderRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomProviderRepository.java index 26ea18c4aaa5..6037f68973cf 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomProviderRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomProviderRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomProviderRepositoryCE; -public interface CustomProviderRepository extends CustomProviderRepositoryCE { - -} +public interface CustomProviderRepository extends CustomProviderRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomProviderRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomProviderRepositoryImpl.java index 8082dda019c9..e75f78ced6cc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomProviderRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomProviderRepositoryImpl.java @@ -8,7 +8,10 @@ @Component public class CustomProviderRepositoryImpl extends CustomProviderRepositoryCEImpl implements CustomProviderRepository { - public CustomProviderRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomProviderRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomTenantRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomTenantRepository.java index 066149705425..19002ae711a8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomTenantRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomTenantRepository.java @@ -2,5 +2,4 @@ import com.appsmith.server.repositories.ce.CustomTenantRepositoryCE; -public interface CustomTenantRepository extends CustomTenantRepositoryCE { -} +public interface CustomTenantRepository extends CustomTenantRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomTenantRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomTenantRepositoryImpl.java index 6f7539b345e8..a74caba9244d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomTenantRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomTenantRepositoryImpl.java @@ -6,9 +6,10 @@ public class CustomTenantRepositoryImpl extends CustomTenantRepositoryCEImpl implements CustomTenantRepository { - public CustomTenantRepositoryImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomTenantRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomThemeRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomThemeRepository.java index 9f6917f5ea68..9ca60ef135a9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomThemeRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomThemeRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomThemeRepositoryCE; -public interface CustomThemeRepository extends CustomThemeRepositoryCE { - -} +public interface CustomThemeRepository extends CustomThemeRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomThemeRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomThemeRepositoryImpl.java index 42e31620d75b..d2e234987e8a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomThemeRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomThemeRepositoryImpl.java @@ -9,7 +9,10 @@ @Component @Slf4j public class CustomThemeRepositoryImpl extends CustomThemeRepositoryCEImpl implements CustomThemeRepository { - public CustomThemeRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomThemeRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUsagePulseRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUsagePulseRepository.java index cd5a01a81324..278bd439c289 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUsagePulseRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUsagePulseRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomUsagePulseRepositoryCE; -public interface CustomUsagePulseRepository extends CustomUsagePulseRepositoryCE { - -} +public interface CustomUsagePulseRepository extends CustomUsagePulseRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUsagePulseRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUsagePulseRepositoryImpl.java index de38d3594540..0a110d1d475c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUsagePulseRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUsagePulseRepositoryImpl.java @@ -8,10 +8,13 @@ @Component @Slf4j -public class CustomUsagePulseRepositoryImpl extends CustomUsagePulseRepositoryCEImpl implements CustomUsagePulseRepository { +public class CustomUsagePulseRepositoryImpl extends CustomUsagePulseRepositoryCEImpl + implements CustomUsagePulseRepository { - public CustomUsagePulseRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomUsagePulseRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepository.java index 28347d023f0b..9c40853e6763 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomUserDataRepositoryCE; -public interface CustomUserDataRepository extends CustomUserDataRepositoryCE { - -} +public interface CustomUserDataRepository extends CustomUserDataRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepositoryImpl.java index bb6dc27f3391..6b486d85b45d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepositoryImpl.java @@ -8,8 +8,10 @@ @Component public class CustomUserDataRepositoryImpl extends CustomUserDataRepositoryCEImpl implements CustomUserDataRepository { - public CustomUserDataRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomUserDataRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserRepository.java index 9889dd144c71..a35ffce52646 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomUserRepositoryCE; -public interface CustomUserRepository extends CustomUserRepositoryCE { - -} +public interface CustomUserRepository extends CustomUserRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserRepositoryImpl.java index f5ad60eef250..13265d40c0a5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserRepositoryImpl.java @@ -10,8 +10,10 @@ @Slf4j public class CustomUserRepositoryImpl extends CustomUserRepositoryCEImpl implements CustomUserRepository { - public CustomUserRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomUserRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomWorkspaceRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomWorkspaceRepository.java index 17fcc4b74f24..ebee18cce259 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomWorkspaceRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomWorkspaceRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.CustomWorkspaceRepositoryCE; -public interface CustomWorkspaceRepository extends CustomWorkspaceRepositoryCE { - -} +public interface CustomWorkspaceRepository extends CustomWorkspaceRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomWorkspaceRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomWorkspaceRepositoryImpl.java index ce7deeeed82e..76d77007ea2a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomWorkspaceRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomWorkspaceRepositoryImpl.java @@ -2,7 +2,6 @@ import com.appsmith.server.repositories.ce.CustomWorkspaceRepositoryCEImpl; import com.appsmith.server.services.SessionUserService; - import lombok.extern.slf4j.Slf4j; import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.data.mongodb.core.convert.MongoConverter; @@ -13,9 +12,11 @@ public class CustomWorkspaceRepositoryImpl extends CustomWorkspaceRepositoryCEImpl implements CustomWorkspaceRepository { - public CustomWorkspaceRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, - SessionUserService sessionUserService, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomWorkspaceRepositoryImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + SessionUserService sessionUserService, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, sessionUserService, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceRepository.java index 013bbf09b817..ee7d7c291b6e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface DatasourceRepository extends DatasourceRepositoryCE, CustomDatasourceRepository { - -} +public interface DatasourceRepository extends DatasourceRepositoryCE, CustomDatasourceRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceStorageRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceStorageRepository.java index eda60ae315d6..807cd1fd613c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceStorageRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceStorageRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface DatasourceStorageRepository - extends DatasourceStorageRepositoryCE, CustomDatasourceStorageRepository { -} +public interface DatasourceStorageRepository extends DatasourceStorageRepositoryCE, CustomDatasourceStorageRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceStructureRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceStructureRepository.java index c66bfeda806d..f8ec8f52591e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceStructureRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/DatasourceStructureRepository.java @@ -4,5 +4,5 @@ import org.springframework.stereotype.Repository; @Repository -public interface DatasourceStructureRepository extends DatasourceStructureRepositoryCE, CustomDatasourceStructureRepository { -} +public interface DatasourceStructureRepository + extends DatasourceStructureRepositoryCE, CustomDatasourceStructureRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/GitDeployKeysRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/GitDeployKeysRepository.java index da1cf5f3428b..db803a427945 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/GitDeployKeysRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/GitDeployKeysRepository.java @@ -3,6 +3,6 @@ import com.appsmith.server.domains.GitDeployKeys; import reactor.core.publisher.Mono; -public interface GitDeployKeysRepository extends BaseRepository<GitDeployKeys, String>{ +public interface GitDeployKeysRepository extends BaseRepository<GitDeployKeys, String> { Mono<GitDeployKeys> findByEmail(String email); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/GroupRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/GroupRepository.java index 58b86edb0bb8..e1c21d397393 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/GroupRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/GroupRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface GroupRepository extends GroupRepositoryCE, CustomGroupRepository { - -} +public interface GroupRepository extends GroupRepositoryCE, CustomGroupRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/InviteUserRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/InviteUserRepository.java index a1a23d1bdfdd..367120c9b980 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/InviteUserRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/InviteUserRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface InviteUserRepository extends InviteUserRepositoryCE { - -} +public interface InviteUserRepository extends InviteUserRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/LayoutRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/LayoutRepository.java index 4f29ab5e4305..2d21aa35083d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/LayoutRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/LayoutRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface LayoutRepository extends LayoutRepositoryCE { - -} +public interface LayoutRepository extends LayoutRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NewActionRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NewActionRepository.java index 1499223dd164..91478b39a276 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NewActionRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NewActionRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface NewActionRepository extends NewActionRepositoryCE, CustomNewActionRepository { - -} +public interface NewActionRepository extends NewActionRepositoryCE, CustomNewActionRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NewPageRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NewPageRepository.java index 09b8c3caad01..772cd247e8e6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NewPageRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NewPageRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface NewPageRepository extends NewPageRepositoryCE, CustomNewPageRepository { - -} +public interface NewPageRepository extends NewPageRepositoryCE, CustomNewPageRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NotificationRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NotificationRepository.java index afed9499332f..d49a581cd005 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NotificationRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/NotificationRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface NotificationRepository extends NotificationRepositoryCE, CustomNotificationRepository { - -} +public interface NotificationRepository extends NotificationRepositoryCE, CustomNotificationRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PageRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PageRepository.java index 93cdc4d02614..33f8e9979247 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PageRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PageRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface PageRepository extends PageRepositoryCE, CustomPageRepository { - -} +public interface PageRepository extends PageRepositoryCE, CustomPageRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PasswordResetTokenRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PasswordResetTokenRepository.java index 8309c78fbe2d..ac5d2e2f213c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PasswordResetTokenRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PasswordResetTokenRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.PasswordResetTokenRepositoryCE; -public interface PasswordResetTokenRepository extends PasswordResetTokenRepositoryCE { - -} +public interface PasswordResetTokenRepository extends PasswordResetTokenRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PermissionGroupRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PermissionGroupRepository.java index 8528a2c62e31..86d6773940d7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PermissionGroupRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PermissionGroupRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface PermissionGroupRepository extends PermissionGroupRepositoryCE, CustomPermissionGroupRepository { - -} +public interface PermissionGroupRepository extends PermissionGroupRepositoryCE, CustomPermissionGroupRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PluginRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PluginRepository.java index dda763ee0aa8..d5bab8480f3d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PluginRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/PluginRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface PluginRepository extends PluginRepositoryCE, CustomPluginRepository { - -} +public interface PluginRepository extends PluginRepositoryCE, CustomPluginRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ProviderRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ProviderRepository.java index 96299896a558..519e51de0969 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ProviderRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ProviderRepository.java @@ -2,6 +2,4 @@ import com.appsmith.server.repositories.ce.ProviderRepositoryCE; -public interface ProviderRepository extends ProviderRepositoryCE, CustomProviderRepository { - -} +public interface ProviderRepository extends ProviderRepositoryCE, CustomProviderRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/TenantRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/TenantRepository.java index be31843358b0..3c138f24e290 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/TenantRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/TenantRepository.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface TenantRepository extends TenantRepositoryCE, CustomTenantRepository { -} +public interface TenantRepository extends TenantRepositoryCE, CustomTenantRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ThemeRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ThemeRepository.java index dc712acb78bc..3690c5d879b3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ThemeRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ThemeRepository.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface ThemeRepository extends ThemeRepositoryCE, CustomThemeRepository { -} +public interface ThemeRepository extends ThemeRepositoryCE, CustomThemeRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UsagePulseRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UsagePulseRepository.java index 6af0915ce3e6..4aec2d930e30 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UsagePulseRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UsagePulseRepository.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface UsagePulseRepository extends UsagePulseRepositoryCE, CustomUsagePulseRepository { -} +public interface UsagePulseRepository extends UsagePulseRepositoryCE, CustomUsagePulseRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UserDataRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UserDataRepository.java index 7b20346098fd..b67ea108b77d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UserDataRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UserDataRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface UserDataRepository extends UserDataRepositoryCE, CustomUserDataRepository { - -} +public interface UserDataRepository extends UserDataRepositoryCE, CustomUserDataRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UserRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UserRepository.java index e1fb9a7037ee..0d9acdeb9998 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UserRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/UserRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface UserRepository extends UserRepositoryCE, CustomUserRepository { - -} +public interface UserRepository extends UserRepositoryCE, CustomUserRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/WorkspaceRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/WorkspaceRepository.java index 4b275b81f4c8..2b9ae3f7b97c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/WorkspaceRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/WorkspaceRepository.java @@ -4,6 +4,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface WorkspaceRepository extends WorkspaceRepositoryCE, CustomWorkspaceRepository { - -} +public interface WorkspaceRepository extends WorkspaceRepositoryCE, CustomWorkspaceRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ActionCollectionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ActionCollectionRepositoryCE.java index 062108681ecf..7380a6d068d6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ActionCollectionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ActionCollectionRepositoryCE.java @@ -5,6 +5,7 @@ import com.appsmith.server.repositories.CustomActionCollectionRepository; import reactor.core.publisher.Flux; -public interface ActionCollectionRepositoryCE extends BaseRepository<ActionCollection, String>, CustomActionCollectionRepository { +public interface ActionCollectionRepositoryCE + extends BaseRepository<ActionCollection, String>, CustomActionCollectionRepository { Flux<ActionCollection> findByApplicationId(String applicationId); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ActionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ActionRepositoryCE.java index ed2e0bd6acf4..fa31c3215a0e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ActionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ActionRepositoryCE.java @@ -15,8 +15,7 @@ public interface ActionRepositoryCE extends BaseRepository<Action, String>, Cust Flux<Action> findDistinctActionsByNameInAndPageIdAndActionConfiguration_HttpMethodAndUserSetOnLoad( Set<String> names, String pageId, String httpMethod, Boolean userSetOnLoad); - Flux<Action> findDistinctActionsByNameInAndPageIdAndExecuteOnLoadTrue( - Set<String> names, String pageId); + Flux<Action> findDistinctActionsByNameInAndPageIdAndExecuteOnLoadTrue(Set<String> names, String pageId); Mono<Long> countByDatasourceId(String datasourceId); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApiTemplateRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApiTemplateRepositoryCE.java index 8d9b12cc8458..12227bce5008 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApiTemplateRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApiTemplateRepositoryCE.java @@ -4,5 +4,4 @@ import com.appsmith.server.repositories.BaseRepository; import com.appsmith.server.repositories.CustomApiTemplateRepository; -public interface ApiTemplateRepositoryCE extends BaseRepository<ApiTemplate, String>, CustomApiTemplateRepository { -} +public interface ApiTemplateRepositoryCE extends BaseRepository<ApiTemplate, String>, CustomApiTemplateRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApplicationRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApplicationRepositoryCE.java index bce7dc280980..07880fe1bd40 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApplicationRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApplicationRepositoryCE.java @@ -21,5 +21,4 @@ public interface ApplicationRepositoryCE extends BaseRepository<Application, Str Mono<Long> countByDeletedAtNull(); Mono<Application> findByIdAndExportWithConfiguration(String id, boolean exportWithConfiguration); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApplicationSnapshotRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApplicationSnapshotRepositoryCE.java index e768f9eb8cc6..2be4d29f9681 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApplicationSnapshotRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ApplicationSnapshotRepositoryCE.java @@ -5,7 +5,8 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -public interface ApplicationSnapshotRepositoryCE extends CustomApplicationSnapshotRepositoryCE, BaseRepository<ApplicationSnapshot, String> { +public interface ApplicationSnapshotRepositoryCE + extends CustomApplicationSnapshotRepositoryCE, BaseRepository<ApplicationSnapshot, String> { Flux<ApplicationSnapshot> findByApplicationId(String applicationId); Mono<Void> deleteAllByApplicationId(String applicationId); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/AssetRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/AssetRepositoryCE.java index 528c0d68aca0..f5874692d793 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/AssetRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/AssetRepositoryCE.java @@ -3,5 +3,4 @@ import com.appsmith.server.domains.Asset; import com.appsmith.server.repositories.BaseRepository; -public interface AssetRepositoryCE extends BaseRepository<Asset, String> { -} +public interface AssetRepositoryCE extends BaseRepository<Asset, String> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java index 4a5d58bdd01e..296f0cfe91c4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java @@ -66,18 +66,21 @@ public abstract class BaseAppsmithRepositoryCEImpl<T extends BaseDomain> { protected final CacheableRepositoryHelper cacheableRepositoryHelper; - protected final static int NO_RECORD_LIMIT = -1; + protected static final int NO_RECORD_LIMIT = -1; - protected final static int NO_SKIP = 0; + protected static final int NO_SKIP = 0; @Autowired @SuppressWarnings("unchecked") - public BaseAppsmithRepositoryCEImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public BaseAppsmithRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { this.mongoOperations = mongoOperations; this.mongoConverter = mongoConverter; this.cacheableRepositoryHelper = cacheableRepositoryHelper; - this.genericDomain = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), BaseAppsmithRepositoryCEImpl.class); + this.genericDomain = + (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), BaseAppsmithRepositoryCEImpl.class); } public static final String fieldName(Path<?> path) { @@ -85,18 +88,18 @@ public static final String fieldName(Path<?> path) { } public static final Criteria notDeleted() { - return new Criteria().andOperator( - //Older check for deleted - new Criteria().orOperator( - where(FieldName.DELETED).exists(false), - where(FieldName.DELETED).is(false) - ), - //New check for deleted - new Criteria().orOperator( - where(FieldName.DELETED_AT).exists(false), - where(FieldName.DELETED_AT).is(null) - ) - ); + return new Criteria() + .andOperator( + // Older check for deleted + new Criteria() + .orOperator( + where(FieldName.DELETED).exists(false), + where(FieldName.DELETED).is(false)), + // New check for deleted + new Criteria() + .orOperator( + where(FieldName.DELETED_AT).exists(false), + where(FieldName.DELETED_AT).is(null))); } @Deprecated @@ -105,15 +108,16 @@ public static final Criteria userAcl(Set<String> permissionGroups, AclPermission return criteria.orElse(null); } - public static final Optional<Criteria> userAcl(Set<String> permissionGroups, Optional<AclPermission> permission) { if (permission.isEmpty()) { return Optional.empty(); } // Check if the permission is being provided by any of the permission groups Criteria permissionGroupCriteria = Criteria.where(fieldName(QBaseDomain.baseDomain.policies)) - .elemMatch(Criteria.where("permissionGroups").in(permissionGroups) - .and("permission").is(permission.get().getValue())); + .elemMatch(Criteria.where("permissionGroups") + .in(permissionGroups) + .and("permission") + .is(permission.get().getValue())); return Optional.of(permissionGroupCriteria); } @@ -145,27 +149,26 @@ public Mono<T> findById(String id, List<String> projectionFieldNames, Optional<A return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ID)); } - return getCurrentUserPermissionGroupsIfRequired(permission) - .flatMap(permissionGroups -> { - Query query = new Query(getIdCriteria(id)); - query.addCriteria(notDeleted()); - Optional<Criteria> userAcl = userAcl(permissionGroups, permission); - if (userAcl.isPresent()) { - query.addCriteria(userAcl.get()); - } - - if (!isEmpty(projectionFieldNames)) { - projectionFieldNames.stream() - .forEach(projectionFieldName -> { - query.fields().include(projectionFieldName); - }); - } + return getCurrentUserPermissionGroupsIfRequired(permission).flatMap(permissionGroups -> { + Query query = new Query(getIdCriteria(id)); + query.addCriteria(notDeleted()); + Optional<Criteria> userAcl = userAcl(permissionGroups, permission); + if (userAcl.isPresent()) { + query.addCriteria(userAcl.get()); + } - return mongoOperations.query(this.genericDomain) - .matching(query) - .one() - .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); + if (!isEmpty(projectionFieldNames)) { + projectionFieldNames.stream().forEach(projectionFieldName -> { + query.fields().include(projectionFieldName); }); + } + + return mongoOperations + .query(this.genericDomain) + .matching(query) + .one() + .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); + }); } public Mono<T> findById(String id, Optional<AclPermission> permission) { @@ -206,10 +209,16 @@ public Mono<T> updateById(String id, T resource, Optional<AclPermission> permiss if (userAcl.isPresent()) { query.addCriteria(userAcl.get()); } - return mongoOperations.updateFirst(query, updateObj, resource.getClass()) + return mongoOperations + .updateFirst(query, updateObj, resource.getClass()) .flatMap(obj -> { if (obj.getMatchedCount() == 0) { - return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, resource.getClass().getSimpleName().toLowerCase(), id)); + return Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + resource.getClass() + .getSimpleName() + .toLowerCase(), + id)); } return findById(id, permission); }) @@ -220,15 +229,20 @@ public Mono<T> updateById(String id, T resource, Optional<AclPermission> permiss }); } - public Mono<UpdateResult> updateFieldByDefaultIdAndBranchName(String defaultId, String defaultIdPath, Map<String, Object> fieldNameValueMap, String branchName, - String branchNamePath, AclPermission permission) { + public Mono<UpdateResult> updateFieldByDefaultIdAndBranchName( + String defaultId, + String defaultIdPath, + Map<String, Object> fieldNameValueMap, + String branchName, + String branchNamePath, + AclPermission permission) { return ReactiveSecurityContextHolder.getContext() .map(ctx -> ctx.getAuthentication()) .map(auth -> auth.getPrincipal()) .flatMap(principal -> getAllPermissionGroupsForUser((User) principal)) .flatMap(permissionGroups -> { - Query query = new Query(new Criteria().andOperator(notDeleted(), userAcl(permissionGroups, - permission))); + Query query = + new Query(new Criteria().andOperator(notDeleted(), userAcl(permissionGroups, permission))); query.addCriteria(Criteria.where(defaultIdPath).is(defaultId)); if (!isBlank(branchName)) { @@ -261,11 +275,10 @@ public Mono<UpdateResult> updateById(String id, Update updateObj, Optional<AclPe return mongoOperations.updateFirst(query, updateObj, this.genericDomain); } - return getCurrentUserPermissionGroupsIfRequired(permission) - .flatMap(permissionGroups -> { - query.addCriteria(new Criteria().andOperator(notDeleted(), userAcl(permissionGroups, permission.get()))); - return mongoOperations.updateFirst(query, updateObj, this.genericDomain); - }); + return getCurrentUserPermissionGroupsIfRequired(permission).flatMap(permissionGroups -> { + query.addCriteria(new Criteria().andOperator(notDeleted(), userAcl(permissionGroups, permission.get()))); + return mongoOperations.updateFirst(query, updateObj, this.genericDomain); + }); } public Mono<UpdateResult> updateByCriteria(List<Criteria> criteriaList, Update updateObj) { @@ -301,27 +314,29 @@ protected Mono<Set<String>> getCurrentUserPermissionGroups() { } protected Mono<T> queryOne(List<Criteria> criterias, List<String> projectionFieldNames, AclPermission permission) { - Mono<Set<String>> permissionGroupsMono = getCurrentUserPermissionGroupsIfRequired(Optional.ofNullable(permission)); - - return permissionGroupsMono - .flatMap(permissionGroups -> { - return mongoOperations.query(this.genericDomain) - .matching(createQueryWithPermission(criterias, projectionFieldNames, permissionGroups, permission)) - .one() - .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); - }); + Mono<Set<String>> permissionGroupsMono = + getCurrentUserPermissionGroupsIfRequired(Optional.ofNullable(permission)); + + return permissionGroupsMono.flatMap(permissionGroups -> { + return mongoOperations + .query(this.genericDomain) + .matching(createQueryWithPermission(criterias, projectionFieldNames, permissionGroups, permission)) + .one() + .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); + }); } - protected Mono<T> queryOne(List<Criteria> criterias, List<String> projectionFieldNames, Optional<AclPermission> permission) { + protected Mono<T> queryOne( + List<Criteria> criterias, List<String> projectionFieldNames, Optional<AclPermission> permission) { Mono<Set<String>> permissionGroupsMono = getCurrentUserPermissionGroupsIfRequired(permission); - return permissionGroupsMono - .flatMap(permissionGroups -> { - return mongoOperations.query(this.genericDomain) - .matching(createQueryWithPermission(criterias, projectionFieldNames, permissionGroups, permission)) - .one() - .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); - }); + return permissionGroupsMono.flatMap(permissionGroups -> { + return mongoOperations + .query(this.genericDomain) + .matching(createQueryWithPermission(criterias, projectionFieldNames, permissionGroups, permission)) + .one() + .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); + }); } @Deprecated @@ -332,39 +347,42 @@ protected Mono<T> queryFirst(List<Criteria> criterias, AclPermission aclPermissi protected Mono<T> queryFirst(List<Criteria> criterias, Optional<AclPermission> permission) { Mono<Set<String>> permissionGroupsMono = getCurrentUserPermissionGroupsIfRequired(permission); - return permissionGroupsMono - .flatMap(permissionGroups -> { - return mongoOperations.query(this.genericDomain) - .matching(createQueryWithPermission(criterias, null, permissionGroups, permission)) - .first() - .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); - }); + return permissionGroupsMono.flatMap(permissionGroups -> { + return mongoOperations + .query(this.genericDomain) + .matching(createQueryWithPermission(criterias, null, permissionGroups, permission)) + .first() + .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); + }); } @Deprecated - protected Query createQueryWithPermission(List<Criteria> criterias, Set<String> permissionGroups, AclPermission aclPermission) { + protected Query createQueryWithPermission( + List<Criteria> criterias, Set<String> permissionGroups, AclPermission aclPermission) { return createQueryWithPermission(criterias, null, permissionGroups, aclPermission); } - protected Query createQueryWithPermission(List<Criteria> criterias, Set<String> permissionGroups, Optional<AclPermission> permission) { + protected Query createQueryWithPermission( + List<Criteria> criterias, Set<String> permissionGroups, Optional<AclPermission> permission) { return createQueryWithPermission(criterias, null, permissionGroups, permission.orElse(null)); } - protected Query createQueryWithPermission(List<Criteria> criterias, - List<String> projectionFieldNames, - Set<String> permissionGroups, - Optional<AclPermission> permission) { + protected Query createQueryWithPermission( + List<Criteria> criterias, + List<String> projectionFieldNames, + Set<String> permissionGroups, + Optional<AclPermission> permission) { return createQueryWithPermission(criterias, projectionFieldNames, permissionGroups, permission.orElse(null)); } - protected Query createQueryWithPermission(List<Criteria> criterias, - List<String> projectionFieldNames, - Set<String> permissionGroups, - AclPermission aclPermission) { + protected Query createQueryWithPermission( + List<Criteria> criterias, + List<String> projectionFieldNames, + Set<String> permissionGroups, + AclPermission aclPermission) { Query query = new Query(); - criterias.stream() - .forEach(criteria -> query.addCriteria(criteria)); + criterias.stream().forEach(criteria -> query.addCriteria(criteria)); if (aclPermission == null) { query.addCriteria(new Criteria().andOperator(notDeleted())); } else { @@ -372,8 +390,7 @@ protected Query createQueryWithPermission(List<Criteria> criterias, } if (!isEmpty(projectionFieldNames)) { - projectionFieldNames.stream() - .forEach(fieldName -> query.fields().include(fieldName)); + projectionFieldNames.stream().forEach(fieldName -> query.fields().include(fieldName)); } return query; @@ -387,10 +404,8 @@ protected Mono<Long> count(List<Criteria> criterias, AclPermission aclPermission protected Mono<Long> count(List<Criteria> criterias, Optional<AclPermission> permission) { Mono<Set<String>> permissionGroupsMono = getCurrentUserPermissionGroupsIfRequired(permission); - return permissionGroupsMono - .flatMap(permissionGroups -> - mongoOperations.count(createQueryWithPermission(criterias, permissionGroups, permission), this.genericDomain) - ); + return permissionGroupsMono.flatMap(permissionGroups -> mongoOperations.count( + createQueryWithPermission(criterias, permissionGroups, permission), this.genericDomain)); } protected Mono<Long> count(List<Criteria> criteriaList) { @@ -399,7 +414,8 @@ protected Mono<Long> count(List<Criteria> criteriaList) { @Deprecated public Flux<T> queryAll(List<Criteria> criterias, AclPermission aclPermission) { - return queryAll(criterias, Optional.empty(), Optional.ofNullable(aclPermission), Optional.empty(), NO_RECORD_LIMIT); + return queryAll( + criterias, Optional.empty(), Optional.ofNullable(aclPermission), Optional.empty(), NO_RECORD_LIMIT); } public Flux<T> queryAll(List<Criteria> criterias, Optional<AclPermission> permission) { @@ -408,7 +424,12 @@ public Flux<T> queryAll(List<Criteria> criterias, Optional<AclPermission> permis @Deprecated public Flux<T> queryAll(List<Criteria> criterias, AclPermission aclPermission, Sort sort) { - return queryAll(criterias, Optional.empty(), Optional.ofNullable(aclPermission), Optional.ofNullable(sort), NO_RECORD_LIMIT); + return queryAll( + criterias, + Optional.empty(), + Optional.ofNullable(aclPermission), + Optional.ofNullable(sort), + NO_RECORD_LIMIT); } public Flux<T> queryAll(List<Criteria> criterias, Optional<AclPermission> permission, Optional<Sort> sort) { @@ -416,49 +437,84 @@ public Flux<T> queryAll(List<Criteria> criterias, Optional<AclPermission> permis } @Deprecated - public Flux<T> queryAll(List<Criteria> criterias, List<String> includeFields, AclPermission aclPermission, Sort sort) { - return queryAll(criterias, Optional.ofNullable(includeFields), Optional.ofNullable(aclPermission), Optional.ofNullable(sort), NO_RECORD_LIMIT); - } - - public Flux<T> queryAll(List<Criteria> criterias, Optional<List<String>> includeFields, Optional<AclPermission> aclPermission, Optional<Sort> sort) { + public Flux<T> queryAll( + List<Criteria> criterias, List<String> includeFields, AclPermission aclPermission, Sort sort) { + return queryAll( + criterias, + Optional.ofNullable(includeFields), + Optional.ofNullable(aclPermission), + Optional.ofNullable(sort), + NO_RECORD_LIMIT); + } + + public Flux<T> queryAll( + List<Criteria> criterias, + Optional<List<String>> includeFields, + Optional<AclPermission> aclPermission, + Optional<Sort> sort) { return queryAll(criterias, includeFields, aclPermission, sort, NO_RECORD_LIMIT); } @Deprecated - public Flux<T> queryAll(List<Criteria> criterias, List<String> includeFields, AclPermission aclPermission, Sort sort, int limit) { - return queryAll(criterias, Optional.ofNullable(includeFields), Optional.ofNullable(aclPermission), Optional.ofNullable(sort), limit); - } - - public Flux<T> queryAll(List<Criteria> criterias, Optional<List<String>> includeFields, Optional<AclPermission> permission, Optional<Sort> sort, int limit) { + public Flux<T> queryAll( + List<Criteria> criterias, List<String> includeFields, AclPermission aclPermission, Sort sort, int limit) { + return queryAll( + criterias, + Optional.ofNullable(includeFields), + Optional.ofNullable(aclPermission), + Optional.ofNullable(sort), + limit); + } + + public Flux<T> queryAll( + List<Criteria> criterias, + Optional<List<String>> includeFields, + Optional<AclPermission> permission, + Optional<Sort> sort, + int limit) { Mono<Set<String>> permissionGroupsMono = getCurrentUserPermissionGroupsIfRequired(permission); - return permissionGroupsMono - .flatMapMany(permissionGroups -> queryAllWithPermissionGroups(criterias, includeFields, permission, sort, permissionGroups, limit, NO_SKIP)); + return permissionGroupsMono.flatMapMany(permissionGroups -> queryAllWithPermissionGroups( + criterias, includeFields, permission, sort, permissionGroups, limit, NO_SKIP)); } - public Flux<T> queryAll(List<Criteria> criterias, Optional<List<String>> includeFields, Optional<AclPermission> permission, Sort sort, int limit, int skip) { + public Flux<T> queryAll( + List<Criteria> criterias, + Optional<List<String>> includeFields, + Optional<AclPermission> permission, + Sort sort, + int limit, + int skip) { Mono<Set<String>> permissionGroupsMono = getCurrentUserPermissionGroupsIfRequired(permission); - return permissionGroupsMono - .flatMapMany(permissionGroups -> queryAllWithPermissionGroups(criterias, includeFields, permission, Optional.of(sort), permissionGroups, limit, skip)); + return permissionGroupsMono.flatMapMany(permissionGroups -> queryAllWithPermissionGroups( + criterias, includeFields, permission, Optional.of(sort), permissionGroups, limit, skip)); } @Deprecated - public Flux<T> queryAllWithPermissionGroups(List<Criteria> criterias, - List<String> includeFields, - AclPermission aclPermission, - Sort sort, - Set<String> permissionGroups, - int limit) { - return queryAllWithPermissionGroups(criterias, Optional.ofNullable(includeFields), - Optional.ofNullable(aclPermission), Optional.ofNullable(sort), permissionGroups, limit, NO_SKIP); - } - - public Flux<T> queryAllWithPermissionGroups(List<Criteria> criterias, - Optional<List<String>> includeFields, - Optional<AclPermission> aclPermission, - Optional<Sort> sortOptional, - Set<String> permissionGroups, - int limit, - int skip) { + public Flux<T> queryAllWithPermissionGroups( + List<Criteria> criterias, + List<String> includeFields, + AclPermission aclPermission, + Sort sort, + Set<String> permissionGroups, + int limit) { + return queryAllWithPermissionGroups( + criterias, + Optional.ofNullable(includeFields), + Optional.ofNullable(aclPermission), + Optional.ofNullable(sort), + permissionGroups, + limit, + NO_SKIP); + } + + public Flux<T> queryAllWithPermissionGroups( + List<Criteria> criterias, + Optional<List<String>> includeFields, + Optional<AclPermission> aclPermission, + Optional<Sort> sortOptional, + Set<String> permissionGroups, + int limit, + int skip) { final ArrayList<Criteria> criteriaList = new ArrayList<>(criterias); Query query = new Query(); includeFields.ifPresent(fields -> { @@ -476,7 +532,8 @@ public Flux<T> queryAllWithPermissionGroups(List<Criteria> criterias, andCriteria.andOperator(criteriaList.toArray(new Criteria[0])); query.addCriteria(andCriteria); sortOptional.ifPresent(sort -> query.with(sort)); - return mongoOperations.query(this.genericDomain) + return mongoOperations + .query(this.genericDomain) .matching(query) .all() .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); @@ -523,19 +580,15 @@ protected Mono<Set<String>> getAllPermissionGroupsForUser(User user) { Mono<User> userMono = Mono.just(user); if (user.getTenantId() == null) { - userMono = cacheableRepositoryHelper.getDefaultTenantId() - .map(tenantId -> { - user.setTenantId(tenantId); - return user; - }); + userMono = cacheableRepositoryHelper.getDefaultTenantId().map(tenantId -> { + user.setTenantId(tenantId); + return user; + }); } - - return userMono - .flatMap(userWithTenant -> Mono.zip( + return userMono.flatMap(userWithTenant -> Mono.zip( cacheableRepositoryHelper.getPermissionGroupsOfUser(userWithTenant), - getAnonymousUserPermissionGroups() - )) + getAnonymousUserPermissionGroups())) .map(tuple -> { Set<String> permissionGroups = new HashSet<>(tuple.getT1()); @@ -562,26 +615,25 @@ public Mono<T> queryOne(List<Criteria> criterias, List<String> projectionFieldNa Query query = new Query(new Criteria().andOperator(criterias)); if (!isEmpty(projectionFieldNames)) { - projectionFieldNames.stream() - .forEach(projectionFieldName -> { - query.fields().include(projectionFieldName); - }); + projectionFieldNames.stream().forEach(projectionFieldName -> { + query.fields().include(projectionFieldName); + }); } - return mongoOperations.query(this.genericDomain) + return mongoOperations + .query(this.genericDomain) .matching(query) .one(); }); } - public static Query getQuery(List<Criteria> criteria) { Query query = new Query(); criteria.forEach(query::addCriteria); return query; } - /* + /* Db query methods */ diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCEImpl.java index 413d43281d4e..2629602b6915 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCEImpl.java @@ -55,12 +55,16 @@ public Mono<Set<String>> getPermissionGroupsOfUser(User user) { return getPermissionGroupsOfAnonymousUser(); } - if (user.getEmail() == null || user.getEmail().isEmpty() || user.getId() == null || user.getId().isEmpty()) { + if (user.getEmail() == null + || user.getEmail().isEmpty() + || user.getId() == null + || user.getId().isEmpty()) { return Mono.error(new AppsmithException(AppsmithError.SESSION_BAD_STATE)); } - - Criteria assignedToUserIdsCriteria = Criteria.where(fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)).is(user.getId()); + Criteria assignedToUserIdsCriteria = Criteria.where( + fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)) + .is(user.getId()); Criteria notDeletedCriteria = notDeleted(); Criteria andCriteria = new Criteria(); @@ -69,7 +73,8 @@ public Mono<Set<String>> getPermissionGroupsOfUser(User user) { Query query = new Query(); query.addCriteria(andCriteria); - return mongoOperations.find(query, PermissionGroup.class) + return mongoOperations + .find(query, PermissionGroup.class) .map(permissionGroup -> permissionGroup.getId()) .collect(Collectors.toSet()); } @@ -81,11 +86,17 @@ public Mono<Set<String>> preFillAnonymousUserPermissionGroupIdsCache() { return Mono.just(anonymousUserPermissionGroupIds); } - log.debug("In memory cache miss for anonymous user permission groups. Fetching from DB and adding it to in memory storage."); + log.debug( + "In memory cache miss for anonymous user permission groups. Fetching from DB and adding it to in memory storage."); // All public access is via a single permission group. Fetch the same and set the cache with it. - return mongoOperations.findOne(Query.query(Criteria.where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)), Config.class) - .map(publicPermissionGroupConfig -> Set.of(publicPermissionGroupConfig.getConfig().getAsString(PERMISSION_GROUP_ID))) + return mongoOperations + .findOne( + Query.query( + Criteria.where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)), + Config.class) + .map(publicPermissionGroupConfig -> + Set.of(publicPermissionGroupConfig.getConfig().getAsString(PERMISSION_GROUP_ID))) .doOnSuccess(permissionGroupIds -> anonymousUserPermissionGroupIds = permissionGroupIds); } @@ -114,18 +125,19 @@ public Mono<User> getAnonymousUser(String tenantId) { return Mono.just(tenantAnonymousUserMap.get(tenantId)); } - Criteria anonymousUserCriteria = Criteria.where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER); - Criteria tenantIdCriteria = Criteria.where(fieldName(QUser.user.tenantId)).is(tenantId); + Criteria anonymousUserCriteria = + Criteria.where(fieldName(QUser.user.email)).is(FieldName.ANONYMOUS_USER); + Criteria tenantIdCriteria = + Criteria.where(fieldName(QUser.user.tenantId)).is(tenantId); Query query = new Query(); query.addCriteria(anonymousUserCriteria); query.addCriteria(tenantIdCriteria); - return mongoOperations.findOne(query, User.class) - .map(anonymousUser -> { - tenantAnonymousUserMap.put(tenantId, anonymousUser); - return anonymousUser; - }); + return mongoOperations.findOne(query, User.class).map(anonymousUser -> { + tenantAnonymousUserMap.put(tenantId, anonymousUser); + return anonymousUser; + }); } @Override @@ -134,15 +146,15 @@ public Mono<User> getAnonymousUser() { return getAnonymousUser(defaultTenantId); } - Criteria defaultTenantCriteria = Criteria.where(fieldName(QTenant.tenant.slug)).is(FieldName.DEFAULT); + Criteria defaultTenantCriteria = + Criteria.where(fieldName(QTenant.tenant.slug)).is(FieldName.DEFAULT); Query query = new Query(); query.addCriteria(defaultTenantCriteria); - return mongoOperations.findOne(query, Tenant.class) - .flatMap(defaultTenant -> { - defaultTenantId = defaultTenant.getId(); - return getAnonymousUser(defaultTenant.getId()); - }); + return mongoOperations.findOne(query, Tenant.class).flatMap(defaultTenant -> { + defaultTenantId = defaultTenant.getId(); + return getAnonymousUser(defaultTenant.getId()); + }); } @Override @@ -151,14 +163,14 @@ public Mono<String> getDefaultTenantId() { return Mono.just(defaultTenantId); } - Criteria defaultTenantCriteria = Criteria.where(fieldName(QTenant.tenant.slug)).is(FieldName.DEFAULT); + Criteria defaultTenantCriteria = + Criteria.where(fieldName(QTenant.tenant.slug)).is(FieldName.DEFAULT); Query query = new Query(); query.addCriteria(defaultTenantCriteria); - return mongoOperations.findOne(query, Tenant.class) - .map(defaultTenant -> { - defaultTenantId = defaultTenant.getId(); - return defaultTenantId; - }); + return mongoOperations.findOne(query, Tenant.class).map(defaultTenant -> { + defaultTenantId = defaultTenant.getId(); + return defaultTenantId; + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java index 3eca125ba804..1ad82feddc2e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java @@ -16,23 +16,34 @@ public interface CustomActionCollectionRepositoryCE extends AppsmithRepository<A Flux<ActionCollection> findByApplicationId(String applicationId, AclPermission aclPermission, Sort sort); - Flux<ActionCollection> findByApplicationId(String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort); + Flux<ActionCollection> findByApplicationId( + String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort); - Flux<ActionCollection> findByApplicationIdAndViewMode(String applicationId, boolean viewMode, AclPermission aclPermission); + Flux<ActionCollection> findByApplicationIdAndViewMode( + String applicationId, boolean viewMode, AclPermission aclPermission); - Flux<ActionCollection> findAllActionCollectionsByNamePageIdsViewModeAndBranch(String name, List<String> pageIds, boolean viewMode, String branchName, AclPermission aclPermission, Sort sort); + Flux<ActionCollection> findAllActionCollectionsByNamePageIdsViewModeAndBranch( + String name, + List<String> pageIds, + boolean viewMode, + String branchName, + AclPermission aclPermission, + Sort sort); Flux<ActionCollection> findByPageId(String pageId, AclPermission permission); Flux<ActionCollection> findByPageId(String pageId); - Mono<ActionCollection> findByBranchNameAndDefaultCollectionId(String branchName, String defaultCollectionId, AclPermission permission); + Mono<ActionCollection> findByBranchNameAndDefaultCollectionId( + String branchName, String defaultCollectionId, AclPermission permission); - Mono<ActionCollection> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission); + Mono<ActionCollection> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, AclPermission permission); Flux<ActionCollection> findByDefaultApplicationId(String defaultApplicationId, Optional<AclPermission> permission); - Mono<ActionCollection> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission); + Mono<ActionCollection> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission); Flux<ActionCollection> findByListOfPageIds(List<String> pageIds, AclPermission permission); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java index 3b3c3639122b..43c3ded77058 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java @@ -33,70 +33,89 @@ public class CustomActionCollectionRepositoryCEImpl extends BaseAppsmithRepositoryImpl<ActionCollection> implements CustomActionCollectionRepositoryCE { - public CustomActionCollectionRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomActionCollectionRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - @Override @Deprecated public Flux<ActionCollection> findByApplicationId(String applicationId, AclPermission aclPermission, Sort sort) { - Criteria applicationCriteria = where(fieldName(QActionCollection.actionCollection.applicationId)).is(applicationId); + Criteria applicationCriteria = where(fieldName(QActionCollection.actionCollection.applicationId)) + .is(applicationId); return queryAll(List.of(applicationCriteria), aclPermission, sort); } @Override - public Flux<ActionCollection> findByApplicationId(String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort) { + public Flux<ActionCollection> findByApplicationId( + String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort) { - Criteria applicationCriteria = where(fieldName(QActionCollection.actionCollection.applicationId)).is(applicationId); + Criteria applicationCriteria = where(fieldName(QActionCollection.actionCollection.applicationId)) + .is(applicationId); return queryAll(List.of(applicationCriteria), aclPermission, sort); } @Override - public Flux<ActionCollection> findByApplicationIdAndViewMode(String applicationId, boolean viewMode, AclPermission aclPermission) { + public Flux<ActionCollection> findByApplicationIdAndViewMode( + String applicationId, boolean viewMode, AclPermission aclPermission) { List<Criteria> criteria = new ArrayList<>(); - Criteria applicationCriterion = where(fieldName(QActionCollection.actionCollection.applicationId)).is(applicationId); + Criteria applicationCriterion = where(fieldName(QActionCollection.actionCollection.applicationId)) + .is(applicationId); criteria.add(applicationCriterion); if (Boolean.FALSE.equals(viewMode)) { - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriterion = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object + // would exist. To handle this, only fetch non-deleted actions + Criteria deletedCriterion = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.deletedAt)) + .is(null); criteria.add(deletedCriterion); } return queryAll(criteria, aclPermission); - } @Override - public Flux<ActionCollection> findAllActionCollectionsByNamePageIdsViewModeAndBranch(String name, List<String> pageIds, boolean viewMode, String branchName, AclPermission aclPermission, Sort sort) { + public Flux<ActionCollection> findAllActionCollectionsByNamePageIdsViewModeAndBranch( + String name, + List<String> pageIds, + boolean viewMode, + String branchName, + AclPermission aclPermission, + Sort sort) { /** * TODO : This function is called by get(params) to get all actions by params and hence * only covers criteria of few fields like page id, name, etc. Make this generic to cover * all possible fields */ - List<Criteria> criteriaList = new ArrayList<>(); if (!StringUtils.isEmpty(branchName)) { - criteriaList.add(where(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME).is(branchName)); + criteriaList.add(where(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME) + .is(branchName)); } // Fetch published actions if (Boolean.TRUE.equals(viewMode)) { if (name != null) { - Criteria nameCriteria = where(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.name)).is(name); + Criteria nameCriteria = where(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName(QActionCollection.actionCollection.publishedCollection.name)) + .is(name); criteriaList.add(nameCriteria); } if (pageIds != null && !pageIds.isEmpty()) { - Criteria pageCriteria = where(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.pageId)).in(pageIds); + Criteria pageCriteria = where(fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName(QActionCollection.actionCollection.publishedCollection.pageId)) + .in(pageIds); criteriaList.add(pageCriteria); } } @@ -104,17 +123,24 @@ public Flux<ActionCollection> findAllActionCollectionsByNamePageIdsViewModeAndBr else { if (name != null) { - Criteria nameCriteria = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.name)).is(name); + Criteria nameCriteria = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.name)) + .is(name); criteriaList.add(nameCriteria); } if (pageIds != null && !pageIds.isEmpty()) { - Criteria pageCriteria = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId)).in(pageIds); + Criteria pageCriteria = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId)) + .in(pageIds); criteriaList.add(pageCriteria); } - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriteria = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object + // would exist. To handle this, only fetch non-deleted actions + Criteria deletedCriteria = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.deletedAt)) + .is(null); criteriaList.add(deletedCriteria); } @@ -123,13 +149,14 @@ public Flux<ActionCollection> findAllActionCollectionsByNamePageIdsViewModeAndBr @Override public Flux<ActionCollection> findByPageId(String pageId, AclPermission aclPermission) { - String unpublishedPage = fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId); - String publishedPage = fieldName(QActionCollection.actionCollection.publishedCollection) + "." + fieldName(QActionCollection.actionCollection.publishedCollection.pageId); + String unpublishedPage = fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId); + String publishedPage = fieldName(QActionCollection.actionCollection.publishedCollection) + "." + + fieldName(QActionCollection.actionCollection.publishedCollection.pageId); - Criteria pageCriteria = new Criteria().orOperator( - where(unpublishedPage).is(pageId), - where(publishedPage).is(pageId) - ); + Criteria pageCriteria = new Criteria() + .orOperator( + where(unpublishedPage).is(pageId), where(publishedPage).is(pageId)); return queryAll(List.of(pageCriteria), aclPermission); } @@ -140,85 +167,99 @@ public Flux<ActionCollection> findByPageId(String pageId) { } @Override - public Mono<ActionCollection> findByBranchNameAndDefaultCollectionId(String branchName, String defaultCollectionId, AclPermission permission) { + public Mono<ActionCollection> findByBranchNameAndDefaultCollectionId( + String branchName, String defaultCollectionId, AclPermission permission) { final String defaultResources = fieldName(QActionCollection.actionCollection.defaultResources); - Criteria defaultCollectionIdCriteria = where(defaultResources + "." + FieldName.COLLECTION_ID).is(defaultCollectionId); - Criteria branchCriteria = where(defaultResources + "." + FieldName.BRANCH_NAME).is(branchName); + Criteria defaultCollectionIdCriteria = + where(defaultResources + "." + FieldName.COLLECTION_ID).is(defaultCollectionId); + Criteria branchCriteria = + where(defaultResources + "." + FieldName.BRANCH_NAME).is(branchName); return queryOne(List.of(defaultCollectionIdCriteria, branchCriteria), permission); } @Override - public Mono<ActionCollection> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission) { + public Mono<ActionCollection> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, AclPermission permission) { return findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, gitSyncId, Optional.ofNullable(permission)); } @Override - public Mono<ActionCollection> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission) { + public Mono<ActionCollection> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission) { final String defaultResources = fieldName(QBranchAwareDomain.branchAwareDomain.defaultResources); - Criteria defaultAppIdCriteria = where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); + Criteria defaultAppIdCriteria = + where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); Criteria gitSyncIdCriteria = where(FieldName.GIT_SYNC_ID).is(gitSyncId); return queryFirst(List.of(defaultAppIdCriteria, gitSyncIdCriteria), permission); } @Override - public Flux<ActionCollection> findByDefaultApplicationId(String defaultApplicationId, Optional<AclPermission> permission) { + public Flux<ActionCollection> findByDefaultApplicationId( + String defaultApplicationId, Optional<AclPermission> permission) { final String defaultResources = fieldName(QBranchAwareDomain.branchAwareDomain.defaultResources); - Criteria defaultAppIdCriteria = where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); + Criteria defaultAppIdCriteria = + where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); return queryAll(List.of(defaultAppIdCriteria), permission); } @Override public Flux<ActionCollection> findByListOfPageIds(List<String> pageIds, AclPermission permission) { - Criteria pageIdCriteria = where( - fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + - fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId)).in(pageIds); + Criteria pageIdCriteria = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId)) + .in(pageIds); return queryAll(List.of(pageIdCriteria), permission); } @Override public Flux<ActionCollection> findByListOfPageIds(List<String> pageIds, Optional<AclPermission> permission) { - Criteria pageIdCriteria = where( - fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + - fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId)).in(pageIds); + Criteria pageIdCriteria = where(fieldName(QActionCollection.actionCollection.unpublishedCollection) + "." + + fieldName(QActionCollection.actionCollection.unpublishedCollection.pageId)) + .in(pageIds); return queryAll(List.of(pageIdCriteria), permission); } @Override public Mono<List<InsertManyResult>> bulkInsert(List<ActionCollection> actionCollectionList) { - if(CollectionUtils.isEmpty(actionCollectionList)) { + if (CollectionUtils.isEmpty(actionCollectionList)) { return Mono.just(Collections.emptyList()); } // convert the list of action collections to a list of DBObjects - List<Document> dbObjects = actionCollectionList.stream().map(actionCollection -> { - Document document = new Document(); - mongoOperations.getConverter().write(actionCollection, document); - return document; - }).collect(Collectors.toList()); - - return mongoOperations.getCollection(mongoOperations.getCollectionName(ActionCollection.class)) + List<Document> dbObjects = actionCollectionList.stream() + .map(actionCollection -> { + Document document = new Document(); + mongoOperations.getConverter().write(actionCollection, document); + return document; + }) + .collect(Collectors.toList()); + + return mongoOperations + .getCollection(mongoOperations.getCollectionName(ActionCollection.class)) .flatMapMany(documentMongoCollection -> documentMongoCollection.insertMany(dbObjects)) .collectList(); } @Override public Mono<List<BulkWriteResult>> bulkUpdate(List<ActionCollection> actionCollections) { - if(CollectionUtils.isEmpty(actionCollections)) { + if (CollectionUtils.isEmpty(actionCollections)) { return Mono.just(Collections.emptyList()); } // convert the list of new actions to a list of DBObjects - List<WriteModel<Document>> dbObjects = actionCollections.stream().map(actionCollection -> { - assert actionCollection.getId() != null; - Document document = new Document(); - mongoOperations.getConverter().write(actionCollection, document); - document.remove("_id"); - return (WriteModel<Document>) new UpdateOneModel<Document>( - new Document("_id", new ObjectId(actionCollection.getId())), new Document("$set", document) - ); - }).collect(Collectors.toList()); - - return mongoOperations.getCollection(mongoOperations.getCollectionName(ActionCollection.class)) + List<WriteModel<Document>> dbObjects = actionCollections.stream() + .map(actionCollection -> { + assert actionCollection.getId() != null; + Document document = new Document(); + mongoOperations.getConverter().write(actionCollection, document); + document.remove("_id"); + return (WriteModel<Document>) new UpdateOneModel<Document>( + new Document("_id", new ObjectId(actionCollection.getId())), + new Document("$set", document)); + }) + .collect(Collectors.toList()); + + return mongoOperations + .getCollection(mongoOperations.getCollectionName(ActionCollection.class)) .flatMapMany(documentMongoCollection -> documentMongoCollection.bulkWrite(dbObjects)) .collectList(); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionRepositoryCE.java index b487bb339a67..3e6c1e721b29 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionRepositoryCE.java @@ -16,10 +16,9 @@ public interface CustomActionRepositoryCE extends AppsmithRepository<Action> { Flux<Action> findByPageId(String pageId, AclPermission aclPermission); - Flux<Action> findActionsByNameInAndPageIdAndActionConfiguration_HttpMethod(Set<String> names, - String pageId, - String httpMethod, - AclPermission aclPermission); + Flux<Action> findActionsByNameInAndPageIdAndActionConfiguration_HttpMethod( + Set<String> names, String pageId, String httpMethod, AclPermission aclPermission); - Flux<Action> findAllActionsByNameAndPageIds(String name, List<String> pageIds, AclPermission aclPermission, Sort sort); + Flux<Action> findAllActionsByNameAndPageIds( + String name, List<String> pageIds, AclPermission aclPermission, Sort sort); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionRepositoryCEImpl.java index 25f2c64bc105..35c14c098aa8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionRepositoryCEImpl.java @@ -19,9 +19,13 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; -public class CustomActionRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Action> implements CustomActionRepositoryCE { +public class CustomActionRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Action> + implements CustomActionRepositoryCE { - public CustomActionRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomActionRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @@ -40,10 +44,8 @@ public Flux<Action> findByPageId(String pageId, AclPermission aclPermission) { } @Override - public Flux<Action> findActionsByNameInAndPageIdAndActionConfiguration_HttpMethod(Set<String> names, - String pageId, - String httpMethod, - AclPermission aclPermission) { + public Flux<Action> findActionsByNameInAndPageIdAndActionConfiguration_HttpMethod( + Set<String> names, String pageId, String httpMethod, AclPermission aclPermission) { Criteria namesCriteria = where(fieldName(QAction.action.name)).in(names); Criteria pageCriteria = where(fieldName(QAction.action.pageId)).is(pageId); String httpMethodQueryKey = fieldName(QAction.action.actionConfiguration) @@ -56,14 +58,13 @@ public Flux<Action> findActionsByNameInAndPageIdAndActionConfiguration_HttpMetho } @Override - public Flux<Action> findAllActionsByNameAndPageIds(String name, List<String> pageIds, AclPermission aclPermission, - Sort sort) { + public Flux<Action> findAllActionsByNameAndPageIds( + String name, List<String> pageIds, AclPermission aclPermission, Sort sort) { /** * TODO : This function is called by get(params) to get all actions by params and hence * only covers criteria of few fields like page id, name, etc. Make this generic to cover * all possible fields */ - List<Criteria> criteriaList = new ArrayList<>(); if (name != null) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApiTemplateRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApiTemplateRepositoryCE.java index a92cb5e47eae..38feaac190c8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApiTemplateRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApiTemplateRepositoryCE.java @@ -3,5 +3,4 @@ import com.appsmith.external.models.ApiTemplate; import com.appsmith.server.repositories.AppsmithRepository; -public interface CustomApiTemplateRepositoryCE extends AppsmithRepository<ApiTemplate> { -} +public interface CustomApiTemplateRepositoryCE extends AppsmithRepository<ApiTemplate> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApiTemplateRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApiTemplateRepositoryCEImpl.java index 084d9b48329c..645c4c719697 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApiTemplateRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApiTemplateRepositoryCEImpl.java @@ -9,7 +9,10 @@ public class CustomApiTemplateRepositoryCEImpl extends BaseAppsmithRepositoryImpl<ApiTemplate> implements CustomApiTemplateRepositoryCE { - public CustomApiTemplateRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomApiTemplateRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCE.java index 972897fe4568..4ae25c1dc907 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCE.java @@ -35,7 +35,8 @@ public interface CustomApplicationRepositoryCE extends AppsmithRepository<Applic Flux<Application> findByClonedFromApplicationId(String applicationId, AclPermission permission); - Mono<UpdateResult> addPageToApplication(String applicationId, String pageId, boolean isDefault, String defaultPageId); + Mono<UpdateResult> addPageToApplication( + String applicationId, String pageId, boolean isDefault, String defaultPageId); Mono<UpdateResult> setPages(String applicationId, List<ApplicationPage> pages); @@ -43,20 +44,24 @@ public interface CustomApplicationRepositoryCE extends AppsmithRepository<Applic Mono<UpdateResult> setGitAuth(String applicationId, GitAuth gitAuth, AclPermission aclPermission); - Mono<Application> getApplicationByGitBranchAndDefaultApplicationId(String defaultApplicationId, String branchName, Optional<AclPermission> permission); + Mono<Application> getApplicationByGitBranchAndDefaultApplicationId( + String defaultApplicationId, String branchName, Optional<AclPermission> permission); - Mono<Application> getApplicationByGitBranchAndDefaultApplicationId(String defaultApplicationId, String branchName, AclPermission aclPermission); + Mono<Application> getApplicationByGitBranchAndDefaultApplicationId( + String defaultApplicationId, String branchName, AclPermission aclPermission); - Mono<Application> getApplicationByGitBranchAndDefaultApplicationId(String defaultApplicationId, - List<String> projectionFieldNames, - String branchName, - AclPermission aclPermission); + Mono<Application> getApplicationByGitBranchAndDefaultApplicationId( + String defaultApplicationId, + List<String> projectionFieldNames, + String branchName, + AclPermission aclPermission); Flux<Application> getApplicationByGitDefaultApplicationId(String defaultApplicationId, AclPermission permission); Mono<List<String>> getAllApplicationId(String workspaceId); - Mono<UpdateResult> setAppTheme(String applicationId, String editModeThemeId, String publishedModeThemeId, AclPermission aclPermission); + Mono<UpdateResult> setAppTheme( + String applicationId, String editModeThemeId, String publishedModeThemeId, AclPermission aclPermission); Mono<Long> countByWorkspaceId(String workspaceId); @@ -66,8 +71,13 @@ Mono<Application> getApplicationByGitBranchAndDefaultApplicationId(String defaul Mono<Application> getApplicationByDefaultApplicationIdAndDefaultBranch(String defaultApplicationId); - Mono<UpdateResult> updateFieldByDefaultIdAndBranchName(String defaultId, String defaultIdPath, Map<String, - Object> fieldNameValueMap, String branchName, String branchNamePath, AclPermission permission); + Mono<UpdateResult> updateFieldByDefaultIdAndBranchName( + String defaultId, + String defaultIdPath, + Map<String, Object> fieldNameValueMap, + String branchName, + String branchNamePath, + AclPermission permission); Mono<Application> findByNameAndWorkspaceId(String applicationName, String workspaceId, AclPermission permission); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java index bedbae1d2227..253417321a5a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java @@ -41,10 +41,11 @@ public class CustomApplicationRepositoryCEImpl extends BaseAppsmithRepositoryImp private final ApplicationPermission applicationPermission; @Autowired - public CustomApplicationRepositoryCEImpl(@NonNull ReactiveMongoOperations mongoOperations, - @NonNull MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper, - ApplicationPermission applicationPermission) { + public CustomApplicationRepositoryCEImpl( + @NonNull ReactiveMongoOperations mongoOperations, + @NonNull MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper, + ApplicationPermission applicationPermission) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); this.cacheableRepositoryHelper = cacheableRepositoryHelper; this.applicationPermission = applicationPermission; @@ -57,7 +58,8 @@ protected Criteria getIdCriteria(Object id) { @Override public Mono<Application> findByIdAndWorkspaceId(String id, String workspaceId, AclPermission permission) { - Criteria workspaceIdCriteria = where(fieldName(QApplication.application.workspaceId)).is(workspaceId); + Criteria workspaceIdCriteria = + where(fieldName(QApplication.application.workspaceId)).is(workspaceId); Criteria idCriteria = getIdCriteria(id); return queryOne(List.of(idCriteria, workspaceIdCriteria), permission); @@ -71,13 +73,15 @@ public Mono<Application> findByName(String name, AclPermission permission) { @Override public Flux<Application> findByWorkspaceId(String workspaceId, AclPermission permission) { - Criteria workspaceIdCriteria = where(fieldName(QApplication.application.workspaceId)).is(workspaceId); + Criteria workspaceIdCriteria = + where(fieldName(QApplication.application.workspaceId)).is(workspaceId); return queryAll(List.of(workspaceIdCriteria), permission); } @Override public Flux<Application> findByMultipleWorkspaceIds(Set<String> workspaceIds, AclPermission permission) { - Criteria workspaceIdCriteria = where(fieldName(QApplication.application.workspaceId)).in(workspaceIds); + Criteria workspaceIdCriteria = + where(fieldName(QApplication.application.workspaceId)).in(workspaceIds); return queryAll(List.of(workspaceIdCriteria), permission); } @@ -88,11 +92,10 @@ public Flux<Application> findAllUserApps(AclPermission permission) { .map(auth -> (User) auth.getPrincipal()) .flatMap(user -> { if (user.getTenantId() == null) { - return cacheableRepositoryHelper.getDefaultTenantId() - .map(tenantId -> { - user.setTenantId(tenantId); - return user; - }); + return cacheableRepositoryHelper.getDefaultTenantId().map(tenantId -> { + user.setTenantId(tenantId); + return user; + }); } return Mono.just(user); }); @@ -100,18 +103,19 @@ public Flux<Application> findAllUserApps(AclPermission permission) { return currentUserWithTenantMono .flatMap(cacheableRepositoryHelper::getPermissionGroupsOfUser) .flatMapMany(permissionGroups -> queryAllWithPermissionGroups( - List.of(), null, permission, null, permissionGroups, NO_RECORD_LIMIT) - ); + List.of(), null, permission, null, permissionGroups, NO_RECORD_LIMIT)); } @Override public Flux<Application> findByClonedFromApplicationId(String applicationId, AclPermission permission) { - Criteria clonedFromCriteria = where(fieldName(QApplication.application.clonedFromApplicationId)).is(applicationId); + Criteria clonedFromCriteria = where(fieldName(QApplication.application.clonedFromApplicationId)) + .is(applicationId); return queryAll(List.of(clonedFromCriteria), permission); } @Override - public Mono<UpdateResult> addPageToApplication(String applicationId, String pageId, boolean isDefault, String defaultPageId) { + public Mono<UpdateResult> addPageToApplication( + String applicationId, String pageId, boolean isDefault, String defaultPageId) { final ApplicationPage applicationPage = new ApplicationPage(); applicationPage.setIsDefault(isDefault); applicationPage.setDefaultPageId(defaultPageId); @@ -119,8 +123,7 @@ public Mono<UpdateResult> addPageToApplication(String applicationId, String page return mongoOperations.updateFirst( Query.query(getIdCriteria(applicationId)), new Update().push(fieldName(QApplication.application.pages), applicationPage), - Application.class - ); + Application.class); } @Override @@ -128,8 +131,7 @@ public Mono<UpdateResult> setPages(String applicationId, List<ApplicationPage> p return mongoOperations.updateFirst( Query.query(getIdCriteria(applicationId)), new Update().set(fieldName(QApplication.application.pages), pages), - Application.class - ); + Application.class); } @Override @@ -138,16 +140,16 @@ public Mono<UpdateResult> setDefaultPage(String applicationId, String pageId) { // be to pages and not publishedPages final Mono<UpdateResult> setAllAsNonDefaultMono = mongoOperations.updateFirst( - Query.query(getIdCriteria(applicationId)).addCriteria(Criteria.where("pages.isDefault").is(true)), + Query.query(getIdCriteria(applicationId)) + .addCriteria(Criteria.where("pages.isDefault").is(true)), new Update().set("pages.$.isDefault", false), - Application.class - ); + Application.class); final Mono<UpdateResult> setDefaultMono = mongoOperations.updateFirst( - Query.query(getIdCriteria(applicationId)).addCriteria(Criteria.where("pages._id").is(new ObjectId(pageId))), + Query.query(getIdCriteria(applicationId)) + .addCriteria(Criteria.where("pages._id").is(new ObjectId(pageId))), new Update().set("pages.$.isDefault", true), - Application.class - ); + Application.class); return setAllAsNonDefaultMono.then(setDefaultMono); } @@ -156,9 +158,10 @@ public Mono<UpdateResult> setDefaultPage(String applicationId, String pageId) { public Mono<UpdateResult> setGitAuth(String applicationId, GitAuth gitAuth, AclPermission aclPermission) { Update updateObj = new Update(); gitAuth.setGeneratedAt(Instant.now()); - String path = String.format("%s.%s", fieldName(QApplication.application.gitApplicationMetadata), - fieldName(QApplication.application.gitApplicationMetadata.gitAuth) - ); + String path = String.format( + "%s.%s", + fieldName(QApplication.application.gitApplicationMetadata), + fieldName(QApplication.application.gitApplicationMetadata.gitAuth)); updateObj.set(path, gitAuth); return this.updateById(applicationId, updateObj, aclPermission); @@ -166,38 +169,53 @@ public Mono<UpdateResult> setGitAuth(String applicationId, GitAuth gitAuth, AclP @Override @Deprecated - public Mono<Application> getApplicationByGitBranchAndDefaultApplicationId(String defaultApplicationId, String branchName, AclPermission aclPermission) { + public Mono<Application> getApplicationByGitBranchAndDefaultApplicationId( + String defaultApplicationId, String branchName, AclPermission aclPermission) { return getApplicationByGitBranchAndDefaultApplicationId(defaultApplicationId, null, branchName, aclPermission); } @Override - public Mono<Application> getApplicationByGitBranchAndDefaultApplicationId(String defaultApplicationId, - List<String> projectionFieldNames, - String branchName, - AclPermission aclPermission) { + public Mono<Application> getApplicationByGitBranchAndDefaultApplicationId( + String defaultApplicationId, + List<String> projectionFieldNames, + String branchName, + AclPermission aclPermission) { String gitApplicationMetadata = fieldName(QApplication.application.gitApplicationMetadata); - Criteria defaultAppCriteria = where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.defaultApplicationId)).is(defaultApplicationId); - Criteria branchNameCriteria = where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.branchName)).is(branchName); + Criteria defaultAppCriteria = where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.defaultApplicationId)) + .is(defaultApplicationId); + Criteria branchNameCriteria = where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.branchName)) + .is(branchName); return queryOne(List.of(defaultAppCriteria, branchNameCriteria), projectionFieldNames, aclPermission); } @Override - public Mono<Application> getApplicationByGitBranchAndDefaultApplicationId(String defaultApplicationId, String branchName, Optional<AclPermission> aclPermission) { + public Mono<Application> getApplicationByGitBranchAndDefaultApplicationId( + String defaultApplicationId, String branchName, Optional<AclPermission> aclPermission) { String gitApplicationMetadata = fieldName(QApplication.application.gitApplicationMetadata); - Criteria defaultAppCriteria = where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.defaultApplicationId)).is(defaultApplicationId); - Criteria branchNameCriteria = where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.branchName)).is(branchName); + Criteria defaultAppCriteria = where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.defaultApplicationId)) + .is(defaultApplicationId); + Criteria branchNameCriteria = where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.branchName)) + .is(branchName); return queryOne(List.of(defaultAppCriteria, branchNameCriteria), null, aclPermission); } @Override - public Flux<Application> getApplicationByGitDefaultApplicationId(String defaultApplicationId, AclPermission permission) { + public Flux<Application> getApplicationByGitDefaultApplicationId( + String defaultApplicationId, AclPermission permission) { String gitApplicationMetadata = fieldName(QApplication.application.gitApplicationMetadata); - Criteria applicationIdCriteria = where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.defaultApplicationId)).is(defaultApplicationId); - Criteria deletionCriteria = where(fieldName(QApplication.application.deleted)).ne(true); + Criteria applicationIdCriteria = where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.defaultApplicationId)) + .is(defaultApplicationId); + Criteria deletionCriteria = + where(fieldName(QApplication.application.deleted)).ne(true); return queryAll(List.of(applicationIdCriteria, deletionCriteria), permission); } @@ -212,14 +230,16 @@ public Mono<List<String>> getAllApplicationId(String workspaceId) { Query query = new Query(); query.addCriteria(where(fieldName(QApplication.application.workspaceId)).is(workspaceId)); query.fields().include(fieldName(QApplication.application.id)); - return mongoOperations.find(query, Application.class) + return mongoOperations + .find(query, Application.class) .map(BaseDomain::getId) .collectList(); } @Override public Mono<Long> countByWorkspaceId(String workspaceId) { - Criteria workspaceIdCriteria = where(fieldName(QApplication.application.workspaceId)).is(workspaceId); + Criteria workspaceIdCriteria = + where(fieldName(QApplication.application.workspaceId)).is(workspaceId); return this.count(List.of(workspaceIdCriteria)); } @@ -228,7 +248,9 @@ public Mono<Long> getGitConnectedApplicationWithPrivateRepoCount(String workspac String gitApplicationMetadata = fieldName(QApplication.application.gitApplicationMetadata); Query query = new Query(); query.addCriteria(where(fieldName(QApplication.application.workspaceId)).is(workspaceId)); - query.addCriteria(where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.isRepoPrivate)).is(Boolean.TRUE)); + query.addCriteria(where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.isRepoPrivate)) + .is(Boolean.TRUE)); query.addCriteria(notDeleted()); return mongoOperations.count(query, Application.class); } @@ -238,10 +260,16 @@ public Flux<Application> getGitConnectedApplicationByWorkspaceId(String workspac String gitApplicationMetadata = fieldName(QApplication.application.gitApplicationMetadata); // isRepoPrivate and gitAuth will be stored only with default application which ensures we will have only single // application per repo - Criteria repoCriteria = where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.isRepoPrivate)).exists(Boolean.TRUE); - Criteria gitAuthCriteria = where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.gitAuth)).exists(Boolean.TRUE); - Criteria workspaceIdCriteria = where(fieldName(QApplication.application.workspaceId)).is(workspaceId); - return queryAll(List.of(workspaceIdCriteria, repoCriteria, gitAuthCriteria), applicationPermission.getEditPermission()); + Criteria repoCriteria = where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.isRepoPrivate)) + .exists(Boolean.TRUE); + Criteria gitAuthCriteria = where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.gitAuth)) + .exists(Boolean.TRUE); + Criteria workspaceIdCriteria = + where(fieldName(QApplication.application.workspaceId)).is(workspaceId); + return queryAll( + List.of(workspaceIdCriteria, repoCriteria, gitAuthCriteria), applicationPermission.getEditPermission()); } @Override @@ -249,16 +277,21 @@ public Mono<Application> getApplicationByDefaultApplicationIdAndDefaultBranch(St String gitApplicationMetadata = fieldName(QApplication.application.gitApplicationMetadata); Query query = new Query(); - query.addCriteria(where(gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.defaultApplicationId)).is(defaultApplicationId)); + query.addCriteria(where(gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.defaultApplicationId)) + .is(defaultApplicationId)); query.addCriteria(where(fieldName(QApplication.application.deleted)).ne(true)); - query.equals(where("this." + gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.branchName)) - .equals("this." + gitApplicationMetadata + "." + fieldName(QApplication.application.gitApplicationMetadata.defaultBranchName))); + query.equals(where("this." + gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.branchName)) + .equals("this." + gitApplicationMetadata + "." + + fieldName(QApplication.application.gitApplicationMetadata.defaultBranchName))); return mongoOperations.findOne(query, Application.class); } @Override - public Mono<UpdateResult> setAppTheme(String applicationId, String editModeThemeId, String publishedModeThemeId, AclPermission aclPermission) { + public Mono<UpdateResult> setAppTheme( + String applicationId, String editModeThemeId, String publishedModeThemeId, AclPermission aclPermission) { Update updateObj = new Update(); if (StringUtils.hasLength(editModeThemeId)) { updateObj = updateObj.set(fieldName(QApplication.application.editModeThemeId), editModeThemeId); @@ -271,16 +304,24 @@ public Mono<UpdateResult> setAppTheme(String applicationId, String editModeTheme } @Override - public Mono<UpdateResult> updateFieldByDefaultIdAndBranchName(String defaultId, String defaultIdPath, Map<String, Object> fieldValueMap, String branchName, - String branchNamePath, AclPermission permission) { - return super.updateFieldByDefaultIdAndBranchName(defaultId, defaultIdPath, fieldValueMap, branchName, - branchNamePath, permission); + public Mono<UpdateResult> updateFieldByDefaultIdAndBranchName( + String defaultId, + String defaultIdPath, + Map<String, Object> fieldValueMap, + String branchName, + String branchNamePath, + AclPermission permission) { + return super.updateFieldByDefaultIdAndBranchName( + defaultId, defaultIdPath, fieldValueMap, branchName, branchNamePath, permission); } @Override - public Mono<Application> findByNameAndWorkspaceId(String applicationName, String workspaceId, AclPermission permission) { - Criteria workspaceIdCriteria = where(fieldName(QApplication.application.workspaceId)).is(workspaceId); - Criteria applicationNameCriteria = where(fieldName(QApplication.application.name)).is(applicationName); + public Mono<Application> findByNameAndWorkspaceId( + String applicationName, String workspaceId, AclPermission permission) { + Criteria workspaceIdCriteria = + where(fieldName(QApplication.application.workspaceId)).is(workspaceId); + Criteria applicationNameCriteria = + where(fieldName(QApplication.application.name)).is(applicationName); return queryOne(List.of(workspaceIdCriteria, applicationNameCriteria), permission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationSnapshotRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationSnapshotRepositoryCEImpl.java index a5d01593decc..a6dc06328827 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationSnapshotRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationSnapshotRepositoryCEImpl.java @@ -15,26 +15,26 @@ public class CustomApplicationSnapshotRepositoryCEImpl extends BaseAppsmithRepositoryImpl<ApplicationSnapshot> implements CustomApplicationSnapshotRepositoryCE { - public CustomApplicationSnapshotRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomApplicationSnapshotRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override public Mono<ApplicationSnapshot> findWithoutData(String applicationId) { List<Criteria> criteriaList = new ArrayList<>(); - criteriaList.add( - Criteria.where(fieldName(QApplicationSnapshot.applicationSnapshot.applicationId)).is(applicationId) - ); - criteriaList.add( - Criteria.where(fieldName(QApplicationSnapshot.applicationSnapshot.chunkOrder)).is(1) - ); + criteriaList.add(Criteria.where(fieldName(QApplicationSnapshot.applicationSnapshot.applicationId)) + .is(applicationId)); + criteriaList.add(Criteria.where(fieldName(QApplicationSnapshot.applicationSnapshot.chunkOrder)) + .is(1)); List<String> fieldNames = List.of( fieldName(QApplicationSnapshot.applicationSnapshot.applicationId), fieldName(QApplicationSnapshot.applicationSnapshot.chunkOrder), fieldName(QApplicationSnapshot.applicationSnapshot.createdAt), - fieldName(QApplicationSnapshot.applicationSnapshot.updatedAt) - ); + fieldName(QApplicationSnapshot.applicationSnapshot.updatedAt)); return queryOne(criteriaList, fieldNames); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomCollectionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomCollectionRepositoryCE.java index 7f24a983dc54..551a6d5da21f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomCollectionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomCollectionRepositoryCE.java @@ -3,5 +3,4 @@ import com.appsmith.server.domains.Collection; import com.appsmith.server.repositories.AppsmithRepository; -public interface CustomCollectionRepositoryCE extends AppsmithRepository<Collection> { -} +public interface CustomCollectionRepositoryCE extends AppsmithRepository<Collection> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomCollectionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomCollectionRepositoryCEImpl.java index ff2cdc28bea2..473aaa1862f7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomCollectionRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomCollectionRepositoryCEImpl.java @@ -7,10 +7,14 @@ import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.data.mongodb.core.convert.MongoConverter; -public class CustomCollectionRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Collection> implements CustomCollectionRepositoryCE { +public class CustomCollectionRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Collection> + implements CustomCollectionRepositoryCE { @Autowired - public CustomCollectionRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomCollectionRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomConfigRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomConfigRepositoryCEImpl.java index b5ccc2da5e39..66730f8b2041 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomConfigRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomConfigRepositoryCEImpl.java @@ -16,9 +16,13 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; -public class CustomConfigRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Config> implements CustomConfigRepositoryCE { +public class CustomConfigRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Config> + implements CustomConfigRepositoryCE { - public CustomConfigRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomConfigRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @@ -31,16 +35,16 @@ public Mono<Config> findByName(String name, AclPermission permission) { @Override public Mono<Config> findByNameAsUser(String name, User user, AclPermission permission) { - return getAllPermissionGroupsForUser(user) - .flatMap(permissionGroups -> { - Criteria nameCriteria = where(fieldName(QConfig.config1.name)).is(name); - Query query = new Query(nameCriteria); - query.addCriteria(new Criteria().andOperator(notDeleted(), userAcl(permissionGroups, permission))); - - return mongoOperations.query(this.genericDomain) - .matching(query) - .one() - .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); - }); + return getAllPermissionGroupsForUser(user).flatMap(permissionGroups -> { + Criteria nameCriteria = where(fieldName(QConfig.config1.name)).is(name); + Query query = new Query(nameCriteria); + query.addCriteria(new Criteria().andOperator(notDeleted(), userAcl(permissionGroups, permission))); + + return mongoOperations + .query(this.genericDomain) + .matching(query) + .one() + .flatMap(obj -> setUserPermissionsInObject(obj, permissionGroups)); + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceRepositoryCE.java index 161eadaf3471..5b1495845e91 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceRepositoryCE.java @@ -22,5 +22,4 @@ public interface CustomDatasourceRepositoryCE extends AppsmithRepository<Datasou Mono<Datasource> findById(String id, AclPermission aclPermission); Flux<Datasource> findAllByIds(Set<String> ids, AclPermission permission); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceRepositoryCEImpl.java index d4358b04392d..04d7e5b9adb9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceRepositoryCEImpl.java @@ -18,37 +18,47 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; -public class CustomDatasourceRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Datasource> implements CustomDatasourceRepositoryCE { +public class CustomDatasourceRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Datasource> + implements CustomDatasourceRepositoryCE { - public CustomDatasourceRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomDatasourceRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override @Deprecated public Flux<Datasource> findAllByWorkspaceId(String workspaceId, AclPermission permission) { - Criteria workspaceIdCriteria = where(fieldName(QDatasource.datasource.workspaceId)).is(workspaceId); + Criteria workspaceIdCriteria = + where(fieldName(QDatasource.datasource.workspaceId)).is(workspaceId); return queryAll(List.of(workspaceIdCriteria), permission, Sort.by(fieldName(QDatasource.datasource.name))); } @Override public Flux<Datasource> findAllByWorkspaceId(String workspaceId, Optional<AclPermission> permission) { - Criteria workspaceIdCriteria = where(fieldName(QDatasource.datasource.workspaceId)).is(workspaceId); - return queryAll(List.of(workspaceIdCriteria), permission, Optional.of(Sort.by(fieldName(QDatasource.datasource.name)))); + Criteria workspaceIdCriteria = + where(fieldName(QDatasource.datasource.workspaceId)).is(workspaceId); + return queryAll( + List.of(workspaceIdCriteria), permission, Optional.of(Sort.by(fieldName(QDatasource.datasource.name)))); } @Override @Deprecated public Mono<Datasource> findByNameAndWorkspaceId(String name, String workspaceId, AclPermission aclPermission) { Criteria nameCriteria = where(fieldName(QDatasource.datasource.name)).is(name); - Criteria workspaceIdCriteria = where(fieldName(QDatasource.datasource.workspaceId)).is(workspaceId); + Criteria workspaceIdCriteria = + where(fieldName(QDatasource.datasource.workspaceId)).is(workspaceId); return queryOne(List.of(nameCriteria, workspaceIdCriteria), aclPermission); } @Override - public Mono<Datasource> findByNameAndWorkspaceId(String name, String workspaceId, Optional<AclPermission> aclPermission) { + public Mono<Datasource> findByNameAndWorkspaceId( + String name, String workspaceId, Optional<AclPermission> aclPermission) { Criteria nameCriteria = where(fieldName(QDatasource.datasource.name)).is(name); - Criteria workspaceIdCriteria = where(fieldName(QDatasource.datasource.workspaceId)).is(workspaceId); + Criteria workspaceIdCriteria = + where(fieldName(QDatasource.datasource.workspaceId)).is(workspaceId); return queryOne(List.of(nameCriteria, workspaceIdCriteria), null, aclPermission); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStorageRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStorageRepositoryCE.java index c62cff4e00c5..0a1f3951b5cc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStorageRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStorageRepositoryCE.java @@ -2,10 +2,5 @@ import com.appsmith.external.models.DatasourceStorage; import com.appsmith.server.repositories.AppsmithRepository; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import java.util.List; - -public interface CustomDatasourceStorageRepositoryCE extends AppsmithRepository<DatasourceStorage> { -} +public interface CustomDatasourceStorageRepositoryCE extends AppsmithRepository<DatasourceStorage> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStorageRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStorageRepositoryCEImpl.java index 07f75fbcbace..c59dd3783549 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStorageRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStorageRepositoryCEImpl.java @@ -1,25 +1,18 @@ package com.appsmith.server.repositories.ce; import com.appsmith.external.models.DatasourceStorage; -import com.appsmith.external.models.QDatasourceStorage; import com.appsmith.server.repositories.BaseAppsmithRepositoryImpl; import com.appsmith.server.repositories.CacheableRepositoryHelper; import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.data.mongodb.core.convert.MongoConverter; -import org.springframework.data.mongodb.core.query.Criteria; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import java.util.List; - -public class CustomDatasourceStorageRepositoryCEImpl - extends BaseAppsmithRepositoryImpl<DatasourceStorage> +public class CustomDatasourceStorageRepositoryCEImpl extends BaseAppsmithRepositoryImpl<DatasourceStorage> implements CustomDatasourceStorageRepositoryCE { - - public CustomDatasourceStorageRepositoryCEImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomDatasourceStorageRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStructureRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStructureRepositoryCEImpl.java index cd7d0c31bd0a..c2aa1ea3726e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStructureRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomDatasourceStructureRepositoryCEImpl.java @@ -17,28 +17,30 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; @Component -public class CustomDatasourceStructureRepositoryCEImpl - extends BaseAppsmithRepositoryImpl<DatasourceStorageStructure> +public class CustomDatasourceStructureRepositoryCEImpl extends BaseAppsmithRepositoryImpl<DatasourceStorageStructure> implements CustomDatasourceStructureRepositoryCE { - public CustomDatasourceStructureRepositoryCEImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomDatasourceStructureRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } public static Criteria getDatasourceIdAndEnvironmentIdCriteria(String datasourceId, String environmentId) { - return new Criteria().andOperator( - where(fieldName(QDatasourceStorageStructure.datasourceStorageStructure.datasourceId)).is(datasourceId), - where(fieldName(QDatasourceStorageStructure.datasourceStorageStructure.environmentId)).is(environmentId) - ); + return new Criteria() + .andOperator( + where(fieldName(QDatasourceStorageStructure.datasourceStorageStructure.datasourceId)) + .is(datasourceId), + where(fieldName(QDatasourceStorageStructure.datasourceStorageStructure.environmentId)) + .is(environmentId)); } @Override - public Mono<UpdateResult> updateStructure(String datasourceId, String environmentId, DatasourceStructure structure) { + public Mono<UpdateResult> updateStructure( + String datasourceId, String environmentId, DatasourceStructure structure) { return mongoOperations.upsert( new Query().addCriteria(getDatasourceIdAndEnvironmentIdCriteria(datasourceId, environmentId)), Update.update(fieldName(QDatasourceStorageStructure.datasourceStorageStructure.structure), structure), - DatasourceStorageStructure.class - ); + DatasourceStorageStructure.class); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomGroupRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomGroupRepositoryCEImpl.java index cb9add30b389..6d404ce4a6f4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomGroupRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomGroupRepositoryCEImpl.java @@ -16,16 +16,19 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; @Slf4j -public class CustomGroupRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Group> - implements CustomGroupRepositoryCE { +public class CustomGroupRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Group> implements CustomGroupRepositoryCE { - public CustomGroupRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomGroupRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override public Flux<Group> getAllByWorkspaceId(String workspaceId) { - Criteria workspaceIdCriteria = where(fieldName(QGroup.group.workspaceId)).is(workspaceId); + Criteria workspaceIdCriteria = + where(fieldName(QGroup.group.workspaceId)).is(workspaceId); return queryAll(List.of(workspaceIdCriteria), Optional.empty()); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomJSLibRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomJSLibRepositoryCE.java index 5fe6cb56c1ba..e79a56d95812 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomJSLibRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomJSLibRepositoryCE.java @@ -6,4 +6,4 @@ public interface CustomJSLibRepositoryCE extends AppsmithRepository<CustomJSLib> { Mono<CustomJSLib> findByUidString(String uidString); -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomJSLibRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomJSLibRepositoryCEImpl.java index 0b1b47132b8f..9d245ccdd216 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomJSLibRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomJSLibRepositoryCEImpl.java @@ -13,19 +13,22 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; -public class CustomJSLibRepositoryCEImpl extends BaseAppsmithRepositoryImpl<CustomJSLib> implements CustomJSLibRepositoryCE { +public class CustomJSLibRepositoryCEImpl extends BaseAppsmithRepositoryImpl<CustomJSLib> + implements CustomJSLibRepositoryCE { private static final String UID_STRING_IDENTIFIER = "uidString"; - public CustomJSLibRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomJSLibRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } /* - Each custom JS library is supposed to be unique across the branches and applications. This is considered a shared resource and hence - we don't store separate versions of JS library for each branch or user. And this is the reason why branch name is not used. - Custom JS library doesn't have any user or application specific data and carries no risk and hence no ACL check is made while fetching the data. - */ + Each custom JS library is supposed to be unique across the branches and applications. This is considered a shared resource and hence + we don't store separate versions of JS library for each branch or user. And this is the reason why branch name is not used. + Custom JS library doesn't have any user or application specific data and carries no risk and hence no ACL check is made while fetching the data. + */ @Override public Mono<CustomJSLib> findByUidString(String uidString) { Criteria uidStringMatchCriteria = where(UID_STRING_IDENTIFIER).is(uidString); @@ -33,4 +36,4 @@ public Mono<CustomJSLib> findByUidString(String uidString) { listOfCriteria.add(uidStringMatchCriteria); return queryOne(listOfCriteria, List.of()); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java index e7fdaded87e0..e380d985e975 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java @@ -29,46 +29,49 @@ public interface CustomNewActionRepositoryCE extends AppsmithRepository<NewActio Flux<NewAction> findUnpublishedActionsByNameInAndPageId(Set<String> names, String pageId, AclPermission permission); - Flux<NewAction> findUnpublishedActionsByPageIdAndExecuteOnLoadSetByUserTrue(String pageId, AclPermission permission); + Flux<NewAction> findUnpublishedActionsByPageIdAndExecuteOnLoadSetByUserTrue( + String pageId, AclPermission permission); - Flux<NewAction> findUnpublishedActionsForRestApiOnLoad(Set<String> names, - String pageId, - String httpMethod, - Boolean userSetOnLoad, AclPermission aclPermission); + Flux<NewAction> findUnpublishedActionsForRestApiOnLoad( + Set<String> names, String pageId, String httpMethod, Boolean userSetOnLoad, AclPermission aclPermission); - Flux<NewAction> findAllActionsByNameAndPageIdsAndViewMode(String name, List<String> pageIds, Boolean viewMode, AclPermission aclPermission, Sort sort); + Flux<NewAction> findAllActionsByNameAndPageIdsAndViewMode( + String name, List<String> pageIds, Boolean viewMode, AclPermission aclPermission, Sort sort); - Flux<NewAction> findUnpublishedActionsByNameInAndPageIdAndExecuteOnLoadTrue(Set<String> names, - String pageId, - AclPermission permission); + Flux<NewAction> findUnpublishedActionsByNameInAndPageIdAndExecuteOnLoadTrue( + Set<String> names, String pageId, AclPermission permission); Flux<NewAction> findByApplicationId(String applicationId, AclPermission aclPermission, Sort sort); - Flux<NewAction> findByApplicationId(String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort); + Flux<NewAction> findByApplicationId( + String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort); Flux<NewAction> findByApplicationIdAndViewMode(String applicationId, Boolean viewMode, AclPermission aclPermission); Mono<Long> countByDatasourceId(String datasourceId); - Mono<NewAction> findByBranchNameAndDefaultActionId(String branchName, String defaultActionId, AclPermission permission); + Mono<NewAction> findByBranchNameAndDefaultActionId( + String branchName, String defaultActionId, AclPermission permission); - Mono<NewAction> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission); + Mono<NewAction> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, AclPermission permission); Flux<NewAction> findByDefaultApplicationId(String defaultApplicationId, Optional<AclPermission> permission); - Mono<NewAction> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission); + Mono<NewAction> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission); Flux<NewAction> findByListOfPageIds(List<String> pageIds, AclPermission permission); Flux<NewAction> findByListOfPageIds(List<String> pageIds, Optional<AclPermission> permission); - Flux<NewAction> findNonJsActionsByApplicationIdAndViewMode(String applicationId, Boolean viewMode, AclPermission aclPermission); + Flux<NewAction> findNonJsActionsByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, AclPermission aclPermission); - Flux<NewAction> findAllNonJsActionsByNameAndPageIdsAndViewMode(String name, List<String> pageIds, - Boolean viewMode, - AclPermission aclPermission, - Sort sort); + Flux<NewAction> findAllNonJsActionsByNameAndPageIdsAndViewMode( + String name, List<String> pageIds, Boolean viewMode, AclPermission aclPermission, Sort sort); Mono<List<InsertManyResult>> bulkInsert(List<NewAction> newActions); + Mono<List<BulkWriteResult>> bulkUpdate(List<NewAction> newActions); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java index 4c46adced219..2e40af829390 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java @@ -38,55 +38,69 @@ public class CustomNewActionRepositoryCEImpl extends BaseAppsmithRepositoryImpl<NewAction> implements CustomNewActionRepositoryCE { - public CustomNewActionRepositoryCEImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomNewActionRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override public Flux<NewAction> findByApplicationId(String applicationId, AclPermission aclPermission) { - Criteria applicationIdCriteria = where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); + Criteria applicationIdCriteria = + where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); return queryAll(List.of(applicationIdCriteria), aclPermission); } @Override - public Flux<NewAction> findByApplicationId(String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort) { - Criteria applicationIdCriteria = where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); + public Flux<NewAction> findByApplicationId( + String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort) { + Criteria applicationIdCriteria = + where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); return queryAll(List.of(applicationIdCriteria), aclPermission, sort); } @Override public Mono<NewAction> findByUnpublishedNameAndPageId(String name, String pageId, AclPermission aclPermission) { - Criteria nameCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.name)).is(name); - Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId)).is(pageId); - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + Criteria nameCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.name)) + .is(name); + Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .is(pageId); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would + // exist. To handle this, only fetch non-deleted actions + Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); return queryOne(List.of(nameCriteria, pageCriteria, deletedCriteria), aclPermission); } @Override public Flux<NewAction> findByPageId(String pageId, AclPermission aclPermission) { - String unpublishedPage = fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId); - String publishedPage = fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.pageId); + String unpublishedPage = fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId); + String publishedPage = fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.pageId); - Criteria pageCriteria = new Criteria().orOperator( - where(unpublishedPage).is(pageId), - where(publishedPage).is(pageId) - ); + Criteria pageCriteria = new Criteria() + .orOperator( + where(unpublishedPage).is(pageId), where(publishedPage).is(pageId)); return queryAll(List.of(pageCriteria), aclPermission); } @Override public Flux<NewAction> findByPageId(String pageId, Optional<AclPermission> aclPermission) { - String unpublishedPage = fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId); - String publishedPage = fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.pageId); + String unpublishedPage = fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId); + String publishedPage = fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.pageId); - Criteria pageCriteria = new Criteria().orOperator( - where(unpublishedPage).is(pageId), - where(publishedPage).is(pageId) - ); + Criteria pageCriteria = new Criteria() + .orOperator( + where(unpublishedPage).is(pageId), where(publishedPage).is(pageId)); return queryAll(List.of(pageCriteria), aclPermission); } @@ -105,16 +119,23 @@ public Flux<NewAction> findByPageIdAndViewMode(String pageId, Boolean viewMode, // Fetch published actions if (Boolean.TRUE.equals(viewMode)) { - pageCriterion = where(fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.pageId)).is(pageId); + pageCriterion = where(fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.pageId)) + .is(pageId); criteria.add(pageCriterion); } // Fetch unpublished actions else { - pageCriterion = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId)).is(pageId); + pageCriterion = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .is(pageId); criteria.add(pageCriterion); - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object + // would exist. To handle this, only fetch non-deleted actions + Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); criteria.add(deletedCriteria); } return queryAll(criteria, aclPermission); @@ -122,24 +143,20 @@ public Flux<NewAction> findByPageIdAndViewMode(String pageId, Boolean viewMode, @Override public Flux<NewAction> findUnpublishedActionsForRestApiOnLoad( - Set<String> names, - String pageId, - String httpMethod, - Boolean userSetOnLoad, - AclPermission aclPermission) { + Set<String> names, String pageId, String httpMethod, Boolean userSetOnLoad, AclPermission aclPermission) { Criteria namesCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) - + "." - + fieldName(QNewAction.newAction.unpublishedAction.name)) + + "." + + fieldName(QNewAction.newAction.unpublishedAction.name)) .in(names); Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) - + "." - + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) .is(pageId); Criteria userSetOnLoadCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) - + "." - + fieldName(QNewAction.newAction.unpublishedAction.userSetOnLoad)) + + "." + + fieldName(QNewAction.newAction.unpublishedAction.userSetOnLoad)) .is(userSetOnLoad); String httpMethodQueryKey = fieldName(QNewAction.newAction.unpublishedAction) @@ -155,29 +172,29 @@ public Flux<NewAction> findUnpublishedActionsForRestApiOnLoad( } @Override - public Flux<NewAction> findAllActionsByNameAndPageIdsAndViewMode(String name, - List<String> pageIds, - Boolean viewMode, - AclPermission aclPermission, - Sort sort) { + public Flux<NewAction> findAllActionsByNameAndPageIdsAndViewMode( + String name, List<String> pageIds, Boolean viewMode, AclPermission aclPermission, Sort sort) { /** * TODO : This function is called by get(params) to get all actions by params and hence * only covers criteria of few fields like page id, name, etc. Make this generic to cover * all possible fields */ - List<Criteria> criteriaList = new ArrayList<>(); // Fetch published actions if (Boolean.TRUE.equals(viewMode)) { if (name != null) { - Criteria nameCriteria = where(fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.name)).is(name); + Criteria nameCriteria = where(fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.name)) + .is(name); criteriaList.add(nameCriteria); } if (pageIds != null && !pageIds.isEmpty()) { - Criteria pageCriteria = where(fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.pageId)).in(pageIds); + Criteria pageCriteria = where(fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.pageId)) + .in(pageIds); criteriaList.add(pageCriteria); } } @@ -185,17 +202,24 @@ public Flux<NewAction> findAllActionsByNameAndPageIdsAndViewMode(String name, else { if (name != null) { - Criteria nameCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.name)).is(name); + Criteria nameCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.name)) + .is(name); criteriaList.add(nameCriteria); } if (pageIds != null && !pageIds.isEmpty()) { - Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId)).in(pageIds); + Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .in(pageIds); criteriaList.add(pageCriteria); } - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object + // would exist. To handle this, only fetch non-deleted actions + Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); criteriaList.add(deletedCriteria); } @@ -203,61 +227,89 @@ public Flux<NewAction> findAllActionsByNameAndPageIdsAndViewMode(String name, } @Override - public Flux<NewAction> findUnpublishedActionsByNameInAndPageIdAndExecuteOnLoadTrue(Set<String> names, - String pageId, - AclPermission permission) { + public Flux<NewAction> findUnpublishedActionsByNameInAndPageIdAndExecuteOnLoadTrue( + Set<String> names, String pageId, AclPermission permission) { List<Criteria> criteriaList = new ArrayList<>(); if (names != null) { - Criteria namesCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.name)).in(names); + Criteria namesCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.name)) + .in(names); criteriaList.add(namesCriteria); } - Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId)).is(pageId); + Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .is(pageId); criteriaList.add(pageCriteria); - Criteria executeOnLoadCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.executeOnLoad)).is(Boolean.TRUE); + Criteria executeOnLoadCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.executeOnLoad)) + .is(Boolean.TRUE); criteriaList.add(executeOnLoadCriteria); - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would + // exist. To handle this, only fetch non-deleted actions + Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); criteriaList.add(deletedCriteria); return queryAll(criteriaList, permission); } @Override - public Flux<NewAction> findUnpublishedActionsByNameInAndPageId(Set<String> names, String pageId, AclPermission permission) { + public Flux<NewAction> findUnpublishedActionsByNameInAndPageId( + Set<String> names, String pageId, AclPermission permission) { List<Criteria> criteriaList = new ArrayList<>(); if (names != null) { - Criteria namesCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.name)).in(names); - Criteria fullyQualifiedNamesCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.fullyQualifiedName)).in(names); + Criteria namesCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.name)) + .in(names); + Criteria fullyQualifiedNamesCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.fullyQualifiedName)) + .in(names); criteriaList.add(new Criteria().orOperator(namesCriteria, fullyQualifiedNamesCriteria)); } - Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId)).is(pageId); + Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .is(pageId); criteriaList.add(pageCriteria); - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would + // exist. To handle this, only fetch non-deleted actions + Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); criteriaList.add(deletedCriteria); return queryAll(criteriaList, permission); } @Override - public Flux<NewAction> findUnpublishedActionsByPageIdAndExecuteOnLoadSetByUserTrue(String pageId, AclPermission permission) { + public Flux<NewAction> findUnpublishedActionsByPageIdAndExecuteOnLoadSetByUserTrue( + String pageId, AclPermission permission) { List<Criteria> criteriaList = new ArrayList<>(); - Criteria executeOnLoadCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.executeOnLoad)).is(Boolean.TRUE); + Criteria executeOnLoadCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.executeOnLoad)) + .is(Boolean.TRUE); criteriaList.add(executeOnLoadCriteria); - Criteria setByUserCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.userSetOnLoad)).is(Boolean.TRUE); + Criteria setByUserCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.userSetOnLoad)) + .is(Boolean.TRUE); criteriaList.add(setByUserCriteria); - Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId)).is(pageId); + Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .is(pageId); criteriaList.add(pageCriteria); - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would + // exist. To handle this, only fetch non-deleted actions + Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); criteriaList.add(deletedCriteria); return queryAll(criteriaList, permission); @@ -266,24 +318,28 @@ public Flux<NewAction> findUnpublishedActionsByPageIdAndExecuteOnLoadSetByUserTr @Override public Flux<NewAction> findByApplicationId(String applicationId, AclPermission aclPermission, Sort sort) { - Criteria applicationCriteria = where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); + Criteria applicationCriteria = + where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); return queryAll(List.of(applicationCriteria), aclPermission, sort); } @Override - public Flux<NewAction> findByApplicationIdAndViewMode(String applicationId, - Boolean viewMode, - AclPermission aclPermission) { + public Flux<NewAction> findByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, AclPermission aclPermission) { List<Criteria> criteria = new ArrayList<>(); - Criteria applicationCriterion = where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); + Criteria applicationCriterion = + where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); criteria.add(applicationCriterion); if (Boolean.FALSE.equals(viewMode)) { - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriterion = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object + // would exist. To handle this, only fetch non-deleted actions + Criteria deletedCriterion = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); criteria.add(deletedCriterion); } @@ -292,14 +348,15 @@ public Flux<NewAction> findByApplicationIdAndViewMode(String applicationId, @Override public Mono<Long> countByDatasourceId(String datasourceId) { - Criteria unpublishedDatasourceCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) - + ".datasource._id") + Criteria unpublishedDatasourceCriteria = where( + fieldName(QNewAction.newAction.unpublishedAction) + ".datasource._id") .is(new ObjectId(datasourceId)); - Criteria publishedDatasourceCriteria = where(fieldName(QNewAction.newAction.publishedAction) - + ".datasource._id") + Criteria publishedDatasourceCriteria = where( + fieldName(QNewAction.newAction.publishedAction) + ".datasource._id") .is(new ObjectId(datasourceId)); - Criteria datasourceCriteria = where(FieldName.DELETED_AT).is(null) + Criteria datasourceCriteria = where(FieldName.DELETED_AT) + .is(null) .orOperator(unpublishedDatasourceCriteria, publishedDatasourceCriteria); Query query = new Query(); @@ -309,22 +366,28 @@ public Mono<Long> countByDatasourceId(String datasourceId) { } @Override - public Mono<NewAction> findByBranchNameAndDefaultActionId(String branchName, String defaultActionId, AclPermission permission) { + public Mono<NewAction> findByBranchNameAndDefaultActionId( + String branchName, String defaultActionId, AclPermission permission) { final String defaultResources = fieldName(QNewAction.newAction.defaultResources); - Criteria defaultActionIdCriteria = where(defaultResources + "." + FieldName.ACTION_ID).is(defaultActionId); - Criteria branchCriteria = where(defaultResources + "." + FieldName.BRANCH_NAME).is(branchName); + Criteria defaultActionIdCriteria = + where(defaultResources + "." + FieldName.ACTION_ID).is(defaultActionId); + Criteria branchCriteria = + where(defaultResources + "." + FieldName.BRANCH_NAME).is(branchName); return queryOne(List.of(defaultActionIdCriteria, branchCriteria), permission); } @Override - public Mono<NewAction> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission) { + public Mono<NewAction> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, AclPermission permission) { return findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, gitSyncId, Optional.ofNullable(permission)); } @Override - public Mono<NewAction> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission) { + public Mono<NewAction> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission) { final String defaultResources = fieldName(QBranchAwareDomain.branchAwareDomain.defaultResources); - Criteria defaultAppIdCriteria = where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); + Criteria defaultAppIdCriteria = + where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); Criteria gitSyncIdCriteria = where(FieldName.GIT_SYNC_ID).is(gitSyncId); return queryFirst(List.of(defaultAppIdCriteria, gitSyncIdCriteria), permission); } @@ -332,34 +395,41 @@ public Mono<NewAction> findByGitSyncIdAndDefaultApplicationId(String defaultAppl @Override public Flux<NewAction> findByListOfPageIds(List<String> pageIds, AclPermission permission) { - Criteria pageIdCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + - fieldName(QNewAction.newAction.unpublishedAction.pageId)).in(pageIds); + Criteria pageIdCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .in(pageIds); return queryAll(List.of(pageIdCriteria), permission); } @Override public Flux<NewAction> findByListOfPageIds(List<String> pageIds, Optional<AclPermission> permission) { - Criteria pageIdCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + - fieldName(QNewAction.newAction.unpublishedAction.pageId)).in(pageIds); + Criteria pageIdCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .in(pageIds); return queryAll(List.of(pageIdCriteria), permission); } @Override - public Flux<NewAction> findNonJsActionsByApplicationIdAndViewMode(String applicationId, Boolean viewMode, - AclPermission aclPermission) { + public Flux<NewAction> findNonJsActionsByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, AclPermission aclPermission) { List<Criteria> criteria = new ArrayList<>(); - Criteria applicationCriterion = where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); + Criteria applicationCriterion = + where(fieldName(QNewAction.newAction.applicationId)).is(applicationId); criteria.add(applicationCriterion); - Criteria nonJsTypeCriteria = where(fieldName(QNewAction.newAction.pluginType)).ne(PluginType.JS); + Criteria nonJsTypeCriteria = + where(fieldName(QNewAction.newAction.pluginType)).ne(PluginType.JS); criteria.add(nonJsTypeCriteria); if (Boolean.FALSE.equals(viewMode)) { - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriterion = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object + // would exist. To handle this, only fetch non-deleted actions + Criteria deletedCriterion = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); criteria.add(deletedCriterion); } @@ -367,24 +437,28 @@ public Flux<NewAction> findNonJsActionsByApplicationIdAndViewMode(String applica } @Override - public Flux<NewAction> findAllNonJsActionsByNameAndPageIdsAndViewMode(String name, List<String> pageIds, - Boolean viewMode, AclPermission aclPermission, - Sort sort) { + public Flux<NewAction> findAllNonJsActionsByNameAndPageIdsAndViewMode( + String name, List<String> pageIds, Boolean viewMode, AclPermission aclPermission, Sort sort) { List<Criteria> criteriaList = new ArrayList<>(); - Criteria nonJsTypeCriteria = where(fieldName(QNewAction.newAction.pluginType)).ne(PluginType.JS); + Criteria nonJsTypeCriteria = + where(fieldName(QNewAction.newAction.pluginType)).ne(PluginType.JS); criteriaList.add(nonJsTypeCriteria); // Fetch published actions if (Boolean.TRUE.equals(viewMode)) { if (name != null) { - Criteria nameCriteria = where(fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.name)).is(name); + Criteria nameCriteria = where(fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.name)) + .is(name); criteriaList.add(nameCriteria); } if (pageIds != null && !pageIds.isEmpty()) { - Criteria pageCriteria = where(fieldName(QNewAction.newAction.publishedAction) + "." + fieldName(QNewAction.newAction.publishedAction.pageId)).in(pageIds); + Criteria pageCriteria = where(fieldName(QNewAction.newAction.publishedAction) + "." + + fieldName(QNewAction.newAction.publishedAction.pageId)) + .in(pageIds); criteriaList.add(pageCriteria); } @@ -393,17 +467,24 @@ public Flux<NewAction> findAllNonJsActionsByNameAndPageIdsAndViewMode(String nam else { if (name != null) { - Criteria nameCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.name)).is(name); + Criteria nameCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.name)) + .is(name); criteriaList.add(nameCriteria); } if (pageIds != null && !pageIds.isEmpty()) { - Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.pageId)).in(pageIds); + Criteria pageCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.pageId)) + .in(pageIds); criteriaList.add(pageCriteria); } - // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object would exist. To handle this, only fetch non-deleted actions - Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)).is(null); + // In case an action has been deleted in edit mode, but still exists in deployed mode, NewAction object + // would exist. To handle this, only fetch non-deleted actions + Criteria deletedCriteria = where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.deletedAt)) + .is(null); criteriaList.add(deletedCriteria); } @@ -425,39 +506,44 @@ public Flux<NewAction> findAllNonJsActionsByNameAndPageIdsAndViewMode(String nam */ @Override public Mono<List<InsertManyResult>> bulkInsert(List<NewAction> newActions) { - if(CollectionUtils.isEmpty(newActions)) { + if (CollectionUtils.isEmpty(newActions)) { return Mono.just(Collections.emptyList()); } // convert the list of new actions to a list of DBObjects - List<Document> dbObjects = newActions.stream().map(newAction -> { - Document document = new Document(); - mongoOperations.getConverter().write(newAction, document); - return document; - }).collect(Collectors.toList()); - - return mongoOperations.getCollection(mongoOperations.getCollectionName(NewAction.class)) + List<Document> dbObjects = newActions.stream() + .map(newAction -> { + Document document = new Document(); + mongoOperations.getConverter().write(newAction, document); + return document; + }) + .collect(Collectors.toList()); + + return mongoOperations + .getCollection(mongoOperations.getCollectionName(NewAction.class)) .flatMapMany(documentMongoCollection -> documentMongoCollection.insertMany(dbObjects)) .collectList(); } @Override public Mono<List<BulkWriteResult>> bulkUpdate(List<NewAction> newActions) { - if(CollectionUtils.isEmpty(newActions)) { + if (CollectionUtils.isEmpty(newActions)) { return Mono.just(Collections.emptyList()); } // convert the list of new actions to a list of DBObjects - List<WriteModel<Document>> dbObjects = newActions.stream().map(newAction -> { - assert newAction.getId() != null; - Document document = new Document(); - mongoOperations.getConverter().write(newAction, document); - document.remove("_id"); - return (WriteModel<Document>) new UpdateOneModel<Document>( - new Document("_id", new ObjectId(newAction.getId())), new Document("$set", document) - ); - }).collect(Collectors.toList()); - - return mongoOperations.getCollection(mongoOperations.getCollectionName(NewAction.class)) + List<WriteModel<Document>> dbObjects = newActions.stream() + .map(newAction -> { + assert newAction.getId() != null; + Document document = new Document(); + mongoOperations.getConverter().write(newAction, document); + document.remove("_id"); + return (WriteModel<Document>) new UpdateOneModel<Document>( + new Document("_id", new ObjectId(newAction.getId())), new Document("$set", document)); + }) + .collect(Collectors.toList()); + + return mongoOperations + .getCollection(mongoOperations.getCollectionName(NewAction.class)) .flatMapMany(documentMongoCollection -> documentMongoCollection.bulkWrite(dbObjects)) .collectList(); } @@ -465,7 +551,8 @@ public Mono<List<BulkWriteResult>> bulkUpdate(List<NewAction> newActions) { @Override public Flux<NewAction> findByDefaultApplicationId(String defaultApplicationId, Optional<AclPermission> permission) { final String defaultResources = fieldName(QBranchAwareDomain.branchAwareDomain.defaultResources); - Criteria defaultAppIdCriteria = where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); + Criteria defaultAppIdCriteria = + where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); return queryAll(List.of(defaultAppIdCriteria), permission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewPageRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewPageRepositoryCE.java index 2c8cbc5e3a03..f4a3c8ba3039 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewPageRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewPageRepositoryCE.java @@ -18,21 +18,26 @@ public interface CustomNewPageRepositoryCE extends AppsmithRepository<NewPage> { Flux<NewPage> findByApplicationIdAndNonDeletedEditMode(String applicationId, AclPermission aclPermission); - Mono<NewPage> findByIdAndLayoutsIdAndViewMode(String id, String layoutId, AclPermission aclPermission, Boolean viewMode); + Mono<NewPage> findByIdAndLayoutsIdAndViewMode( + String id, String layoutId, AclPermission aclPermission, Boolean viewMode); Mono<NewPage> findByNameAndViewMode(String name, AclPermission aclPermission, Boolean viewMode); - Mono<NewPage> findByNameAndApplicationIdAndViewMode(String name, String applicationId, AclPermission aclPermission, Boolean viewMode); + Mono<NewPage> findByNameAndApplicationIdAndViewMode( + String name, String applicationId, AclPermission aclPermission, Boolean viewMode); Flux<NewPage> findAllPageDTOsByIds(List<String> ids, AclPermission aclPermission); Mono<String> getNameByPageId(String pageId, boolean isPublishedName); - Mono<NewPage> findPageByBranchNameAndDefaultPageId(String branchName, String defaultPageId, AclPermission permission); + Mono<NewPage> findPageByBranchNameAndDefaultPageId( + String branchName, String defaultPageId, AclPermission permission); Flux<NewPage> findSlugsByApplicationIds(List<String> applicationIds, AclPermission aclPermission); - Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission); + Mono<NewPage> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, AclPermission permission); - Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission); + Mono<NewPage> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewPageRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewPageRepositoryCEImpl.java index eccf760cfe63..31b7a5952d19 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewPageRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewPageRepositoryCEImpl.java @@ -27,32 +27,42 @@ public class CustomNewPageRepositoryCEImpl extends BaseAppsmithRepositoryImpl<NewPage> implements CustomNewPageRepositoryCE { - public CustomNewPageRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomNewPageRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override public Flux<NewPage> findByApplicationId(String applicationId, AclPermission aclPermission) { - Criteria applicationIdCriteria = where(fieldName(QNewPage.newPage.applicationId)).is(applicationId); + Criteria applicationIdCriteria = + where(fieldName(QNewPage.newPage.applicationId)).is(applicationId); return queryAll(List.of(applicationIdCriteria), aclPermission); } @Override public Flux<NewPage> findByApplicationId(String applicationId, Optional<AclPermission> permission) { - Criteria applicationIdCriteria = where(fieldName(QNewPage.newPage.applicationId)).is(applicationId); + Criteria applicationIdCriteria = + where(fieldName(QNewPage.newPage.applicationId)).is(applicationId); return queryAll(List.of(applicationIdCriteria), permission); } @Override public Flux<NewPage> findByApplicationIdAndNonDeletedEditMode(String applicationId, AclPermission aclPermission) { - Criteria applicationIdCriteria = where(fieldName(QNewPage.newPage.applicationId)).is(applicationId); - // In case a page has been deleted in edit mode, but still exists in deployed mode, NewPage object would exist. To handle this, only fetch non-deleted pages - Criteria activeEditModeCriteria = where(fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.deletedAt)).is(null); + Criteria applicationIdCriteria = + where(fieldName(QNewPage.newPage.applicationId)).is(applicationId); + // In case a page has been deleted in edit mode, but still exists in deployed mode, NewPage object would exist. + // To handle this, only fetch non-deleted pages + Criteria activeEditModeCriteria = where(fieldName(QNewPage.newPage.unpublishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.deletedAt)) + .is(null); return queryAll(List.of(applicationIdCriteria, activeEditModeCriteria), aclPermission); } @Override - public Mono<NewPage> findByIdAndLayoutsIdAndViewMode(String id, String layoutId, AclPermission aclPermission, Boolean viewMode) { + public Mono<NewPage> findByIdAndLayoutsIdAndViewMode( + String id, String layoutId, AclPermission aclPermission, Boolean viewMode) { String layoutsIdKey; String layoutsKey; @@ -61,12 +71,17 @@ public Mono<NewPage> findByIdAndLayoutsIdAndViewMode(String id, String layoutId, criteria.add(idCriterion); if (Boolean.TRUE.equals(viewMode)) { - layoutsKey = fieldName(QNewPage.newPage.publishedPage) + "." + fieldName(QNewPage.newPage.publishedPage.layouts); + layoutsKey = + fieldName(QNewPage.newPage.publishedPage) + "." + fieldName(QNewPage.newPage.publishedPage.layouts); } else { - layoutsKey = fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.layouts); - - // In case a page has been deleted in edit mode, but still exists in deployed mode, NewPage object would exist. To handle this, only fetch non-deleted pages - Criteria deletedCriterion = where(fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.deletedAt)).is(null); + layoutsKey = fieldName(QNewPage.newPage.unpublishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.layouts); + + // In case a page has been deleted in edit mode, but still exists in deployed mode, NewPage object would + // exist. To handle this, only fetch non-deleted pages + Criteria deletedCriterion = where(fieldName(QNewPage.newPage.unpublishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.deletedAt)) + .is(null); criteria.add(deletedCriterion); } layoutsIdKey = layoutsKey + "." + fieldName(QLayout.layout.id); @@ -86,8 +101,11 @@ public Mono<NewPage> findByNameAndViewMode(String name, AclPermission aclPermiss criteria.add(nameCriterion); if (Boolean.FALSE.equals(viewMode)) { - // In case a page has been deleted in edit mode, but still exists in deployed mode, NewPage object would exist. To handle this, only fetch non-deleted pages - Criteria deletedCriterion = where(fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.deletedAt)).is(null); + // In case a page has been deleted in edit mode, but still exists in deployed mode, NewPage object would + // exist. To handle this, only fetch non-deleted pages + Criteria deletedCriterion = where(fieldName(QNewPage.newPage.unpublishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.deletedAt)) + .is(null); criteria.add(deletedCriterion); } @@ -95,19 +113,24 @@ public Mono<NewPage> findByNameAndViewMode(String name, AclPermission aclPermiss } @Override - public Mono<NewPage> findByNameAndApplicationIdAndViewMode(String name, String applicationId, AclPermission aclPermission, Boolean viewMode) { + public Mono<NewPage> findByNameAndApplicationIdAndViewMode( + String name, String applicationId, AclPermission aclPermission, Boolean viewMode) { List<Criteria> criteria = new ArrayList<>(); Criteria nameCriterion = getNameCriterion(name, viewMode); criteria.add(nameCriterion); - Criteria applicationIdCriterion = where(fieldName(QNewPage.newPage.applicationId)).is(applicationId); + Criteria applicationIdCriterion = + where(fieldName(QNewPage.newPage.applicationId)).is(applicationId); criteria.add(applicationIdCriterion); if (Boolean.FALSE.equals(viewMode)) { - // In case a page has been deleted in edit mode, but still exists in deployed mode, NewPage object would exist. To handle this, only fetch non-deleted pages - Criteria deletedCriteria = where(fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.deletedAt)).is(null); + // In case a page has been deleted in edit mode, but still exists in deployed mode, NewPage object would + // exist. To handle this, only fetch non-deleted pages + Criteria deletedCriteria = where(fieldName(QNewPage.newPage.unpublishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.deletedAt)) + .is(null); criteria.add(deletedCriteria); } @@ -122,23 +145,22 @@ public Flux<NewPage> findAllPageDTOsByIds(List<String> ids, AclPermission aclPer fieldName(QNewPage.newPage.policies), (fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.name)), (fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.icon)), - (fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.isHidden)), + (fieldName(QNewPage.newPage.unpublishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.isHidden)), (fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.slug)), - (fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.customSlug)), + (fieldName(QNewPage.newPage.unpublishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.customSlug)), (fieldName(QNewPage.newPage.publishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.name)), (fieldName(QNewPage.newPage.publishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.icon)), - (fieldName(QNewPage.newPage.publishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.isHidden)), + (fieldName(QNewPage.newPage.publishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.isHidden)), (fieldName(QNewPage.newPage.publishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.slug)), - (fieldName(QNewPage.newPage.publishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.customSlug)) - )); + (fieldName(QNewPage.newPage.publishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.customSlug)))); Criteria idsCriterion = where("id").in(ids); - return this.queryAll( - new ArrayList<>(List.of(idsCriterion)), - includedFields, - aclPermission, - null); + return this.queryAll(new ArrayList<>(List.of(idsCriterion)), includedFields, aclPermission, null); } private Criteria getNameCriterion(String name, Boolean viewMode) { @@ -147,7 +169,8 @@ private Criteria getNameCriterion(String name, Boolean viewMode) { if (Boolean.TRUE.equals(viewMode)) { nameKey = fieldName(QNewPage.newPage.publishedPage) + "." + fieldName(QNewPage.newPage.publishedPage.name); } else { - nameKey = fieldName(QNewPage.newPage.unpublishedPage) + "." + fieldName(QNewPage.newPage.unpublishedPage.name); + nameKey = fieldName(QNewPage.newPage.unpublishedPage) + "." + + fieldName(QNewPage.newPage.unpublishedPage.name); } return where(nameKey).is(name); } @@ -156,7 +179,8 @@ private Criteria getNameCriterion(String name, Boolean viewMode) { public Mono<String> getNameByPageId(String pageId, boolean isPublishedName) { return mongoOperations .query(NewPage.class) - .matching(Query.query(Criteria.where(fieldName(QNewPage.newPage.id)).is(pageId))) + .matching(Query.query( + Criteria.where(fieldName(QNewPage.newPage.id)).is(pageId))) .one() .map(p -> { PageDTO page = (isPublishedName ? p.getPublishedPage() : p.getUnpublishedPage()); @@ -169,47 +193,56 @@ public Mono<String> getNameByPageId(String pageId, boolean isPublishedName) { } @Override - public Mono<NewPage> findPageByBranchNameAndDefaultPageId(String branchName, String defaultPageId, AclPermission permission) { + public Mono<NewPage> findPageByBranchNameAndDefaultPageId( + String branchName, String defaultPageId, AclPermission permission) { final String defaultResources = fieldName(QNewPage.newPage.defaultResources); - Criteria defaultPageIdCriteria = where(defaultResources + "." + FieldName.PAGE_ID).is(defaultPageId); - Criteria branchCriteria = where(defaultResources + "." + FieldName.BRANCH_NAME).is(branchName); + Criteria defaultPageIdCriteria = + where(defaultResources + "." + FieldName.PAGE_ID).is(defaultPageId); + Criteria branchCriteria = + where(defaultResources + "." + FieldName.BRANCH_NAME).is(branchName); return queryOne(List.of(defaultPageIdCriteria, branchCriteria), permission); } @Override public Flux<NewPage> findSlugsByApplicationIds(List<String> applicationIds, AclPermission aclPermission) { - Criteria applicationIdCriteria = where(fieldName(QNewPage.newPage.applicationId)).in(applicationIds); + Criteria applicationIdCriteria = + where(fieldName(QNewPage.newPage.applicationId)).in(applicationIds); String unpublishedSlugFieldPath = String.format( - "%s.%s", fieldName(QNewPage.newPage.unpublishedPage), fieldName(QNewPage.newPage.unpublishedPage.slug) - ); + "%s.%s", fieldName(QNewPage.newPage.unpublishedPage), fieldName(QNewPage.newPage.unpublishedPage.slug)); String unpublishedCustomSlugFieldPath = String.format( - "%s.%s", fieldName(QNewPage.newPage.unpublishedPage), fieldName(QNewPage.newPage.unpublishedPage.customSlug) - ); + "%s.%s", + fieldName(QNewPage.newPage.unpublishedPage), fieldName(QNewPage.newPage.unpublishedPage.customSlug)); String publishedSlugFieldPath = String.format( - "%s.%s", fieldName(QNewPage.newPage.publishedPage), fieldName(QNewPage.newPage.publishedPage.slug) - ); + "%s.%s", fieldName(QNewPage.newPage.publishedPage), fieldName(QNewPage.newPage.publishedPage.slug)); String publishedCustomSlugFieldPath = String.format( - "%s.%s", fieldName(QNewPage.newPage.publishedPage), fieldName(QNewPage.newPage.publishedPage.customSlug) - ); + "%s.%s", + fieldName(QNewPage.newPage.publishedPage), fieldName(QNewPage.newPage.publishedPage.customSlug)); String applicationIdFieldPath = fieldName(QNewPage.newPage.applicationId); return queryAll( List.of(applicationIdCriteria), - List.of(unpublishedSlugFieldPath, unpublishedCustomSlugFieldPath, publishedSlugFieldPath, publishedCustomSlugFieldPath, applicationIdFieldPath), + List.of( + unpublishedSlugFieldPath, + unpublishedCustomSlugFieldPath, + publishedSlugFieldPath, + publishedCustomSlugFieldPath, + applicationIdFieldPath), aclPermission, - null - ); + null); } @Override - public Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission) { + public Mono<NewPage> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, AclPermission permission) { return findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, gitSyncId, Optional.ofNullable(permission)); } @Override - public Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission) { + public Mono<NewPage> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission) { final String defaultResources = fieldName(QBranchAwareDomain.branchAwareDomain.defaultResources); - Criteria defaultAppIdCriteria = where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); + Criteria defaultAppIdCriteria = + where(defaultResources + "." + FieldName.APPLICATION_ID).is(defaultApplicationId); Criteria gitSyncIdCriteria = where(FieldName.GIT_SYNC_ID).is(gitSyncId); return queryFirst(List.of(defaultAppIdCriteria, gitSyncIdCriteria), permission); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNotificationRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNotificationRepositoryCEImpl.java index 652e4dc61350..e8abc79f8b19 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNotificationRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNotificationRepositoryCEImpl.java @@ -18,19 +18,23 @@ public class CustomNotificationRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Notification> implements CustomNotificationRepositoryCE { - public CustomNotificationRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomNotificationRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override - public Mono<UpdateResult> updateIsReadByForUsernameAndIdList(String forUsername, List<String> idList, boolean isRead) { + public Mono<UpdateResult> updateIsReadByForUsernameAndIdList( + String forUsername, List<String> idList, boolean isRead) { return mongoOperations.updateMulti( - query(where(fieldName(QNotification.notification.forUsername)).is(forUsername) - .and(fieldName(QNotification.notification.id)).in(idList) - ), + query(where(fieldName(QNotification.notification.forUsername)) + .is(forUsername) + .and(fieldName(QNotification.notification.id)) + .in(idList)), new Update().set(fieldName(QNotification.notification.isRead), isRead), - Notification.class - ); + Notification.class); } @Override @@ -38,8 +42,6 @@ public Mono<UpdateResult> updateIsReadByForUsername(String forUsername, boolean return mongoOperations.updateMulti( query(where(fieldName(QNotification.notification.forUsername)).is(forUsername)), new Update().set(fieldName(QNotification.notification.isRead), isRead), - Notification.class - ); + Notification.class); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPageRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPageRepositoryCEImpl.java index 999bfcf3cb54..5acd4efc4502 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPageRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPageRepositoryCEImpl.java @@ -16,14 +16,15 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; -public class CustomPageRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Page> - implements CustomPageRepositoryCE { +public class CustomPageRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Page> implements CustomPageRepositoryCE { - public CustomPageRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomPageRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - @Override public Mono<Page> findByIdAndLayoutsId(String id, String layoutId, AclPermission aclPermission) { @@ -43,14 +44,16 @@ public Mono<Page> findByName(String name, AclPermission aclPermission) { @Override public Flux<Page> findByApplicationId(String applicationId, AclPermission aclPermission) { - Criteria applicationIdCriteria = where(fieldName(QPage.page.applicationId)).is(applicationId); + Criteria applicationIdCriteria = + where(fieldName(QPage.page.applicationId)).is(applicationId); return queryAll(List.of(applicationIdCriteria), aclPermission); } @Override public Mono<Page> findByNameAndApplicationId(String name, String applicationId, AclPermission aclPermission) { Criteria nameCriteria = where(fieldName(QPage.page.name)).is(name); - Criteria applicationIdCriteria = where(fieldName(QPage.page.applicationId)).is(applicationId); + Criteria applicationIdCriteria = + where(fieldName(QPage.page.applicationId)).is(applicationId); return queryOne(List.of(nameCriteria, applicationIdCriteria), aclPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPermissionGroupRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPermissionGroupRepositoryCE.java index 54f2a645fb42..44923e2147db 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPermissionGroupRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPermissionGroupRepositoryCE.java @@ -14,7 +14,8 @@ public interface CustomPermissionGroupRepositoryCE extends AppsmithRepository<PermissionGroup> { - Flux<PermissionGroup> findAllByAssignedToUserIdAndDefaultWorkspaceId(String userId, String workspaceId, AclPermission permission); + Flux<PermissionGroup> findAllByAssignedToUserIdAndDefaultWorkspaceId( + String userId, String workspaceId, AclPermission permission); Mono<UpdateResult> updateById(String id, Update updateObj); @@ -26,9 +27,8 @@ public interface CustomPermissionGroupRepositoryCE extends AppsmithRepository<Pe Mono<Void> evictAllPermissionGroupCachesForUser(String email, String tenantId); - Flux<PermissionGroup> findAllByAssignedToUserIn(Set<String> userIds, - Optional<List<String>> includeFields, - Optional<AclPermission> permission); + Flux<PermissionGroup> findAllByAssignedToUserIn( + Set<String> userIds, Optional<List<String>> includeFields, Optional<AclPermission> permission); Mono<Set<String>> getCurrentUserPermissionGroups(); -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPermissionGroupRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPermissionGroupRepositoryCEImpl.java index 5968ca8efcd3..38220cfcca45 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPermissionGroupRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPermissionGroupRepositoryCEImpl.java @@ -27,17 +27,24 @@ public class CustomPermissionGroupRepositoryCEImpl extends BaseAppsmithRepositoryImpl<PermissionGroup> implements CustomPermissionGroupRepositoryCE { - public CustomPermissionGroupRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomPermissionGroupRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override - public Flux<PermissionGroup> findAllByAssignedToUserIdAndDefaultWorkspaceId(String userId, String workspaceId, - AclPermission permission) { - Criteria assignedToUserIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)).in(userId); - Criteria defaultWorkspaceIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainId)).is(workspaceId); - Criteria defaultDomainTypeCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainType)).is(Workspace.class.getSimpleName()); - return queryAll(List.of(assignedToUserIdCriteria, defaultWorkspaceIdCriteria, defaultDomainTypeCriteria), permission); + public Flux<PermissionGroup> findAllByAssignedToUserIdAndDefaultWorkspaceId( + String userId, String workspaceId, AclPermission permission) { + Criteria assignedToUserIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)) + .in(userId); + Criteria defaultWorkspaceIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainId)) + .is(workspaceId); + Criteria defaultDomainTypeCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainType)) + .is(Workspace.class.getSimpleName()); + return queryAll( + List.of(assignedToUserIdCriteria, defaultWorkspaceIdCriteria, defaultDomainTypeCriteria), permission); } @Override @@ -51,15 +58,19 @@ public Mono<UpdateResult> updateById(String id, Update updateObj) { @Override public Flux<PermissionGroup> findByDefaultWorkspaceId(String workspaceId, AclPermission permission) { - Criteria defaultWorkspaceIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainId)).is(workspaceId); - Criteria defaultDomainTypeCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainType)).is(Workspace.class.getSimpleName()); + Criteria defaultWorkspaceIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainId)) + .is(workspaceId); + Criteria defaultDomainTypeCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainType)) + .is(Workspace.class.getSimpleName()); return queryAll(List.of(defaultWorkspaceIdCriteria, defaultDomainTypeCriteria), permission); } @Override public Flux<PermissionGroup> findByDefaultWorkspaceIds(Set<String> workspaceIds, AclPermission permission) { - Criteria defaultWorkspaceIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainId)).in(workspaceIds); - Criteria defaultDomainTypeCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainType)).is(Workspace.class.getSimpleName()); + Criteria defaultWorkspaceIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainId)) + .in(workspaceIds); + Criteria defaultDomainTypeCriteria = where(fieldName(QPermissionGroup.permissionGroup.defaultDomainType)) + .is(Workspace.class.getSimpleName()); return queryAll(List.of(defaultWorkspaceIdCriteria, defaultDomainTypeCriteria), permission); } @@ -79,13 +90,11 @@ public Mono<Set<String>> getCurrentUserPermissionGroups() { } @Override - public Flux<PermissionGroup> findAllByAssignedToUserIn(Set<String> userIds, Optional<List<String>> includeFields, Optional<AclPermission> permission) { - Criteria assignedToUserIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)).in(userIds); - return queryAll(List.of(assignedToUserIdCriteria), - includeFields, - permission, - Optional.empty(), - NO_RECORD_LIMIT - ); + public Flux<PermissionGroup> findAllByAssignedToUserIn( + Set<String> userIds, Optional<List<String>> includeFields, Optional<AclPermission> permission) { + Criteria assignedToUserIdCriteria = where(fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)) + .in(userIds); + return queryAll( + List.of(assignedToUserIdCriteria), includeFields, permission, Optional.empty(), NO_RECORD_LIMIT); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPluginRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPluginRepositoryCEImpl.java index 8c510c04dbd9..6dfdeeff802e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPluginRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomPluginRepositoryCEImpl.java @@ -11,20 +11,24 @@ import java.util.List; -public class CustomPluginRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Plugin> implements CustomPluginRepositoryCE { +public class CustomPluginRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Plugin> + implements CustomPluginRepositoryCE { - public CustomPluginRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomPluginRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override public Flux<Plugin> findDefaultPluginIcons() { - Criteria criteria = Criteria.where(fieldName(QPlugin.plugin.defaultInstall)).is(Boolean.TRUE); + Criteria criteria = + Criteria.where(fieldName(QPlugin.plugin.defaultInstall)).is(Boolean.TRUE); List<String> projections = List.of( fieldName(QPlugin.plugin.name), fieldName(QPlugin.plugin.packageName), - fieldName(QPlugin.plugin.iconLocation) - ); + fieldName(QPlugin.plugin.iconLocation)); return this.queryAll(List.of(criteria), projections, null, null); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomProviderRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomProviderRepositoryCE.java index 45a102d82dd4..f19475b6b0f6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomProviderRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomProviderRepositoryCE.java @@ -3,6 +3,4 @@ import com.appsmith.external.models.Provider; import com.appsmith.server.repositories.AppsmithRepository; -public interface CustomProviderRepositoryCE extends AppsmithRepository<Provider> { - -} +public interface CustomProviderRepositoryCE extends AppsmithRepository<Provider> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomProviderRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomProviderRepositoryCEImpl.java index 06802214bddd..ba970b44ea0a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomProviderRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomProviderRepositoryCEImpl.java @@ -6,9 +6,13 @@ import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.data.mongodb.core.convert.MongoConverter; -public class CustomProviderRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Provider> implements CustomProviderRepositoryCE { +public class CustomProviderRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Provider> + implements CustomProviderRepositoryCE { - public CustomProviderRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomProviderRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomTenantRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomTenantRepositoryCE.java index d6b7af32903c..e9cc3b92c097 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomTenantRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomTenantRepositoryCE.java @@ -3,6 +3,4 @@ import com.appsmith.server.domains.Tenant; import com.appsmith.server.repositories.AppsmithRepository; -public interface CustomTenantRepositoryCE extends AppsmithRepository<Tenant> { - -} +public interface CustomTenantRepositoryCE extends AppsmithRepository<Tenant> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomTenantRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomTenantRepositoryCEImpl.java index aab12c7ae1d7..cfb863faa938 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomTenantRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomTenantRepositoryCEImpl.java @@ -8,11 +8,13 @@ import org.springframework.data.mongodb.core.convert.MongoConverter; @Slf4j -public class CustomTenantRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Tenant> implements CustomTenantRepositoryCE { +public class CustomTenantRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Tenant> + implements CustomTenantRepositoryCE { - public CustomTenantRepositoryCEImpl(ReactiveMongoOperations mongoOperations, - MongoConverter mongoConverter, - CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomTenantRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomThemeRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomThemeRepositoryCEImpl.java index b3d142251d77..26f0c44cd68e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomThemeRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomThemeRepositoryCEImpl.java @@ -25,30 +25,37 @@ @Component @Slf4j public class CustomThemeRepositoryCEImpl extends BaseAppsmithRepositoryImpl<Theme> implements CustomThemeRepositoryCE { - public CustomThemeRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomThemeRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - @Override public Flux<Theme> getApplicationThemes(String applicationId, AclPermission aclPermission) { - Criteria appThemeCriteria = Criteria.where(fieldName(QTheme.theme.applicationId)).is(applicationId); - Criteria systemThemeCriteria = Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(Boolean.TRUE); + Criteria appThemeCriteria = + Criteria.where(fieldName(QTheme.theme.applicationId)).is(applicationId); + Criteria systemThemeCriteria = + Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(Boolean.TRUE); Criteria criteria = new Criteria().orOperator(appThemeCriteria, systemThemeCriteria); return queryAll(List.of(criteria), aclPermission); } @Override public Flux<Theme> getSystemThemes() { - Criteria systemThemeCriteria = Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(Boolean.TRUE); + Criteria systemThemeCriteria = + Criteria.where(fieldName(QTheme.theme.isSystemTheme)).is(Boolean.TRUE); return queryAll(List.of(systemThemeCriteria), AclPermission.READ_THEMES); } @Override public Mono<Theme> getSystemThemeByName(String themeName) { String findNameRegex = String.format("^%s$", Pattern.quote(themeName)); - Criteria criteria = where(fieldName(QTheme.theme.name)).regex(findNameRegex, "i") - .and(fieldName(QTheme.theme.isSystemTheme)).is(true); + Criteria criteria = where(fieldName(QTheme.theme.name)) + .regex(findNameRegex, "i") + .and(fieldName(QTheme.theme.isSystemTheme)) + .is(true); return queryOne(List.of(criteria), AclPermission.READ_THEMES); } @@ -64,18 +71,22 @@ private Mono<Boolean> archiveThemeByCriteria(Criteria criteria) { update.set(fieldName(QTheme.theme.deleted), true); update.set(fieldName(QTheme.theme.deletedAt), Instant.now()); return updateByCriteria(List.of(criteria, permissionCriteria), update); - }).map(updateResult -> updateResult.getModifiedCount() > 0); + }) + .map(updateResult -> updateResult.getModifiedCount() > 0); } @Override public Mono<Boolean> archiveByApplicationId(String applicationId) { - return archiveThemeByCriteria(where(fieldName(QTheme.theme.applicationId)).is(applicationId)); + return archiveThemeByCriteria( + where(fieldName(QTheme.theme.applicationId)).is(applicationId)); } @Override public Mono<Boolean> archiveDraftThemesById(String editModeThemeId, String publishedModeThemeId) { - Criteria criteria = where(fieldName(QTheme.theme.id)).in(editModeThemeId, publishedModeThemeId) - .and(fieldName(QTheme.theme.isSystemTheme)).is(false); + Criteria criteria = where(fieldName(QTheme.theme.id)) + .in(editModeThemeId, publishedModeThemeId) + .and(fieldName(QTheme.theme.isSystemTheme)) + .is(false); return archiveThemeByCriteria(criteria); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUsagePulseRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUsagePulseRepositoryCE.java index b8634ff078e2..486611b5bc43 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUsagePulseRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUsagePulseRepositoryCE.java @@ -1,4 +1,3 @@ package com.appsmith.server.repositories.ce; -public interface CustomUsagePulseRepositoryCE { -} +public interface CustomUsagePulseRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUsagePulseRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUsagePulseRepositoryCEImpl.java index e84ad3ca790d..90f3e424c083 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUsagePulseRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUsagePulseRepositoryCEImpl.java @@ -10,10 +10,13 @@ @Component @Slf4j -public class CustomUsagePulseRepositoryCEImpl extends BaseAppsmithRepositoryImpl<UsagePulse> implements CustomUsagePulseRepositoryCE { +public class CustomUsagePulseRepositoryCEImpl extends BaseAppsmithRepositoryImpl<UsagePulse> + implements CustomUsagePulseRepositoryCE { - public CustomUsagePulseRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomUsagePulseRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserDataRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserDataRepositoryCE.java index 30cd79c97ed3..02be001d3899 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserDataRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserDataRepositoryCE.java @@ -17,5 +17,4 @@ public interface CustomUserDataRepositoryCE extends AppsmithRepository<UserData> Flux<UserData> findPhotoAssetsByUserIds(Iterable<String> userId); Mono<String> fetchMostRecentlyUsedWorkspaceId(String userId); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserDataRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserDataRepositoryCEImpl.java index 278d8932cde8..53dd18060271 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserDataRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserDataRepositoryCEImpl.java @@ -21,33 +21,34 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; -public class CustomUserDataRepositoryCEImpl extends BaseAppsmithRepositoryImpl<UserData> implements CustomUserDataRepositoryCE { +public class CustomUserDataRepositoryCEImpl extends BaseAppsmithRepositoryImpl<UserData> + implements CustomUserDataRepositoryCE { - public CustomUserDataRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomUserDataRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @Override public Mono<UpdateResult> saveReleaseNotesViewedVersion(String userId, String version) { - return mongoOperations - .upsert( - query(where(fieldName(QUserData.userData.userId)).is(userId)), - Update - .update(fieldName(QUserData.userData.releaseNotesViewedVersion), version) - .setOnInsert(fieldName(QUserData.userData.userId), userId), - UserData.class - ); + return mongoOperations.upsert( + query(where(fieldName(QUserData.userData.userId)).is(userId)), + Update.update(fieldName(QUserData.userData.releaseNotesViewedVersion), version) + .setOnInsert(fieldName(QUserData.userData.userId), userId), + UserData.class); } @Override - public Mono<UpdateResult> removeIdFromRecentlyUsedList(String userId, String workspaceId, List<String> applicationIds) { + public Mono<UpdateResult> removeIdFromRecentlyUsedList( + String userId, String workspaceId, List<String> applicationIds) { Update update = new Update().pull(fieldName(QUserData.userData.recentlyUsedWorkspaceIds), workspaceId); if (!CollectionUtils.isEmpty(applicationIds)) { update = update.pullAll(fieldName(QUserData.userData.recentlyUsedAppIds), applicationIds.toArray()); } return mongoOperations.updateFirst( - query(where(fieldName(QUserData.userData.userId)).is(userId)), update, UserData.class - ); + query(where(fieldName(QUserData.userData.userId)).is(userId)), update, UserData.class); } /** @@ -61,10 +62,8 @@ public Mono<UpdateResult> removeIdFromRecentlyUsedList(String userId, String wor public Flux<UserData> findPhotoAssetsByUserIds(Iterable<String> userId) { // need to convert from Iterable to ArrayList because the "in" method of criteria takes a collection as input Criteria criteria = where(fieldName(QUserData.userData.userId)).in(Lists.newArrayList(userId)); - List<String> fieldsToInclude = List.of( - fieldName(QUserData.userData.profilePhotoAssetId), - fieldName(QUserData.userData.userId) - ); + List<String> fieldsToInclude = + List.of(fieldName(QUserData.userData.profilePhotoAssetId), fieldName(QUserData.userData.userId)); return queryAll(List.of(criteria), Optional.of(fieldsToInclude), Optional.empty(), Optional.empty()); } @@ -74,11 +73,9 @@ public Mono<String> fetchMostRecentlyUsedWorkspaceId(String userId) { query.fields().include(fieldName(QUserData.userData.recentlyUsedWorkspaceIds)); - return mongoOperations.findOne(query, UserData.class) - .map(userData -> { - final List<String> recentlyUsedWorkspaceIds = userData.getRecentlyUsedWorkspaceIds(); - return CollectionUtils.isEmpty(recentlyUsedWorkspaceIds) ? "" : recentlyUsedWorkspaceIds.get(0); - }); + return mongoOperations.findOne(query, UserData.class).map(userData -> { + final List<String> recentlyUsedWorkspaceIds = userData.getRecentlyUsedWorkspaceIds(); + return CollectionUtils.isEmpty(recentlyUsedWorkspaceIds) ? "" : recentlyUsedWorkspaceIds.get(0); + }); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCE.java index 4435dbb7eee2..afdb0fdebc1f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCE.java @@ -23,6 +23,11 @@ public interface CustomUserRepositoryCE extends AppsmithRepository<User> { Mono<Boolean> isUsersEmpty(); - Flux<User> getAllByEmails(Set<String> emails, Optional<AclPermission> aclPermission, int limit, int skip, StringPath sortKey, Sort.Direction sortDirection); - + Flux<User> getAllByEmails( + Set<String> emails, + Optional<AclPermission> aclPermission, + int limit, + int skip, + StringPath sortKey, + Sort.Direction sortDirection); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCEImpl.java index 1dfbc406a1bb..a59505b874e0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCEImpl.java @@ -28,7 +28,10 @@ @Slf4j public class CustomUserRepositoryCEImpl extends BaseAppsmithRepositoryImpl<User> implements CustomUserRepositoryCE { - public CustomUserRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomUserRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); } @@ -80,24 +83,24 @@ public Mono<Boolean> isUsersEmpty() { q.fields().include(fieldName(QUser.user.email)); // Basically limit to system generated emails plus 1 more. q.limit(getSystemGeneratedUserEmails().size() + 1); - return mongoOperations.find(q, User.class) + return mongoOperations + .find(q, User.class) .filter(user -> !getSystemGeneratedUserEmails().contains(user.getEmail())) .count() .map(count -> count == 0); } @Override - public Flux<User> getAllByEmails(Set<String> emails, Optional<AclPermission> aclPermission, int limit, int skip, StringPath sortKey, Sort.Direction sortDirection) { + public Flux<User> getAllByEmails( + Set<String> emails, + Optional<AclPermission> aclPermission, + int limit, + int skip, + StringPath sortKey, + Sort.Direction sortDirection) { Sort sortBy = Sort.by(sortDirection, fieldName(sortKey)); Criteria emailCriteria = where(fieldName(QUser.user.email)).in(emails); - return queryAll( - List.of(emailCriteria), - Optional.empty(), - aclPermission, - sortBy, - limit, - skip - ); + return queryAll(List.of(emailCriteria), Optional.empty(), aclPermission, sortBy, limit, skip); } protected Set<String> getSystemGeneratedUserEmails() { @@ -105,5 +108,4 @@ protected Set<String> getSystemGeneratedUserEmails() { systemGeneratedEmails.add(FieldName.ANONYMOUS_USER); return systemGeneratedEmails; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomWorkspaceRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomWorkspaceRepositoryCEImpl.java index d42d5e3db4b1..1f6b39268d33 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomWorkspaceRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomWorkspaceRepositoryCEImpl.java @@ -27,8 +27,11 @@ public class CustomWorkspaceRepositoryCEImpl extends BaseAppsmithRepositoryImpl< private final SessionUserService sessionUserService; - public CustomWorkspaceRepositoryCEImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter, - SessionUserService sessionUserService, CacheableRepositoryHelper cacheableRepositoryHelper) { + public CustomWorkspaceRepositoryCEImpl( + ReactiveMongoOperations mongoOperations, + MongoConverter mongoConverter, + SessionUserService sessionUserService, + CacheableRepositoryHelper cacheableRepositoryHelper) { super(mongoOperations, mongoConverter, cacheableRepositoryHelper); this.sessionUserService = sessionUserService; } @@ -41,9 +44,11 @@ public Mono<Workspace> findByName(String name, AclPermission aclPermission) { } @Override - public Flux<Workspace> findByIdsIn(Set<String> workspaceIds, String tenantId, AclPermission aclPermission, Sort sort) { + public Flux<Workspace> findByIdsIn( + Set<String> workspaceIds, String tenantId, AclPermission aclPermission, Sort sort) { Criteria workspaceIdCriteria = where(fieldName(QWorkspace.workspace.id)).in(workspaceIds); - Criteria tenantIdCriteria = where(fieldName(QWorkspace.workspace.tenantId)).is(tenantId); + Criteria tenantIdCriteria = + where(fieldName(QWorkspace.workspace.tenantId)).is(tenantId); return queryAll(List.of(workspaceIdCriteria, tenantIdCriteria), aclPermission, sort); } @@ -54,8 +59,7 @@ public Mono<Void> updateUserRoleNames(String userId, String userName) { .updateMulti( Query.query(Criteria.where("userRoles.userId").is(userId)), Update.update("userRoles.$.name", userName), - Workspace.class - ) + Workspace.class) .then(); } @@ -66,11 +70,10 @@ public Flux<Workspace> findAllWorkspaces() { @Override public Flux<Workspace> findAll(AclPermission permission) { - return sessionUserService.getCurrentUser() - .flatMapMany(user -> { - Criteria tenantIdCriteria = where(fieldName(QWorkspace.workspace.tenantId)).is(user.getTenantId()); - return queryAll(List.of(tenantIdCriteria), permission); - }); - + return sessionUserService.getCurrentUser().flatMapMany(user -> { + Criteria tenantIdCriteria = + where(fieldName(QWorkspace.workspace.tenantId)).is(user.getTenantId()); + return queryAll(List.of(tenantIdCriteria), permission); + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceRepositoryCE.java index 5a7b4a6ee15c..e96ba300023d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceRepositoryCE.java @@ -15,5 +15,4 @@ public interface DatasourceRepositoryCE extends BaseRepository<Datasource, Strin Flux<Datasource> findAllByWorkspaceId(String workspaceId); Mono<Long> countByDeletedAtNull(); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceStorageRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceStorageRepositoryCE.java index 5154cb9b51fd..390f61e1c97b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceStorageRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceStorageRepositoryCE.java @@ -5,11 +5,8 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import java.util.List; - public interface DatasourceStorageRepositoryCE extends BaseRepository<DatasourceStorage, String> { Flux<DatasourceStorage> findByDatasourceId(String datasourceId); Mono<DatasourceStorage> findByDatasourceIdAndEnvironmentId(String datasourceId, String environmentId); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceStructureRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceStructureRepositoryCE.java index 7ab1a1bcde11..01d780f12871 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceStructureRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/DatasourceStructureRepositoryCE.java @@ -9,5 +9,4 @@ public interface DatasourceStructureRepositoryCE extends BaseRepository<DatasourceStorageStructure, String>, CustomDatasourceStructureRepository { Mono<DatasourceStorageStructure> findByDatasourceIdAndEnvironmentId(String datasourceId, String environmentId); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/GroupRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/GroupRepositoryCE.java index 1d0feed42fcd..ba2e6424200f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/GroupRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/GroupRepositoryCE.java @@ -4,6 +4,4 @@ import com.appsmith.server.repositories.BaseRepository; import com.appsmith.server.repositories.CustomGroupRepository; -public interface GroupRepositoryCE extends BaseRepository<Group, String>, CustomGroupRepository { - -} +public interface GroupRepositoryCE extends BaseRepository<Group, String>, CustomGroupRepository {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/LayoutRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/LayoutRepositoryCE.java index 11dc4534bb07..852d7d141441 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/LayoutRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/LayoutRepositoryCE.java @@ -3,5 +3,4 @@ import com.appsmith.server.domains.Layout; import com.appsmith.server.repositories.BaseRepository; -public interface LayoutRepositoryCE extends BaseRepository<Layout, String> { -} +public interface LayoutRepositoryCE extends BaseRepository<Layout, String> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java index a0ae98435b81..e74852d3b521 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java @@ -11,5 +11,4 @@ public interface NewActionRepositoryCE extends BaseRepository<NewAction, String> Flux<NewAction> findByApplicationId(String applicationId); Mono<Long> countByDeletedAtNull(); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewPageRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewPageRepositoryCE.java index 0b08dbba8019..96cc0c264e9f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewPageRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewPageRepositoryCE.java @@ -11,5 +11,4 @@ public interface NewPageRepositoryCE extends BaseRepository<NewPage, String>, Cu Flux<NewPage> findByApplicationId(String applicationId); Mono<Long> countByDeletedAtNull(); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PageRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PageRepositoryCE.java index 8ccb9b8df8fb..da3c791e9c2c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PageRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PageRepositoryCE.java @@ -8,5 +8,4 @@ public interface PageRepositoryCE extends BaseRepository<Page, String>, CustomPageRepository { Flux<Page> findByApplicationId(String applicationId); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PasswordResetTokenRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PasswordResetTokenRepositoryCE.java index ff7adfc4316c..6cff2bc21446 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PasswordResetTokenRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PasswordResetTokenRepositoryCE.java @@ -7,5 +7,4 @@ public interface PasswordResetTokenRepositoryCE extends BaseRepository<PasswordResetToken, String> { Mono<PasswordResetToken> findByEmail(String email); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PermissionGroupRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PermissionGroupRepositoryCE.java index fa7c1191c841..efee4fa509a4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PermissionGroupRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/PermissionGroupRepositoryCE.java @@ -9,7 +9,8 @@ import java.util.Set; -public interface PermissionGroupRepositoryCE extends BaseRepository<PermissionGroup, String>, CustomPermissionGroupRepository { +public interface PermissionGroupRepositoryCE + extends BaseRepository<PermissionGroup, String>, CustomPermissionGroupRepository { Flux<PermissionGroup> findAllById(Set<String> ids); @@ -20,5 +21,4 @@ public interface PermissionGroupRepositoryCE extends BaseRepository<PermissionGr Flux<PermissionGroup> findByDefaultWorkspaceId(String defaultWorkspaceId); Flux<PermissionGroup> findByDefaultDomainIdAndDefaultDomainType(String defaultDomainId, String domainType); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/TenantRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/TenantRepositoryCE.java index 755effbb8628..5f6cbe099db7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/TenantRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/TenantRepositoryCE.java @@ -7,5 +7,4 @@ public interface TenantRepositoryCE extends BaseRepository<Tenant, String>, CustomTenantRepositoryCE { Mono<Tenant> findBySlug(String slug); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ThemeRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ThemeRepositoryCE.java index ea04dc215feb..94da5792826f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ThemeRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/ThemeRepositoryCE.java @@ -5,6 +5,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface ThemeRepositoryCE extends BaseRepository<Theme, String>, CustomThemeRepositoryCE { - -} +public interface ThemeRepositoryCE extends BaseRepository<Theme, String>, CustomThemeRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UsagePulseRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UsagePulseRepositoryCE.java index ed2b00eefcc4..95dc0af37b05 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UsagePulseRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UsagePulseRepositoryCE.java @@ -5,6 +5,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface UsagePulseRepositoryCE extends BaseRepository<UsagePulse, String>, CustomUsagePulseRepositoryCE { - -} +public interface UsagePulseRepositoryCE extends BaseRepository<UsagePulse, String>, CustomUsagePulseRepositoryCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UserDataRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UserDataRepositoryCE.java index 4154291a232c..7af968b83d0a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UserDataRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UserDataRepositoryCE.java @@ -8,5 +8,4 @@ public interface UserDataRepositoryCE extends BaseRepository<UserData, String>, CustomUserDataRepository { Mono<UserData> findByUserId(String userId); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UserRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UserRepositoryCE.java index 005c22046b69..421b2b7e6970 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UserRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/UserRepositoryCE.java @@ -14,5 +14,4 @@ public interface UserRepositoryCE extends BaseRepository<User, String>, CustomUs Mono<Long> countByDeletedAtNull(); Mono<User> findByEmailAndTenantId(String email, String tenantId); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/WorkspaceRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/WorkspaceRepositoryCE.java index 0fa558846603..98e09ce986b5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/WorkspaceRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/WorkspaceRepositoryCE.java @@ -16,5 +16,4 @@ public interface WorkspaceRepositoryCE extends BaseRepository<Workspace, String> Mono<Void> updateUserRoleNames(String userId, String userName); Mono<Long> countByDeletedAtNull(); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ActionCollectionService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ActionCollectionService.java index 3fd4e6f3e02f..f5e2368483cc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ActionCollectionService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ActionCollectionService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ActionCollectionServiceCE; -public interface ActionCollectionService extends ActionCollectionServiceCE { - -} +public interface ActionCollectionService extends ActionCollectionServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ActionCollectionServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ActionCollectionServiceImpl.java index d097384dcaf3..c1dbc63fadd5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ActionCollectionServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ActionCollectionServiceImpl.java @@ -17,21 +17,31 @@ @Slf4j public class ActionCollectionServiceImpl extends ActionCollectionServiceCEImpl implements ActionCollectionService { - public ActionCollectionServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ActionCollectionRepository repository, - AnalyticsService analyticsService, - NewActionService newActionService, - PolicyGenerator policyGenerator, - ApplicationService applicationService, - ResponseUtils responseUtils, - ApplicationPermission applicationPermission, - ActionPermission actionPermission) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - newActionService, policyGenerator, applicationService, responseUtils, applicationPermission, + public ActionCollectionServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ActionCollectionRepository repository, + AnalyticsService analyticsService, + NewActionService newActionService, + PolicyGenerator policyGenerator, + ApplicationService applicationService, + ResponseUtils responseUtils, + ApplicationPermission applicationPermission, + ActionPermission actionPermission) { + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + newActionService, + policyGenerator, + applicationService, + responseUtils, + applicationPermission, actionPermission); - } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AnalyticsService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AnalyticsService.java index 00910c6e1412..b7b81a16177a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AnalyticsService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AnalyticsService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.AnalyticsServiceCE; -public interface AnalyticsService extends AnalyticsServiceCE { - -} +public interface AnalyticsService extends AnalyticsServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AnalyticsServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AnalyticsServiceImpl.java index 4152cf2794e1..2e8d62594d87 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AnalyticsServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AnalyticsServiceImpl.java @@ -15,14 +15,21 @@ public class AnalyticsServiceImpl extends AnalyticsServiceCEImpl implements AnalyticsService { @Autowired - public AnalyticsServiceImpl(@Autowired(required = false) Analytics analytics, - SessionUserService sessionUserService, - CommonConfig commonConfig, - ConfigService configService, - UserUtils userUtils, - ProjectProperties projectProperties, - UserDataRepository userDataRepository) { - super(analytics, sessionUserService, commonConfig, configService, userUtils, projectProperties, userDataRepository); + public AnalyticsServiceImpl( + @Autowired(required = false) Analytics analytics, + SessionUserService sessionUserService, + CommonConfig commonConfig, + ConfigService configService, + UserUtils userUtils, + ProjectProperties projectProperties, + UserDataRepository userDataRepository) { + super( + analytics, + sessionUserService, + commonConfig, + configService, + userUtils, + projectProperties, + userDataRepository); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiImporter.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiImporter.java index 352c55044b60..4057828e6c26 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiImporter.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiImporter.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ApiImporterCE; -public interface ApiImporter extends ApiImporterCE { - -} +public interface ApiImporter extends ApiImporterCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiTemplateService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiTemplateService.java index a619c89e7c92..76692ca6b46f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiTemplateService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiTemplateService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ApiTemplateServiceCE; -public interface ApiTemplateService extends ApiTemplateServiceCE { - -} +public interface ApiTemplateService extends ApiTemplateServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiTemplateServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiTemplateServiceImpl.java index 48e550fd8350..5cec9bfbd231 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiTemplateServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApiTemplateServiceImpl.java @@ -13,12 +13,13 @@ @Slf4j public class ApiTemplateServiceImpl extends ApiTemplateServiceCEImpl implements ApiTemplateService { - public ApiTemplateServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ApiTemplateRepository repository, - AnalyticsService analyticsService) { + public ApiTemplateServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ApiTemplateRepository repository, + AnalyticsService analyticsService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageService.java index 42c67f93cbe1..5a5b91871398 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ApplicationPageServiceCE; -public interface ApplicationPageService extends ApplicationPageServiceCE { - -} +public interface ApplicationPageService extends ApplicationPageServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java index 8251280578dd..de637e7b7190 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java @@ -18,29 +18,46 @@ @Slf4j public class ApplicationPageServiceImpl extends ApplicationPageServiceCEImpl implements ApplicationPageService { - public ApplicationPageServiceImpl(WorkspaceService workspaceService, - ApplicationService applicationService, - SessionUserService sessionUserService, - WorkspaceRepository workspaceRepository, - LayoutActionService layoutActionService, - AnalyticsService analyticsService, - PolicyGenerator policyGenerator, - ApplicationRepository applicationRepository, - NewPageService newPageService, - NewActionService newActionService, - ActionCollectionService actionCollectionService, - GitFileUtils gitFileUtils, - ThemeService themeService, - ResponseUtils responseUtils, - WorkspacePermission workspacePermission, - ApplicationPermission applicationPermission, - PagePermission pagePermission, - ActionPermission actionPermission, - TransactionalOperator transactionalOperator) { + public ApplicationPageServiceImpl( + WorkspaceService workspaceService, + ApplicationService applicationService, + SessionUserService sessionUserService, + WorkspaceRepository workspaceRepository, + LayoutActionService layoutActionService, + AnalyticsService analyticsService, + PolicyGenerator policyGenerator, + ApplicationRepository applicationRepository, + NewPageService newPageService, + NewActionService newActionService, + ActionCollectionService actionCollectionService, + GitFileUtils gitFileUtils, + ThemeService themeService, + ResponseUtils responseUtils, + WorkspacePermission workspacePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission, + TransactionalOperator transactionalOperator) { - super(workspaceService, applicationService, sessionUserService, workspaceRepository, layoutActionService, analyticsService, - policyGenerator, applicationRepository, newPageService, newActionService, actionCollectionService, - gitFileUtils, themeService, responseUtils, workspacePermission, - applicationPermission, pagePermission, actionPermission, transactionalOperator); + super( + workspaceService, + applicationService, + sessionUserService, + workspaceRepository, + layoutActionService, + analyticsService, + policyGenerator, + applicationRepository, + newPageService, + newActionService, + actionCollectionService, + gitFileUtils, + themeService, + responseUtils, + workspacePermission, + applicationPermission, + pagePermission, + actionPermission, + transactionalOperator); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationService.java index d41c527b8e82..cdbd24a48a12 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ApplicationServiceCE; -public interface ApplicationService extends ApplicationServiceCE { - -} +public interface ApplicationService extends ApplicationServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationServiceImpl.java index 637716f1c303..52173dfa09b7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationServiceImpl.java @@ -1,13 +1,12 @@ package com.appsmith.server.services; -import com.appsmith.server.repositories.NewActionRepository; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.helpers.ResponseUtils; import com.appsmith.server.repositories.ApplicationRepository; -import com.appsmith.server.repositories.UserRepository; +import com.appsmith.server.repositories.NewActionRepository; import com.appsmith.server.services.ce.ApplicationServiceCEImpl; import com.appsmith.server.solutions.ApplicationPermission; import com.appsmith.server.solutions.DatasourcePermission; +import com.appsmith.server.solutions.PolicySolution; import jakarta.validation.Validator; import lombok.extern.slf4j.Slf4j; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; @@ -15,28 +14,40 @@ import org.springframework.stereotype.Service; import reactor.core.scheduler.Scheduler; - @Slf4j @Service public class ApplicationServiceImpl extends ApplicationServiceCEImpl implements ApplicationService { - public ApplicationServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ApplicationRepository repository, - AnalyticsService analyticsService, - PolicySolution policySolution, - ConfigService configService, - ResponseUtils responseUtils, - PermissionGroupService permissionGroupService, - NewActionRepository newActionRepository, - AssetService assetService, - DatasourcePermission datasourcePermission, - ApplicationPermission applicationPermission) { + public ApplicationServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ApplicationRepository repository, + AnalyticsService analyticsService, + PolicySolution policySolution, + ConfigService configService, + ResponseUtils responseUtils, + PermissionGroupService permissionGroupService, + NewActionRepository newActionRepository, + AssetService assetService, + DatasourcePermission datasourcePermission, + ApplicationPermission applicationPermission) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, policySolution, - configService, responseUtils, permissionGroupService, newActionRepository, assetService, - datasourcePermission, applicationPermission); + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + policySolution, + configService, + responseUtils, + permissionGroupService, + newActionRepository, + assetService, + datasourcePermission, + applicationPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationSnapshotService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationSnapshotService.java index bd6ce294c423..3898aef05ada 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationSnapshotService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationSnapshotService.java @@ -2,5 +2,4 @@ import com.appsmith.server.services.ce.ApplicationSnapshotServiceCE; -public interface ApplicationSnapshotService extends ApplicationSnapshotServiceCE { -} +public interface ApplicationSnapshotService extends ApplicationSnapshotServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationSnapshotServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationSnapshotServiceImpl.java index fbe1a9d4dd23..9268d4bf558f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationSnapshotServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationSnapshotServiceImpl.java @@ -11,9 +11,22 @@ @Slf4j @Service -public class ApplicationSnapshotServiceImpl extends ApplicationSnapshotServiceCEImpl implements ApplicationSnapshotService { +public class ApplicationSnapshotServiceImpl extends ApplicationSnapshotServiceCEImpl + implements ApplicationSnapshotService { - public ApplicationSnapshotServiceImpl(ApplicationSnapshotRepository applicationSnapshotRepository, ApplicationService applicationService, ImportExportApplicationService importExportApplicationService, ApplicationPermission applicationPermission, Gson gson, ResponseUtils responseUtils) { - super(applicationSnapshotRepository, applicationService, importExportApplicationService, applicationPermission, gson, responseUtils); + public ApplicationSnapshotServiceImpl( + ApplicationSnapshotRepository applicationSnapshotRepository, + ApplicationService applicationService, + ImportExportApplicationService importExportApplicationService, + ApplicationPermission applicationPermission, + Gson gson, + ResponseUtils responseUtils) { + super( + applicationSnapshotRepository, + applicationService, + importExportApplicationService, + applicationPermission, + gson, + responseUtils); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateService.java index 06b5b457f7cc..264f38da9fec 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ApplicationTemplateServiceCE; -public interface ApplicationTemplateService extends ApplicationTemplateServiceCE { - -} +public interface ApplicationTemplateService extends ApplicationTemplateServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateServiceImpl.java index 2fd30e3e5cc7..28f5f46885ed 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateServiceImpl.java @@ -11,16 +11,25 @@ @Service @Slf4j -public class ApplicationTemplateServiceImpl extends ApplicationTemplateServiceCEImpl implements ApplicationTemplateService { - public ApplicationTemplateServiceImpl(CloudServicesConfig cloudServicesConfig, - ReleaseNotesService releaseNotesService, - ImportExportApplicationService importExportApplicationService, - AnalyticsService analyticsService, - UserDataService userDataService, - ApplicationService applicationService, - ResponseUtils responseUtils, - ApplicationPermission applicationPermission) { - super(cloudServicesConfig, releaseNotesService, importExportApplicationService, analyticsService, - userDataService, applicationService, responseUtils, applicationPermission); +public class ApplicationTemplateServiceImpl extends ApplicationTemplateServiceCEImpl + implements ApplicationTemplateService { + public ApplicationTemplateServiceImpl( + CloudServicesConfig cloudServicesConfig, + ReleaseNotesService releaseNotesService, + ImportExportApplicationService importExportApplicationService, + AnalyticsService analyticsService, + UserDataService userDataService, + ApplicationService applicationService, + ResponseUtils responseUtils, + ApplicationPermission applicationPermission) { + super( + cloudServicesConfig, + releaseNotesService, + importExportApplicationService, + analyticsService, + userDataService, + applicationService, + responseUtils, + applicationPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AssetService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AssetService.java index db1690cd3b30..be9a323ae4af 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AssetService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AssetService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.AssetServiceCE; -public interface AssetService extends AssetServiceCE { - -} +public interface AssetService extends AssetServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AssetServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AssetServiceImpl.java index 5c2a397c31a0..7e06aee9520a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AssetServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AssetServiceImpl.java @@ -9,8 +9,7 @@ @Service public class AssetServiceImpl extends AssetServiceCEImpl implements AssetService { - public AssetServiceImpl(AssetRepository repository, - AnalyticsService analyticsService) { + public AssetServiceImpl(AssetRepository repository, AnalyticsService analyticsService) { super(repository, analyticsService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AstService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AstService.java index 1c9259499b8a..c12dc346fd22 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AstService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AstService.java @@ -2,5 +2,4 @@ import com.appsmith.server.services.ce.AstServiceCE; -public interface AstService extends AstServiceCE { -} +public interface AstService extends AstServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AuthenticationValidator.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AuthenticationValidator.java index 43e49377af1c..da926082f0f1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AuthenticationValidator.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/AuthenticationValidator.java @@ -2,7 +2,4 @@ import com.appsmith.server.services.ce.AuthenticationValidatorCE; - -public interface AuthenticationValidator extends AuthenticationValidatorCE { - -} +public interface AuthenticationValidator extends AuthenticationValidatorCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseApiImporter.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseApiImporter.java index fbccfb0ccb77..648086b83069 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseApiImporter.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseApiImporter.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.BaseApiImporterCE; -public abstract class BaseApiImporter extends BaseApiImporterCE implements ApiImporter { - -} +public abstract class BaseApiImporter extends BaseApiImporterCE implements ApiImporter {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java index aa2573ea7d1e..42a69b3aa9cb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java @@ -34,7 +34,8 @@ import static java.util.stream.Collectors.toSet; @Slf4j -public abstract class BaseService<R extends BaseRepository<T, ID> & AppsmithRepository<T>, T extends BaseDomain, ID extends Serializable> +public abstract class BaseService< + R extends BaseRepository<T, ID> & AppsmithRepository<T>, T extends BaseDomain, ID extends Serializable> implements CrudService<T, ID> { final Scheduler scheduler; @@ -49,12 +50,13 @@ public abstract class BaseService<R extends BaseRepository<T, ID> & AppsmithRepo protected final AnalyticsService analyticsService; - public BaseService(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - R repository, - AnalyticsService analyticsService) { + public BaseService( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + R repository, + AnalyticsService analyticsService) { this.scheduler = scheduler; this.validator = validator; this.mongoConverter = mongoConverter; @@ -89,9 +91,11 @@ public Mono<T> update(ID id, T resource, String key) { Map<String, Object> updateMap = update.toMap(); updateMap.entrySet().stream().forEach(entry -> updateObj.set(entry.getKey(), entry.getValue())); - return mongoTemplate.updateFirst(query, updateObj, resource.getClass()) + return mongoTemplate + .updateFirst(query, updateObj, resource.getClass()) .flatMap(obj -> repository.findById(id)) - .flatMap(savedResource -> analyticsService.sendUpdateEvent(savedResource, getAnalyticsProperties(savedResource))); + .flatMap(savedResource -> + analyticsService.sendUpdateEvent(savedResource, getAnalyticsProperties(savedResource))); } protected Flux<T> getWithPermission(MultiValueMap<String, String> params, AclPermission aclPermission) { @@ -111,7 +115,8 @@ protected Flux<T> getWithPermission(MultiValueMap<String, String> params, AclPer @Override public Flux<T> get(MultiValueMap<String, String> params) { - // In the base service we aren't handling the query parameters. In order to filter records using the query params, + // In the base service we aren't handling the query parameters. In order to filter records using the query + // params, // each service must implement it for their usecase. Need to come up with a better strategy for doing this. return repository.findAll(); } @@ -122,7 +127,8 @@ public Mono<T> getById(ID id) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ID)); } - return repository.findById(id) + return repository + .findById(id) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "resource", id))); } @@ -131,7 +137,8 @@ public Mono<T> create(T object) { return Mono.just(object) .flatMap(this::validateObject) .flatMap(repository::save) - .flatMap(savedResource -> analyticsService.sendCreateEvent(savedResource, getAnalyticsProperties(savedResource))); + .flatMap(savedResource -> + analyticsService.sendCreateEvent(savedResource, getAnalyticsProperties(savedResource))); } protected DBObject getDbObject(Object o) { @@ -153,22 +160,20 @@ public Mono<T> archiveById(ID id) { * @return Mono<T> */ protected Mono<T> validateObject(T obj) { - return Mono.just(obj) - .map(validator::validate) - .flatMap(constraint -> { - if (constraint.isEmpty()) { - return Mono.just(obj); - } - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, constraint.stream().findFirst().get().getPropertyPath())); - }); + return Mono.just(obj).map(validator::validate).flatMap(constraint -> { + if (constraint.isEmpty()) { + return Mono.just(obj); + } + return Mono.error(new AppsmithException( + AppsmithError.INVALID_PARAMETER, + constraint.stream().findFirst().get().getPropertyPath())); + }); } - private Map<String, Set<Policy>> getAllPoliciesAsMap(Set<Policy> policies) { - return policies - .stream() - .collect(Collectors.groupingBy(Policy::getPermission, - Collectors.mapping(Function.identity(), toSet()))); + return policies.stream() + .collect( + Collectors.groupingBy(Policy::getPermission, Collectors.mapping(Function.identity(), toSet()))); } @Override diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CacheableFeatureFlagHelper.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CacheableFeatureFlagHelper.java index da856e224881..3e54cb5d1c8b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CacheableFeatureFlagHelper.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CacheableFeatureFlagHelper.java @@ -1,5 +1,5 @@ package com.appsmith.server.services; + import com.appsmith.server.services.ce.CacheableFeatureFlagHelperCE; -public interface CacheableFeatureFlagHelper extends CacheableFeatureFlagHelperCE { -} +public interface CacheableFeatureFlagHelper extends CacheableFeatureFlagHelperCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CacheableFeatureFlagHelperImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CacheableFeatureFlagHelperImpl.java index 409baae9e26c..b1e2b4202810 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CacheableFeatureFlagHelperImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CacheableFeatureFlagHelperImpl.java @@ -7,9 +7,10 @@ @Component @Slf4j -public class CacheableFeatureFlagHelperImpl extends CacheableFeatureFlagHelperCEImpl implements CacheableFeatureFlagHelper { - public CacheableFeatureFlagHelperImpl(TenantService tenantService, ConfigService configService, - CloudServicesConfig cloudServicesConfig) { +public class CacheableFeatureFlagHelperImpl extends CacheableFeatureFlagHelperCEImpl + implements CacheableFeatureFlagHelper { + public CacheableFeatureFlagHelperImpl( + TenantService tenantService, ConfigService configService, CloudServicesConfig cloudServicesConfig) { super(tenantService, configService, cloudServicesConfig); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CaptchaService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CaptchaService.java index 0471ff79ffd6..7eb821cbcfd8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CaptchaService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CaptchaService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.CaptchaServiceCE; -public interface CaptchaService extends CaptchaServiceCE { - -} +public interface CaptchaService extends CaptchaServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CollectionService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CollectionService.java index 78e4c1ee370c..1c0ad1d3c1c7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CollectionService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CollectionService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.CollectionServiceCE; -public interface CollectionService extends CollectionServiceCE { - -} +public interface CollectionService extends CollectionServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CollectionServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CollectionServiceImpl.java index b611871edba6..f690ce69abe3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CollectionServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CollectionServiceImpl.java @@ -13,12 +13,13 @@ @Service public class CollectionServiceImpl extends CollectionServiceCEImpl implements CollectionService { - public CollectionServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - CollectionRepository repository, - AnalyticsService analyticsService) { + public CollectionServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + CollectionRepository repository, + AnalyticsService analyticsService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ConfigService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ConfigService.java index 17b8e0ebe523..c417874a987e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ConfigService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ConfigService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ConfigServiceCE; -public interface ConfigService extends ConfigServiceCE { - -} +public interface ConfigService extends ConfigServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ConfigServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ConfigServiceImpl.java index 1a5cd8f6a2c9..e19ccad98d58 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ConfigServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ConfigServiceImpl.java @@ -11,9 +11,10 @@ @Service public class ConfigServiceImpl extends ConfigServiceCEImpl implements ConfigService { - public ConfigServiceImpl(ConfigRepository repository, - ApplicationRepository applicationRepository, - DatasourceRepository datasourceRepository) { + public ConfigServiceImpl( + ConfigRepository repository, + ApplicationRepository applicationRepository, + DatasourceRepository datasourceRepository) { super(repository, applicationRepository, datasourceRepository); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CrudService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CrudService.java index 18176f6b2dbb..3a634fce3b59 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CrudService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CrudService.java @@ -28,5 +28,4 @@ default Mono<T> archiveByIdAndBranchName(ID id, String branchName) { } Map<String, Object> getAnalyticsProperties(T savedResource); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CurlImporterService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CurlImporterService.java index fb7cc248483e..5edc126e8ff8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CurlImporterService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CurlImporterService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.CurlImporterServiceCE; -public interface CurlImporterService extends CurlImporterServiceCE { - -} +public interface CurlImporterService extends CurlImporterServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CurlImporterServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CurlImporterServiceImpl.java index 5dc78778ed60..e2e98705397f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CurlImporterServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CurlImporterServiceImpl.java @@ -17,8 +17,7 @@ public CurlImporterServiceImpl( NewPageService newPageService, ResponseUtils responseUtils, ObjectMapper objectMapper, - PagePermission pagePermission - ) { + PagePermission pagePermission) { super(pluginService, layoutActionService, newPageService, responseUtils, objectMapper, pagePermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CustomJSLibService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CustomJSLibService.java index 27ae3194b8b1..3526a2a9e6dc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CustomJSLibService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CustomJSLibService.java @@ -2,5 +2,4 @@ import com.appsmith.server.services.ce.CustomJSLibServiceCE; -public interface CustomJSLibService extends CustomJSLibServiceCE { -} \ No newline at end of file +public interface CustomJSLibService extends CustomJSLibServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CustomJSLibServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CustomJSLibServiceImpl.java index bc8c35d24c31..c0239e2af6fa 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CustomJSLibServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CustomJSLibServiceImpl.java @@ -13,10 +13,21 @@ @Slf4j public class CustomJSLibServiceImpl extends CustomJSLibServiceCEImpl implements CustomJSLibService { - public CustomJSLibServiceImpl(Scheduler scheduler, Validator validator, MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, CustomJSLibRepository repository, - ApplicationService applicationService, AnalyticsService analyticsService) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, applicationService, + public CustomJSLibServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + CustomJSLibRepository repository, + ApplicationService applicationService, + AnalyticsService analyticsService) { + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + applicationService, analyticsService); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextService.java index 966058fe1848..a07a90bf2ece 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.DatasourceContextServiceCE; -public interface DatasourceContextService extends DatasourceContextServiceCE { - -} +public interface DatasourceContextService extends DatasourceContextServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextServiceImpl.java index 1835021f6eef..e035453e32bd 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextServiceImpl.java @@ -11,13 +11,20 @@ @Slf4j public class DatasourceContextServiceImpl extends DatasourceContextServiceCEImpl implements DatasourceContextService { - public DatasourceContextServiceImpl(@Lazy DatasourceService datasourceService, - DatasourceStorageService datasourceStorageService, - PluginService pluginService, - PluginExecutorHelper pluginExecutorHelper, - ConfigService configService, - DatasourcePermission datasourcePermission) { + public DatasourceContextServiceImpl( + @Lazy DatasourceService datasourceService, + DatasourceStorageService datasourceStorageService, + PluginService pluginService, + PluginExecutorHelper pluginExecutorHelper, + ConfigService configService, + DatasourcePermission datasourcePermission) { - super(datasourceService, datasourceStorageService, pluginService, pluginExecutorHelper, configService, datasourcePermission); + super( + datasourceService, + datasourceStorageService, + pluginService, + pluginExecutorHelper, + configService, + datasourcePermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceService.java index b3527290fbad..50464094f149 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.DatasourceServiceCE; -public interface DatasourceService extends DatasourceServiceCE { - -} +public interface DatasourceService extends DatasourceServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceServiceImpl.java index 1603774bae13..d06c30a31fee 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceServiceImpl.java @@ -6,7 +6,6 @@ import com.appsmith.server.repositories.NewActionRepository; import com.appsmith.server.services.ce.DatasourceServiceCEImpl; import com.appsmith.server.solutions.DatasourcePermission; -import com.appsmith.server.solutions.DatasourceStorageTransferSolution; import com.appsmith.server.solutions.WorkspacePermission; import jakarta.validation.Validator; import lombok.extern.slf4j.Slf4j; @@ -19,28 +18,42 @@ @Service public class DatasourceServiceImpl extends DatasourceServiceCEImpl implements DatasourceService { - public DatasourceServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - DatasourceRepository repository, - WorkspaceService workspaceService, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - PluginService pluginService, - PluginExecutorHelper pluginExecutorHelper, - PolicyGenerator policyGenerator, - SequenceService sequenceService, - NewActionRepository newActionRepository, - DatasourceContextService datasourceContextService, - DatasourcePermission datasourcePermission, - WorkspacePermission workspacePermission, - DatasourceStorageService datasourceStorageService) { - - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, workspaceService, - analyticsService, sessionUserService, pluginService, pluginExecutorHelper, policyGenerator, - sequenceService, newActionRepository, datasourceContextService, datasourcePermission, - workspacePermission, datasourceStorageService); + public DatasourceServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + DatasourceRepository repository, + WorkspaceService workspaceService, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + PluginService pluginService, + PluginExecutorHelper pluginExecutorHelper, + PolicyGenerator policyGenerator, + SequenceService sequenceService, + NewActionRepository newActionRepository, + DatasourceContextService datasourceContextService, + DatasourcePermission datasourcePermission, + WorkspacePermission workspacePermission, + DatasourceStorageService datasourceStorageService) { + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + workspaceService, + analyticsService, + sessionUserService, + pluginService, + pluginExecutorHelper, + policyGenerator, + sequenceService, + newActionRepository, + datasourceContextService, + datasourcePermission, + workspacePermission, + datasourceStorageService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStorageService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStorageService.java index 95b40a7dcd3e..c3904dd1f841 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStorageService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStorageService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.DatasourceStorageServiceCE; -public interface DatasourceStorageService extends DatasourceStorageServiceCE { - -} +public interface DatasourceStorageService extends DatasourceStorageServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStorageServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStorageServiceImpl.java index dabae49c80bc..3a732d8e92c4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStorageServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStorageServiceImpl.java @@ -11,13 +11,19 @@ @Service @Slf4j public class DatasourceStorageServiceImpl extends DatasourceStorageServiceCEImpl implements DatasourceStorageService { - public DatasourceStorageServiceImpl(DatasourceStorageRepository repository, - DatasourceStorageTransferSolution datasourceStorageTransferSolution, - DatasourcePermission datasourcePermission, - PluginService pluginService, - PluginExecutorHelper pluginExecutorHelper, - AnalyticsService analyticsService) { - super(repository, datasourceStorageTransferSolution, datasourcePermission, pluginService, pluginExecutorHelper, + public DatasourceStorageServiceImpl( + DatasourceStorageRepository repository, + DatasourceStorageTransferSolution datasourceStorageTransferSolution, + DatasourcePermission datasourcePermission, + PluginService pluginService, + PluginExecutorHelper pluginExecutorHelper, + AnalyticsService analyticsService) { + super( + repository, + datasourceStorageTransferSolution, + datasourcePermission, + pluginService, + pluginExecutorHelper, analyticsService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStructureService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStructureService.java index 2c43a13ac70e..abd24bcb6f0e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStructureService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStructureService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.DatasourceStructureServiceCE; -public interface DatasourceStructureService extends DatasourceStructureServiceCE { - -} +public interface DatasourceStructureService extends DatasourceStructureServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStructureServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStructureServiceImpl.java index de05e31c30d9..a013dd0d279f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStructureServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceStructureServiceImpl.java @@ -7,8 +7,8 @@ @Service @Slf4j -public class -DatasourceStructureServiceImpl extends DatasourceStructureServiceCEImpl implements DatasourceStructureService { +public class DatasourceStructureServiceImpl extends DatasourceStructureServiceCEImpl + implements DatasourceStructureService { public DatasourceStructureServiceImpl(DatasourceStructureRepository repository) { super(repository); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/FeatureFlagService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/FeatureFlagService.java index 1c82f849a977..a2458b13e68e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/FeatureFlagService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/FeatureFlagService.java @@ -2,5 +2,4 @@ import com.appsmith.server.services.ce.FeatureFlagServiceCE; -public interface FeatureFlagService extends FeatureFlagServiceCE { -} \ No newline at end of file +public interface FeatureFlagService extends FeatureFlagServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/FeatureFlagServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/FeatureFlagServiceImpl.java index b2130d33a5e0..28da269f282b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/FeatureFlagServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/FeatureFlagServiceImpl.java @@ -7,11 +7,21 @@ @Component public class FeatureFlagServiceImpl extends FeatureFlagServiceCEImpl implements FeatureFlagService { - public FeatureFlagServiceImpl(SessionUserService sessionUserService, FF4j ff4j, TenantService tenantService, - ConfigService configService, CloudServicesConfig cloudServicesConfig, - UserIdentifierService userIdentifierService, - CacheableFeatureFlagHelper cacheableFeatureFlagHelper) { - super(sessionUserService, ff4j, tenantService, configService, cloudServicesConfig, userIdentifierService, cacheableFeatureFlagHelper); + public FeatureFlagServiceImpl( + SessionUserService sessionUserService, + FF4j ff4j, + TenantService tenantService, + ConfigService configService, + CloudServicesConfig cloudServicesConfig, + UserIdentifierService userIdentifierService, + CacheableFeatureFlagHelper cacheableFeatureFlagHelper) { + super( + sessionUserService, + ff4j, + tenantService, + configService, + cloudServicesConfig, + userIdentifierService, + cacheableFeatureFlagHelper); } } - diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitService.java index 2a07f6f4b13e..f5dcc584185c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.GitServiceCE; -public interface GitService extends GitServiceCE { - -} +public interface GitService extends GitServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java index a3740c141949..bf28c7e18fc9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java @@ -1,6 +1,5 @@ package com.appsmith.server.services; - import com.appsmith.external.git.GitExecutor; import com.appsmith.git.service.GitExecutorImpl; import com.appsmith.server.configurations.EmailConfig; @@ -17,7 +16,6 @@ import com.appsmith.server.solutions.ImportExportApplicationService; import com.appsmith.server.solutions.PagePermission; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Import; import org.springframework.stereotype.Service; @@ -25,37 +23,58 @@ @Service @Import({GitExecutorImpl.class}) public class GitServiceImpl extends GitServiceCEImpl implements GitService { - public GitServiceImpl(UserService userService, - UserDataService userDataService, - SessionUserService sessionUserService, - ApplicationService applicationService, - ApplicationPageService applicationPageService, - NewPageService newPageService, - NewActionService newActionService, - ActionCollectionService actionCollectionService, - GitFileUtils fileUtils, - ImportExportApplicationService importExportApplicationService, - GitExecutor gitExecutor, - ResponseUtils responseUtils, - EmailConfig emailConfig, - AnalyticsService analyticsService, - GitCloudServicesUtils gitCloudServicesUtils, - GitDeployKeysRepository gitDeployKeysRepository, - DatasourceService datasourceService, - PluginService pluginService, - DatasourcePermission datasourcePermission, - ApplicationPermission applicationPermission, - PagePermission pagePermission, - ActionPermission actionPermission, - WorkspaceService workspaceService, - RedisUtils redisUtils, - ExecutionTimeLogging executionTimeLogging) { + public GitServiceImpl( + UserService userService, + UserDataService userDataService, + SessionUserService sessionUserService, + ApplicationService applicationService, + ApplicationPageService applicationPageService, + NewPageService newPageService, + NewActionService newActionService, + ActionCollectionService actionCollectionService, + GitFileUtils fileUtils, + ImportExportApplicationService importExportApplicationService, + GitExecutor gitExecutor, + ResponseUtils responseUtils, + EmailConfig emailConfig, + AnalyticsService analyticsService, + GitCloudServicesUtils gitCloudServicesUtils, + GitDeployKeysRepository gitDeployKeysRepository, + DatasourceService datasourceService, + PluginService pluginService, + DatasourcePermission datasourcePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission, + WorkspaceService workspaceService, + RedisUtils redisUtils, + ExecutionTimeLogging executionTimeLogging) { - super(userService, userDataService, sessionUserService, applicationService, applicationPageService, - newPageService, newActionService, actionCollectionService, fileUtils, importExportApplicationService, - gitExecutor, responseUtils, emailConfig, analyticsService, gitCloudServicesUtils, gitDeployKeysRepository, - datasourceService, pluginService, datasourcePermission, applicationPermission, pagePermission, - actionPermission, workspaceService, redisUtils, executionTimeLogging); + super( + userService, + userDataService, + sessionUserService, + applicationService, + applicationPageService, + newPageService, + newActionService, + actionCollectionService, + fileUtils, + importExportApplicationService, + gitExecutor, + responseUtils, + emailConfig, + analyticsService, + gitCloudServicesUtils, + gitDeployKeysRepository, + datasourceService, + pluginService, + datasourcePermission, + applicationPermission, + pagePermission, + actionPermission, + workspaceService, + redisUtils, + executionTimeLogging); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GoogleRecaptchaServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GoogleRecaptchaServiceImpl.java index f1c03150d39a..3334b6661101 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GoogleRecaptchaServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GoogleRecaptchaServiceImpl.java @@ -9,9 +9,10 @@ @Service public class GoogleRecaptchaServiceImpl extends GoogleRecaptchaServiceCEImpl implements CaptchaService { - public GoogleRecaptchaServiceImpl(WebClient.Builder webClientBuilder, - GoogleRecaptchaConfig googleRecaptchaConfig, - ObjectMapper objectMapper) { + public GoogleRecaptchaServiceImpl( + WebClient.Builder webClientBuilder, + GoogleRecaptchaConfig googleRecaptchaConfig, + ObjectMapper objectMapper) { super(webClientBuilder, googleRecaptchaConfig, objectMapper); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GroupService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GroupService.java index d99379c8f1ab..8690883f9fe1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GroupService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GroupService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.GroupServiceCE; -public interface GroupService extends GroupServiceCE { - -} +public interface GroupService extends GroupServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GroupServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GroupServiceImpl.java index 7fe9013cdc56..9a98542dc260 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GroupServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GroupServiceImpl.java @@ -13,15 +13,22 @@ @Slf4j public class GroupServiceImpl extends GroupServiceCEImpl implements GroupService { - public GroupServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - GroupRepository repository, - AnalyticsService analyticsService, - SessionUserService sessionUserService) { + public GroupServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + GroupRepository repository, + AnalyticsService analyticsService, + SessionUserService sessionUserService) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, sessionUserService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/HealthCheckService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/HealthCheckService.java index d02e539f7687..04d2c9e17072 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/HealthCheckService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/HealthCheckService.java @@ -2,5 +2,4 @@ import com.appsmith.server.services.ce.HealthCheckServiceCE; -public interface HealthCheckService extends HealthCheckServiceCE { -} +public interface HealthCheckService extends HealthCheckServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/HealthCheckServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/HealthCheckServiceImpl.java index 2637c5a5532f..64a6614d4a08 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/HealthCheckServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/HealthCheckServiceImpl.java @@ -5,11 +5,11 @@ import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.stereotype.Component; - @Component public class HealthCheckServiceImpl extends HealthCheckServiceCEImpl implements HealthCheckService { - public HealthCheckServiceImpl(ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, - ReactiveMongoTemplate reactiveMongoTemplate) { + public HealthCheckServiceImpl( + ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, + ReactiveMongoTemplate reactiveMongoTemplate) { super(reactiveRedisConnectionFactory, reactiveMongoTemplate); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ItemService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ItemService.java index cca3908e2ce4..7e881d8998e6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ItemService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ItemService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ItemServiceCE; -public interface ItemService extends ItemServiceCE { - -} +public interface ItemService extends ItemServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ItemServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ItemServiceImpl.java index ec45b2e60d31..29dfb6480c26 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ItemServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ItemServiceImpl.java @@ -8,11 +8,12 @@ @Slf4j public class ItemServiceImpl extends ItemServiceCEImpl implements ItemService { - public ItemServiceImpl(ApiTemplateService apiTemplateService, - PluginService pluginService, - MarketplaceService marketplaceService, - NewActionService newActionService, - LayoutActionService layoutActionService) { + public ItemServiceImpl( + ApiTemplateService apiTemplateService, + PluginService pluginService, + MarketplaceService marketplaceService, + NewActionService newActionService, + LayoutActionService layoutActionService) { super(apiTemplateService, pluginService, marketplaceService, newActionService, layoutActionService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionService.java index 24a439fdb7f7..4161cd6ef109 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.LayoutActionServiceCE; -public interface LayoutActionService extends LayoutActionServiceCE { - -} +public interface LayoutActionService extends LayoutActionServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionServiceImpl.java index bad5d9d605ce..994109473e68 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionServiceImpl.java @@ -13,23 +13,34 @@ @Slf4j public class LayoutActionServiceImpl extends LayoutActionServiceCEImpl implements LayoutActionService { - public LayoutActionServiceImpl(ObjectMapper objectMapper, - AnalyticsService analyticsService, - NewPageService newPageService, - NewActionService newActionService, - PageLoadActionsUtil pageLoadActionsUtil, - SessionUserService sessionUserService, - ActionCollectionService actionCollectionService, - CollectionService collectionService, - ApplicationService applicationService, - ResponseUtils responseUtils, - DatasourceService datasourceService, - PagePermission pagePermission, - ActionPermission actionPermission) { - - super(objectMapper, analyticsService, newPageService, newActionService, pageLoadActionsUtil, sessionUserService, - actionCollectionService, collectionService, applicationService, responseUtils, datasourceService, - pagePermission, actionPermission); + public LayoutActionServiceImpl( + ObjectMapper objectMapper, + AnalyticsService analyticsService, + NewPageService newPageService, + NewActionService newActionService, + PageLoadActionsUtil pageLoadActionsUtil, + SessionUserService sessionUserService, + ActionCollectionService actionCollectionService, + CollectionService collectionService, + ApplicationService applicationService, + ResponseUtils responseUtils, + DatasourceService datasourceService, + PagePermission pagePermission, + ActionPermission actionPermission) { + super( + objectMapper, + analyticsService, + newPageService, + newActionService, + pageLoadActionsUtil, + sessionUserService, + actionCollectionService, + collectionService, + applicationService, + responseUtils, + datasourceService, + pagePermission, + actionPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutCollectionService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutCollectionService.java index 21b19791a162..80a633294b49 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutCollectionService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutCollectionService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.LayoutCollectionServiceCE; -public interface LayoutCollectionService extends LayoutCollectionServiceCE { - -} +public interface LayoutCollectionService extends LayoutCollectionServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutCollectionServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutCollectionServiceImpl.java index e2075bfe257a..32a51097cc96 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutCollectionServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutCollectionServiceImpl.java @@ -13,18 +13,28 @@ @Slf4j public class LayoutCollectionServiceImpl extends LayoutCollectionServiceCEImpl implements LayoutCollectionService { - public LayoutCollectionServiceImpl(NewPageService newPageService, - LayoutActionService layoutActionService, - RefactoringSolution refactoringSolution, - ActionCollectionService actionCollectionService, - NewActionService newActionService, - AnalyticsService analyticsService, - ResponseUtils responseUtils, - ActionCollectionRepository actionCollectionRepository, - PagePermission pagePermission, - ActionPermission actionPermission) { + public LayoutCollectionServiceImpl( + NewPageService newPageService, + LayoutActionService layoutActionService, + RefactoringSolution refactoringSolution, + ActionCollectionService actionCollectionService, + NewActionService newActionService, + AnalyticsService analyticsService, + ResponseUtils responseUtils, + ActionCollectionRepository actionCollectionRepository, + PagePermission pagePermission, + ActionPermission actionPermission) { - super(newPageService, layoutActionService, refactoringSolution, actionCollectionService, newActionService, analyticsService, - responseUtils, actionCollectionRepository, pagePermission, actionPermission); + super( + newPageService, + layoutActionService, + refactoringSolution, + actionCollectionService, + newActionService, + analyticsService, + responseUtils, + actionCollectionRepository, + pagePermission, + actionPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutService.java index 063847511062..4633f0c4d095 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.LayoutServiceCE; -public interface LayoutService extends LayoutServiceCE { - -} +public interface LayoutService extends LayoutServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutServiceImpl.java index e06465de6650..db46f8d67d99 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutServiceImpl.java @@ -10,9 +10,8 @@ @Service public class LayoutServiceImpl extends LayoutServiceCEImpl implements LayoutService { - public LayoutServiceImpl(NewPageService newPageService, ResponseUtils responseUtils, - PagePermission pagePermission) { + public LayoutServiceImpl( + NewPageService newPageService, ResponseUtils responseUtils, PagePermission pagePermission) { super(newPageService, responseUtils, pagePermission); } } - diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MarketplaceService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MarketplaceService.java index b059b1e5cf2e..bb3d33374876 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MarketplaceService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MarketplaceService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.MarketplaceServiceCE; -public interface MarketplaceService extends MarketplaceServiceCE { - -} +public interface MarketplaceService extends MarketplaceServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MarketplaceServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MarketplaceServiceImpl.java index d703790747ee..d7260f1b2288 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MarketplaceServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MarketplaceServiceImpl.java @@ -11,9 +11,8 @@ @Service public class MarketplaceServiceImpl extends MarketplaceServiceCEImpl implements MarketplaceService { - public MarketplaceServiceImpl(WebClient.Builder webClientBuilder, - CloudServicesConfig cloudServicesConfig, - ObjectMapper objectMapper) { + public MarketplaceServiceImpl( + WebClient.Builder webClientBuilder, CloudServicesConfig cloudServicesConfig, ObjectMapper objectMapper) { super(webClientBuilder, cloudServicesConfig, objectMapper); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MockDataService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MockDataService.java index 0227ae6e02cb..d780daef55be 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MockDataService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MockDataService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.MockDataServiceCE; -public interface MockDataService extends MockDataServiceCE { - -} +public interface MockDataService extends MockDataServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MockDataServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MockDataServiceImpl.java index 075ab6a45e57..3338b0837d37 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MockDataServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/MockDataServiceImpl.java @@ -9,10 +9,11 @@ @Service public class MockDataServiceImpl extends MockDataServiceCEImpl implements MockDataService { - public MockDataServiceImpl(CloudServicesConfig cloudServicesConfig, - DatasourceService datasourceService, - AnalyticsService analyticsService, - SessionUserService sessionUserService) { + public MockDataServiceImpl( + CloudServicesConfig cloudServicesConfig, + DatasourceService datasourceService, + AnalyticsService analyticsService, + SessionUserService sessionUserService) { super(cloudServicesConfig, datasourceService, analyticsService, sessionUserService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionService.java index bd7dc08f3127..d5e4a4cd8539 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.NewActionServiceCE; -public interface NewActionService extends NewActionServiceCE { - -} +public interface NewActionService extends NewActionServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionServiceImpl.java index 6dca66e5b760..adf7a7cba3db 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewActionServiceImpl.java @@ -2,7 +2,6 @@ import com.appsmith.server.acl.PolicyGenerator; import com.appsmith.server.helpers.PluginExecutorHelper; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.helpers.ResponseUtils; import com.appsmith.server.repositories.NewActionRepository; import com.appsmith.server.services.ce.NewActionServiceCEImpl; @@ -10,6 +9,7 @@ import com.appsmith.server.solutions.ApplicationPermission; import com.appsmith.server.solutions.DatasourcePermission; import com.appsmith.server.solutions.PagePermission; +import com.appsmith.server.solutions.PolicySolution; import io.micrometer.observation.ObservationRegistry; import jakarta.validation.Validator; import lombok.extern.slf4j.Slf4j; @@ -22,34 +22,52 @@ @Slf4j public class NewActionServiceImpl extends NewActionServiceCEImpl implements NewActionService { - public NewActionServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - NewActionRepository repository, - AnalyticsService analyticsService, - DatasourceService datasourceService, - PluginService pluginService, - PluginExecutorHelper pluginExecutorHelper, - MarketplaceService marketplaceService, - PolicyGenerator policyGenerator, - NewPageService newPageService, - ApplicationService applicationService, - PolicySolution policySolution, - ConfigService configService, - ResponseUtils responseUtils, - PermissionGroupService permissionGroupService, - DatasourcePermission datasourcePermission, - ApplicationPermission applicationPermission, - PagePermission pagePermission, - ActionPermission actionPermission, - ObservationRegistry observationRegistry) { - - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - datasourceService, pluginService, pluginExecutorHelper, marketplaceService, - policyGenerator, newPageService, applicationService, policySolution, - configService, responseUtils, permissionGroupService, datasourcePermission, - applicationPermission, pagePermission, actionPermission, observationRegistry); + public NewActionServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + NewActionRepository repository, + AnalyticsService analyticsService, + DatasourceService datasourceService, + PluginService pluginService, + PluginExecutorHelper pluginExecutorHelper, + MarketplaceService marketplaceService, + PolicyGenerator policyGenerator, + NewPageService newPageService, + ApplicationService applicationService, + PolicySolution policySolution, + ConfigService configService, + ResponseUtils responseUtils, + PermissionGroupService permissionGroupService, + DatasourcePermission datasourcePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission, + ObservationRegistry observationRegistry) { + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + datasourceService, + pluginService, + pluginExecutorHelper, + marketplaceService, + policyGenerator, + newPageService, + applicationService, + policySolution, + configService, + responseUtils, + permissionGroupService, + datasourcePermission, + applicationPermission, + pagePermission, + actionPermission, + observationRegistry); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageService.java index 96bbf8a51829..134bb936d59c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.NewPageServiceCE; -public interface NewPageService extends NewPageServiceCE { - -} +public interface NewPageService extends NewPageServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageServiceImpl.java index 0a3a15d2b849..debc3905b142 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NewPageServiceImpl.java @@ -17,20 +17,32 @@ @Slf4j public class NewPageServiceImpl extends NewPageServiceCEImpl implements NewPageService { - public NewPageServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - NewPageRepository repository, - AnalyticsService analyticsService, - ApplicationService applicationService, - UserDataService userDataService, - ResponseUtils responseUtils, - ApplicationPermission applicationPermission, - PagePermission pagePermission, - ApplicationSnapshotRepository applicationSnapshotRepository) { + public NewPageServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + NewPageRepository repository, + AnalyticsService analyticsService, + ApplicationService applicationService, + UserDataService userDataService, + ResponseUtils responseUtils, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ApplicationSnapshotRepository applicationSnapshotRepository) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - applicationService, userDataService, responseUtils, applicationPermission, pagePermission, applicationSnapshotRepository); + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + applicationService, + userDataService, + responseUtils, + applicationPermission, + pagePermission, + applicationSnapshotRepository); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NotificationService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NotificationService.java index 7ce386e4fbd8..ad7e918b28ef 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NotificationService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NotificationService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.NotificationServiceCE; -public interface NotificationService extends NotificationServiceCE { - -} +public interface NotificationService extends NotificationServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NotificationServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NotificationServiceImpl.java index 464aec0e3cdc..6316bbddec8f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NotificationServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/NotificationServiceImpl.java @@ -14,16 +14,24 @@ @Service public class NotificationServiceImpl extends NotificationServiceCEImpl implements NotificationService { - public NotificationServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - NotificationRepository repository, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - ResponseUtils responseUtils) { + public NotificationServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + NotificationRepository repository, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + ResponseUtils responseUtils) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - sessionUserService, responseUtils); + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + sessionUserService, + responseUtils); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PermissionGroupService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PermissionGroupService.java index a05aef891175..2aec6a1f3ed5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PermissionGroupService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PermissionGroupService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.PermissionGroupServiceCE; -public interface PermissionGroupService extends PermissionGroupServiceCE { - -} +public interface PermissionGroupService extends PermissionGroupServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PermissionGroupServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PermissionGroupServiceImpl.java index 2831b9af1ad9..826f7290daa4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PermissionGroupServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PermissionGroupServiceImpl.java @@ -1,11 +1,11 @@ package com.appsmith.server.services; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.repositories.ConfigRepository; import com.appsmith.server.repositories.PermissionGroupRepository; import com.appsmith.server.repositories.UserRepository; import com.appsmith.server.services.ce.PermissionGroupServiceCEImpl; import com.appsmith.server.solutions.PermissionGroupPermission; +import com.appsmith.server.solutions.PolicySolution; import jakarta.validation.Validator; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; import org.springframework.data.mongodb.core.convert.MongoConverter; @@ -15,21 +15,32 @@ @Service public class PermissionGroupServiceImpl extends PermissionGroupServiceCEImpl implements PermissionGroupService { - public PermissionGroupServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - PermissionGroupRepository repository, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - TenantService tenantService, - UserRepository userRepository, - PolicySolution policySolution, - ConfigRepository configRepository, - PermissionGroupPermission permissionGroupPermission) { + public PermissionGroupServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + PermissionGroupRepository repository, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + TenantService tenantService, + UserRepository userRepository, + PolicySolution policySolution, + ConfigRepository configRepository, + PermissionGroupPermission permissionGroupPermission) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - sessionUserService, tenantService, userRepository, policySolution, configRepository, + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + sessionUserService, + tenantService, + userRepository, + policySolution, + configRepository, permissionGroupPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PluginService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PluginService.java index 235cfd62149a..88d903f95f0a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PluginService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PluginService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.PluginServiceCE; -public interface PluginService extends PluginServiceCE { - -} +public interface PluginService extends PluginServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PluginServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PluginServiceImpl.java index 1b75393a0b4e..56ab881b91bc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PluginServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PluginServiceImpl.java @@ -17,21 +17,30 @@ @Service public class PluginServiceImpl extends PluginServiceCEImpl implements PluginService { - public PluginServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - PluginRepository repository, - AnalyticsService analyticsService, - WorkspaceService workspaceService, - PluginManager pluginManager, - ReactiveRedisTemplate<String, - String> reactiveTemplate, - ChannelTopic topic, - ObjectMapper objectMapper) { - - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - workspaceService, pluginManager, reactiveTemplate, topic, objectMapper); + public PluginServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + PluginRepository repository, + AnalyticsService analyticsService, + WorkspaceService workspaceService, + PluginManager pluginManager, + ReactiveRedisTemplate<String, String> reactiveTemplate, + ChannelTopic topic, + ObjectMapper objectMapper) { + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + workspaceService, + pluginManager, + reactiveTemplate, + topic, + objectMapper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PostmanImporterService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PostmanImporterService.java index a509bea3193e..420f33cd14d1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PostmanImporterService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PostmanImporterService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.PostmanImporterServiceCE; -public interface PostmanImporterService extends PostmanImporterServiceCE { - -} +public interface PostmanImporterService extends PostmanImporterServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PostmanImporterServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PostmanImporterServiceImpl.java index 690a4e92ab53..f3aff415a7de 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PostmanImporterServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/PostmanImporterServiceImpl.java @@ -10,9 +10,8 @@ @Service public class PostmanImporterServiceImpl extends PostmanImporterServiceCEImpl implements PostmanImporterService { - public PostmanImporterServiceImpl(NewPageService newPageService, - ResponseUtils responseUtils, - PagePermission pagePermission) { + public PostmanImporterServiceImpl( + NewPageService newPageService, ResponseUtils responseUtils, PagePermission pagePermission) { super(newPageService, responseUtils, pagePermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ProviderService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ProviderService.java index c1a5c8bbc568..19a5496ccb7e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ProviderService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ProviderService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ProviderServiceCE; -public interface ProviderService extends ProviderServiceCE { - -} +public interface ProviderService extends ProviderServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ProviderServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ProviderServiceImpl.java index b820ba023f55..9714a8cb542b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ProviderServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ProviderServiceImpl.java @@ -13,13 +13,13 @@ @Slf4j public class ProviderServiceImpl extends ProviderServiceCEImpl implements ProviderService { - public ProviderServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ProviderRepository repository, - AnalyticsService analyticsService) { + public ProviderServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ProviderRepository repository, + AnalyticsService analyticsService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SequenceService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SequenceService.java index 5b870b2e84d0..d4c5aac5ac71 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SequenceService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SequenceService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.SequenceServiceCE; -public interface SequenceService extends SequenceServiceCE { - -} +public interface SequenceService extends SequenceServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SequenceServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SequenceServiceImpl.java index 71a1c6853d26..cfbe9336085d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SequenceServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SequenceServiceImpl.java @@ -12,5 +12,4 @@ public class SequenceServiceImpl extends SequenceServiceCEImpl implements Sequen public SequenceServiceImpl(ReactiveMongoTemplate mongoTemplate) { super(mongoTemplate); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SessionUserService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SessionUserService.java index f61178edf3b3..8bf7fb6b0752 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SessionUserService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SessionUserService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.SessionUserServiceCE; -public interface SessionUserService extends SessionUserServiceCE { - -} +public interface SessionUserService extends SessionUserServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SessionUserServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SessionUserServiceImpl.java index 3a206f5555ea..ac0525968bf4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SessionUserServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/SessionUserServiceImpl.java @@ -10,8 +10,8 @@ @Service public class SessionUserServiceImpl extends SessionUserServiceCEImpl implements SessionUserService { - public SessionUserServiceImpl(UserRepository userRepository, - ReactiveRedisOperations<String, Object> redisOperations) { + public SessionUserServiceImpl( + UserRepository userRepository, ReactiveRedisOperations<String, Object> redisOperations) { super(userRepository, redisOperations); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/TenantService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/TenantService.java index 9bec676a3224..30b371afa49e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/TenantService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/TenantService.java @@ -2,5 +2,4 @@ import com.appsmith.server.services.ce.TenantServiceCE; -public interface TenantService extends TenantServiceCE { -} +public interface TenantService extends TenantServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/TenantServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/TenantServiceImpl.java index da2931994c0b..d89bf319eb0a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/TenantServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/TenantServiceImpl.java @@ -11,13 +11,14 @@ @Service public class TenantServiceImpl extends TenantServiceCEImpl implements TenantService { - public TenantServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - TenantRepository repository, - AnalyticsService analyticsService, - ConfigService configService) { + public TenantServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + TenantRepository repository, + AnalyticsService analyticsService, + ConfigService configService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, configService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ThemeService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ThemeService.java index 367639e29b3d..1c3f843c513c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ThemeService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ThemeService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.ThemeServiceCE; -public interface ThemeService extends ThemeServiceCE { - -} +public interface ThemeService extends ThemeServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ThemeServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ThemeServiceImpl.java index 70c8c4f0cdb3..18713b922467 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ThemeServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ThemeServiceImpl.java @@ -15,17 +15,27 @@ @Slf4j @Service public class ThemeServiceImpl extends ThemeServiceCEImpl implements ThemeService { - public ThemeServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ThemeRepository repository, - AnalyticsService analyticsService, - ApplicationRepository applicationRepository, - ApplicationService applicationService, - PolicyGenerator policyGenerator, - ApplicationPermission applicationPermission) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - applicationRepository, applicationService, policyGenerator, applicationPermission); + public ThemeServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ThemeRepository repository, + AnalyticsService analyticsService, + ApplicationRepository applicationRepository, + ApplicationService applicationService, + PolicyGenerator policyGenerator, + ApplicationPermission applicationPermission) { + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + applicationRepository, + applicationService, + policyGenerator, + applicationPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UsagePulseService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UsagePulseService.java index 03d3a68c601c..bae48039c7b1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UsagePulseService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UsagePulseService.java @@ -2,5 +2,4 @@ import com.appsmith.server.services.ce.UsagePulseServiceCE; -public interface UsagePulseService extends UsagePulseServiceCE { -} +public interface UsagePulseService extends UsagePulseServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UsagePulseServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UsagePulseServiceImpl.java index 71c63031fea3..f20294f9a1ba 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UsagePulseServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UsagePulseServiceImpl.java @@ -8,13 +8,13 @@ @Service public class UsagePulseServiceImpl extends UsagePulseServiceCEImpl implements UsagePulseService { - public UsagePulseServiceImpl(UsagePulseRepository repository, - SessionUserService sessionUserService, - UserService userService, - TenantService tenantService, - ConfigService configService, - CommonConfig commonConfig) { + public UsagePulseServiceImpl( + UsagePulseRepository repository, + SessionUserService sessionUserService, + UserService userService, + TenantService tenantService, + ConfigService configService, + CommonConfig commonConfig) { super(repository, sessionUserService, userService, tenantService, configService, commonConfig); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserDataService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserDataService.java index 3ed8073293d0..f301d6213f19 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserDataService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserDataService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.UserDataServiceCE; -public interface UserDataService extends UserDataServiceCE { - -} +public interface UserDataService extends UserDataServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserDataServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserDataServiceImpl.java index 70763bc2fd15..7db1d8be8429 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserDataServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserDataServiceImpl.java @@ -15,23 +15,36 @@ @Service public class UserDataServiceImpl extends UserDataServiceCEImpl implements UserDataService { - public UserDataServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - UserDataRepository repository, - AnalyticsService analyticsService, - UserRepository userRepository, - SessionUserService sessionUserService, - AssetService assetService, - ReleaseNotesService releaseNotesService, - FeatureFlagService featureFlagService, - UserChangedHandler userChangedHandler, - ApplicationRepository applicationRepository, - TenantService tenantService) { + public UserDataServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + UserDataRepository repository, + AnalyticsService analyticsService, + UserRepository userRepository, + SessionUserService sessionUserService, + AssetService assetService, + ReleaseNotesService releaseNotesService, + FeatureFlagService featureFlagService, + UserChangedHandler userChangedHandler, + ApplicationRepository applicationRepository, + TenantService tenantService) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, userRepository, - sessionUserService, assetService, releaseNotesService, featureFlagService, userChangedHandler, - applicationRepository, tenantService); + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + userRepository, + sessionUserService, + assetService, + releaseNotesService, + featureFlagService, + userChangedHandler, + applicationRepository, + tenantService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserIdentifierService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserIdentifierService.java index a0f6987d378d..c726b477e285 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserIdentifierService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserIdentifierService.java @@ -2,5 +2,4 @@ import com.appsmith.server.services.ce.UserIdentifierServiceCE; -public interface UserIdentifierService extends UserIdentifierServiceCE { -} +public interface UserIdentifierService extends UserIdentifierServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserService.java index 05c11526b983..58e25f101e7b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.UserServiceCE; -public interface UserService extends UserServiceCE { - -} +public interface UserService extends UserServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserServiceImpl.java index 0636b191d1dc..d83ad14f30e9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserServiceImpl.java @@ -3,13 +3,13 @@ import com.appsmith.external.services.EncryptionService; import com.appsmith.server.configurations.CommonConfig; import com.appsmith.server.configurations.EmailConfig; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.helpers.UserUtils; import com.appsmith.server.notifications.EmailSender; import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.PasswordResetTokenRepository; import com.appsmith.server.repositories.UserRepository; import com.appsmith.server.services.ce.UserServiceCEImpl; +import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.solutions.UserChangedHandler; import jakarta.validation.Validator; import lombok.extern.slf4j.Slf4j; @@ -23,31 +23,50 @@ @Service public class UserServiceImpl extends UserServiceCEImpl implements UserService { - public UserServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - UserRepository repository, - WorkspaceService workspaceService, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - PasswordResetTokenRepository passwordResetTokenRepository, - PasswordEncoder passwordEncoder, - EmailSender emailSender, - ApplicationRepository applicationRepository, - PolicySolution policySolution, - CommonConfig commonConfig, - EmailConfig emailConfig, - UserChangedHandler userChangedHandler, - EncryptionService encryptionService, - UserDataService userDataService, - TenantService tenantService, - PermissionGroupService permissionGroupService, - UserUtils userUtils) { + public UserServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + UserRepository repository, + WorkspaceService workspaceService, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + PasswordResetTokenRepository passwordResetTokenRepository, + PasswordEncoder passwordEncoder, + EmailSender emailSender, + ApplicationRepository applicationRepository, + PolicySolution policySolution, + CommonConfig commonConfig, + EmailConfig emailConfig, + UserChangedHandler userChangedHandler, + EncryptionService encryptionService, + UserDataService userDataService, + TenantService tenantService, + PermissionGroupService permissionGroupService, + UserUtils userUtils) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, workspaceService, analyticsService, - sessionUserService, passwordResetTokenRepository, passwordEncoder, emailSender, applicationRepository, - policySolution, commonConfig, emailConfig, userChangedHandler, encryptionService, userDataService, tenantService, - permissionGroupService, userUtils); + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + workspaceService, + analyticsService, + sessionUserService, + passwordResetTokenRepository, + passwordEncoder, + emailSender, + applicationRepository, + policySolution, + commonConfig, + emailConfig, + userChangedHandler, + encryptionService, + userDataService, + tenantService, + permissionGroupService, + userUtils); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserWorkspaceService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserWorkspaceService.java index d6e8089ef014..32deb6360c79 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserWorkspaceService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserWorkspaceService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.UserWorkspaceServiceCE; -public interface UserWorkspaceService extends UserWorkspaceServiceCE { - -} +public interface UserWorkspaceService extends UserWorkspaceServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserWorkspaceServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserWorkspaceServiceImpl.java index 97e4251bafe9..dc4b90681013 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserWorkspaceServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserWorkspaceServiceImpl.java @@ -1,12 +1,12 @@ package com.appsmith.server.services; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.notifications.EmailSender; import com.appsmith.server.repositories.UserDataRepository; import com.appsmith.server.repositories.UserRepository; import com.appsmith.server.repositories.WorkspaceRepository; import com.appsmith.server.services.ce.UserWorkspaceServiceCEImpl; import com.appsmith.server.solutions.PermissionGroupPermission; +import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.solutions.WorkspacePermission; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -15,19 +15,30 @@ @Slf4j public class UserWorkspaceServiceImpl extends UserWorkspaceServiceCEImpl implements UserWorkspaceService { - public UserWorkspaceServiceImpl(SessionUserService sessionUserService, - WorkspaceRepository workspaceRepository, - UserRepository userRepository, - UserDataRepository userDataRepository, - PolicySolution policySolution, - EmailSender emailSender, - UserDataService userDataService, - PermissionGroupService permissionGroupService, - TenantService tenantService, - WorkspacePermission workspacePermission, - PermissionGroupPermission permissionGroupPermission) { + public UserWorkspaceServiceImpl( + SessionUserService sessionUserService, + WorkspaceRepository workspaceRepository, + UserRepository userRepository, + UserDataRepository userDataRepository, + PolicySolution policySolution, + EmailSender emailSender, + UserDataService userDataService, + PermissionGroupService permissionGroupService, + TenantService tenantService, + WorkspacePermission workspacePermission, + PermissionGroupPermission permissionGroupPermission) { - super(sessionUserService, workspaceRepository, userRepository, userDataRepository, policySolution, emailSender, - userDataService, permissionGroupService, tenantService, workspacePermission, permissionGroupPermission); + super( + sessionUserService, + workspaceRepository, + userRepository, + userDataRepository, + policySolution, + emailSender, + userDataService, + permissionGroupService, + tenantService, + workspacePermission, + permissionGroupPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/WorkspaceService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/WorkspaceService.java index a08c51f3f9f7..17c89710e82b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/WorkspaceService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/WorkspaceService.java @@ -2,6 +2,4 @@ import com.appsmith.server.services.ce.WorkspaceServiceCE; -public interface WorkspaceService extends WorkspaceServiceCE { - -} +public interface WorkspaceService extends WorkspaceServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/WorkspaceServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/WorkspaceServiceImpl.java index e15a61a9a32b..68f27aac6ba4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/WorkspaceServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/WorkspaceServiceImpl.java @@ -1,12 +1,12 @@ package com.appsmith.server.services; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.AssetRepository; import com.appsmith.server.repositories.PluginRepository; import com.appsmith.server.repositories.WorkspaceRepository; import com.appsmith.server.services.ce.WorkspaceServiceCEImpl; import com.appsmith.server.solutions.PermissionGroupPermission; +import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.solutions.WorkspacePermission; import jakarta.validation.Validator; import lombok.extern.slf4j.Slf4j; @@ -20,25 +20,40 @@ @Service public class WorkspaceServiceImpl extends WorkspaceServiceCEImpl implements WorkspaceService { - public WorkspaceServiceImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - WorkspaceRepository repository, - AnalyticsService analyticsService, - PluginRepository pluginRepository, - SessionUserService sessionUserService, - AssetRepository assetRepository, - AssetService assetService, - ApplicationRepository applicationRepository, - PermissionGroupService permissionGroupService, - PolicySolution policySolution, - ModelMapper modelMapper, - WorkspacePermission workspacePermission, - PermissionGroupPermission permissionGroupPermission) { + public WorkspaceServiceImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + WorkspaceRepository repository, + AnalyticsService analyticsService, + PluginRepository pluginRepository, + SessionUserService sessionUserService, + AssetRepository assetRepository, + AssetService assetService, + ApplicationRepository applicationRepository, + PermissionGroupService permissionGroupService, + PolicySolution policySolution, + ModelMapper modelMapper, + WorkspacePermission workspacePermission, + PermissionGroupPermission permissionGroupPermission) { - super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService, - pluginRepository, sessionUserService, assetRepository, assetService, applicationRepository, - permissionGroupService, policySolution, modelMapper, workspacePermission, permissionGroupPermission); + super( + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + pluginRepository, + sessionUserService, + assetRepository, + assetService, + applicationRepository, + permissionGroupService, + policySolution, + modelMapper, + workspacePermission, + permissionGroupPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCE.java index 046ea3f81e84..6d0113d6aa19 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCE.java @@ -21,7 +21,8 @@ public interface ActionCollectionServiceCE extends CrudService<ActionCollection, String> { - Flux<ActionCollection> findAllByApplicationIdAndViewMode(String applicationId, Boolean viewMode, AclPermission permission, Sort sort); + Flux<ActionCollection> findAllByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, AclPermission permission, Sort sort); void generateAndSetPolicies(NewPage page, ActionCollection actionCollection); @@ -29,13 +30,17 @@ public interface ActionCollectionServiceCE extends CrudService<ActionCollection, Flux<ActionCollection> saveAll(List<ActionCollection> collections); - Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode(MultiValueMap<String, String> params, Boolean viewMode); + Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode( + MultiValueMap<String, String> params, Boolean viewMode); - Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode(MultiValueMap<String, String> params, Boolean viewMode, String branchName); + Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode( + MultiValueMap<String, String> params, Boolean viewMode, String branchName); - Mono<ActionCollectionDTO> populateActionCollectionByViewMode(ActionCollectionDTO actionCollectionDTO1, Boolean viewMode); + Mono<ActionCollectionDTO> populateActionCollectionByViewMode( + ActionCollectionDTO actionCollectionDTO1, Boolean viewMode); - Mono<ActionCollectionDTO> splitValidActionsByViewMode(ActionCollectionDTO actionCollectionDTO, List<ActionDTO> actionsList, Boolean viewMode); + Mono<ActionCollectionDTO> splitValidActionsByViewMode( + ActionCollectionDTO actionCollectionDTO, List<ActionDTO> actionsList, Boolean viewMode); Flux<ActionCollectionDTO> getActionCollectionsByViewMode(MultiValueMap<String, String> params, Boolean viewMode); @@ -51,22 +56,27 @@ public interface ActionCollectionServiceCE extends CrudService<ActionCollection, Mono<ActionCollection> findById(String id, AclPermission aclPermission); - Mono<ActionCollectionDTO> findActionCollectionDTObyIdAndViewMode(String id, Boolean viewMode, AclPermission permission); + Mono<ActionCollectionDTO> findActionCollectionDTObyIdAndViewMode( + String id, Boolean viewMode, AclPermission permission); Flux<ActionCollectionViewDTO> getActionCollectionsForViewMode(String applicationId, String branchName); Flux<ActionCollection> findByPageId(String pageId); - Mono<ActionCollection> findByBranchNameAndDefaultCollectionId(String branchName, String defaultCollectionId, AclPermission permission); + Mono<ActionCollection> findByBranchNameAndDefaultCollectionId( + String branchName, String defaultCollectionId, AclPermission permission); Mono<List<ActionCollection>> archiveActionCollectionByApplicationId(String applicationId, AclPermission permission); - void populateDefaultResources(ActionCollection actionCollection, ActionCollection branchedActionCollection,String branchName); - Mono<ImportActionCollectionResultDTO> importActionCollections(ImportActionResultDTO importActionResultDTO, - Application importedApplication, - String branchName, - List<ActionCollection> importedActionCollectionList, - Map<String, String> pluginMap, - Map<String, NewPage> pageNameMap, - ImportApplicationPermissionProvider permissionProvider); + void populateDefaultResources( + ActionCollection actionCollection, ActionCollection branchedActionCollection, String branchName); + + Mono<ImportActionCollectionResultDTO> importActionCollections( + ImportActionResultDTO importActionResultDTO, + Application importedApplication, + String branchName, + List<ActionCollection> importedActionCollectionList, + Map<String, String> pluginMap, + Map<String, NewPage> pageNameMap, + ImportApplicationPermissionProvider permissionProvider); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCEImpl.java index f3566aad9d34..5b6bb5bad452 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCEImpl.java @@ -59,7 +59,8 @@ import static java.lang.Boolean.TRUE; @Slf4j -public class ActionCollectionServiceCEImpl extends BaseService<ActionCollectionRepository, ActionCollection, String> implements ActionCollectionServiceCE { +public class ActionCollectionServiceCEImpl extends BaseService<ActionCollectionRepository, ActionCollection, String> + implements ActionCollectionServiceCE { private final NewActionService newActionService; private final PolicyGenerator policyGenerator; @@ -69,18 +70,19 @@ public class ActionCollectionServiceCEImpl extends BaseService<ActionCollectionR private final ActionPermission actionPermission; @Autowired - public ActionCollectionServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ActionCollectionRepository repository, - AnalyticsService analyticsService, - NewActionService newActionService, - PolicyGenerator policyGenerator, - ApplicationService applicationService, - ResponseUtils responseUtils, - ApplicationPermission applicationPermission, - ActionPermission actionPermission) { + public ActionCollectionServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ActionCollectionRepository repository, + AnalyticsService analyticsService, + NewActionService newActionService, + PolicyGenerator policyGenerator, + ApplicationService applicationService, + ResponseUtils responseUtils, + ApplicationPermission applicationPermission, + ActionPermission actionPermission) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.newActionService = newActionService; @@ -92,27 +94,31 @@ public ActionCollectionServiceCEImpl(Scheduler scheduler, } @Override - public Flux<ActionCollection> findAllByApplicationIdAndViewMode(String applicationId, Boolean viewMode, AclPermission permission, Sort sort) { - return repository.findByApplicationId(applicationId, permission, sort) + public Flux<ActionCollection> findAllByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, AclPermission permission, Sort sort) { + return repository + .findByApplicationId(applicationId, permission, sort) // In case of view mode being true, filter out all the actions which haven't been published .flatMap(collection -> { if (Boolean.TRUE.equals(viewMode)) { - // In case we are trying to fetch published actions but this action has not been published, do not return + // In case we are trying to fetch published actions but this action has not been published, do + // not return if (collection.getPublishedCollection() == null) { return Mono.empty(); } } - // No need to handle the edge case of unpublished action not being present. This is not possible because + // No need to handle the edge case of unpublished action not being present. This is not possible + // because // every created action starts from an unpublishedAction state. return Mono.just(collection); }); } - @Override public void generateAndSetPolicies(NewPage page, ActionCollection actionCollection) { - Set<Policy> documentPolicies = policyGenerator.getAllChildPolicies(page.getPolicies(), Page.class, Action.class); + Set<Policy> documentPolicies = + policyGenerator.getAllChildPolicies(page.getPolicies(), Page.class, Action.class); actionCollection.setPolicies(documentPolicies); } @@ -141,16 +147,15 @@ public Mono<ActionCollection> findByIdAndBranchName(String id, String branchName } @Override - public Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode(MultiValueMap<String, String> params, Boolean viewMode) { + public Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode( + MultiValueMap<String, String> params, Boolean viewMode) { return this.getActionCollectionsByViewMode(params, viewMode) .flatMap(actionCollectionDTO -> this.populateActionCollectionByViewMode(actionCollectionDTO, viewMode)); - } @Override - public Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode(MultiValueMap<String, String> params, - Boolean viewMode, - String branchName) { + public Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode( + MultiValueMap<String, String> params, Boolean viewMode, String branchName) { MultiValueMap<String, String> updatedMap = new LinkedMultiValueMap<>(params); if (!StringUtils.isEmpty(branchName)) { updatedMap.add(FieldName.BRANCH_NAME, branchName); @@ -160,49 +165,52 @@ public Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode(MultiVa } @Override - public Mono<ActionCollectionDTO> populateActionCollectionByViewMode(ActionCollectionDTO actionCollectionDTO1, Boolean viewMode) { - return Mono.just(actionCollectionDTO1) - .flatMap(actionCollectionDTO -> Flux.fromIterable(actionCollectionDTO.getDefaultToBranchedActionIdsMap().values()) - .mergeWith(Flux.fromIterable(actionCollectionDTO.getDefaultToBranchedArchivedActionIdsMap().values())) - .flatMap(actionId -> { - return newActionService.findActionDTObyIdAndViewMode(actionId, viewMode, actionPermission.getReadPermission()); - }) - .collectList() - .flatMap(actionsList -> splitValidActionsByViewMode(actionCollectionDTO, actionsList, viewMode))); + public Mono<ActionCollectionDTO> populateActionCollectionByViewMode( + ActionCollectionDTO actionCollectionDTO1, Boolean viewMode) { + return Mono.just(actionCollectionDTO1).flatMap(actionCollectionDTO -> Flux.fromIterable( + actionCollectionDTO.getDefaultToBranchedActionIdsMap().values()) + .mergeWith(Flux.fromIterable(actionCollectionDTO + .getDefaultToBranchedArchivedActionIdsMap() + .values())) + .flatMap(actionId -> { + return newActionService.findActionDTObyIdAndViewMode( + actionId, viewMode, actionPermission.getReadPermission()); + }) + .collectList() + .flatMap(actionsList -> splitValidActionsByViewMode(actionCollectionDTO, actionsList, viewMode))); } /** * This method splits the actions associated to an action collection into valid and archived actions */ @Override - public Mono<ActionCollectionDTO> splitValidActionsByViewMode(ActionCollectionDTO actionCollectionDTO, List<ActionDTO> actionsList, Boolean viewMode) { - return Mono.just(actionCollectionDTO) - .map(actionCollectionDTO1 -> { - List<ActionDTO> archivedActionList = new ArrayList<>(); - List<ActionDTO> validActionList = new ArrayList<>(); - final List<String> collect = actionsList - .stream() - .parallel() - .map(ActionDTO::getPluginId) - .distinct() - .collect(Collectors.toList()); - if (collect.size() == 1) { - actionCollectionDTO.setPluginId(collect.get(0)); - actionCollectionDTO.setPluginType(actionsList.get(0).getPluginType()); - } - actionsList.forEach(action -> { - if (action.getDeletedAt() == null) { - validActionList.add(action); - } else { - archivedActionList.add(action); - } - }); - actionCollectionDTO.setActions(validActionList); - if (Boolean.FALSE.equals(viewMode)) { - actionCollectionDTO.setArchivedActions(archivedActionList); - } - return actionCollectionDTO; - }); + public Mono<ActionCollectionDTO> splitValidActionsByViewMode( + ActionCollectionDTO actionCollectionDTO, List<ActionDTO> actionsList, Boolean viewMode) { + return Mono.just(actionCollectionDTO).map(actionCollectionDTO1 -> { + List<ActionDTO> archivedActionList = new ArrayList<>(); + List<ActionDTO> validActionList = new ArrayList<>(); + final List<String> collect = actionsList.stream() + .parallel() + .map(ActionDTO::getPluginId) + .distinct() + .collect(Collectors.toList()); + if (collect.size() == 1) { + actionCollectionDTO.setPluginId(collect.get(0)); + actionCollectionDTO.setPluginType(actionsList.get(0).getPluginType()); + } + actionsList.forEach(action -> { + if (action.getDeletedAt() == null) { + validActionList.add(action); + } else { + archivedActionList.add(action); + } + }); + actionCollectionDTO.setActions(validActionList); + if (Boolean.FALSE.equals(viewMode)) { + actionCollectionDTO.setArchivedActions(archivedActionList); + } + return actionCollectionDTO; + }); } @Override @@ -211,59 +219,70 @@ public Flux<ActionCollectionViewDTO> getActionCollectionsForViewMode(String appl return Flux.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID)); } - return applicationService.findBranchedApplicationId(branchName, applicationId, applicationPermission.getReadPermission()) - .flatMapMany(branchedApplicationId -> - repository - .findByApplicationIdAndViewMode(branchedApplicationId, true, actionPermission.getExecutePermission()) - // Filter out all the action collections which haven't been published - .flatMap(actionCollection -> { - if (actionCollection.getPublishedCollection() == null) { - return Mono.empty(); - } - return Mono.just(actionCollection); - }) - .flatMap(actionCollection -> { - ActionCollectionViewDTO actionCollectionViewDTO = new ActionCollectionViewDTO(); - final ActionCollectionDTO publishedCollection = actionCollection.getPublishedCollection(); - actionCollectionViewDTO.setId(actionCollection.getId()); - actionCollectionViewDTO.setName(publishedCollection.getName()); - actionCollectionViewDTO.setPageId(publishedCollection.getPageId()); - actionCollectionViewDTO.setApplicationId(actionCollection.getApplicationId()); - actionCollectionViewDTO.setVariables(publishedCollection.getVariables()); - actionCollectionViewDTO.setBody(publishedCollection.getBody()); - // Update default resources : - // actionCollection.defaultResources contains appId, collectionId and branch(optional). - // Default pageId will be taken from publishedCollection.defaultResources - DefaultResources defaults = actionCollection.getDefaultResources(); - // Consider a situation when collection is not published but user is viewing in deployed mode - if (publishedCollection.getDefaultResources() != null && defaults != null) { - defaults.setPageId(publishedCollection.getDefaultResources().getPageId()); - } else { - log.debug("Unreachable state, unable to find default ids for actionCollection: {}", actionCollection.getId()); - if (defaults == null) { - defaults = new DefaultResources(); - defaults.setApplicationId(actionCollection.getApplicationId()); - defaults.setCollectionId(actionCollection.getId()); - } - defaults.setPageId(actionCollection.getPublishedCollection().getPageId()); - } - actionCollectionViewDTO.setDefaultResources(defaults); - return Flux.fromIterable(publishedCollection.getDefaultToBranchedActionIdsMap().values()) - .flatMap(actionId -> { - return newActionService.findActionDTObyIdAndViewMode(actionId, true, actionPermission.getExecutePermission()); - }) - .collectList() - .map(actionDTOList -> { - actionCollectionViewDTO.setActions(actionDTOList); - return actionCollectionViewDTO; - }); - }) - .map(responseUtils::updateActionCollectionViewDTOWithDefaultResources) - ); + return applicationService + .findBranchedApplicationId(branchName, applicationId, applicationPermission.getReadPermission()) + .flatMapMany(branchedApplicationId -> repository + .findByApplicationIdAndViewMode( + branchedApplicationId, true, actionPermission.getExecutePermission()) + // Filter out all the action collections which haven't been published + .flatMap(actionCollection -> { + if (actionCollection.getPublishedCollection() == null) { + return Mono.empty(); + } + return Mono.just(actionCollection); + }) + .flatMap(actionCollection -> { + ActionCollectionViewDTO actionCollectionViewDTO = new ActionCollectionViewDTO(); + final ActionCollectionDTO publishedCollection = actionCollection.getPublishedCollection(); + actionCollectionViewDTO.setId(actionCollection.getId()); + actionCollectionViewDTO.setName(publishedCollection.getName()); + actionCollectionViewDTO.setPageId(publishedCollection.getPageId()); + actionCollectionViewDTO.setApplicationId(actionCollection.getApplicationId()); + actionCollectionViewDTO.setVariables(publishedCollection.getVariables()); + actionCollectionViewDTO.setBody(publishedCollection.getBody()); + // Update default resources : + // actionCollection.defaultResources contains appId, collectionId and branch(optional). + // Default pageId will be taken from publishedCollection.defaultResources + DefaultResources defaults = actionCollection.getDefaultResources(); + // Consider a situation when collection is not published but user is viewing in deployed + // mode + if (publishedCollection.getDefaultResources() != null && defaults != null) { + defaults.setPageId(publishedCollection + .getDefaultResources() + .getPageId()); + } else { + log.debug( + "Unreachable state, unable to find default ids for actionCollection: {}", + actionCollection.getId()); + if (defaults == null) { + defaults = new DefaultResources(); + defaults.setApplicationId(actionCollection.getApplicationId()); + defaults.setCollectionId(actionCollection.getId()); + } + defaults.setPageId(actionCollection + .getPublishedCollection() + .getPageId()); + } + actionCollectionViewDTO.setDefaultResources(defaults); + return Flux.fromIterable(publishedCollection + .getDefaultToBranchedActionIdsMap() + .values()) + .flatMap(actionId -> { + return newActionService.findActionDTObyIdAndViewMode( + actionId, true, actionPermission.getExecutePermission()); + }) + .collectList() + .map(actionDTOList -> { + actionCollectionViewDTO.setActions(actionDTOList); + return actionCollectionViewDTO; + }); + }) + .map(responseUtils::updateActionCollectionViewDTOWithDefaultResources)); } @Override - public Flux<ActionCollectionDTO> getActionCollectionsByViewMode(MultiValueMap<String, String> params, Boolean viewMode) { + public Flux<ActionCollectionDTO> getActionCollectionsByViewMode( + MultiValueMap<String, String> params, Boolean viewMode) { if (params == null || viewMode == null) { return Flux.empty(); } @@ -271,10 +290,12 @@ public Flux<ActionCollectionDTO> getActionCollectionsByViewMode(MultiValueMap<St // Fetch unpublished pages because GET actions is only called during edit mode. For view mode, different // function call is made which takes care of returning only the essential fields of an action return applicationService - .findBranchedApplicationId(params.getFirst(FieldName.BRANCH_NAME), params.getFirst(FieldName.APPLICATION_ID), applicationPermission.getReadPermission()) - .flatMapMany(childApplicationId -> - repository.findByApplicationIdAndViewMode(childApplicationId, viewMode, actionPermission.getReadPermission()) - ) + .findBranchedApplicationId( + params.getFirst(FieldName.BRANCH_NAME), + params.getFirst(FieldName.APPLICATION_ID), + applicationPermission.getReadPermission()) + .flatMapMany(childApplicationId -> repository.findByApplicationIdAndViewMode( + childApplicationId, viewMode, actionPermission.getReadPermission())) .flatMap(actionCollection -> generateActionCollectionByViewMode(actionCollection, viewMode)); } @@ -296,9 +317,10 @@ public Flux<ActionCollectionDTO> getActionCollectionsByViewMode(MultiValueMap<St if (params.getFirst(FieldName.PAGE_ID) != null) { pageIds.add(params.getFirst(FieldName.PAGE_ID)); } - return repository.findAllActionCollectionsByNamePageIdsViewModeAndBranch(name, pageIds, viewMode, branch, actionPermission.getReadPermission(), sort) - .flatMap(actionCollection -> - generateActionCollectionByViewMode(actionCollection, viewMode)); + return repository + .findAllActionCollectionsByNamePageIdsViewModeAndBranch( + name, pageIds, viewMode, branch, actionPermission.getReadPermission(), sort) + .flatMap(actionCollection -> generateActionCollectionByViewMode(actionCollection, viewMode)); } @Override @@ -307,8 +329,10 @@ public Mono<ActionCollectionDTO> update(String id, ActionCollectionDTO actionCol return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ID)); } - Mono<ActionCollection> actionCollectionMono = repository.findById(id, actionPermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, id))) + Mono<ActionCollection> actionCollectionMono = repository + .findById(id, actionPermission.getEditPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, id))) .cache(); return actionCollectionMono @@ -316,15 +340,16 @@ public Mono<ActionCollectionDTO> update(String id, ActionCollectionDTO actionCol copyNewFieldValuesIntoOldObject(actionCollectionDTO, dbActionCollection.getUnpublishedCollection()); // No need to save defaultPageId at actionCollection level as this will be stored inside the // actionCollectionDTO - DefaultResourcesUtils.createDefaultIdsOrUpdateWithGivenResourceIds(dbActionCollection, dbActionCollection.getDefaultResources().getBranchName()); + DefaultResourcesUtils.createDefaultIdsOrUpdateWithGivenResourceIds( + dbActionCollection, + dbActionCollection.getDefaultResources().getBranchName()); return dbActionCollection; }) .flatMap(actionCollection -> this.update(id, actionCollection)) .flatMap(repository::setUserPermissionsInObject) .flatMap(actionCollection -> this.generateActionCollectionByViewMode(actionCollection, false) .flatMap(actionCollectionDTO1 -> this.populateActionCollectionByViewMode( - actionCollection.getUnpublishedCollection(), - false))); + actionCollection.getUnpublishedCollection(), false))); } @Override @@ -337,28 +362,38 @@ public Mono<ActionCollectionDTO> deleteUnpublishedActionCollection(String id) { return deleteUnpublishedActionCollectionEx(id, Optional.of(actionPermission.getDeletePermission())); } - public Mono<ActionCollectionDTO> deleteUnpublishedActionCollectionEx(String id, Optional<AclPermission> permission) { - Mono<ActionCollection> actionCollectionMono = repository.findById(id, permission) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, id))); + public Mono<ActionCollectionDTO> deleteUnpublishedActionCollectionEx( + String id, Optional<AclPermission> permission) { + Mono<ActionCollection> actionCollectionMono = repository + .findById(id, permission) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, id))); return actionCollectionMono .flatMap(toDelete -> { Mono<ActionCollection> modifiedActionCollectionMono; if (toDelete.getPublishedCollection() != null) { toDelete.getUnpublishedCollection().setDeletedAt(Instant.now()); - modifiedActionCollectionMono = Flux - .fromIterable(toDelete.getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values()) - .flatMap(actionId -> newActionService.deleteUnpublishedAction(actionId) + modifiedActionCollectionMono = Flux.fromIterable(toDelete.getUnpublishedCollection() + .getDefaultToBranchedActionIdsMap() + .values()) + .flatMap(actionId -> newActionService + .deleteUnpublishedAction(actionId) // return an empty action so that the filter can remove it from the list .onErrorResume(throwable -> { - log.debug("Failed to delete action with id {} for collection: {}", actionId, toDelete.getUnpublishedCollection().getName()); + log.debug( + "Failed to delete action with id {} for collection: {}", + actionId, + toDelete.getUnpublishedCollection() + .getName()); log.error(throwable.getMessage()); return Mono.empty(); })) .collectList() .then(repository.save(toDelete)) .flatMap(modifiedActionCollection -> { - return analyticsService.sendArchiveEvent(modifiedActionCollection, getAnalyticsProperties(modifiedActionCollection)); + return analyticsService.sendArchiveEvent( + modifiedActionCollection, getAnalyticsProperties(modifiedActionCollection)); }); } else { // This actionCollection was never published. This document can be safely archived @@ -375,7 +410,7 @@ public Mono<ActionCollectionDTO> deleteUnpublishedActionCollection(String id, St Mono<String> branchedCollectionId = StringUtils.isEmpty(branchName) ? Mono.just(id) : this.findByBranchNameAndDefaultCollectionId(branchName, id, actionPermission.getDeletePermission()) - .map(ActionCollection::getId); + .map(ActionCollection::getId); return branchedCollectionId .flatMap(this::deleteUnpublishedActionCollection) @@ -383,14 +418,16 @@ public Mono<ActionCollectionDTO> deleteUnpublishedActionCollection(String id, St } @Override - public Mono<ActionCollectionDTO> generateActionCollectionByViewMode(ActionCollection actionCollection, Boolean viewMode) { + public Mono<ActionCollectionDTO> generateActionCollectionByViewMode( + ActionCollection actionCollection, Boolean viewMode) { ActionCollectionDTO actionCollectionDTO = null; if (TRUE.equals(viewMode)) { if (actionCollection.getPublishedCollection() != null) { actionCollectionDTO = actionCollection.getPublishedCollection(); } else { - // We are trying to fetch published action but it doesnt exist because the action hasn't been published yet + // We are trying to fetch published action but it doesnt exist because the action hasn't been published + // yet return Mono.empty(); } } else { @@ -411,20 +448,30 @@ public Mono<ActionCollection> findById(String id, AclPermission aclPermission) { } @Override - public Mono<ActionCollectionDTO> findActionCollectionDTObyIdAndViewMode(String id, Boolean viewMode, AclPermission permission) { + public Mono<ActionCollectionDTO> findActionCollectionDTObyIdAndViewMode( + String id, Boolean viewMode, AclPermission permission) { return this.findById(id, permission) .flatMap(action -> this.generateActionCollectionByViewMode(action, viewMode)); } @Override - public Mono<List<ActionCollection>> archiveActionCollectionByApplicationId(String applicationId, AclPermission permission) { - return repository.findByApplicationId(applicationId, permission, null) + public Mono<List<ActionCollection>> archiveActionCollectionByApplicationId( + String applicationId, AclPermission permission) { + return repository + .findByApplicationId(applicationId, permission, null) .flatMap(actionCollection -> { Set<String> actionIds = new HashSet<>(); - actionIds.addAll(actionCollection.getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values()); + actionIds.addAll(actionCollection + .getUnpublishedCollection() + .getDefaultToBranchedActionIdsMap() + .values()); if (actionCollection.getPublishedCollection() != null - && !CollectionUtils.isEmpty(actionCollection.getPublishedCollection().getDefaultToBranchedActionIdsMap())) { - actionIds.addAll(actionCollection.getPublishedCollection().getDefaultToBranchedActionIdsMap().values()); + && !CollectionUtils.isEmpty( + actionCollection.getPublishedCollection().getDefaultToBranchedActionIdsMap())) { + actionIds.addAll(actionCollection + .getPublishedCollection() + .getDefaultToBranchedActionIdsMap() + .values()); } return Flux.fromIterable(actionIds) .flatMap(newActionService::archiveById) @@ -444,8 +491,10 @@ public Flux<ActionCollection> findByPageId(String pageId) { @Override public Mono<ActionCollection> archiveById(String id) { - Mono<ActionCollection> actionCollectionMono = repository.findById(id) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, id))) + Mono<ActionCollection> actionCollectionMono = repository + .findById(id) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, id))) .cache(); return actionCollectionMono .map(actionCollection -> { @@ -453,17 +502,27 @@ public Mono<ActionCollection> archiveById(String id) { final ActionCollectionDTO publishedCollection = actionCollection.getPublishedCollection(); final Set<String> actionIds = new HashSet<>(); if (unpublishedCollection != null) { - actionIds.addAll(unpublishedCollection.getDefaultToBranchedActionIdsMap().values()); - actionIds.addAll(unpublishedCollection.getDefaultToBranchedArchivedActionIdsMap().values()); + actionIds.addAll(unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .values()); + actionIds.addAll(unpublishedCollection + .getDefaultToBranchedArchivedActionIdsMap() + .values()); } - if (publishedCollection != null && !CollectionUtils.isEmpty(publishedCollection.getDefaultToBranchedActionIdsMap())) { - actionIds.addAll(publishedCollection.getDefaultToBranchedActionIdsMap().values()); - actionIds.addAll(publishedCollection.getDefaultToBranchedArchivedActionIdsMap().values()); + if (publishedCollection != null + && !CollectionUtils.isEmpty(publishedCollection.getDefaultToBranchedActionIdsMap())) { + actionIds.addAll(publishedCollection + .getDefaultToBranchedActionIdsMap() + .values()); + actionIds.addAll(publishedCollection + .getDefaultToBranchedArchivedActionIdsMap() + .values()); } return actionIds; }) .flatMapMany(Flux::fromIterable) - .flatMap(actionId -> newActionService.archiveById(actionId) + .flatMap(actionId -> newActionService + .archiveById(actionId) // return an empty action so that the filter can remove it from the list .onErrorResume(throwable -> { log.debug("Failed to delete action with id {} for collection with id: {}", actionId, id); @@ -472,14 +531,18 @@ public Mono<ActionCollection> archiveById(String id) { })) .collectList() .flatMap(actionList -> actionCollectionMono) - .flatMap(actionCollection -> repository.archive(actionCollection).thenReturn(actionCollection)) - .flatMap(deletedActionCollection -> analyticsService.sendDeleteEvent(deletedActionCollection, getAnalyticsProperties(deletedActionCollection))); + .flatMap( + actionCollection -> repository.archive(actionCollection).thenReturn(actionCollection)) + .flatMap(deletedActionCollection -> analyticsService.sendDeleteEvent( + deletedActionCollection, getAnalyticsProperties(deletedActionCollection))); } @Override public Mono<ActionCollection> archiveByIdAndBranchName(String id, String branchName) { - Mono<ActionCollection> branchedCollectionMono = this.findByBranchNameAndDefaultCollectionId(branchName, id, actionPermission.getDeletePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, id))); + Mono<ActionCollection> branchedCollectionMono = this.findByBranchNameAndDefaultCollectionId( + branchName, id, actionPermission.getDeletePermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, id))); return branchedCollectionMono .map(ActionCollection::getId) @@ -488,20 +551,20 @@ public Mono<ActionCollection> archiveByIdAndBranchName(String id, String branchN } @Override - public Mono<ActionCollection> findByBranchNameAndDefaultCollectionId(String branchName, String defaultCollectionId, AclPermission permission) { + public Mono<ActionCollection> findByBranchNameAndDefaultCollectionId( + String branchName, String defaultCollectionId, AclPermission permission) { if (StringUtils.isEmpty(defaultCollectionId)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.COLLECTION_ID)); } else if (StringUtils.isEmpty(branchName)) { return this.findById(defaultCollectionId, permission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, defaultCollectionId)) - ); + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, defaultCollectionId))); } - return repository.findByBranchNameAndDefaultCollectionId(branchName, defaultCollectionId, permission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, defaultCollectionId)) - ); + return repository + .findByBranchNameAndDefaultCollectionId(branchName, defaultCollectionId, permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, defaultCollectionId))); } @Override @@ -509,7 +572,8 @@ public Map<String, Object> getAnalyticsProperties(ActionCollection savedActionCo final ActionCollectionDTO unpublishedCollection = savedActionCollection.getUnpublishedCollection(); Map<String, Object> analyticsProperties = new HashMap<>(); analyticsProperties.put("actionCollectionName", ObjectUtils.defaultIfNull(unpublishedCollection.getName(), "")); - analyticsProperties.put("applicationId", ObjectUtils.defaultIfNull(savedActionCollection.getApplicationId(), "")); + analyticsProperties.put( + "applicationId", ObjectUtils.defaultIfNull(savedActionCollection.getApplicationId(), "")); analyticsProperties.put("pageId", ObjectUtils.defaultIfNull(unpublishedCollection.getPageId(), "")); analyticsProperties.put("orgId", ObjectUtils.defaultIfNull(savedActionCollection.getWorkspaceId(), "")); return analyticsProperties; @@ -524,15 +588,22 @@ public Mono<ActionCollection> create(ActionCollection collection) { } @Override - public void populateDefaultResources(ActionCollection actionCollection, ActionCollection branchedActionCollection,String branchName) { + public void populateDefaultResources( + ActionCollection actionCollection, ActionCollection branchedActionCollection, String branchName) { DefaultResources defaultResources = branchedActionCollection.getDefaultResources(); // Create new action but keep defaultApplicationId and defaultActionId same for both the actions defaultResources.setBranchName(branchName); actionCollection.setDefaultResources(defaultResources); String defaultPageId = branchedActionCollection.getUnpublishedCollection() != null - ? branchedActionCollection.getUnpublishedCollection().getDefaultResources().getPageId() - : branchedActionCollection.getPublishedCollection().getDefaultResources().getPageId(); + ? branchedActionCollection + .getUnpublishedCollection() + .getDefaultResources() + .getPageId() + : branchedActionCollection + .getPublishedCollection() + .getDefaultResources() + .getPageId(); DefaultResources defaultsDTO = new DefaultResources(); defaultsDTO.setPageId(defaultPageId); if (actionCollection.getUnpublishedCollection() != null) { @@ -541,16 +612,17 @@ public void populateDefaultResources(ActionCollection actionCollection, ActionCo if (actionCollection.getPublishedCollection() != null) { actionCollection.getPublishedCollection().setDefaultResources(defaultsDTO); } - actionCollection.getUnpublishedCollection() - .setDeletedAt(branchedActionCollection.getUnpublishedCollection().getDeletedAt()); + actionCollection + .getUnpublishedCollection() + .setDeletedAt( + branchedActionCollection.getUnpublishedCollection().getDeletedAt()); actionCollection.setDeletedAt(branchedActionCollection.getDeletedAt()); actionCollection.setDeleted(branchedActionCollection.getDeleted()); // Set policies from existing branch object actionCollection.setPolicies(branchedActionCollection.getPolicies()); } - private NewPage updatePageInActionCollection(ActionCollectionDTO collectionDTO, - Map<String, NewPage> pageNameMap) { + private NewPage updatePageInActionCollection(ActionCollectionDTO collectionDTO, Map<String, NewPage> pageNameMap) { NewPage parentPage = pageNameMap.get(collectionDTO.getPageId()); if (parentPage == null) { return null; @@ -579,13 +651,14 @@ private NewPage updatePageInActionCollection(ActionCollectionDTO collectionDTO, * @return tuple of imported actionCollectionId and saved actionCollection in DB */ @Override - public Mono<ImportActionCollectionResultDTO> importActionCollections(ImportActionResultDTO importActionResultDTO, - Application application, - String branchName, - List<ActionCollection> importedActionCollectionList, - Map<String, String> pluginMap, - Map<String, NewPage> pageNameMap, - ImportApplicationPermissionProvider permissionProvider) { + public Mono<ImportActionCollectionResultDTO> importActionCollections( + ImportActionResultDTO importActionResultDTO, + Application application, + String branchName, + List<ActionCollection> importedActionCollectionList, + Map<String, String> pluginMap, + Map<String, NewPage> pageNameMap, + ImportApplicationPermissionProvider permissionProvider) { /* Mono.just(application) is created to avoid the eagerly fetching of existing actionCollections * during the pipeline construction. It should be fetched only when the pipeline is subscribed/executed. @@ -595,130 +668,154 @@ public Mono<ImportActionCollectionResultDTO> importActionCollections(ImportActio final String workspaceId = importedApplication.getWorkspaceId(); // Map of gitSyncId to actionCollection of the existing records in DB - Mono<Map<String, ActionCollection>> actionCollectionsInCurrentAppMono = repository.findByApplicationId(importedApplication.getId()) + Mono<Map<String, ActionCollection>> actionCollectionsInCurrentAppMono = repository + .findByApplicationId(importedApplication.getId()) .filter(collection -> collection.getGitSyncId() != null) .collectMap(ActionCollection::getGitSyncId); Mono<Map<String, ActionCollection>> actionCollectionsInBranchesMono; - if(importedApplication.getGitApplicationMetadata() != null) { - final String defaultApplicationId = importedApplication.getGitApplicationMetadata().getDefaultApplicationId(); - actionCollectionsInBranchesMono = repository.findByDefaultApplicationId(defaultApplicationId, Optional.empty()) + if (importedApplication.getGitApplicationMetadata() != null) { + final String defaultApplicationId = + importedApplication.getGitApplicationMetadata().getDefaultApplicationId(); + actionCollectionsInBranchesMono = repository + .findByDefaultApplicationId(defaultApplicationId, Optional.empty()) .filter(actionCollection -> actionCollection.getGitSyncId() != null) .collectMap(ActionCollection::getGitSyncId); } else { actionCollectionsInBranchesMono = Mono.just(Collections.emptyMap()); } - return Mono.zip(actionCollectionsInCurrentAppMono, actionCollectionsInBranchesMono).flatMap(objects -> { - Map<String, ActionCollection> actionsCollectionsInCurrentApp = objects.getT1(); - Map<String, ActionCollection> actionsCollectionsInBranches = objects.getT2(); - - // set the existing action collections in the result DTO, this will be required in next phases - resultDTO.setExistingActionCollections(actionsCollectionsInCurrentApp.values()); - - List<ActionCollection> newActionCollections = new ArrayList<>(); - List<ActionCollection> existingActionCollections = new ArrayList<>(); - - for(ActionCollection actionCollection : importedActionCollectionList) { - if(actionCollection.getUnpublishedCollection() == null - || StringUtils.isEmpty(actionCollection.getUnpublishedCollection().getPageId())) { - continue; // invalid action collection, skip it - } - final String idFromJsonFile = actionCollection.getId(); - NewPage parentPage = new NewPage(); - final ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); - final ActionCollectionDTO publishedCollection = actionCollection.getPublishedCollection(); + return Mono.zip(actionCollectionsInCurrentAppMono, actionCollectionsInBranchesMono) + .flatMap(objects -> { + Map<String, ActionCollection> actionsCollectionsInCurrentApp = objects.getT1(); + Map<String, ActionCollection> actionsCollectionsInBranches = objects.getT2(); - // If pageId is missing in the actionCollectionDTO create a fallback pageId - final String fallbackParentPageId = unpublishedCollection.getPageId(); + // set the existing action collections in the result DTO, this will be required in next phases + resultDTO.setExistingActionCollections(actionsCollectionsInCurrentApp.values()); - if (unpublishedCollection.getName() != null) { - unpublishedCollection.setDefaultToBranchedActionIdsMap(importActionResultDTO.getUnpublishedCollectionIdToActionIdsMap().get(idFromJsonFile)); - unpublishedCollection.setPluginId(pluginMap.get(unpublishedCollection.getPluginId())); - parentPage = updatePageInActionCollection(unpublishedCollection, pageNameMap); - } + List<ActionCollection> newActionCollections = new ArrayList<>(); + List<ActionCollection> existingActionCollections = new ArrayList<>(); - if (publishedCollection != null && publishedCollection.getName() != null) { - publishedCollection.setDefaultToBranchedActionIdsMap(importActionResultDTO.getPublishedCollectionIdToActionIdsMap().get(idFromJsonFile)); - publishedCollection.setPluginId(pluginMap.get(publishedCollection.getPluginId())); - if (StringUtils.isEmpty(publishedCollection.getPageId())) { - publishedCollection.setPageId(fallbackParentPageId); - } - NewPage publishedCollectionPage = updatePageInActionCollection(publishedCollection, pageNameMap); - parentPage = parentPage == null ? publishedCollectionPage : parentPage; - } + for (ActionCollection actionCollection : importedActionCollectionList) { + if (actionCollection.getUnpublishedCollection() == null + || StringUtils.isEmpty(actionCollection + .getUnpublishedCollection() + .getPageId())) { + continue; // invalid action collection, skip it + } + final String idFromJsonFile = actionCollection.getId(); + NewPage parentPage = new NewPage(); + final ActionCollectionDTO unpublishedCollection = + actionCollection.getUnpublishedCollection(); + final ActionCollectionDTO publishedCollection = actionCollection.getPublishedCollection(); + + // If pageId is missing in the actionCollectionDTO create a fallback pageId + final String fallbackParentPageId = unpublishedCollection.getPageId(); + + if (unpublishedCollection.getName() != null) { + unpublishedCollection.setDefaultToBranchedActionIdsMap(importActionResultDTO + .getUnpublishedCollectionIdToActionIdsMap() + .get(idFromJsonFile)); + unpublishedCollection.setPluginId(pluginMap.get(unpublishedCollection.getPluginId())); + parentPage = updatePageInActionCollection(unpublishedCollection, pageNameMap); + } - actionCollection.makePristine(); - actionCollection.setWorkspaceId(workspaceId); - actionCollection.setApplicationId(importedApplication.getId()); - - // Check if the action has gitSyncId and if it's already in DB - if (actionCollection.getGitSyncId() != null - && actionsCollectionsInCurrentApp.containsKey(actionCollection.getGitSyncId())) { - - //Since the resource is already present in DB, just update resource - ActionCollection existingActionCollection = actionsCollectionsInCurrentApp.get(actionCollection.getGitSyncId()); - - Set<Policy> existingPolicy = existingActionCollection.getPolicies(); - copyNestedNonNullProperties(actionCollection, existingActionCollection); - // Update branchName - existingActionCollection.getDefaultResources().setBranchName(branchName); - // Recover the deleted state present in DB from imported actionCollection - existingActionCollection.getUnpublishedCollection().setDeletedAt(actionCollection.getUnpublishedCollection().getDeletedAt()); - existingActionCollection.setDeletedAt(actionCollection.getDeletedAt()); - existingActionCollection.setDeleted(actionCollection.getDeleted()); - existingActionCollection.setPolicies(existingPolicy); - - existingActionCollection.updateForBulkWriteOperation(); - existingActionCollections.add(existingActionCollection); - resultDTO.getSavedActionCollectionIds().add(existingActionCollection.getId()); - resultDTO.getSavedActionCollectionMap().put(idFromJsonFile, existingActionCollection); - } else { - if(!permissionProvider.canCreateAction(parentPage)) { - throw new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, parentPage.getId()); - } + if (publishedCollection != null && publishedCollection.getName() != null) { + publishedCollection.setDefaultToBranchedActionIdsMap(importActionResultDTO + .getPublishedCollectionIdToActionIdsMap() + .get(idFromJsonFile)); + publishedCollection.setPluginId(pluginMap.get(publishedCollection.getPluginId())); + if (StringUtils.isEmpty(publishedCollection.getPageId())) { + publishedCollection.setPageId(fallbackParentPageId); + } + NewPage publishedCollectionPage = + updatePageInActionCollection(publishedCollection, pageNameMap); + parentPage = parentPage == null ? publishedCollectionPage : parentPage; + } - if (importedApplication.getGitApplicationMetadata() != null) { - final String defaultApplicationId = importedApplication.getGitApplicationMetadata().getDefaultApplicationId(); - if(actionsCollectionsInBranches.containsKey(actionCollection.getGitSyncId())) { - ActionCollection branchedActionCollection = actionsCollectionsInBranches.get(actionCollection.getGitSyncId()); - populateDefaultResources(actionCollection, branchedActionCollection, branchName); + actionCollection.makePristine(); + actionCollection.setWorkspaceId(workspaceId); + actionCollection.setApplicationId(importedApplication.getId()); + + // Check if the action has gitSyncId and if it's already in DB + if (actionCollection.getGitSyncId() != null + && actionsCollectionsInCurrentApp.containsKey(actionCollection.getGitSyncId())) { + + // Since the resource is already present in DB, just update resource + ActionCollection existingActionCollection = + actionsCollectionsInCurrentApp.get(actionCollection.getGitSyncId()); + + Set<Policy> existingPolicy = existingActionCollection.getPolicies(); + copyNestedNonNullProperties(actionCollection, existingActionCollection); + // Update branchName + existingActionCollection.getDefaultResources().setBranchName(branchName); + // Recover the deleted state present in DB from imported actionCollection + existingActionCollection + .getUnpublishedCollection() + .setDeletedAt(actionCollection + .getUnpublishedCollection() + .getDeletedAt()); + existingActionCollection.setDeletedAt(actionCollection.getDeletedAt()); + existingActionCollection.setDeleted(actionCollection.getDeleted()); + existingActionCollection.setPolicies(existingPolicy); + + existingActionCollection.updateForBulkWriteOperation(); + existingActionCollections.add(existingActionCollection); + resultDTO.getSavedActionCollectionIds().add(existingActionCollection.getId()); + resultDTO.getSavedActionCollectionMap().put(idFromJsonFile, existingActionCollection); } else { - DefaultResources defaultResources = new DefaultResources(); - defaultResources.setApplicationId(defaultApplicationId); - defaultResources.setBranchName(branchName); - actionCollection.setDefaultResources(defaultResources); + if (!permissionProvider.canCreateAction(parentPage)) { + throw new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, parentPage.getId()); + } + + if (importedApplication.getGitApplicationMetadata() != null) { + final String defaultApplicationId = importedApplication + .getGitApplicationMetadata() + .getDefaultApplicationId(); + if (actionsCollectionsInBranches.containsKey(actionCollection.getGitSyncId())) { + ActionCollection branchedActionCollection = + actionsCollectionsInBranches.get(actionCollection.getGitSyncId()); + populateDefaultResources( + actionCollection, branchedActionCollection, branchName); + } else { + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setApplicationId(defaultApplicationId); + defaultResources.setBranchName(branchName); + actionCollection.setDefaultResources(defaultResources); + } + } + + // this will generate the id and other auto generated fields e.g. createdAt + actionCollection.updateForBulkWriteOperation(); + generateAndSetPolicies(parentPage, actionCollection); + + // create or update default resources for the action + // values already set to defaultResources are kept unchanged + DefaultResourcesUtils.createDefaultIdsOrUpdateWithGivenResourceIds( + actionCollection, branchName); + + // generate gitSyncId if it's not present + if (actionCollection.getGitSyncId() == null) { + actionCollection.setGitSyncId( + actionCollection.getApplicationId() + "_" + new ObjectId()); + } + + // it's new actionCollection + newActionCollections.add(actionCollection); + resultDTO.getSavedActionCollectionIds().add(actionCollection.getId()); + resultDTO.getSavedActionCollectionMap().put(idFromJsonFile, actionCollection); } } - - // this will generate the id and other auto generated fields e.g. createdAt - actionCollection.updateForBulkWriteOperation(); - generateAndSetPolicies(parentPage, actionCollection); - - // create or update default resources for the action - // values already set to defaultResources are kept unchanged - DefaultResourcesUtils.createDefaultIdsOrUpdateWithGivenResourceIds(actionCollection, branchName); - - // generate gitSyncId if it's not present - if (actionCollection.getGitSyncId() == null) { - actionCollection.setGitSyncId(actionCollection.getApplicationId() + "_" + new ObjectId()); - } - - // it's new actionCollection - newActionCollections.add(actionCollection); - resultDTO.getSavedActionCollectionIds().add(actionCollection.getId()); - resultDTO.getSavedActionCollectionMap().put(idFromJsonFile, actionCollection); - } - } - log.info("Saving action collections in bulk. New: {}, Updated: {}", - newActionCollections.size(), - existingActionCollections.size() - ); - return repository.bulkInsert(newActionCollections) - .then(repository.bulkUpdate(existingActionCollections)) - .thenReturn(resultDTO); - }); + log.info( + "Saving action collections in bulk. New: {}, Updated: {}", + newActionCollections.size(), + existingActionCollections.size()); + return repository + .bulkInsert(newActionCollections) + .then(repository.bulkUpdate(existingActionCollections)) + .thenReturn(resultDTO); + }); }); - } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCE.java index 16e899c02d78..5583ebcad498 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCE.java @@ -16,7 +16,8 @@ public interface AnalyticsServiceCE { Mono<User> identifyUser(User user, UserData userData, String recentlyUsedWorkspaceId); - void identifyInstance(String instanceId, String role, String useCase, String adminEmail, String adminFullName, String ip); + void identifyInstance( + String instanceId, String role, String useCase, String adminEmail, String adminFullName, String ip); Mono<Void> sendEvent(String event, String userId, Map<String, ?> properties); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java index da0916946da9..b9a8bf519112 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java @@ -53,13 +53,14 @@ public class AnalyticsServiceCEImpl implements AnalyticsServiceCE { private final UserDataRepository userDataRepository; @Autowired - public AnalyticsServiceCEImpl(@Autowired(required = false) Analytics analytics, - SessionUserService sessionUserService, - CommonConfig commonConfig, - ConfigService configService, - UserUtils userUtils, - ProjectProperties projectProperties, - UserDataRepository userDataRepository) { + public AnalyticsServiceCEImpl( + @Autowired(required = false) Analytics analytics, + SessionUserService sessionUserService, + CommonConfig commonConfig, + ConfigService configService, + UserUtils userUtils, + ProjectProperties projectProperties, + UserDataRepository userDataRepository) { this.analytics = analytics; this.sessionUserService = sessionUserService; this.commonConfig = commonConfig; @@ -99,16 +100,16 @@ public Mono<User> identifyUser(User user, UserData userData, String recentlyUsed Mono<Boolean> isSuperUserMono = userUtils.isSuperUser(user); final Mono<String> recentlyUsedWorkspaceIdMono = StringUtils.isEmpty(recentlyUsedWorkspaceId) - ? userDataRepository.fetchMostRecentlyUsedWorkspaceId(user.getId()).defaultIfEmpty("") + ? userDataRepository + .fetchMostRecentlyUsedWorkspaceId(user.getId()) + .defaultIfEmpty("") : Mono.just(recentlyUsedWorkspaceId); return Mono.zip( Mono.just(user), isSuperUserMono, - configService.getInstanceId() - .defaultIfEmpty("unknown-instance-id"), - recentlyUsedWorkspaceIdMono - ) + configService.getInstanceId().defaultIfEmpty("unknown-instance-id"), + recentlyUsedWorkspaceIdMono) .map(tuple -> { final User savedUser = tuple.getT1(); final boolean isSuperUser = tuple.getT2(); @@ -135,15 +136,14 @@ public Mono<User> identifyUser(User user, UserData userData, String recentlyUsed "instanceId", instanceId, "mostRecentlyUsedWorkspaceId", tuple.getT4(), "role", ObjectUtils.defaultIfNull(userData.getRole(), ""), - "goal", ObjectUtils.defaultIfNull(userData.getUseCase(), "") - )) - ); + "goal", ObjectUtils.defaultIfNull(userData.getUseCase(), "")))); analytics.flush(); return savedUser; }); } - public void identifyInstance(String instanceId, String role, String useCase, String adminEmail, String adminFullName, String ip) { + public void identifyInstance( + String instanceId, String role, String useCase, String adminEmail, String adminFullName, String ip) { if (!isActive()) { return; } @@ -151,15 +151,20 @@ public void identifyInstance(String instanceId, String role, String useCase, Str analytics.enqueue(IdentifyMessage.builder() .userId(instanceId) .traits(Map.of( - "isInstance", true, // Is this "identify" data-point for a user or an instance? - ROLE, ObjectUtils.defaultIfNull(role, ""), - GOAL, ObjectUtils.defaultIfNull(useCase, ""), - EMAIL, ObjectUtils.defaultIfNull(adminEmail, ""), - NAME, ObjectUtils.defaultIfNull(adminFullName, ""), - IP, ObjectUtils.defaultIfNull(ip, "unknown"), - IP_ADDRESS, ObjectUtils.defaultIfNull(ip, "unknown") - )) - ); + "isInstance", + true, // Is this "identify" data-point for a user or an instance? + ROLE, + ObjectUtils.defaultIfNull(role, ""), + GOAL, + ObjectUtils.defaultIfNull(useCase, ""), + EMAIL, + ObjectUtils.defaultIfNull(adminEmail, ""), + NAME, + ObjectUtils.defaultIfNull(adminFullName, ""), + IP, + ObjectUtils.defaultIfNull(ip, "unknown"), + IP_ADDRESS, + ObjectUtils.defaultIfNull(ip, "unknown")))); analytics.flush(); } @@ -187,7 +192,8 @@ public Mono<Void> sendEvent(String event, String userId, Map<String, ?> properti if (userId != null && hashUserId && !commonConfig.isCloudHosting() - // But send the email intact for the subscribe event, which is sent only if the user has explicitly agreed to it. + // But send the email intact for the subscribe event, which is sent only if the user has explicitly + // agreed to it. && !AnalyticsEvents.SUBSCRIBE_MARKETING_EMAILS.name().equals(event)) { final String hashedUserId = hash(userId); analyticsProperties.remove("request"); @@ -211,9 +217,8 @@ public Mono<Void> sendEvent(String event, String userId, Map<String, ?> properti return Mono.zip( ExchangeUtils.getAnonymousUserIdFromCurrentRequest(), ExchangeUtils.getUserAgentFromCurrentRequest(), - configService.getInstanceId() - .defaultIfEmpty("unknown-instance-id") - ).map(tuple -> { + configService.getInstanceId().defaultIfEmpty("unknown-instance-id")) + .map(tuple -> { final String userIdFromClient = tuple.getT1(); final String userAgent = tuple.getT2(); final String instanceId = tuple.getT3(); @@ -221,17 +226,18 @@ public Mono<Void> sendEvent(String event, String userId, Map<String, ?> properti if (FieldName.ANONYMOUS_USER.equals(finalUserId)) { userIdToSend = StringUtils.defaultIfEmpty(userIdFromClient, FieldName.ANONYMOUS_USER); } - TrackMessage.Builder messageBuilder = TrackMessage.builder(event) - .userId(userIdToSend) - .context(Map.of( - "userAgent", userAgent - )); + TrackMessage.Builder messageBuilder = + TrackMessage.builder(event).userId(userIdToSend).context(Map.of("userAgent", userAgent)); // For Installation Setup Complete event we are using `instanceId` as tracking id // As this does not satisfy the email validation it's not getting hashed correctly - if (AnalyticsEvents.INSTALLATION_SETUP_COMPLETE.getEventName().equals(event) + if (AnalyticsEvents.INSTALLATION_SETUP_COMPLETE + .getEventName() + .equals(event) && analyticsProperties.containsKey(EMAIL)) { - String email = analyticsProperties.get(EMAIL) != null ? analyticsProperties.get(EMAIL).toString() : ""; + String email = analyticsProperties.get(EMAIL) != null + ? analyticsProperties.get(EMAIL).toString() + : ""; analyticsProperties.put(EMAIL_DOMAIN_HASH, getEmailDomainHash(email)); } else { analyticsProperties.put(EMAIL_DOMAIN_HASH, emailDomainHash); @@ -261,32 +267,34 @@ public <T> Mono<T> sendObjectEvent(AnalyticsEvents event, T object, Map<String, // We will create an anonymous user object for event tracking if no user is present // Without this, a lot of flows meant for anonymous users will error out - // In case the event needs to be sent during sign in, then `sessionUserService.getCurrentUser()` returns Mono.empty() + // In case the event needs to be sent during sign in, then `sessionUserService.getCurrentUser()` returns + // Mono.empty() // Handle the same by returning an anonymous user only for sending events. User anonymousUser = new User(); anonymousUser.setName(FieldName.ANONYMOUS_USER); anonymousUser.setEmail(FieldName.ANONYMOUS_USER); anonymousUser.setIsAnonymous(true); - Mono<User> userMono = sessionUserService.getCurrentUser() - .switchIfEmpty(Mono.just(anonymousUser)); + Mono<User> userMono = sessionUserService.getCurrentUser().switchIfEmpty(Mono.just(anonymousUser)); - return userMono - .flatMap(user -> Mono.zip( + return userMono.flatMap(user -> Mono.zip( user.isAnonymous() ? ExchangeUtils.getAnonymousUserIdFromCurrentRequest() : Mono.just(user.getUsername()), - Mono.just(user) - )) + Mono.just(user))) .flatMap(tuple -> { final String id = tuple.getT1(); final User user = tuple.getT2(); - // In case the user is anonymous, don't raise an event, unless it's a signup, logout, page view or action execution event. - boolean isEventUserSignUpOrLogout = object instanceof User && (event == AnalyticsEvents.CREATE || event == AnalyticsEvents.LOGOUT); + // In case the user is anonymous, don't raise an event, unless it's a signup, logout, page view or + // action execution event. + boolean isEventUserSignUpOrLogout = object instanceof User + && (event == AnalyticsEvents.CREATE || event == AnalyticsEvents.LOGOUT); boolean isEventPageView = object instanceof NewPage && event == AnalyticsEvents.VIEW; - boolean isEventActionExecution = object instanceof ActionDTO && event == AnalyticsEvents.EXECUTE_ACTION; - boolean isAvoidLoggingEvent = user.isAnonymous() && !(isEventUserSignUpOrLogout || isEventPageView || isEventActionExecution); + boolean isEventActionExecution = + object instanceof ActionDTO && event == AnalyticsEvents.EXECUTE_ACTION; + boolean isAvoidLoggingEvent = user.isAnonymous() + && !(isEventUserSignUpOrLogout || isEventPageView || isEventActionExecution); if (isAvoidLoggingEvent) { return Mono.just(object); } @@ -303,14 +311,14 @@ public <T> Mono<T> sendObjectEvent(AnalyticsEvents event, T object, Map<String, } if (analyticsProperties.containsKey(FieldName.CLOUD_HOSTED_EXTRA_PROPS)) { if (commonConfig.isCloudHosting()) { - Map<String, Object> extraPropsForCloudHostedInstance = (Map<String, Object>) analyticsProperties.get(FieldName.CLOUD_HOSTED_EXTRA_PROPS); + Map<String, Object> extraPropsForCloudHostedInstance = + (Map<String, Object>) analyticsProperties.get(FieldName.CLOUD_HOSTED_EXTRA_PROPS); analyticsProperties.putAll(extraPropsForCloudHostedInstance); } analyticsProperties.remove(FieldName.CLOUD_HOSTED_EXTRA_PROPS); } - return sendEvent(eventTag, username, analyticsProperties) - .thenReturn(object); + return sendEvent(eventTag, username, analyticsProperties).thenReturn(object); }); } @@ -322,10 +330,13 @@ public <T> Mono<T> sendObjectEvent(AnalyticsEvents event, T object, Map<String, * @return String */ private <T> String getEventTag(AnalyticsEvents event, T object) { - // In case of action execution or instance setting update, event.getEventName() only is used to support backward compatibility of event name + // In case of action execution or instance setting update, event.getEventName() only is used to support backward + // compatibility of event name List<AnalyticsEvents> nonResourceEvents = getNonResourceEvents(); boolean isNonResourceEvent = nonResourceEvents.contains(event); - final String eventTag = isNonResourceEvent ? event.getEventName() : event.getEventName() + "_" + object.getClass().getSimpleName().toUpperCase(); + final String eventTag = isNonResourceEvent + ? event.getEventName() + : event.getEventName() + "_" + object.getClass().getSimpleName().toUpperCase(); return eventTag; } @@ -346,8 +357,7 @@ public List<AnalyticsEvents> getNonResourceEvents() { AnalyticsEvents.DS_TEST_EVENT_FAILED, AnalyticsEvents.DS_SCHEMA_FETCH_EVENT, AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_SUCCESS, - AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED - ); + AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED); } public <T extends BaseDomain> Mono<T> sendCreateEvent(T object, Map<String, Object> extraProperties) { @@ -379,9 +389,8 @@ public <T extends BaseDomain> Mono<T> sendDeleteEvent(T object) { } public String convertWithStream(Map<String, ?> map) { - String mapAsString = map.keySet().stream() - .map(key -> key + "=" + map.get(key)) - .collect(Collectors.joining(", ", "{", "}")); + String mapAsString = + map.keySet().stream().map(key -> key + "=" + map.get(key)).collect(Collectors.joining(", ", "{", "}")); return mapAsString; } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiImporterCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiImporterCE.java index ea6e3cd60b10..546a3e0a9605 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiImporterCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiImporterCE.java @@ -6,5 +6,4 @@ public interface ApiImporterCE { Mono<ActionDTO> importAction(Object input, String pageId, String name, String workspaceId, String branchName); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiTemplateServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiTemplateServiceCE.java index 5d5ebb89ed63..fb389b44043b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiTemplateServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiTemplateServiceCE.java @@ -3,5 +3,4 @@ import com.appsmith.external.models.ApiTemplate; import com.appsmith.server.services.CrudService; -public interface ApiTemplateServiceCE extends CrudService<ApiTemplate, String> { -} +public interface ApiTemplateServiceCE extends CrudService<ApiTemplate, String> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiTemplateServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiTemplateServiceCEImpl.java index 6b30a584a7eb..a17f7d5b4dfc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiTemplateServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApiTemplateServiceCEImpl.java @@ -15,16 +15,17 @@ import reactor.core.publisher.Flux; import reactor.core.scheduler.Scheduler; - @Slf4j -public class ApiTemplateServiceCEImpl extends BaseService<ApiTemplateRepository, ApiTemplate, String> implements ApiTemplateServiceCE { - - public ApiTemplateServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ApiTemplateRepository repository, - AnalyticsService analyticsService) { +public class ApiTemplateServiceCEImpl extends BaseService<ApiTemplateRepository, ApiTemplate, String> + implements ApiTemplateServiceCE { + + public ApiTemplateServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ApiTemplateRepository repository, + AnalyticsService analyticsService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java index 5e8e17c47714..d1fc4f9bcf5a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java @@ -75,7 +75,6 @@ import static com.appsmith.server.acl.AclPermission.MANAGE_APPLICATIONS; import static org.apache.commons.lang.ObjectUtils.defaultIfNull; - @Slf4j @RequiredArgsConstructor public class ApplicationPageServiceCEImpl implements ApplicationPageServiceCE { @@ -102,7 +101,6 @@ public class ApplicationPageServiceCEImpl implements ApplicationPageServiceCE { private final ActionPermission actionPermission; private final TransactionalOperator transactionalOperator; - public static final Integer EVALUATION_VERSION = 2; @Override @@ -131,24 +129,24 @@ public Mono<PageDTO> createPage(PageDTO page) { } } - Mono<Application> applicationMono = applicationService.findById(page.getApplicationId(), applicationPermission.getPageCreatePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, page.getApplicationId()))) + Mono<Application> applicationMono = applicationService + .findById(page.getApplicationId(), applicationPermission.getPageCreatePermission()) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, page.getApplicationId()))) .cache(); - Mono<PageDTO> pageMono = applicationMono - .map(application -> { - generateAndSetPagePolicies(application, page); - if (page.getDefaultResources() == null) { - DefaultResources defaults = new DefaultResources(); - defaults.setApplicationId(page.getApplicationId()); - page.setDefaultResources(defaults); - } - return page; - }); + Mono<PageDTO> pageMono = applicationMono.map(application -> { + generateAndSetPagePolicies(application, page); + if (page.getDefaultResources() == null) { + DefaultResources defaults = new DefaultResources(); + defaults.setApplicationId(page.getApplicationId()); + page.setDefaultResources(defaults); + } + return page; + }); - return pageMono - .flatMap(newPageService::createDefault) - //After the page has been saved, update the application (save the page id inside the application) + return pageMono.flatMap(newPageService::createDefault) + // After the page has been saved, update the application (save the page id inside the application) .zipWith(applicationMono) .flatMap(tuple -> { final PageDTO savedPage = tuple.getT1(); @@ -161,13 +159,18 @@ public Mono<PageDTO> createPage(PageDTO page) { public Mono<PageDTO> createPageWithBranchName(PageDTO page, String branchName) { - DefaultResources defaultResources = page.getDefaultResources() == null ? new DefaultResources() : page.getDefaultResources(); + DefaultResources defaultResources = + page.getDefaultResources() == null ? new DefaultResources() : page.getDefaultResources(); if (StringUtils.isEmpty(defaultResources.getApplicationId())) { // Client will be aware of default application Id only so we are safe to assume this defaultResources.setApplicationId(page.getApplicationId()); } defaultResources.setBranchName(branchName); - return applicationService.findBranchedApplicationId(branchName, defaultResources.getApplicationId(), applicationPermission.getPageCreatePermission()) + return applicationService + .findBranchedApplicationId( + branchName, + defaultResources.getApplicationId(), + applicationPermission.getPageCreatePermission()) .flatMap(branchedApplicationId -> { page.setApplicationId(branchedApplicationId); page.setDefaultResources(defaultResources); @@ -187,25 +190,29 @@ public Mono<PageDTO> createPageWithBranchName(PageDTO page, String branchName) { @Override public Mono<UpdateResult> addPageToApplication(Application application, PageDTO page, Boolean isDefault) { - String defaultPageId = page.getDefaultResources() == null || StringUtils.isEmpty(page.getDefaultResources().getPageId()) - ? page.getId() : page.getDefaultResources().getPageId(); + String defaultPageId = page.getDefaultResources() == null + || StringUtils.isEmpty(page.getDefaultResources().getPageId()) + ? page.getId() + : page.getDefaultResources().getPageId(); if (isDuplicatePage(application, page.getId())) { - return applicationRepository.addPageToApplication(application.getId(), page.getId(), isDefault, defaultPageId) + return applicationRepository + .addPageToApplication(application.getId(), page.getId(), isDefault, defaultPageId) .doOnSuccess(result -> { if (result.getModifiedCount() != 1) { - log.error("Add page to application didn't update anything, probably because application wasn't found."); + log.error( + "Add page to application didn't update anything, probably because application wasn't found."); } }); } else { return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY, page.getId())); } - } private Boolean isDuplicatePage(Application application, String pageId) { if (application.getPages() != null) { - int count = (int) application.getPages().stream().filter( - applicationPage -> applicationPage.getId().equals(pageId)).count(); + int count = (int) application.getPages().stream() + .filter(applicationPage -> applicationPage.getId().equals(pageId)) + .count(); if (count > 0) { return Boolean.FALSE; } @@ -219,9 +226,9 @@ private PageDTO getDslEscapedPage(PageDTO page) { return page; } for (Layout layout : layouts) { - if (layout.getDsl() == null || - layout.getMongoEscapedWidgetNames() == null || - layout.getMongoEscapedWidgetNames().isEmpty()) { + if (layout.getDsl() == null + || layout.getMongoEscapedWidgetNames() == null + || layout.getMongoEscapedWidgetNames().isEmpty()) { continue; } layout.setDsl(layoutActionService.unescapeMongoSpecialCharacters(layout)); @@ -232,16 +239,17 @@ private PageDTO getDslEscapedPage(PageDTO page) { @Override public Mono<PageDTO> getPage(NewPage newPage, boolean viewMode) { - return newPageService.getPageByViewMode(newPage, viewMode) - .map(page -> getDslEscapedPage(page)); + return newPageService.getPageByViewMode(newPage, viewMode).map(page -> getDslEscapedPage(page)); } @Override public Mono<PageDTO> getPage(String pageId, boolean viewMode) { AclPermission permission = pagePermission.getReadPermission(); - return newPageService.findPageById(pageId, permission, viewMode) + return newPageService + .findPageById(pageId, permission, viewMode) .map(newPage -> getDslEscapedPage(newPage)) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, pageId))); + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, pageId))); } @Override @@ -249,7 +257,8 @@ public Mono<PageDTO> getPageByBranchAndDefaultPageId(String defaultPageId, Strin // Fetch the page with read permission in both editor and in viewer. AclPermission permission = pagePermission.getReadPermission(); - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, permission) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, permission) .flatMap(newPage -> { return sendPageViewAnalyticsEvent(newPage, viewMode).then(getPage(newPage, viewMode)); }) @@ -261,7 +270,7 @@ public Mono<PageDTO> getPageByName(String applicationName, String pageName, bool AclPermission appPermission; AclPermission pagePermission1; if (viewMode) { - //If view is set, then this user is trying to view the application + // If view is set, then this user is trying to view the application appPermission = applicationPermission.getReadPermission(); pagePermission1 = pagePermission.getReadPermission(); } else { @@ -271,9 +280,12 @@ public Mono<PageDTO> getPageByName(String applicationName, String pageName, bool return applicationService .findByName(applicationName, appPermission) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE + " by application name", applicationName))) - .flatMap(application -> newPageService.findByNameAndApplicationIdAndViewMode(pageName, application.getId(), pagePermission1, viewMode)) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE + " by page name", pageName))); + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE + " by application name", applicationName))) + .flatMap(application -> newPageService.findByNameAndApplicationIdAndViewMode( + pageName, application.getId(), pagePermission1, viewMode)) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE + " by page name", pageName))); } @Override @@ -283,30 +295,34 @@ public Mono<Application> makePageDefault(PageDTO page) { @Override public Mono<Application> makePageDefault(String applicationId, String pageId) { - // Since this can only happen during edit, the page in question is unpublished page. Set the view mode accordingly + // Since this can only happen during edit, the page in question is unpublished page. Set the view mode + // accordingly Boolean viewMode = false; - return newPageService.findPageById(pageId, pagePermission.getEditPermission(), viewMode) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, pageId))) + return newPageService + .findPageById(pageId, pagePermission.getEditPermission(), viewMode) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, pageId))) // Check if the page actually belongs to the application. .flatMap(page -> { if (page.getApplicationId().equals(applicationId)) { return Mono.just(page); } - return Mono.error(new AppsmithException(AppsmithError.PAGE_DOESNT_BELONG_TO_APPLICATION, page.getName(), applicationId)); + return Mono.error(new AppsmithException( + AppsmithError.PAGE_DOESNT_BELONG_TO_APPLICATION, page.getName(), applicationId)); }) .then(applicationService.findById(applicationId, applicationPermission.getEditPermission())) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) - .flatMap(application -> - applicationRepository - .setDefaultPage(applicationId, pageId) - .then(applicationService.getById(applicationId)) - ); + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) + .flatMap(application -> applicationRepository + .setDefaultPage(applicationId, pageId) + .then(applicationService.getById(applicationId))); } @Override public Mono<Application> makePageDefault(String defaultApplicationId, String defaultPageId, String branchName) { // TODO remove the dependency of applicationId as pageId and branch can get the exact resource - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) .flatMap(branchedPage -> makePageDefault(branchedPage.getApplicationId(), branchedPage.getId())) .map(responseUtils::updateApplicationWithDefaultResources); } @@ -343,14 +359,16 @@ public Mono<Application> createApplication(Application application, String works Application application1 = tuple.getT1(); application1.setModifiedBy(tuple.getT2().getUsername()); // setting modified by to current user // assign the default theme id to edit mode - return themeService.getDefaultThemeId().map(themeId -> { - application1.setEditModeThemeId(themeId); - application1.setPublishedModeThemeId(themeId); - return themeId; - }).then(applicationService.createDefaultApplication(application1)); + return themeService + .getDefaultThemeId() + .map(themeId -> { + application1.setEditModeThemeId(themeId); + application1.setPublishedModeThemeId(themeId); + return themeId; + }) + .then(applicationService.createDefaultApplication(application1)); }) .flatMap(savedApplication -> { - PageDTO page = new PageDTO(); page.setName(FieldName.DEFAULT_PAGE_NAME); page.setApplicationId(savedApplication.getId()); @@ -363,7 +381,7 @@ public Mono<Application> createApplication(Application application, String works defaults.setApplicationId(page.getApplicationId()); page.setDefaultResources(defaults); } - //Set the page policies + // Set the page policies generateAndSetPagePolicies(savedApplication, page); return newPageService @@ -372,28 +390,32 @@ public Mono<Application> createApplication(Application application, String works // Now publish this newly created app with default states so that // launching of newly created application is possible. .flatMap(updatedApplication -> publish(savedApplication.getId(), false) - .then(applicationService.findById(savedApplication.getId(), applicationPermission.getReadPermission()))); + .then(applicationService.findById( + savedApplication.getId(), applicationPermission.getReadPermission()))); }); } @Override public Mono<Application> setApplicationPolicies(Mono<User> userMono, String workspaceId, Application application) { - return userMono - .flatMap(user -> { - Mono<Workspace> workspaceMono = workspaceRepository.findById(workspaceId, workspacePermission.getApplicationCreatePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); - - return workspaceMono.map(org -> { - application.setWorkspaceId(org.getId()); - Set<Policy> documentPolicies = policyGenerator.getAllChildPolicies(org.getPolicies(), Workspace.class, Application.class); - application.setPolicies(documentPolicies); - return application; - }); - }); + return userMono.flatMap(user -> { + Mono<Workspace> workspaceMono = workspaceRepository + .findById(workspaceId, workspacePermission.getApplicationCreatePermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); + + return workspaceMono.map(org -> { + application.setWorkspaceId(org.getId()); + Set<Policy> documentPolicies = + policyGenerator.getAllChildPolicies(org.getPolicies(), Workspace.class, Application.class); + application.setPolicies(documentPolicies); + return application; + }); + }); } public void generateAndSetPagePolicies(Application application, PageDTO page) { - Set<Policy> documentPolicies = policyGenerator.getAllChildPolicies(application.getPolicies(), Application.class, Page.class); + Set<Policy> documentPolicies = + policyGenerator.getAllChildPolicies(application.getPolicies(), Application.class, Page.class); page.setPolicies(documentPolicies); } @@ -407,8 +429,10 @@ public void generateAndSetPagePolicies(Application application, PageDTO page) { public Mono<Application> deleteApplication(String id) { log.debug("Archiving application with id: {}", id); - Mono<Application> applicationMono = applicationRepository.findById(id, applicationPermission.getDeletePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, id))) + Mono<Application> applicationMono = applicationRepository + .findById(id, applicationPermission.getDeletePermission()) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, id))) .cache(); /* As part of git sync feature a new application will be created for each branch with reference to main application @@ -419,9 +443,11 @@ public Mono<Application> deleteApplication(String id) { return applicationMono .flatMapMany(application -> { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); - if (gitData != null && !StringUtils.isEmpty(gitData.getDefaultApplicationId()) && !StringUtils.isEmpty(gitData.getRepoName())) { - return applicationService - .findAllApplicationsByDefaultApplicationId(gitData.getDefaultApplicationId(), applicationPermission.getDeletePermission()); + if (gitData != null + && !StringUtils.isEmpty(gitData.getDefaultApplicationId()) + && !StringUtils.isEmpty(gitData.getRepoName())) { + return applicationService.findAllApplicationsByDefaultApplicationId( + gitData.getDefaultApplicationId(), applicationPermission.getDeletePermission()); } return Flux.fromIterable(List.of(application)); }) @@ -432,12 +458,14 @@ public Mono<Application> deleteApplication(String id) { .then(applicationMono) .flatMap(application -> { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); - if (gitData != null && !StringUtils.isEmpty(gitData.getDefaultApplicationId()) && !StringUtils.isEmpty(gitData.getRepoName())) { + if (gitData != null + && !StringUtils.isEmpty(gitData.getDefaultApplicationId()) + && !StringUtils.isEmpty(gitData.getRepoName())) { String repoName = gitData.getRepoName(); - Path repoPath = Paths.get(application.getWorkspaceId(), gitData.getDefaultApplicationId(), repoName); + Path repoPath = + Paths.get(application.getWorkspaceId(), gitData.getDefaultApplicationId(), repoName); // Delete git repo from local - return gitFileUtils.deleteLocalRepo(repoPath) - .then(Mono.just(application)); + return gitFileUtils.deleteLocalRepo(repoPath).then(Mono.just(application)); } return Mono.just(application); }); @@ -445,19 +473,21 @@ public Mono<Application> deleteApplication(String id) { public Mono<Application> deleteApplicationByResource(Application application) { log.debug("Archiving actionCollections, actions, pages and themes for applicationId: {}", application.getId()); - return actionCollectionService.archiveActionCollectionByApplicationId(application.getId(), actionPermission.getDeletePermission()) - .then(newActionService.archiveActionsByApplicationId(application.getId(), actionPermission.getDeletePermission())) - .then(newPageService.archivePagesByApplicationId(application.getId(), pagePermission.getDeletePermission())) + return actionCollectionService + .archiveActionCollectionByApplicationId(application.getId(), actionPermission.getDeletePermission()) + .then(newActionService.archiveActionsByApplicationId( + application.getId(), actionPermission.getDeletePermission())) + .then(newPageService.archivePagesByApplicationId( + application.getId(), pagePermission.getDeletePermission())) .then(themeService.archiveApplicationThemes(application)) .flatMap(applicationService::archive) .flatMap(deletedApplication -> { final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.APPLICATION, deletedApplication - ); - final Map<String, Object> data = Map.of( - FieldName.EVENT_DATA, eventData - ); + FieldName.APP_MODE, + ApplicationMode.EDIT.toString(), + FieldName.APPLICATION, + deletedApplication); + final Map<String, Object> data = Map.of(FieldName.EVENT_DATA, eventData); return analyticsService.sendDeleteEvent(deletedApplication, data); }); @@ -466,28 +496,30 @@ public Mono<Application> deleteApplicationByResource(Application application) { @Override public Mono<PageDTO> clonePage(String pageId) { - return newPageService.findById(pageId, pagePermission.getEditPermission()) + return newPageService + .findById(pageId, pagePermission.getEditPermission()) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Clone Page"))) - .flatMap(page -> - applicationService.saveLastEditInformation(page.getApplicationId()) - .then(clonePageGivenApplicationId(pageId, page.getApplicationId(), " Copy")) - ); + .flatMap(page -> applicationService + .saveLastEditInformation(page.getApplicationId()) + .then(clonePageGivenApplicationId(pageId, page.getApplicationId(), " Copy"))); } @Override public Mono<PageDTO> clonePageByDefaultPageIdAndBranch(String defaultPageId, String branchName) { - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) .flatMap(newPage -> clonePage(newPage.getId())) .map(responseUtils::updatePageDTOWithDefaultResources); } - private Mono<PageDTO> clonePageGivenApplicationId(String pageId, - String applicationId, - @Nullable String newPageNameSuffix) { + private Mono<PageDTO> clonePageGivenApplicationId( + String pageId, String applicationId, @Nullable String newPageNameSuffix) { // Find the source page and then prune the page layout fields to only contain the required fields that should be // copied. - Mono<PageDTO> sourcePageMono = newPageService.findPageById(pageId, pagePermission.getEditPermission(), false) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, pageId))) + Mono<PageDTO> sourcePageMono = newPageService + .findPageById(pageId, pagePermission.getEditPermission(), false) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, pageId))) .flatMap(page -> Flux.fromIterable(page.getLayouts()) .map(layout -> { Layout newLayout = new Layout(); @@ -501,12 +533,12 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, .map(layouts -> { page.setLayouts(layouts); return page; - }) - ); + })); final Flux<ActionCollection> sourceActionCollectionsFlux = actionCollectionService.findByPageId(pageId); - Flux<NewAction> sourceActionFlux = newActionService.findByPageId(pageId, actionPermission.getEditPermission()) + Flux<NewAction> sourceActionFlux = newActionService + .findByPageId(pageId, actionPermission.getEditPermission()) // Set collection reference in actions to null to reset to the new application's collections later .map(newAction -> { if (newAction.getUnpublishedAction() != null) { @@ -519,11 +551,14 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, return sourcePageMono .flatMap(page -> { - Mono<ApplicationPagesDTO> pageNamesMono = newPageService - .findApplicationPagesByApplicationIdViewMode(page.getApplicationId(), false, false); + Mono<ApplicationPagesDTO> pageNamesMono = + newPageService.findApplicationPagesByApplicationIdViewMode( + page.getApplicationId(), false, false); - Mono<Application> destinationApplicationMono = applicationService.findById(applicationId, applicationPermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))); + Mono<Application> destinationApplicationMono = applicationService + .findById(applicationId, applicationPermission.getEditPermission()) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))); return Mono.zip(pageNamesMono, destinationApplicationMono) // If a new page name suffix is given, @@ -535,8 +570,7 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, if (!Strings.isNullOrEmpty(newPageNameSuffix)) { String newPageName = page.getName() + newPageNameSuffix; - Set<String> names = pageNames.getPages() - .stream() + Set<String> names = pageNames.getPages().stream() .map(PageNameIdDTO::getName) .collect(Collectors.toSet()); @@ -580,20 +614,24 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, * taken care of - e.g. onPageLoad setting is copied from action setting instead of * being set to off by default. */ - AppsmithEventContext eventContext = new AppsmithEventContext(AppsmithEventContextType.CLONE_PAGE); - return Mono.zip(layoutActionService.createAction( - action.getUnpublishedAction(), - eventContext, Boolean.FALSE) + AppsmithEventContext eventContext = + new AppsmithEventContext(AppsmithEventContextType.CLONE_PAGE); + return Mono.zip( + layoutActionService + .createAction( + action.getUnpublishedAction(), eventContext, Boolean.FALSE) .map(ActionDTO::getId), - Mono.justOrEmpty(originalActionId) - ); + Mono.justOrEmpty(originalActionId)); }) - .collect(HashMap<String, String>::new, (map, tuple2) -> map.put(tuple2.getT2(), tuple2.getT1())) + .collect( + HashMap<String, String>::new, + (map, tuple2) -> map.put(tuple2.getT2(), tuple2.getT1())) .flatMap(actionIdsMap -> { // Pick all action collections return sourceActionCollectionsFlux .flatMap(actionCollection -> { - final ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); + final ActionCollectionDTO unpublishedCollection = + actionCollection.getUnpublishedCollection(); unpublishedCollection.setPageId(newPageId); actionCollection.setApplicationId(clonedPage.getApplicationId()); @@ -603,11 +641,14 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, DefaultResources defaultResourcesForDTO = new DefaultResources(); defaultResourcesForDTO.setPageId(clonedPageDefaultResources.getPageId()); - actionCollection.getUnpublishedCollection().setDefaultResources(defaultResourcesForDTO); + actionCollection + .getUnpublishedCollection() + .setDefaultResources(defaultResourcesForDTO); // Replace all action Ids from map Map<String, String> updatedDefaultToBranchedActionId = new HashMap<>(); - // Check if the application is connected with git and update defaultActionIds accordingly + // Check if the application is connected with git and update + // defaultActionIds accordingly // // 1. If the app is connected with git keep the actionDefaultId as it is and // update branchedActionId only @@ -622,9 +663,12 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, // Filter out the actionIds for which the reference is not // present in cloned actions, this happens when we have // deleted action in unpublished mode - if (StringUtils.hasLength(oldActionId) && StringUtils.hasLength(actionIdsMap.get(oldActionId))) { - updatedDefaultToBranchedActionId - .put(actionIdsMap.get(oldActionId), actionIdsMap.get(oldActionId)); + if (StringUtils.hasLength(oldActionId) + && StringUtils.hasLength( + actionIdsMap.get(oldActionId))) { + updatedDefaultToBranchedActionId.put( + actionIdsMap.get(oldActionId), + actionIdsMap.get(oldActionId)); } }); } else { @@ -634,13 +678,16 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, // Filter out the actionIds for which the reference is not // present in cloned actions, this happens when we have // deleted action in unpublished mode - if (StringUtils.hasLength(defaultId) && StringUtils.hasLength(actionIdsMap.get(oldActionId))) { - updatedDefaultToBranchedActionId - .put(defaultId, actionIdsMap.get(oldActionId)); + if (StringUtils.hasLength(defaultId) + && StringUtils.hasLength( + actionIdsMap.get(oldActionId))) { + updatedDefaultToBranchedActionId.put( + defaultId, actionIdsMap.get(oldActionId)); } }); } - unpublishedCollection.setDefaultToBranchedActionIdsMap(updatedDefaultToBranchedActionId); + unpublishedCollection.setDefaultToBranchedActionIdsMap( + updatedDefaultToBranchedActionId); // Set id as null, otherwise create (which is using under the hood save) // will try to overwrite same resource instead of creating a new resource @@ -648,28 +695,45 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, // Set published version to null as the published version of the page does // not exists when we clone the page. actionCollection.setPublishedCollection(null); - actionCollection.getDefaultResources().setPageId(null); + actionCollection + .getDefaultResources() + .setPageId(null); // Assign new gitSyncId for cloned actionCollection - actionCollection.setGitSyncId(actionCollection.getApplicationId() + "_" + new ObjectId()); - return actionCollectionService.create(actionCollection) + actionCollection.setGitSyncId( + actionCollection.getApplicationId() + "_" + new ObjectId()); + return actionCollectionService + .create(actionCollection) .flatMap(savedActionCollection -> { - if (!StringUtils.hasLength(savedActionCollection.getDefaultResources().getCollectionId())) { - savedActionCollection.getDefaultResources().setCollectionId(savedActionCollection.getId()); - return actionCollectionService.update(savedActionCollection.getId(), savedActionCollection); + if (!StringUtils.hasLength(savedActionCollection + .getDefaultResources() + .getCollectionId())) { + savedActionCollection + .getDefaultResources() + .setCollectionId(savedActionCollection.getId()); + return actionCollectionService.update( + savedActionCollection.getId(), + savedActionCollection); } return Mono.just(savedActionCollection); }) - .flatMap(newlyCreatedActionCollection -> - Flux.fromIterable(updatedDefaultToBranchedActionId.values()) - .flatMap(newActionService::findById) - .flatMap(newlyCreatedAction -> { - newlyCreatedAction.getUnpublishedAction().setCollectionId(newlyCreatedActionCollection.getId()); - newlyCreatedAction.getUnpublishedAction().getDefaultResources() - .setCollectionId(newlyCreatedActionCollection.getDefaultResources().getCollectionId()); - return newActionService.update(newlyCreatedAction.getId(), newlyCreatedAction); - }) - .collectList() - ); + .flatMap(newlyCreatedActionCollection -> Flux.fromIterable( + updatedDefaultToBranchedActionId.values()) + .flatMap(newActionService::findById) + .flatMap(newlyCreatedAction -> { + newlyCreatedAction + .getUnpublishedAction() + .setCollectionId( + newlyCreatedActionCollection.getId()); + newlyCreatedAction + .getUnpublishedAction() + .getDefaultResources() + .setCollectionId(newlyCreatedActionCollection + .getDefaultResources() + .getCollectionId()); + return newActionService.update( + newlyCreatedAction.getId(), newlyCreatedAction); + }) + .collectList()); }) .collectList(); }) @@ -682,27 +746,28 @@ private Mono<PageDTO> clonePageGivenApplicationId(String pageId, return Flux.fromIterable(layouts) .flatMap(layout -> { layout.setDsl(layoutActionService.unescapeMongoSpecialCharacters(layout)); - return layoutActionService.updateLayout(savedPage.getId(), savedPage.getApplicationId(), layout.getId(), layout); + return layoutActionService.updateLayout( + savedPage.getId(), savedPage.getApplicationId(), layout.getId(), layout); }) .collectList() .thenReturn(savedPage); }) .flatMap(page -> { - Mono<Application> applicationMono = applicationService.findById(page.getApplicationId(), applicationPermission.getEditPermission()); - return applicationMono - .flatMap(application -> { - ApplicationPage applicationPage = new ApplicationPage(); - applicationPage.setId(page.getId()); - applicationPage.setIsDefault(false); - if (StringUtils.isEmpty(page.getDefaultResources().getPageId())) { - applicationPage.setDefaultPageId(page.getId()); - } else { - applicationPage.setDefaultPageId(page.getDefaultResources().getPageId()); - } - application.getPages().add(applicationPage); - return applicationService.save(application) - .thenReturn(page); - }); + Mono<Application> applicationMono = applicationService.findById( + page.getApplicationId(), applicationPermission.getEditPermission()); + return applicationMono.flatMap(application -> { + ApplicationPage applicationPage = new ApplicationPage(); + applicationPage.setId(page.getId()); + applicationPage.setIsDefault(false); + if (StringUtils.isEmpty(page.getDefaultResources().getPageId())) { + applicationPage.setDefaultPageId(page.getId()); + } else { + applicationPage.setDefaultPageId( + page.getDefaultResources().getPageId()); + } + application.getPages().add(applicationPage); + return applicationService.save(application).thenReturn(page); + }); }); } @@ -715,43 +780,48 @@ public Mono<Application> cloneApplication(String applicationId, String branchNam // 1. Find valid application to clone, depending on branch Mono<Application> applicationMono = applicationService - .findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + .findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getEditPermission()) .flatMap(application -> { // For git connected application user can update the default branch // In such cases we should fork the application from the new default branch if (StringUtils.isEmpty(branchName) - && !Optional.ofNullable(application.getGitApplicationMetadata()).isEmpty() - && !application.getGitApplicationMetadata().getBranchName() - .equals(application.getGitApplicationMetadata().getDefaultBranchName())) { + && !Optional.ofNullable(application.getGitApplicationMetadata()) + .isEmpty() + && !application + .getGitApplicationMetadata() + .getBranchName() + .equals(application + .getGitApplicationMetadata() + .getDefaultBranchName())) { return applicationService.findByBranchNameAndDefaultApplicationId( application.getGitApplicationMetadata().getDefaultBranchName(), applicationId, - applicationPermission.getEditPermission() - ); + applicationPermission.getEditPermission()); } return Mono.just(application); }) .cache(); // 2. Find the name for the cloned application which wouldn't lead to duplicate key exception - Mono<String> newAppNameMono = applicationMono - .flatMap(application -> applicationService - // TODO: Convert this into a query that projects only application names - .findAllApplicationsByWorkspaceId(application.getWorkspaceId()) - .map(Application::getName) - .collect(Collectors.toSet()) - .map(appNames -> { - String newAppName = application.getName() + " Copy"; - int i = 0; - String name = newAppName; - while (appNames.contains(name)) { - i++; - name = newAppName + i; - } - return name; - })); + Mono<String> newAppNameMono = applicationMono.flatMap(application -> applicationService + // TODO: Convert this into a query that projects only application names + .findAllApplicationsByWorkspaceId(application.getWorkspaceId()) + .map(Application::getName) + .collect(Collectors.toSet()) + .map(appNames -> { + String newAppName = application.getName() + " Copy"; + int i = 0; + String name = newAppName; + while (appNames.contains(name)) { + i++; + name = newAppName + i; + } + return name; + })); - // We don't have to sanitise the response to update the Ids with the default ones as client want child application only + // We don't have to sanitise the response to update the Ids with the default ones as client want child + // application only Mono<Application> clonedResultMono = Mono.zip(applicationMono, newAppNameMono) .flatMap(tuple -> { Application sourceApplication = tuple.getT1(); @@ -762,7 +832,8 @@ public Mono<Application> cloneApplication(String applicationId, String branchNam // Remove the git related data before cloning sourceApplication.setGitApplicationMetadata(null); - // Create a new clone application object without the pages using the parameterized Application constructor + // Create a new clone application object without the pages using the parameterized Application + // constructor Application newApplication = new Application(sourceApplication); newApplication.setName(newName); newApplication.setLastEditedAt(Instant.now()); @@ -782,10 +853,12 @@ public Mono<Application> cloneApplication(String applicationId, String branchNam .flatMap(applicationUserTuple2 -> { Application application1 = applicationUserTuple2.getT1(); // setting modified by to current user - application1.setModifiedBy(applicationUserTuple2.getT2().getUsername()); + application1.setModifiedBy( + applicationUserTuple2.getT2().getUsername()); return applicationService.createDefaultApplication(application1); }) - // 4. Now fetch the pages of the source application, clone and add them to this new application + // 4. Now fetch the pages of the source application, clone and add them to this new + // application .flatMap(savedApplication -> Flux.fromIterable(sourceApplication.getPages()) .flatMap(applicationPage -> { String pageId = applicationPage.getId(); @@ -805,37 +878,44 @@ public Mono<Application> cloneApplication(String applicationId, String branchNam .flatMap(clonedPages -> { savedApplication.setPages(clonedPages); return applicationService.save(savedApplication); - }) - ) + })) // 5. Duplicate the source application's themes if required i.e. if they were customized - .flatMap(application -> - themeService.cloneThemeToApplication(sourceApplication.getEditModeThemeId(), application) - .zipWith(themeService.cloneThemeToApplication(sourceApplication.getPublishedModeThemeId(), application)) - .flatMap(themesZip -> { - String editModeThemeId = themesZip.getT1().getId(); - String publishedModeThemeId = themesZip.getT2().getId(); - application.setEditModeThemeId(editModeThemeId); - application.setPublishedModeThemeId(publishedModeThemeId); - return applicationService.setAppTheme( - application.getId(), editModeThemeId, publishedModeThemeId, applicationPermission.getEditPermission() - ).thenReturn(application); - }) - ) + .flatMap(application -> themeService + .cloneThemeToApplication(sourceApplication.getEditModeThemeId(), application) + .zipWith(themeService.cloneThemeToApplication( + sourceApplication.getPublishedModeThemeId(), application)) + .flatMap(themesZip -> { + String editModeThemeId = + themesZip.getT1().getId(); + String publishedModeThemeId = + themesZip.getT2().getId(); + application.setEditModeThemeId(editModeThemeId); + application.setPublishedModeThemeId(publishedModeThemeId); + return applicationService + .setAppTheme( + application.getId(), + editModeThemeId, + publishedModeThemeId, + applicationPermission.getEditPermission()) + .thenReturn(application); + })) // 6. Publish copy of application .flatMap(application -> publish(application.getId(), false)) .flatMap(application -> sendCloneApplicationAnalyticsEvent(sourceApplication, application)); }); - // Clone Application is currently a slow API because it needs to create application, clone all the pages, and then - // clone all the actions. This process may take time and the client may cancel the request. This leads to the flow + // Clone Application is currently a slow API because it needs to create application, clone all the pages, and + // then + // clone all the actions. This process may take time and the client may cancel the request. This leads to the + // flow // getting stopped midway producing corrupted clones. The following ensures that even though the client may have - // cancelled the flow, the cloning of the application should proceed uninterrupted and whenever the user refreshes + // cancelled the flow, the cloning of the application should proceed uninterrupted and whenever the user + // refreshes // the page, the cloned application is available and is in sane state. // To achieve this, we use a synchronous sink which does not take subscription cancellations into account. This - // means that even if the subscriber has cancelled its subscription, the create method still generates its event. - return Mono.create(sink -> clonedResultMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + // means that even if the subscriber has cancelled its subscription, the create method still generates its + // event. + return Mono.create(sink -> clonedResultMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } /** @@ -860,7 +940,6 @@ public Mono<PageDTO> deleteUnpublishedPage(String id) { return deleteUnpublishedPageEx(id, Optional.of(pagePermission.getDeletePermission())); } - /** * This function archives the unpublished page. This also archives the unpublished action. The reason that the * entire action is not deleted at this point is to handle the following edge case : @@ -875,11 +954,14 @@ public Mono<PageDTO> deleteUnpublishedPage(String id) { */ private Mono<PageDTO> deleteUnpublishedPageEx(String id, Optional<AclPermission> permission) { - return newPageService.findById(id, permission) + return newPageService + .findById(id, permission) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, id))) .flatMap(page -> { - log.debug("Going to archive pageId: {} for applicationId: {}", page.getId(), page.getApplicationId()); - Mono<Application> applicationMono = applicationService.getById(page.getApplicationId()) + log.debug( + "Going to archive pageId: {} for applicationId: {}", page.getId(), page.getApplicationId()); + Mono<Application> applicationMono = applicationService + .getById(page.getApplicationId()) .flatMap(application -> { application.getPages().removeIf(p -> p.getId().equals(page.getId())); return applicationService.save(application); @@ -896,12 +978,9 @@ private Mono<PageDTO> deleteUnpublishedPageEx(String id, Optional<AclPermission> Mono<PageDTO> archivedPageMono = newPageMono .flatMap(newPage -> { - final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString() - ); - final Map<String, Object> data = Map.of( - FieldName.EVENT_DATA, eventData - ); + final Map<String, Object> eventData = + Map.of(FieldName.APP_MODE, ApplicationMode.EDIT.toString()); + final Map<String, Object> data = Map.of(FieldName.EVENT_DATA, eventData); return analyticsService.sendDeleteEvent(newPage, data); }) @@ -912,21 +991,30 @@ private Mono<PageDTO> deleteUnpublishedPageEx(String id, Optional<AclPermission> * actionCollection which will be deleted while deleting the collection, this will avoid the race * condition for delete action */ - Mono<List<ActionDTO>> archivedActionsMono = newActionService.findByPageId(page.getId(), actionPermission.getDeletePermission()) - .filter(newAction -> !StringUtils.hasLength(newAction.getUnpublishedAction().getCollectionId())) + Mono<List<ActionDTO>> archivedActionsMono = newActionService + .findByPageId(page.getId(), actionPermission.getDeletePermission()) + .filter(newAction -> !StringUtils.hasLength( + newAction.getUnpublishedAction().getCollectionId())) .flatMap(action -> { log.debug("Going to archive actionId: {} for applicationId: {}", action.getId(), id); return newActionService.deleteUnpublishedAction(action.getId()); - }).collectList(); + }) + .collectList(); /** * Only delete unpublished action collection and not the entire action collection. */ - Mono<List<ActionCollectionDTO>> archivedActionCollectionsMono = actionCollectionService.findByPageId(page.getId()) + Mono<List<ActionCollectionDTO>> archivedActionCollectionsMono = actionCollectionService + .findByPageId(page.getId()) .flatMap(actionCollection -> { - log.debug("Going to archive actionCollectionId: {} for applicationId: {}", actionCollection.getId(), id); - return actionCollectionService.deleteUnpublishedActionCollection(actionCollection.getId()); - }).collectList(); + log.debug( + "Going to archive actionCollectionId: {} for applicationId: {}", + actionCollection.getId(), + id); + return actionCollectionService.deleteUnpublishedActionCollection( + actionCollection.getId()); + }) + .collectList(); // Page is deleted only after other resources are deleted return Mono.zip(archivedActionsMono, archivedActionCollectionsMono, applicationMono) @@ -934,24 +1022,32 @@ private Mono<PageDTO> deleteUnpublishedPageEx(String id, Optional<AclPermission> List<ActionDTO> actions = tuple.getT1(); final List<ActionCollectionDTO> actionCollections = tuple.getT2(); Application application = tuple.getT3(); - log.debug("Archived {} actions and {} action collections for applicationId: {}", actions.size(), actionCollections.size(), application.getId()); + log.debug( + "Archived {} actions and {} action collections for applicationId: {}", + actions.size(), + actionCollections.size(), + application.getId()); return application; }) .then(archivedPageMono) .map(pageDTO -> { - log.debug("Archived pageId: {} for applicationId: {}", pageDTO.getId(), pageDTO.getApplicationId()); + log.debug( + "Archived pageId: {} for applicationId: {}", + pageDTO.getId(), + pageDTO.getApplicationId()); return pageDTO; }) .flatMap(pageDTO -> // save the last edit information as page is deleted from application - applicationService.saveLastEditInformation(pageDTO.getApplicationId()) - .thenReturn(pageDTO) - ); + applicationService + .saveLastEditInformation(pageDTO.getApplicationId()) + .thenReturn(pageDTO)); }); } public Mono<PageDTO> deleteUnpublishedPageByBranchAndDefaultPageId(String defaultPageId, String branchName) { - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getDeletePermission()) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getDeletePermission()) .flatMap(newPage -> deleteUnpublishedPage(newPage.getId())) .map(responseUtils::updatePageDTOWithDefaultResources) .as(transactionalOperator::transactional); @@ -971,17 +1067,18 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual * Please note that it is a cached Mono, hence please be careful with using this Mono to update / read data * when latest updated application object is desired. */ - Mono<Application> applicationMono = applicationService.findById(applicationId, applicationPermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) + Mono<Application> applicationMono = applicationService + .findById(applicationId, applicationPermission.getEditPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) .cache(); - Mono<Theme> publishThemeMono = applicationMono.flatMap( - application -> themeService.publishTheme(application.getId()) - ); + Mono<Theme> publishThemeMono = + applicationMono.flatMap(application -> themeService.publishTheme(application.getId())); Set<CustomJSLibApplicationDTO> updatedPublishedJSLibDTOs = new HashSet<>(); Mono<List<NewPage>> publishApplicationAndPages = applicationMono - //Return all the pages in the Application + // Return all the pages in the Application .flatMap(application -> { // Update published custom JS lib objects. application.setPublishedCustomJSLibs(application.getUnpublishedCustomJSLibs()); @@ -994,13 +1091,18 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual pages = new ArrayList<>(); } - // This is the time to delete any page which was deleted in edit mode but still exists in the published mode + // This is the time to delete any page which was deleted in edit mode but still exists in the + // published mode List<ApplicationPage> publishedPages = application.getPublishedPages(); if (publishedPages == null) { publishedPages = new ArrayList<>(); } - Set<String> publishedPageIds = publishedPages.stream().map(applicationPage -> applicationPage.getId()).collect(Collectors.toSet()); - Set<String> editedPageIds = pages.stream().map(applicationPage -> applicationPage.getId()).collect(Collectors.toSet()); + Set<String> publishedPageIds = publishedPages.stream() + .map(applicationPage -> applicationPage.getId()) + .collect(Collectors.toSet()); + Set<String> editedPageIds = pages.stream() + .map(applicationPage -> applicationPage.getId()) + .collect(Collectors.toSet()); /** * Now add the published page ids and edited page ids into a single set and then remove the edited @@ -1038,12 +1140,15 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual .thenReturn(pages); }) .flatMapMany(Flux::fromIterable) - //In each page, copy each layout's dsl to publishedDsl field + // In each page, copy each layout's dsl to publishedDsl field .flatMap(applicationPage -> newPageService .findById(applicationPage.getId(), pagePermission.getEditPermission()) - // For a git connected app if the user does not have permission to edit few pages in master branch - // They don't get access to the same resources in feature branch. When they do operations like commit and push we publish the changes automatically - // and this will fail due to permission issue. Hence removing the throwing error part and handling it gracefully + // For a git connected app if the user does not have permission to edit few pages in master + // branch + // They don't get access to the same resources in feature branch. When they do operations like + // commit and push we publish the changes automatically + // and this will fail due to permission issue. Hence removing the throwing error part and + // handling it gracefully // Only the pages which the user pocesses permission will be published .map(page -> { page.setPublishedPage(page.getUnpublishedPage()); @@ -1058,8 +1163,7 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual .flatMap(newAction -> { // If the action was deleted in edit mode, now this document can be safely archived if (newAction.getUnpublishedAction().getDeletedAt() != null) { - return newActionService.archive(newAction) - .then(Mono.empty()); + return newActionService.archive(newAction).then(Mono.empty()); } // Publish the action by copying the unpublished actionDTO to published actionDTO newAction.setPublishedAction(newAction.getUnpublishedAction()); @@ -1074,7 +1178,8 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual .flatMap(collection -> { // If the collection was deleted in edit mode, now this can be safely deleted from the repository if (collection.getUnpublishedCollection().getDeletedAt() != null) { - return actionCollectionService.archiveById(collection.getId()) + return actionCollectionService + .archiveById(collection.getId()) .then(Mono.empty()); } // Publish the collection by copying the unpublished collectionDTO to published collectionDTO @@ -1085,10 +1190,14 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual .collectList(); return publishApplicationAndPages - .flatMap(newPages -> Mono.zip(publishedActionsListMono, publishedActionCollectionsListMono, - publishThemeMono)) - .then(sendApplicationPublishedEvent(publishApplicationAndPages, publishedActionsListMono, - publishedActionCollectionsListMono, Mono.just(updatedPublishedJSLibDTOs), applicationId, + .flatMap(newPages -> + Mono.zip(publishedActionsListMono, publishedActionCollectionsListMono, publishThemeMono)) + .then(sendApplicationPublishedEvent( + publishApplicationAndPages, + publishedActionsListMono, + publishedActionCollectionsListMono, + Mono.just(updatedPublishedJSLibDTOs), + applicationId, isPublishedManually)); } @@ -1099,19 +1208,20 @@ private int getActionCount(Map<PluginType, Collection<NewAction>> pluginTypeColl return 0; } - private Mono<Application> sendApplicationPublishedEvent(Mono<List<NewPage>> publishApplicationAndPages, - Mono<Map<PluginType, Collection<NewAction>>> publishedActionsFlux, - Mono<List<ActionCollection>> publishedActionsCollectionFlux, - Mono<Set<CustomJSLibApplicationDTO>> publishedJSLibDTOsMono, - String applicationId, boolean isPublishedManually) { + private Mono<Application> sendApplicationPublishedEvent( + Mono<List<NewPage>> publishApplicationAndPages, + Mono<Map<PluginType, Collection<NewAction>>> publishedActionsFlux, + Mono<List<ActionCollection>> publishedActionsCollectionFlux, + Mono<Set<CustomJSLibApplicationDTO>> publishedJSLibDTOsMono, + String applicationId, + boolean isPublishedManually) { return Mono.zip( publishApplicationAndPages, publishedActionsFlux, publishedActionsCollectionFlux, // not using existing applicationMono because we need the latest Application after published applicationService.findById(applicationId, applicationPermission.getEditPermission()), - publishedJSLibDTOsMono - ) + publishedJSLibDTOsMono) .flatMap(objects -> { Application application = objects.getT4(); Map<String, Object> extraProperties = new HashMap<>(); @@ -1128,7 +1238,8 @@ private Mono<Application> sendApplicationPublishedEvent(Mono<List<NewPage>> publ extraProperties.put("jsFuncCount", jsFuncCount); extraProperties.put("saasQueryCount", saasQueryCount); extraProperties.put("remoteQueryCount", remoteQueryCount); - extraProperties.put("queryCount", (dbQueryCount + apiCount + jsFuncCount + saasQueryCount + remoteQueryCount)); + extraProperties.put( + "queryCount", (dbQueryCount + apiCount + jsFuncCount + saasQueryCount + remoteQueryCount)); extraProperties.put("actionCollectionCount", objects.getT3().size()); extraProperties.put("jsLibsCount", objects.getT5().size()); extraProperties.put("appId", defaultIfNull(application.getId(), "")); @@ -1138,18 +1249,18 @@ private Mono<Application> sendApplicationPublishedEvent(Mono<List<NewPage>> publ extraProperties.put("publishedAt", defaultIfNull(application.getLastDeployedAt(), "")); final Map<String, Object> eventData = Map.of( - FieldName.APPLICATION, application, - FieldName.APP_MODE, ApplicationMode.EDIT.toString() - ); + FieldName.APPLICATION, application, FieldName.APP_MODE, ApplicationMode.EDIT.toString()); extraProperties.put(FieldName.EVENT_DATA, eventData); - return analyticsService.sendObjectEvent(AnalyticsEvents.PUBLISH_APPLICATION, application, extraProperties); + return analyticsService.sendObjectEvent( + AnalyticsEvents.PUBLISH_APPLICATION, application, extraProperties); }); } @Override public Mono<Application> publish(String defaultApplicationId, String branchName, boolean isPublishedManually) { - return applicationService.findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) + return applicationService + .findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) .flatMap(branchedApplicationId -> publish(branchedApplicationId, isPublishedManually)) .map(responseUtils::updateApplicationWithDefaultResources); } @@ -1164,11 +1275,16 @@ public Mono<Application> publish(String defaultApplicationId, String branchName, * @return Application object with the latest order **/ @Override - public Mono<ApplicationPagesDTO> reorderPage(String defaultAppId, String defaultPageId, Integer order, String branchName) { - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, defaultPageId))) - .zipWhen(branchedPage -> applicationService.findById(branchedPage.getApplicationId(), applicationPermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultAppId)))) + public Mono<ApplicationPagesDTO> reorderPage( + String defaultAppId, String defaultPageId, Integer order, String branchName) { + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, defaultPageId))) + .zipWhen(branchedPage -> applicationService + .findById(branchedPage.getApplicationId(), applicationPermission.getEditPermission()) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultAppId)))) .flatMap(tuple -> { final NewPage branchedPage = tuple.getT1(); Application application = tuple.getT2(); @@ -1189,8 +1305,10 @@ public Mono<ApplicationPagesDTO> reorderPage(String defaultAppId, String default return applicationRepository .setPages(application.getId(), pages) - .flatMap(updateResult -> sendPageOrderAnalyticsEvent(application, defaultPageId, order, branchName)) - .then(newPageService.findApplicationPagesByApplicationIdViewMode(application.getId(), Boolean.FALSE, false)); + .flatMap(updateResult -> + sendPageOrderAnalyticsEvent(application, defaultPageId, order, branchName)) + .then(newPageService.findApplicationPagesByApplicationIdViewMode( + application.getId(), Boolean.FALSE, false)); }) .map(responseUtils::updateApplicationPagesDTOWithDefaultResources); } @@ -1208,26 +1326,25 @@ public Mono<Application> createOrUpdateSuffixedApplication(Application applicati application.setName(actualName); Mono<User> userMono = sessionUserService.getCurrentUser().cache(); - Mono<Application> applicationWithPoliciesMono = this.setApplicationPolicies(userMono, application.getWorkspaceId(), application); - Mono<Application> applicationMono = applicationService.findByNameAndWorkspaceId(actualName, application.getWorkspaceId(), MANAGE_APPLICATIONS); + Mono<Application> applicationWithPoliciesMono = + this.setApplicationPolicies(userMono, application.getWorkspaceId(), application); + Mono<Application> applicationMono = applicationService.findByNameAndWorkspaceId( + actualName, application.getWorkspaceId(), MANAGE_APPLICATIONS); // We are taking pessimistic approach as this flow is used in import application where we are using transactions // which creates problem if we hit duplicate key exception return applicationMono - .flatMap(application1 -> - this.createOrUpdateSuffixedApplication(application, name, 1 + suffix) - ) - .switchIfEmpty(Mono.defer(() -> - applicationWithPoliciesMono - .zipWith(userMono) - .flatMap(tuple -> { - Application application1 = tuple.getT1(); - application1.setModifiedBy(tuple.getT2().getUsername()); // setting modified by to current user - // We can't use create or createApplication method here as we are expecting update operation if the - // _id is available with application object - return applicationService.save(application); - }) - )); + .flatMap(application1 -> this.createOrUpdateSuffixedApplication(application, name, 1 + suffix)) + .switchIfEmpty(Mono.defer( + () -> applicationWithPoliciesMono.zipWith(userMono).flatMap(tuple -> { + Application application1 = tuple.getT1(); + application1.setModifiedBy( + tuple.getT2().getUsername()); // setting modified by to current user + // We can't use create or createApplication method here as we are expecting update operation + // if the + // _id is available with application object + return applicationService.save(application); + }))); } /** @@ -1237,25 +1354,23 @@ public Mono<Application> createOrUpdateSuffixedApplication(Application applicati * @param application The newly created application by cloning * @return The newly created application by cloning */ - private Mono<Application> sendCloneApplicationAnalyticsEvent(Application sourceApplication, Application application) { - return workspaceService.getById(application.getWorkspaceId()) - .flatMap(workspace -> { - final Map<String, Object> eventData = Map.of( - FieldName.SOURCE_APPLICATION, sourceApplication, - FieldName.APPLICATION, application, - FieldName.WORKSPACE, workspace, - FieldName.APP_MODE, ApplicationMode.EDIT.toString() - ); - - final Map<String, Object> data = Map.of( - FieldName.SOURCE_APPLICATION_ID, sourceApplication.getId(), - FieldName.APPLICATION_ID, application.getId(), - FieldName.WORKSPACE_ID, workspace.getId(), - FieldName.EVENT_DATA, eventData - ); - - return analyticsService.sendObjectEvent(AnalyticsEvents.CLONE, application, data); - }); + private Mono<Application> sendCloneApplicationAnalyticsEvent( + Application sourceApplication, Application application) { + return workspaceService.getById(application.getWorkspaceId()).flatMap(workspace -> { + final Map<String, Object> eventData = Map.of( + FieldName.SOURCE_APPLICATION, sourceApplication, + FieldName.APPLICATION, application, + FieldName.WORKSPACE, workspace, + FieldName.APP_MODE, ApplicationMode.EDIT.toString()); + + final Map<String, Object> data = Map.of( + FieldName.SOURCE_APPLICATION_ID, sourceApplication.getId(), + FieldName.APPLICATION_ID, application.getId(), + FieldName.WORKSPACE_ID, workspace.getId(), + FieldName.EVENT_DATA, eventData); + + return analyticsService.sendObjectEvent(AnalyticsEvents.CLONE, application, data); + }); } /** @@ -1269,32 +1384,32 @@ private Mono<NewPage> sendPageViewAnalyticsEvent(NewPage newPage, boolean viewMo String view = viewMode ? ApplicationMode.PUBLISHED.toString() : ApplicationMode.EDIT.toString(); final Map<String, Object> eventData = Map.of( FieldName.PAGE, newPage, - FieldName.APP_MODE, view - ); + FieldName.APP_MODE, view); - final Map<String, Object> data = Map.of( - FieldName.EVENT_DATA, eventData - ); + final Map<String, Object> data = Map.of(FieldName.EVENT_DATA, eventData); return analyticsService.sendObjectEvent(AnalyticsEvents.VIEW, newPage, data); } - private Mono<Application> sendPageOrderAnalyticsEvent(Application application, String pageId, int order, String branchName) { - final Map<String, Object> eventData = Map.of( - FieldName.APPLICATION, application, - FieldName.APP_MODE, ApplicationMode.EDIT.toString() - ); + private Mono<Application> sendPageOrderAnalyticsEvent( + Application application, String pageId, int order, String branchName) { + final Map<String, Object> eventData = + Map.of(FieldName.APPLICATION, application, FieldName.APP_MODE, ApplicationMode.EDIT.toString()); final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, application.getId(), - FieldName.WORKSPACE_ID, application.getWorkspaceId(), - FieldName.PAGE_ID, pageId, - FieldName.PAGE_ORDER, order, - FieldName.EVENT_DATA, eventData, - FieldName.BRANCH_NAME, defaultIfNull(branchName, "") - ); + FieldName.APPLICATION_ID, + application.getId(), + FieldName.WORKSPACE_ID, + application.getWorkspaceId(), + FieldName.PAGE_ID, + pageId, + FieldName.PAGE_ORDER, + order, + FieldName.EVENT_DATA, + eventData, + FieldName.BRANCH_NAME, + defaultIfNull(branchName, "")); return analyticsService.sendObjectEvent(AnalyticsEvents.PAGE_REORDER, application, data); - } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCE.java index 18fe993fb3ad..513b3e306319 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCE.java @@ -45,7 +45,8 @@ public interface ApplicationServiceCE extends CrudService<Application, String> { Mono<Application> changeViewAccess(String id, ApplicationAccessDTO applicationAccessDTO); - Mono<Application> changeViewAccess(String defaultApplicationId, String branchName, ApplicationAccessDTO applicationAccessDTO); + Mono<Application> changeViewAccess( + String defaultApplicationId, String branchName, ApplicationAccessDTO applicationAccessDTO); Flux<Application> findAllApplicationsByWorkspaceId(String workspaceId); @@ -61,21 +62,20 @@ public interface ApplicationServiceCE extends CrudService<Application, String> { Mono<GitAuthDTO> getSshKey(String applicationId); - Mono<Application> findByBranchNameAndDefaultApplicationId(String branchName, - String defaultApplicationId, - AclPermission aclPermission); + Mono<Application> findByBranchNameAndDefaultApplicationId( + String branchName, String defaultApplicationId, AclPermission aclPermission); - Mono<String> findBranchedApplicationId(Optional<String> branchName, String defaultApplicationId, Optional<AclPermission> permission); + Mono<String> findBranchedApplicationId( + Optional<String> branchName, String defaultApplicationId, Optional<AclPermission> permission); - Mono<Application> findByBranchNameAndDefaultApplicationId(String branchName, - String defaultApplicationId, - List<String> projectionFieldNames, - AclPermission aclPermission); + Mono<Application> findByBranchNameAndDefaultApplicationId( + String branchName, + String defaultApplicationId, + List<String> projectionFieldNames, + AclPermission aclPermission); - Mono<Application> findByBranchNameAndDefaultApplicationIdAndFieldName(String branchName, - String defaultApplicationId, - String fieldName, - AclPermission aclPermission); + Mono<Application> findByBranchNameAndDefaultApplicationIdAndFieldName( + String branchName, String defaultApplicationId, String fieldName, AclPermission aclPermission); Mono<String> findBranchedApplicationId(String branchName, String defaultApplicationId, AclPermission permission); @@ -87,7 +87,8 @@ Mono<Application> findByBranchNameAndDefaultApplicationIdAndFieldName(String bra String getRandomAppCardColor(); - Mono<UpdateResult> setAppTheme(String applicationId, String editModeThemeId, String publishedModeThemeId, AclPermission aclPermission); + Mono<UpdateResult> setAppTheme( + String applicationId, String editModeThemeId, String publishedModeThemeId, AclPermission aclPermission); Mono<Application> getApplicationByDefaultApplicationIdAndDefaultBranch(String defaultApplicationId); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCEImpl.java index 63a167d98353..4ced8f9749b9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationServiceCEImpl.java @@ -68,7 +68,8 @@ import static org.apache.commons.lang3.StringUtils.isBlank; @Slf4j -public class ApplicationServiceCEImpl extends BaseService<ApplicationRepository, Application, String> implements ApplicationServiceCE { +public class ApplicationServiceCEImpl extends BaseService<ApplicationRepository, Application, String> + implements ApplicationServiceCE { private final PolicySolution policySolution; private final ConfigService configService; @@ -79,23 +80,24 @@ public class ApplicationServiceCEImpl extends BaseService<ApplicationRepository, private final DatasourcePermission datasourcePermission; private final ApplicationPermission applicationPermission; - private final static Integer MAX_RETRIES = 5; + private static final Integer MAX_RETRIES = 5; @Autowired - public ApplicationServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ApplicationRepository repository, - AnalyticsService analyticsService, - PolicySolution policySolution, - ConfigService configService, - ResponseUtils responseUtils, - PermissionGroupService permissionGroupService, - NewActionRepository newActionRepository, - AssetService assetService, - DatasourcePermission datasourcePermission, - ApplicationPermission applicationPermission) { + public ApplicationServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ApplicationRepository repository, + AnalyticsService analyticsService, + PolicySolution policySolution, + ConfigService configService, + ResponseUtils responseUtils, + PermissionGroupService permissionGroupService, + NewActionRepository newActionRepository, + AssetService assetService, + DatasourcePermission datasourcePermission, + ApplicationPermission applicationPermission) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.policySolution = policySolution; @@ -111,7 +113,9 @@ public ApplicationServiceCEImpl(Scheduler scheduler, @Override public Flux<Application> get(MultiValueMap<String, String> params) { if (!StringUtils.isEmpty(params.getFirst(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME))) { - params.add("gitApplicationMetadata.branchName", params.getFirst(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME)); + params.add( + "gitApplicationMetadata.branchName", + params.getFirst(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME)); params.remove(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME); } return setTransientFields(super.getWithPermission(params, applicationPermission.getReadPermission())) @@ -124,9 +128,11 @@ public Mono<Application> getById(String id) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ID)); } - return repository.findById(id, applicationPermission.getReadPermission()) + return repository + .findById(id, applicationPermission.getReadPermission()) .flatMap(this::setTransientFields) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, id))); + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, id))); } @Override @@ -136,34 +142,30 @@ public Mono<Application> findByIdAndBranchName(String id, String branchName) { @Override public Mono<Application> findByIdAndBranchName(String id, List<String> projectionFieldNames, String branchName) { - return this.findByBranchNameAndDefaultApplicationId(branchName, id, projectionFieldNames, - applicationPermission.getReadPermission()) + return this.findByBranchNameAndDefaultApplicationId( + branchName, id, projectionFieldNames, applicationPermission.getReadPermission()) .map(responseUtils::updateApplicationWithDefaultResources); } @Override public Mono<Application> findById(String id) { - return repository.findById(id) - .flatMap(this::setTransientFields); + return repository.findById(id).flatMap(this::setTransientFields); } @Override @Deprecated public Mono<Application> findById(String id, AclPermission aclPermission) { - return repository.findById(id, aclPermission) - .flatMap(this::setTransientFields); + return repository.findById(id, aclPermission).flatMap(this::setTransientFields); } @Override public Mono<Application> findById(String id, Optional<AclPermission> aclPermission) { - return repository.findById(id, aclPermission) - .flatMap(this::setTransientFields); + return repository.findById(id, aclPermission).flatMap(this::setTransientFields); } @Override public Mono<Application> findByIdAndWorkspaceId(String id, String workspaceId, AclPermission permission) { - return repository.findByIdAndWorkspaceId(id, workspaceId, permission) - .flatMap(this::setTransientFields); + return repository.findByIdAndWorkspaceId(id, workspaceId, permission).flatMap(this::setTransientFields); } @Override @@ -178,8 +180,7 @@ public Flux<Application> findByClonedFromApplicationId(String applicationId, Acl @Override public Mono<Application> findByName(String name, AclPermission permission) { - return repository.findByName(name, permission) - .flatMap(this::setTransientFields); + return repository.findByName(name, permission).flatMap(this::setTransientFields); } @Override @@ -193,17 +194,19 @@ public Mono<Application> save(Application application) { if (appVersion < ApplicationVersion.EARLIEST_VERSION || appVersion > ApplicationVersion.LATEST_VERSION) { return Mono.error(new AppsmithException( AppsmithError.INVALID_PARAMETER, - QApplication.application.applicationVersion.getMetadata().getName() - )); + QApplication.application + .applicationVersion + .getMetadata() + .getName())); } } - return repository.save(application) - .flatMap(this::setTransientFields); + return repository.save(application).flatMap(this::setTransientFields); } @Override public Mono<Application> create(Application object) { - throw new UnsupportedOperationException("Please use `ApplicationPageService.createApplication` to create an application."); + throw new UnsupportedOperationException( + "Please use `ApplicationPageService.createApplication` to create an application."); } /** @@ -223,20 +226,19 @@ private Mono<Application> createSuffixedApplication(Application application, Str if (!StringUtils.hasLength(application.getColor())) { application.setColor(getRandomAppCardColor()); } - return super.create(application) - .onErrorResume(DuplicateKeyException.class, error -> { - if (error.getMessage() != null - // Catch only if error message contains workspace_app_deleted_gitApplicationMetadata mongo error - && error.getMessage().contains("workspace_app_deleted_gitApplicationMetadata")) { - if (suffix > MAX_RETRIES) { - return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY_PAGE_RELOAD, name)); - } else { - // The duplicate key error is because of the `name` field. - return createSuffixedApplication(application, name, suffix + 1); - } - } - throw error; - }); + return super.create(application).onErrorResume(DuplicateKeyException.class, error -> { + if (error.getMessage() != null + // Catch only if error message contains workspace_app_deleted_gitApplicationMetadata mongo error + && error.getMessage().contains("workspace_app_deleted_gitApplicationMetadata")) { + if (suffix > MAX_RETRIES) { + return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY_PAGE_RELOAD, name)); + } else { + // The duplicate key error is because of the `name` field. + return createSuffixedApplication(application, name, suffix + 1); + } + } + throw error; + }); } /** @@ -264,61 +266,75 @@ public Mono<Application> update(String id, Application application) { if (appVersion < ApplicationVersion.EARLIEST_VERSION || appVersion > ApplicationVersion.LATEST_VERSION) { return Mono.error(new AppsmithException( AppsmithError.INVALID_PARAMETER, - QApplication.application.applicationVersion.getMetadata().getName() - )); + QApplication.application + .applicationVersion + .getMetadata() + .getName())); } } Mono<String> applicationIdMono; GitApplicationMetadata gitData = application.getGitApplicationMetadata(); - if (gitData != null && !StringUtils.isEmpty(gitData.getBranchName()) && !StringUtils.isEmpty(gitData.getDefaultApplicationId())) { - applicationIdMono = this.findByBranchNameAndDefaultApplicationId(gitData.getBranchName(), gitData.getDefaultApplicationId(), applicationPermission.getEditPermission()) + if (gitData != null + && !StringUtils.isEmpty(gitData.getBranchName()) + && !StringUtils.isEmpty(gitData.getDefaultApplicationId())) { + applicationIdMono = this.findByBranchNameAndDefaultApplicationId( + gitData.getBranchName(), + gitData.getDefaultApplicationId(), + applicationPermission.getEditPermission()) .map(Application::getId); } else { applicationIdMono = Mono.just(id); } - return applicationIdMono - .flatMap(appId -> repository.updateById(appId, application, applicationPermission.getEditPermission()) - .onErrorResume(error -> { - if (error instanceof DuplicateKeyException) { - // Error message : E11000 duplicate key error collection: appsmith.application index: - // workspace_app_deleted_gitApplicationMetadata dup key: - // { organizationId: "******", name: "AppName", deletedAt: null } - if (error.getCause().getMessage().contains("workspace_app_deleted_gitApplicationMetadata")) { - return Mono.error( - new AppsmithException(AppsmithError.DUPLICATE_KEY_USER_ERROR, FieldName.APPLICATION, FieldName.NAME) - ); - } - return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY, DuplicateKeyExceptionUtils.extractConflictingObjectName(((DuplicateKeyException) error).getCause().getMessage()))); - } - return Mono.error(error); - }) - .flatMap(application1 -> this.setTransientFields(application1)) - .flatMap(application1 -> { - final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.APPLICATION, application1 - ); - final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, application1.getId(), - FieldName.WORKSPACE_ID, application1.getWorkspaceId(), - FieldName.EVENT_DATA, eventData - ); - return analyticsService.sendUpdateEvent(application1, data); - })); - } - - public Mono<UpdateResult> update(String defaultApplicationId, Map<String, Object> fieldNameValueMap, String branchName) { + return applicationIdMono.flatMap(appId -> repository + .updateById(appId, application, applicationPermission.getEditPermission()) + .onErrorResume(error -> { + if (error instanceof DuplicateKeyException) { + // Error message : E11000 duplicate key error collection: appsmith.application index: + // workspace_app_deleted_gitApplicationMetadata dup key: + // { organizationId: "******", name: "AppName", deletedAt: null } + if (error.getCause().getMessage().contains("workspace_app_deleted_gitApplicationMetadata")) { + return Mono.error(new AppsmithException( + AppsmithError.DUPLICATE_KEY_USER_ERROR, FieldName.APPLICATION, FieldName.NAME)); + } + return Mono.error(new AppsmithException( + AppsmithError.DUPLICATE_KEY, + DuplicateKeyExceptionUtils.extractConflictingObjectName(((DuplicateKeyException) error) + .getCause() + .getMessage()))); + } + return Mono.error(error); + }) + .flatMap(application1 -> this.setTransientFields(application1)) + .flatMap(application1 -> { + final Map<String, Object> eventData = Map.of( + FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.APPLICATION, application1); + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, application1.getId(), + FieldName.WORKSPACE_ID, application1.getWorkspaceId(), + FieldName.EVENT_DATA, eventData); + return analyticsService.sendUpdateEvent(application1, data); + })); + } + + public Mono<UpdateResult> update( + String defaultApplicationId, Map<String, Object> fieldNameValueMap, String branchName) { String defaultIdPath = "id"; if (!isBlank(branchName)) { defaultIdPath = "gitApplicationMetadata.defaultApplicationId"; } - return repository.updateFieldByDefaultIdAndBranchName(defaultApplicationId, defaultIdPath, fieldNameValueMap, - branchName, "gitApplicationMetadata.branchName", MANAGE_APPLICATIONS); + return repository.updateFieldByDefaultIdAndBranchName( + defaultApplicationId, + defaultIdPath, + fieldNameValueMap, + branchName, + "gitApplicationMetadata.branchName", + MANAGE_APPLICATIONS); } public Mono<Application> update(String defaultApplicationId, Application application, String branchName) { - return this.findByBranchNameAndDefaultApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) + return this.findByBranchNameAndDefaultApplicationId( + branchName, defaultApplicationId, applicationPermission.getEditPermission()) .flatMap(branchedApplication -> { application.setPages(null); application.setGitApplicationMetadata(null); @@ -326,20 +342,29 @@ public Mono<Application> update(String defaultApplicationId, Application applica * Retaining the logoAssetId field value while updating NavigationSetting */ if (application.getUnpublishedApplicationDetail() != null) { - ApplicationDetail presetApplicationDetail = ObjectUtils.defaultIfNull(branchedApplication.getApplicationDetail(), new ApplicationDetail()); + ApplicationDetail presetApplicationDetail = ObjectUtils.defaultIfNull( + branchedApplication.getApplicationDetail(), new ApplicationDetail()); if (branchedApplication.getUnpublishedApplicationDetail() == null) { branchedApplication.setUnpublishedApplicationDetail(new ApplicationDetail()); } - Application.NavigationSetting requestNavSetting = application.getUnpublishedApplicationDetail().getNavigationSetting(); + Application.NavigationSetting requestNavSetting = + application.getUnpublishedApplicationDetail().getNavigationSetting(); if (requestNavSetting != null) { - Application.NavigationSetting presetNavSetting = ObjectUtils.defaultIfNull(branchedApplication.getUnpublishedApplicationDetail().getNavigationSetting(), new Application.NavigationSetting()); + Application.NavigationSetting presetNavSetting = ObjectUtils.defaultIfNull( + branchedApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting(), + new Application.NavigationSetting()); String presetLogoAssetId = ObjectUtils.defaultIfNull(presetNavSetting.getLogoAssetId(), ""); - String requestLogoAssetId = ObjectUtils.defaultIfNull(requestNavSetting.getLogoAssetId(), null); - requestNavSetting.setLogoAssetId(ObjectUtils.defaultIfNull(requestLogoAssetId, presetLogoAssetId)); + String requestLogoAssetId = + ObjectUtils.defaultIfNull(requestNavSetting.getLogoAssetId(), null); + requestNavSetting.setLogoAssetId( + ObjectUtils.defaultIfNull(requestLogoAssetId, presetLogoAssetId)); presetApplicationDetail.setNavigationSetting(requestNavSetting); } - Application.AppPositioning requestAppPositioning = application.getUnpublishedApplicationDetail().getAppPositioning(); + Application.AppPositioning requestAppPositioning = + application.getUnpublishedApplicationDetail().getAppPositioning(); if (requestAppPositioning != null) { presetApplicationDetail.setAppPositioning(requestAppPositioning); } @@ -357,16 +382,22 @@ public Mono<Application> archive(Application application) { @Override public Mono<Application> changeViewAccess(String id, ApplicationAccessDTO applicationAccessDTO) { - Mono<String> publicPermissionGroupIdMono = permissionGroupService.getPublicPermissionGroupId().cache(); + Mono<String> publicPermissionGroupIdMono = + permissionGroupService.getPublicPermissionGroupId().cache(); - Mono<Application> updateApplicationMono = repository.findById(id, applicationPermission.getMakePublicPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION, id))) + Mono<Application> updateApplicationMono = repository + .findById(id, applicationPermission.getMakePublicPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION, id))) .zipWith(publicPermissionGroupIdMono) .flatMap(tuple -> { Application application = tuple.getT1(); String publicPermissionGroupId = tuple.getT2(); - boolean isApplicationPublic = permissionGroupService.isEntityAccessible(application, applicationPermission.getReadPermission().getValue(), publicPermissionGroupId); + boolean isApplicationPublic = permissionGroupService.isEntityAccessible( + application, + applicationPermission.getReadPermission().getValue(), + publicPermissionGroupId); if (applicationAccessDTO.getPublicAccess().equals(isApplicationPublic)) { // No change. Return the application as is. @@ -375,29 +406,27 @@ public Mono<Application> changeViewAccess(String id, ApplicationAccessDTO applic // Now update the policies to change the access to the application return generateAndSetPoliciesForPublicView( - application, - publicPermissionGroupId, - applicationAccessDTO.getPublicAccess() - ); + application, publicPermissionGroupId, applicationAccessDTO.getPublicAccess()); }) .flatMap(this::setTransientFields); // Use a synchronous sink which does not take subscription cancellations into account. This that even if the // subscriber has cancelled its subscription, the create method will still generate its event. - return Mono.create(sink -> updateApplicationMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> updateApplicationMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override - public Mono<Application> changeViewAccess(String defaultApplicationId, - String branchName, - ApplicationAccessDTO applicationAccessDTO) { + public Mono<Application> changeViewAccess( + String defaultApplicationId, String branchName, ApplicationAccessDTO applicationAccessDTO) { // For git connected application update the policy for all the branch's - return findAllApplicationsByDefaultApplicationId(defaultApplicationId, applicationPermission.getMakePublicPermission()) - .switchIfEmpty(this.findByBranchNameAndDefaultApplicationId(branchName, defaultApplicationId, applicationPermission.getMakePublicPermission())) + return findAllApplicationsByDefaultApplicationId( + defaultApplicationId, applicationPermission.getMakePublicPermission()) + .switchIfEmpty(this.findByBranchNameAndDefaultApplicationId( + branchName, defaultApplicationId, applicationPermission.getMakePublicPermission())) .flatMap(branchedApplication -> changeViewAccess(branchedApplication.getId(), applicationAccessDTO)) - .then(repository.findById(defaultApplicationId, applicationPermission.getMakePublicPermission()) + .then(repository + .findById(defaultApplicationId, applicationPermission.getMakePublicPermission()) .flatMap(this::setTransientFields) .map(responseUtils::updateApplicationWithDefaultResources)); } @@ -410,29 +439,32 @@ public Flux<Application> findAllApplicationsByWorkspaceId(String workspaceId) { @Override public Mono<Application> getApplicationInViewMode(String defaultApplicationId, String branchName) { - return this.findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getReadPermission()) + return this.findBranchedApplicationId( + branchName, defaultApplicationId, applicationPermission.getReadPermission()) .flatMap(this::getApplicationInViewMode) .map(responseUtils::updateApplicationWithDefaultResources); } @Override public Mono<Application> getApplicationInViewMode(String applicationId) { - return repository.findById(applicationId, applicationPermission.getReadPermission()) + return repository + .findById(applicationId, applicationPermission.getReadPermission()) .map(application -> { application.setViewMode(true); return application; }); } - private Mono<? extends Application> generateAndSetPoliciesForPublicView(Application application, - String permissionGroupId, - Boolean addViewAccess) { + private Mono<? extends Application> generateAndSetPoliciesForPublicView( + Application application, String permissionGroupId, Boolean addViewAccess) { - Map<String, Policy> applicationPolicyMap = policySolution - .generatePolicyFromPermissionWithPermissionGroup(READ_APPLICATIONS, permissionGroupId); + Map<String, Policy> applicationPolicyMap = + policySolution.generatePolicyFromPermissionWithPermissionGroup(READ_APPLICATIONS, permissionGroupId); - List<Mono<Void>> updateInheritedDomainsList = updatePoliciesForInheritingDomains(application, applicationPolicyMap, addViewAccess); - List<Mono<Void>> updateIndependentDomainsList = updatePoliciesForIndependentDomains(application, permissionGroupId, addViewAccess); + List<Mono<Void>> updateInheritedDomainsList = + updatePoliciesForInheritingDomains(application, applicationPolicyMap, addViewAccess); + List<Mono<Void>> updateIndependentDomainsList = + updatePoliciesForIndependentDomains(application, permissionGroupId, addViewAccess); return Flux.fromIterable(updateInheritedDomainsList) .flatMap(voidMono -> voidMono) @@ -442,25 +474,26 @@ private Mono<? extends Application> generateAndSetPoliciesForPublicView(Applicat .flatMap(app -> { Application updatedApplication; if (addViewAccess) { - updatedApplication = policySolution.addPoliciesToExistingObject(applicationPolicyMap, application); + updatedApplication = + policySolution.addPoliciesToExistingObject(applicationPolicyMap, application); } else { - updatedApplication = policySolution.removePoliciesFromExistingObject(applicationPolicyMap, application); + updatedApplication = + policySolution.removePoliciesFromExistingObject(applicationPolicyMap, application); } return repository.save(updatedApplication); }); - } - protected List<Mono<Void>> updatePoliciesForIndependentDomains(Application application, - String permissionGroupId, - Boolean addViewAccess) { + protected List<Mono<Void>> updatePoliciesForIndependentDomains( + Application application, String permissionGroupId, Boolean addViewAccess) { List<Mono<Void>> list = new ArrayList<>(); - Map<String, Policy> datasourcePolicyMap = policySolution - .generatePolicyFromPermissionWithPermissionGroup(datasourcePermission.getExecutePermission(), permissionGroupId); + Map<String, Policy> datasourcePolicyMap = policySolution.generatePolicyFromPermissionWithPermissionGroup( + datasourcePermission.getExecutePermission(), permissionGroupId); - Mono<Void> updatedDatasourcesMono = newActionRepository.findByApplicationId(application.getId()) + Mono<Void> updatedDatasourcesMono = newActionRepository + .findByApplicationId(application.getId()) .collectList() .flatMap(actions -> { Set<String> datasourceIds = new HashSet<>(); @@ -468,25 +501,26 @@ protected List<Mono<Void>> updatePoliciesForIndependentDomains(Application appli ActionDTO unpublishedAction = action.getUnpublishedAction(); ActionDTO publishedAction = action.getPublishedAction(); - if (unpublishedAction.getDatasource() != null && - unpublishedAction.getDatasource().getId() != null) { + if (unpublishedAction.getDatasource() != null + && unpublishedAction.getDatasource().getId() != null) { datasourceIds.add(unpublishedAction.getDatasource().getId()); } - if (publishedAction != null && - publishedAction.getDatasource() != null && - publishedAction.getDatasource().getId() != null) { + if (publishedAction != null + && publishedAction.getDatasource() != null + && publishedAction.getDatasource().getId() != null) { datasourceIds.add(publishedAction.getDatasource().getId()); } } // Update the datasource policies without permission since the applications and datasources are at - // the same level in the hierarchy. A user may have permission to change view on application, but may + // the same level in the hierarchy. A user may have permission to change view on application, but + // may // not have explicit permissions on the datasource. - Mono<Void> updatedDatasourcesMono1 = - policySolution.updateWithNewPoliciesToDatasourcesByDatasourceIdsWithoutPermission(datasourceIds, - datasourcePolicyMap, addViewAccess) - .then(); + Mono<Void> updatedDatasourcesMono1 = policySolution + .updateWithNewPoliciesToDatasourcesByDatasourceIdsWithoutPermission( + datasourceIds, datasourcePolicyMap, addViewAccess) + .then(); return updatedDatasourcesMono1; }); @@ -495,19 +529,17 @@ protected List<Mono<Void>> updatePoliciesForIndependentDomains(Application appli return list; } - protected List<Mono<Void>> updatePoliciesForInheritingDomains(Application application, - Map<String, Policy> applicationPolicyMap, - Boolean addViewAccess) { + protected List<Mono<Void>> updatePoliciesForInheritingDomains( + Application application, Map<String, Policy> applicationPolicyMap, Boolean addViewAccess) { List<Mono<Void>> list = new ArrayList<>(); - Map<String, Policy> pagePolicyMap = policySolution - .generateInheritedPoliciesFromSourcePolicies(applicationPolicyMap, Application.class, Page.class); - Map<String, Policy> actionPolicyMap = policySolution - .generateInheritedPoliciesFromSourcePolicies(pagePolicyMap, Page.class, Action.class); + Map<String, Policy> pagePolicyMap = policySolution.generateInheritedPoliciesFromSourcePolicies( + applicationPolicyMap, Application.class, Page.class); + Map<String, Policy> actionPolicyMap = + policySolution.generateInheritedPoliciesFromSourcePolicies(pagePolicyMap, Page.class, Action.class); Map<String, Policy> themePolicyMap = policySolution.generateInheritedPoliciesFromSourcePolicies( - applicationPolicyMap, Application.class, Theme.class - ); + applicationPolicyMap, Application.class, Theme.class); final Mono<Void> updatedPagesMono = policySolution .updateWithApplicationPermissionsToAllItsPages(application.getId(), pagePolicyMap, addViewAccess) @@ -517,12 +549,14 @@ protected List<Mono<Void>> updatePoliciesForInheritingDomains(Application applic .updateWithPagePermissionsToAllItsActions(application.getId(), actionPolicyMap, addViewAccess) .then(); list.add(updatedActionsMono); - // Use the same policy map as actions for action collections since action collections have the same kind of permissions + // Use the same policy map as actions for action collections since action collections have the same kind of + // permissions final Mono<Void> updatedActionCollectionsMono = policySolution .updateWithPagePermissionsToAllItsActionCollections(application.getId(), actionPolicyMap, addViewAccess) .then(); list.add(updatedActionCollectionsMono); - final Mono<Void> updatedThemesMono = policySolution.updateThemePolicies(application, themePolicyMap, addViewAccess) + final Mono<Void> updatedThemesMono = policySolution + .updateThemePolicies(application, themePolicyMap, addViewAccess) .then(); list.add(updatedThemesMono); @@ -534,21 +568,29 @@ public Mono<Application> setTransientFields(Application application) { } private Flux<Application> setTransientFields(Flux<Application> applicationsFlux) { - Flux<String> publicPermissionGroupIdFlux = permissionGroupService.getPublicPermissionGroupId().cache().repeat(); + Flux<String> publicPermissionGroupIdFlux = + permissionGroupService.getPublicPermissionGroupId().cache().repeat(); // Set isPublic field if the application is public - Flux<Application> updatedApplicationWithIsPublicFlux = permissionGroupService.getPublicPermissionGroupId().cache().repeat() + Flux<Application> updatedApplicationWithIsPublicFlux = permissionGroupService + .getPublicPermissionGroupId() + .cache() + .repeat() .zipWith(applicationsFlux) .map(tuple -> { Application application = tuple.getT2(); String publicPermissionGroupId = tuple.getT1(); - application.setIsPublic(permissionGroupService.isEntityAccessible(application, applicationPermission.getReadPermission().getValue(), publicPermissionGroupId)); + application.setIsPublic(permissionGroupService.isEntityAccessible( + application, + applicationPermission.getReadPermission().getValue(), + publicPermissionGroupId)); return application; }); - return configService.getTemplateApplications() + return configService + .getTemplateApplications() .map(application -> application.getId()) .defaultIfEmpty("") .collectList() @@ -575,10 +617,10 @@ private Flux<Application> setTransientFields(Flux<Application> applicationsFlux) @Override public Mono<GitAuth> createOrUpdateSshKeyPair(String applicationId, String keyType) { GitAuth gitAuth = GitDeployKeyGenerator.generateSSHKey(keyType); - return repository.findById(applicationId, applicationPermission.getEditPermission()) + return repository + .findById(applicationId, applicationPermission.getEditPermission()) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "application", applicationId) - )) + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "application", applicationId))) .flatMap(application -> { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); // Check if the current application is the root application @@ -599,16 +641,20 @@ public Mono<GitAuth> createOrUpdateSshKeyPair(String applicationId, String keyTy return save(application); } // Children application with update SSH key request for root application - // Fetch root application and then make updates. We are storing the git metadata only in root application + // Fetch root application and then make updates. We are storing the git metadata only in root + // application if (StringUtils.isEmpty(gitData.getDefaultApplicationId())) { - throw new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, + throw new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, "Unable to find root application, please connect your application to remote repo to resolve this issue."); } gitAuth.setRegeneratedKey(true); - return repository.findById(gitData.getDefaultApplicationId(), applicationPermission.getEditPermission()) + return repository + .findById(gitData.getDefaultApplicationId(), applicationPermission.getEditPermission()) .flatMap(defaultApplication -> { - GitApplicationMetadata gitApplicationMetadata = defaultApplication.getGitApplicationMetadata(); + GitApplicationMetadata gitApplicationMetadata = + defaultApplication.getGitApplicationMetadata(); gitApplicationMetadata.setDefaultApplicationId(defaultApplication.getId()); gitApplicationMetadata.setGitAuth(gitAuth); defaultApplication.setGitApplicationMetadata(gitApplicationMetadata); @@ -619,16 +665,18 @@ public Mono<GitAuth> createOrUpdateSshKeyPair(String applicationId, String keyTy // Send generate SSH key analytics event assert application.getId() != null; final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.APPLICATION, application - ); + FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.APPLICATION, application); final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, application.getId(), - "organizationId", application.getWorkspaceId(), - "isRegeneratedKey", gitAuth.isRegeneratedKey(), - FieldName.EVENT_DATA, eventData - ); - return analyticsService.sendObjectEvent(AnalyticsEvents.GENERATE_SSH_KEY, application, data) + FieldName.APPLICATION_ID, + application.getId(), + "organizationId", + application.getWorkspaceId(), + "isRegeneratedKey", + gitAuth.isRegeneratedKey(), + FieldName.EVENT_DATA, + eventData); + return analyticsService + .sendObjectEvent(AnalyticsEvents.GENERATE_SSH_KEY, application, data) .onErrorResume(e -> { log.warn("Error sending ssh key generation data point", e); return Mono.just(application); @@ -645,18 +693,17 @@ public Mono<GitAuth> createOrUpdateSshKeyPair(String applicationId, String keyTy */ @Override public Mono<GitAuthDTO> getSshKey(String applicationId) { - return repository.findById(applicationId, applicationPermission.getEditPermission()) - .switchIfEmpty( - Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION_ID, applicationId)) - ) + return repository + .findById(applicationId, applicationPermission.getEditPermission()) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION_ID, applicationId))) .flatMap(application -> { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); List<GitDeployKeyDTO> gitDeployKeyDTOList = GitDeployKeyGenerator.getSupportedProtocols(); if (gitData == null) { return Mono.error(new AppsmithException( AppsmithError.INVALID_GIT_CONFIGURATION, - "Can't find valid SSH key. Please configure the application with git" - )); + "Can't find valid SSH key. Please configure the application with git")); } // Check if the application is root application if (applicationId.equals(gitData.getDefaultApplicationId())) { @@ -671,15 +718,16 @@ public Mono<GitAuthDTO> getSshKey(String applicationId) { if (gitData.getDefaultApplicationId() == null) { throw new AppsmithException( AppsmithError.INVALID_GIT_CONFIGURATION, - "Can't find root application. Please configure the application with git" - ); + "Can't find root application. Please configure the application with git"); } - - return repository.findById(gitData.getDefaultApplicationId(), applicationPermission.getEditPermission()) + return repository + .findById(gitData.getDefaultApplicationId(), applicationPermission.getEditPermission()) .map(rootApplication -> { GitAuthDTO gitAuthDTO = new GitAuthDTO(); - GitAuth gitAuth = rootApplication.getGitApplicationMetadata().getGitAuth(); + GitAuth gitAuth = rootApplication + .getGitApplicationMetadata() + .getGitAuth(); gitAuth.setDocUrl(Assets.GIT_DEPLOY_KEY_DOC_URL); gitAuthDTO.setPublicKey(gitAuth.getPublicKey()); gitAuthDTO.setPrivateKey(gitAuth.getPrivateKey()); @@ -690,46 +738,48 @@ public Mono<GitAuthDTO> getSshKey(String applicationId) { }); } - public Mono<Application> findByBranchNameAndDefaultApplicationId(String branchName, - String defaultApplicationId, - AclPermission aclPermission) { + public Mono<Application> findByBranchNameAndDefaultApplicationId( + String branchName, String defaultApplicationId, AclPermission aclPermission) { return findByBranchNameAndDefaultApplicationId(branchName, defaultApplicationId, null, aclPermission); } @Override - public Mono<Application> findByBranchNameAndDefaultApplicationId(String branchName, - String defaultApplicationId, - List<String> projectionFieldNames, - AclPermission aclPermission) { + public Mono<Application> findByBranchNameAndDefaultApplicationId( + String branchName, + String defaultApplicationId, + List<String> projectionFieldNames, + AclPermission aclPermission) { if (StringUtils.isEmpty(branchName)) { - return repository.findById(defaultApplicationId, projectionFieldNames, aclPermission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId)) - ); + return repository + .findById(defaultApplicationId, projectionFieldNames, aclPermission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId))); } - return repository.getApplicationByGitBranchAndDefaultApplicationId(defaultApplicationId, projectionFieldNames - , branchName, aclPermission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId + "," + branchName)) - ); + return repository + .getApplicationByGitBranchAndDefaultApplicationId( + defaultApplicationId, projectionFieldNames, branchName, aclPermission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + FieldName.APPLICATION, + defaultApplicationId + "," + branchName))); } @Override - public Mono<Application> findByBranchNameAndDefaultApplicationIdAndFieldName(String branchName, - String defaultApplicationId, - String fieldName, - AclPermission aclPermission) { + public Mono<Application> findByBranchNameAndDefaultApplicationIdAndFieldName( + String branchName, String defaultApplicationId, String fieldName, AclPermission aclPermission) { if (StringUtils.isEmpty(branchName)) { - return repository.findById(defaultApplicationId, aclPermission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId)) - ); + return repository + .findById(defaultApplicationId, aclPermission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId))); } - return repository.getApplicationByGitBranchAndDefaultApplicationId(defaultApplicationId, branchName, aclPermission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId + "," + branchName)) - ); + return repository + .getApplicationByGitBranchAndDefaultApplicationId(defaultApplicationId, branchName, aclPermission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + FieldName.APPLICATION, + defaultApplicationId + "," + branchName))); } /** @@ -746,38 +796,50 @@ public Mono<Application> saveLastEditInformation(String applicationId) { application.setLastEditedAt(Instant.now()); application.setIsManualUpdate(true); /* - We're not setting updatedAt and modifiedBy fields to the application DTO because these fields will be set - by the updateById method of the BaseAppsmithRepositoryImpl - */ - return repository.updateById(applicationId, application, applicationPermission.getEditPermission()) // it'll do a set operation + We're not setting updatedAt and modifiedBy fields to the application DTO because these fields will be set + by the updateById method of the BaseAppsmithRepositoryImpl + */ + return repository + .updateById( + applicationId, + application, + applicationPermission.getEditPermission()) // it'll do a set operation .flatMap(this::setTransientFields); } - public Mono<String> findBranchedApplicationId(String branchName, String defaultApplicationId, AclPermission permission) { + public Mono<String> findBranchedApplicationId( + String branchName, String defaultApplicationId, AclPermission permission) { if (!StringUtils.hasLength(branchName)) { if (!StringUtils.hasLength(defaultApplicationId)) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID, defaultApplicationId)); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID, defaultApplicationId)); } return Mono.just(defaultApplicationId); } - return repository.getApplicationByGitBranchAndDefaultApplicationId(defaultApplicationId, branchName, permission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId + ", " + branchName)) - ) + return repository + .getApplicationByGitBranchAndDefaultApplicationId(defaultApplicationId, branchName, permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + FieldName.APPLICATION, + defaultApplicationId + ", " + branchName))) .map(Application::getId); } - public Mono<String> findBranchedApplicationId(Optional<String> branchName, String defaultApplicationId, Optional<AclPermission> permission) { + public Mono<String> findBranchedApplicationId( + Optional<String> branchName, String defaultApplicationId, Optional<AclPermission> permission) { if (branchName.isEmpty()) { if (!StringUtils.hasLength(defaultApplicationId)) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID, defaultApplicationId)); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID, defaultApplicationId)); } return Mono.just(defaultApplicationId); } - return repository.getApplicationByGitBranchAndDefaultApplicationId(defaultApplicationId, branchName.get(), permission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId + ", " + branchName)) - ) + return repository + .getApplicationByGitBranchAndDefaultApplicationId(defaultApplicationId, branchName.get(), permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + FieldName.APPLICATION, + defaultApplicationId + ", " + branchName))) .map(Application::getId); } @@ -791,7 +853,8 @@ public Mono<String> findBranchedApplicationId(Optional<String> branchName, Strin * @return Application flux which match the condition */ @Override - public Flux<Application> findAllApplicationsByDefaultApplicationId(String defaultApplicationId, AclPermission permission) { + public Flux<Application> findAllApplicationsByDefaultApplicationId( + String defaultApplicationId, AclPermission permission) { return repository.getApplicationByGitDefaultApplicationId(defaultApplicationId, permission); } @@ -811,7 +874,8 @@ public String getRandomAppCardColor() { } @Override - public Mono<UpdateResult> setAppTheme(String applicationId, String editModeThemeId, String publishedModeThemeId, AclPermission aclPermission) { + public Mono<UpdateResult> setAppTheme( + String applicationId, String editModeThemeId, String publishedModeThemeId, AclPermission aclPermission) { return repository.setAppTheme(applicationId, editModeThemeId, publishedModeThemeId, aclPermission); } @@ -827,50 +891,50 @@ public Mono<Application> findByIdAndExportWithConfiguration(String applicationId @Override public Mono<Application> saveAppNavigationLogo(String branchName, String applicationId, Part filePart) { - return this.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return this.findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getEditPermission()) .flatMap(branchedApplication -> { - - branchedApplication.setUnpublishedApplicationDetail(ObjectUtils.defaultIfNull(branchedApplication.getUnpublishedApplicationDetail(), new ApplicationDetail())); + branchedApplication.setUnpublishedApplicationDetail(ObjectUtils.defaultIfNull( + branchedApplication.getUnpublishedApplicationDetail(), new ApplicationDetail())); Application.NavigationSetting rootAppUnpublishedNavigationSetting = ObjectUtils.defaultIfNull( - branchedApplication.getUnpublishedApplicationDetail().getNavigationSetting(), - new Application.NavigationSetting() - ); + branchedApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting(), + new Application.NavigationSetting()); - String rootAppLogoAssetId = ObjectUtils.defaultIfNull( - rootAppUnpublishedNavigationSetting.getLogoAssetId(), - "" - ); + String rootAppLogoAssetId = + ObjectUtils.defaultIfNull(rootAppUnpublishedNavigationSetting.getLogoAssetId(), ""); final Mono<String> prevAssetIdMono = Mono.just(rootAppLogoAssetId); final Mono<Asset> uploaderMono = assetService.upload(List.of(filePart), MAX_LOGO_SIZE_KB, false); - return Mono.zip(prevAssetIdMono, uploaderMono) - .flatMap(tuple -> { - final String oldAssetId = tuple.getT1(); - final Asset uploadedAsset = tuple.getT2(); - Application.NavigationSetting navSetting = ObjectUtils.defaultIfNull( - branchedApplication.getUnpublishedApplicationDetail().getNavigationSetting(), - new Application.NavigationSetting()); - navSetting.setLogoAssetId(uploadedAsset.getId()); - branchedApplication.getUnpublishedApplicationDetail().setNavigationSetting(navSetting); - - final Mono<Application> updateMono = this.update(applicationId, branchedApplication, branchName); - - if (!StringUtils.hasLength(oldAssetId)) { - return updateMono; - } else { - return assetService.remove(oldAssetId).then(updateMono); - } - - }); - + return Mono.zip(prevAssetIdMono, uploaderMono).flatMap(tuple -> { + final String oldAssetId = tuple.getT1(); + final Asset uploadedAsset = tuple.getT2(); + Application.NavigationSetting navSetting = ObjectUtils.defaultIfNull( + branchedApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting(), + new Application.NavigationSetting()); + navSetting.setLogoAssetId(uploadedAsset.getId()); + branchedApplication.getUnpublishedApplicationDetail().setNavigationSetting(navSetting); + + final Mono<Application> updateMono = + this.update(applicationId, branchedApplication, branchName); + + if (!StringUtils.hasLength(oldAssetId)) { + return updateMono; + } else { + return assetService.remove(oldAssetId).then(updateMono); + } + }); }); } - @Override - public Mono<Application> findByNameAndWorkspaceId(String applicationName, String workspaceId, AclPermission permission) { + public Mono<Application> findByNameAndWorkspaceId( + String applicationName, String workspaceId, AclPermission permission) { return repository.findByNameAndWorkspaceId(applicationName, workspaceId, permission); } @@ -881,15 +945,22 @@ public Mono<Boolean> isApplicationConnectedToGit(String applicationId) { } return this.getById(applicationId) .map(application -> application.getGitApplicationMetadata() != null - && StringUtils.hasLength(application.getGitApplicationMetadata().getRemoteUrl())); + && StringUtils.hasLength( + application.getGitApplicationMetadata().getRemoteUrl())); } @Override public Mono<Void> deleteAppNavigationLogo(String branchName, String applicationId) { - return this.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return this.findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getEditPermission()) .flatMap(branchedApplication -> { - branchedApplication.setUnpublishedApplicationDetail(ObjectUtils.defaultIfNull(branchedApplication.getUnpublishedApplicationDetail(), new ApplicationDetail())); - Application.NavigationSetting unpublishedNavSetting = ObjectUtils.defaultIfNull(branchedApplication.getUnpublishedApplicationDetail().getNavigationSetting(), new Application.NavigationSetting()); + branchedApplication.setUnpublishedApplicationDetail(ObjectUtils.defaultIfNull( + branchedApplication.getUnpublishedApplicationDetail(), new ApplicationDetail())); + Application.NavigationSetting unpublishedNavSetting = ObjectUtils.defaultIfNull( + branchedApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting(), + new Application.NavigationSetting()); String navLogoAssetId = ObjectUtils.defaultIfNull(unpublishedNavSetting.getLogoAssetId(), ""); @@ -900,7 +971,6 @@ public Mono<Void> deleteAppNavigationLogo(String branchName, String applicationI .flatMap(assetService::remove); } - @Override public Map<String, Object> getAnalyticsProperties(Application savedApplication) { Map<String, Object> analyticsProperties = new HashMap<>(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceCEImpl.java index bb8e490ecd4b..09eeb4d23064 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceCEImpl.java @@ -36,20 +36,20 @@ public class ApplicationSnapshotServiceCEImpl implements ApplicationSnapshotServ @Override public Mono<Boolean> createApplicationSnapshot(String applicationId, String branchName) { - return applicationService.findBranchedApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return applicationService + .findBranchedApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) /* SerialiseApplicationObjective=VERSION_CONTROL because this API can be invoked from developers. exportApplicationById method check for MANAGE_PERMISSION if SerialiseApplicationObjective=SHARE. */ - .flatMap(branchedAppId -> - Mono.zip( - importExportApplicationService.exportApplicationById(branchedAppId, SerialiseApplicationObjective.VERSION_CONTROL), - Mono.just(branchedAppId) - ) - ) + .flatMap(branchedAppId -> Mono.zip( + importExportApplicationService.exportApplicationById( + branchedAppId, SerialiseApplicationObjective.VERSION_CONTROL), + Mono.just(branchedAppId))) .flatMapMany(objects -> { String branchedAppId = objects.getT2(); ApplicationJson applicationJson = objects.getT1(); - return applicationSnapshotRepository.deleteAllByApplicationId(branchedAppId) + return applicationSnapshotRepository + .deleteAllByApplicationId(branchedAppId) .thenMany(createSnapshots(branchedAppId, applicationJson)); }) .then(Mono.just(Boolean.TRUE)); @@ -66,38 +66,37 @@ private Flux<ApplicationSnapshot> createSnapshots(String applicationId, Applicat @Override public Mono<ApplicationSnapshot> getWithoutDataByApplicationId(String applicationId, String branchName) { // get application first to check the permission and get child aka branched application ID - return applicationService.findBranchedApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return applicationService + .findBranchedApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) .flatMap(applicationSnapshotRepository::findWithoutData) .defaultIfEmpty(new ApplicationSnapshot()); } @Override public Mono<Application> restoreSnapshot(String applicationId, String branchName) { - return applicationService.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getEditPermission()) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId)) - ) - .flatMap( - application -> getApplicationJsonStringFromSnapShot(application.getId()) - .zipWith(Mono.just(application)) - ) + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) + .flatMap(application -> getApplicationJsonStringFromSnapShot(application.getId()) + .zipWith(Mono.just(application))) .flatMap(objects -> { String applicationJsonString = objects.getT1(); Application application = objects.getT2(); ApplicationJson applicationJson = gson.fromJson(applicationJsonString, ApplicationJson.class); return importExportApplicationService.restoreSnapshot( - application.getWorkspaceId(), applicationJson, application.getId(), branchName - ); + application.getWorkspaceId(), applicationJson, application.getId(), branchName); }) - .flatMap(application -> - applicationSnapshotRepository.deleteAllByApplicationId(application.getId()) - .thenReturn(application) - ) + .flatMap(application -> applicationSnapshotRepository + .deleteAllByApplicationId(application.getId()) + .thenReturn(application)) .map(responseUtils::updateApplicationWithDefaultResources); } private Mono<String> getApplicationJsonStringFromSnapShot(String applicationId) { - return applicationSnapshotRepository.findByApplicationId(applicationId) + return applicationSnapshotRepository + .findByApplicationId(applicationId) .sort(Comparator.comparingInt(ApplicationSnapshot::getChunkOrder)) .map(ApplicationSnapshot::getData) .collectList() @@ -140,12 +139,12 @@ private List<ApplicationSnapshot> createSnapshotsObjects(byte[] bytes, String ap @Override public Mono<Boolean> deleteSnapshot(String applicationId, String branchName) { // find root application by applicationId and branchName - return applicationService.findBranchedApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return applicationService + .findBranchedApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId)) - ) - .flatMap(branchedAppId -> - applicationSnapshotRepository.deleteAllByApplicationId(branchedAppId).thenReturn(Boolean.TRUE) - ); + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) + .flatMap(branchedAppId -> applicationSnapshotRepository + .deleteAllByApplicationId(branchedAppId) + .thenReturn(Boolean.TRUE)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCE.java index ac1cac12e218..bc8537c5156a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCE.java @@ -20,7 +20,8 @@ public interface ApplicationTemplateServiceCE { Mono<ApplicationImportDTO> importApplicationFromTemplate(String templateId, String workspaceId); - Mono<ApplicationImportDTO> mergeTemplateWithApplication(String templateId, String applicationId, String workspaceId, String branchName, List<String> pagesToImport); + Mono<ApplicationImportDTO> mergeTemplateWithApplication( + String templateId, String applicationId, String workspaceId, String branchName, List<String> pagesToImport); Mono<ApplicationTemplate> getFilters(); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java index f0d04cf285bf..7d61e471ead3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java @@ -41,7 +41,6 @@ import java.util.List; import java.util.Map; - @Service public class ApplicationTemplateServiceCEImpl implements ApplicationTemplateServiceCE { private final CloudServicesConfig cloudServicesConfig; @@ -53,14 +52,15 @@ public class ApplicationTemplateServiceCEImpl implements ApplicationTemplateServ private final ResponseUtils responseUtils; private final ApplicationPermission applicationPermission; - public ApplicationTemplateServiceCEImpl(CloudServicesConfig cloudServicesConfig, - ReleaseNotesService releaseNotesService, - ImportExportApplicationService importExportApplicationService, - AnalyticsService analyticsService, - UserDataService userDataService, - ApplicationService applicationService, - ResponseUtils responseUtils, - ApplicationPermission applicationPermission) { + public ApplicationTemplateServiceCEImpl( + CloudServicesConfig cloudServicesConfig, + ReleaseNotesService releaseNotesService, + ImportExportApplicationService importExportApplicationService, + AnalyticsService analyticsService, + UserDataService userDataService, + ApplicationService applicationService, + ResponseUtils responseUtils, + ApplicationPermission applicationPermission) { this.cloudServicesConfig = cloudServicesConfig; this.releaseNotesService = releaseNotesService; this.importExportApplicationService = importExportApplicationService; @@ -73,8 +73,7 @@ public ApplicationTemplateServiceCEImpl(CloudServicesConfig cloudServicesConfig, @Override public Flux<ApplicationTemplate> getSimilarTemplates(String templateId, MultiValueMap<String, String> params) { - UriComponents uriComponents = UriComponentsBuilder - .fromUriString(cloudServicesConfig.getBaseUrl()) + UriComponents uriComponents = UriComponentsBuilder.fromUriString(cloudServicesConfig.getBaseUrl()) .pathSegment("api/v1/app-templates", templateId, "similar") .queryParams(params) .queryParam("version", releaseNotesService.getRunningVersion()) @@ -82,26 +81,24 @@ public Flux<ApplicationTemplate> getSimilarTemplates(String templateId, MultiVal String apiUrl = uriComponents.toUriString(); - return WebClientUtils - .create(apiUrl) - .get() - .exchangeToFlux(clientResponse -> { - if (clientResponse.statusCode().equals(HttpStatus.OK)) { - return clientResponse.bodyToFlux(ApplicationTemplate.class); - } else if (clientResponse.statusCode().isError()) { - return Flux.error(new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, clientResponse.statusCode())); - } else { - return clientResponse.createException().flatMapMany(Flux::error); - } - }); + return WebClientUtils.create(apiUrl).get().exchangeToFlux(clientResponse -> { + if (clientResponse.statusCode().equals(HttpStatus.OK)) { + return clientResponse.bodyToFlux(ApplicationTemplate.class); + } else if (clientResponse.statusCode().isError()) { + return Flux.error( + new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, clientResponse.statusCode())); + } else { + return clientResponse.createException().flatMapMany(Flux::error); + } + }); } @Override public Mono<List<ApplicationTemplate>> getActiveTemplates(List<String> templateIds) { final String baseUrl = cloudServicesConfig.getBaseUrl(); - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.newInstance() - .queryParam("version", releaseNotesService.getRunningVersion()); + UriComponentsBuilder uriComponentsBuilder = + UriComponentsBuilder.newInstance().queryParam("version", releaseNotesService.getRunningVersion()); if (!CollectionUtils.isEmpty(templateIds)) { uriComponentsBuilder.queryParam("id", templateIds); @@ -110,34 +107,33 @@ public Mono<List<ApplicationTemplate>> getActiveTemplates(List<String> templateI // uriComponents will build url in format: version=version&id=id1&id=id2&id=id3 UriComponents uriComponents = uriComponentsBuilder.build(); - return WebClientUtils - .create(baseUrl + "/api/v1/app-templates?" + uriComponents.getQuery()) + return WebClientUtils.create(baseUrl + "/api/v1/app-templates?" + uriComponents.getQuery()) .get() .exchangeToFlux(clientResponse -> { if (clientResponse.statusCode().equals(HttpStatus.OK)) { return clientResponse.bodyToFlux(ApplicationTemplate.class); } else if (clientResponse.statusCode().isError()) { - return Flux.error(new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, clientResponse.statusCode())); + return Flux.error( + new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, clientResponse.statusCode())); } else { return clientResponse.createException().flatMapMany(Flux::error); } }) - .collectList().zipWith(userDataService.getForCurrentUser()) + .collectList() + .zipWith(userDataService.getForCurrentUser()) .map(objects -> { List<ApplicationTemplate> applicationTemplateList = objects.getT1(); UserData userData = objects.getT2(); List<String> recentlyUsedTemplateIds = userData.getRecentlyUsedTemplateIds(); if (!CollectionUtils.isEmpty(recentlyUsedTemplateIds)) { - applicationTemplateList.sort( - Comparator.comparingInt(o -> { - int index = recentlyUsedTemplateIds.indexOf(o.getId()); - if (index < 0) { - // template not in recent list, return a large value so that it's sorted out to the end - index = Integer.MAX_VALUE; - } - return index; - }) - ); + applicationTemplateList.sort(Comparator.comparingInt(o -> { + int index = recentlyUsedTemplateIds.indexOf(o.getId()); + if (index < 0) { + // template not in recent list, return a large value so that it's sorted out to the end + index = Integer.MAX_VALUE; + } + return index; + })); } return applicationTemplateList; }); @@ -147,14 +143,14 @@ public Mono<List<ApplicationTemplate>> getActiveTemplates(List<String> templateI public Mono<ApplicationTemplate> getTemplateDetails(String templateId) { final String baseUrl = cloudServicesConfig.getBaseUrl(); - return WebClientUtils - .create(baseUrl + "/api/v1/app-templates/" + templateId) + return WebClientUtils.create(baseUrl + "/api/v1/app-templates/" + templateId) .get() .exchangeToMono(clientResponse -> { if (clientResponse.statusCode().equals(HttpStatus.OK)) { return clientResponse.bodyToMono(ApplicationTemplate.class); } else if (clientResponse.statusCode().isError()) { - return Mono.error(new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, clientResponse.statusCode())); + return Mono.error( + new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, clientResponse.statusCode())); } else { return clientResponse.createException().flatMap(Mono::error); } @@ -164,9 +160,9 @@ public Mono<ApplicationTemplate> getTemplateDetails(String templateId) { private Mono<ApplicationJson> getApplicationJsonFromTemplate(String templateId) { final String baseUrl = cloudServicesConfig.getBaseUrl(); final String templateUrl = baseUrl + "/api/v1/app-templates/" + templateId + "/application"; - /* using a custom url builder factory because default builder always encodes URL. - It's expected that the appDataUrl is already encoded, so we don't need to encode that again. - Encoding an encoded URL will not work and end up resulting a 404 error */ + /* using a custom url builder factory because default builder always encodes URL. + It's expected that the appDataUrl is already encoded, so we don't need to encode that again. + Encoding an encoded URL will not work and end up resulting a 404 error */ final int size = 4 * 1024 * 1024; // 4 MB final ExchangeStrategies strategies = ExchangeStrategies.builder() .codecs(codecs -> codecs.defaultCodecs().maxInMemorySize(size)) @@ -185,68 +181,64 @@ private Mono<ApplicationJson> getApplicationJsonFromTemplate(String templateId) Gson gson = new GsonBuilder() .registerTypeAdapter(Instant.class, new ISOStringToInstantConverter()) .create(); - Type fileType = new TypeToken<ApplicationJson>() { - }.getType(); + Type fileType = new TypeToken<ApplicationJson>() {}.getType(); ApplicationJson jsonFile = gson.fromJson(jsonString, fileType); return jsonFile; }) .switchIfEmpty( - Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "template", templateId)) - ); + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "template", templateId))); } @Override public Mono<ApplicationImportDTO> importApplicationFromTemplate(String templateId, String workspaceId) { return getApplicationJsonFromTemplate(templateId) - .flatMap(applicationJson -> importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson)) - .flatMap(application -> importExportApplicationService - .getApplicationImportDTO(application.getId(), application.getWorkspaceId(), application)) + .flatMap(applicationJson -> importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson)) + .flatMap(application -> importExportApplicationService.getApplicationImportDTO( + application.getId(), application.getWorkspaceId(), application)) .flatMap(applicationImportDTO -> { Application application = applicationImportDTO.getApplication(); ApplicationTemplate applicationTemplate = new ApplicationTemplate(); applicationTemplate.setId(templateId); final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.APPLICATION, application - ); + FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.APPLICATION, application); final Map<String, Object> data = Map.of( FieldName.APPLICATION_ID, application.getId(), FieldName.WORKSPACE_ID, application.getWorkspaceId(), FieldName.TEMPLATE_APPLICATION_NAME, application.getName(), - FieldName.EVENT_DATA, eventData - ); + FieldName.EVENT_DATA, eventData); - return analyticsService.sendObjectEvent(AnalyticsEvents.FORK, applicationTemplate, data) + return analyticsService + .sendObjectEvent(AnalyticsEvents.FORK, applicationTemplate, data) .thenReturn(applicationImportDTO); }); } @Override public Mono<List<ApplicationTemplate>> getRecentlyUsedTemplates() { - return userDataService.getForCurrentUser() - .flatMap(userData -> { - List<String> templateIds = userData.getRecentlyUsedTemplateIds(); - if (!CollectionUtils.isEmpty(templateIds)) { - return getActiveTemplates(templateIds); - } - return Mono.empty(); - }); + return userDataService.getForCurrentUser().flatMap(userData -> { + List<String> templateIds = userData.getRecentlyUsedTemplateIds(); + if (!CollectionUtils.isEmpty(templateIds)) { + return getActiveTemplates(templateIds); + } + return Mono.empty(); + }); } @Override public Mono<ApplicationTemplate> getFilters() { final String baseUrl = cloudServicesConfig.getBaseUrl(); - return WebClientUtils - .create(baseUrl + "/api/v1/app-templates/filters") + return WebClientUtils.create(baseUrl + "/api/v1/app-templates/filters") .get() .exchangeToMono(clientResponse -> { if (clientResponse.statusCode().equals(HttpStatus.OK)) { return clientResponse.bodyToMono(ApplicationTemplate.class); } else if (clientResponse.statusCode().isError()) { - return Mono.error(new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, clientResponse.statusCode())); + return Mono.error( + new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, clientResponse.statusCode())); } else { return clientResponse.createException().flatMap(Mono::error); } @@ -270,45 +262,51 @@ public NoEncodingUriBuilderFactory(String baseUriTemplate) { * subscription, the create method still generates its event. */ @Override - public Mono<ApplicationImportDTO> mergeTemplateWithApplication(String templateId, - String applicationId, - String organizationId, - String branchName, - List<String> pagesToImport) { + public Mono<ApplicationImportDTO> mergeTemplateWithApplication( + String templateId, + String applicationId, + String organizationId, + String branchName, + List<String> pagesToImport) { Mono<ApplicationImportDTO> importedApplicationMono = getApplicationJsonFromTemplate(templateId) .flatMap(applicationJson -> { if (branchName != null) { - return applicationService.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) - .flatMap(application -> importExportApplicationService.mergeApplicationJsonWithApplication(organizationId, application.getId(), branchName, applicationJson, pagesToImport)); + return applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getEditPermission()) + .flatMap(application -> + importExportApplicationService.mergeApplicationJsonWithApplication( + organizationId, + application.getId(), + branchName, + applicationJson, + pagesToImport)); } - return importExportApplicationService.mergeApplicationJsonWithApplication(organizationId, applicationId, branchName, applicationJson, pagesToImport); + return importExportApplicationService.mergeApplicationJsonWithApplication( + organizationId, applicationId, branchName, applicationJson, pagesToImport); }) .flatMap(application -> importExportApplicationService.getApplicationImportDTO( - application.getId(), application.getWorkspaceId(), application) - ) + application.getId(), application.getWorkspaceId(), application)) .flatMap(applicationImportDTO -> { responseUtils.updateApplicationWithDefaultResources(applicationImportDTO.getApplication()); Application application = applicationImportDTO.getApplication(); ApplicationTemplate applicationTemplate = new ApplicationTemplate(); applicationTemplate.setId(templateId); final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.APPLICATION, application - ); + FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.APPLICATION, application); final Map<String, Object> data = Map.of( FieldName.APPLICATION_ID, application.getId(), FieldName.WORKSPACE_ID, application.getWorkspaceId(), FieldName.TEMPLATE_APPLICATION_NAME, application.getName(), - FieldName.EVENT_DATA, eventData - ); + FieldName.EVENT_DATA, eventData); - return analyticsService.sendObjectEvent(AnalyticsEvents.FORK, applicationTemplate, data) + return analyticsService + .sendObjectEvent(AnalyticsEvents.FORK, applicationTemplate, data) .thenReturn(applicationImportDTO); }); - return Mono.create(sink -> importedApplicationMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> importedApplicationMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AssetServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AssetServiceCEImpl.java index afb8b47b2a71..faa3d19b62f2 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AssetServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AssetServiceCEImpl.java @@ -43,13 +43,10 @@ public class AssetServiceCEImpl implements AssetServiceCE { MediaType.IMAGE_JPEG, MediaType.IMAGE_PNG, MediaType.valueOf("image/x-icon"), - MediaType.valueOf("image/vnd.microsoft.icon") - ); + MediaType.valueOf("image/vnd.microsoft.icon")); - private static final Set<String> ALLOWED_CONTENT_TYPES_STR = Set.of( - MediaType.IMAGE_JPEG_VALUE, - MediaType.IMAGE_PNG_VALUE - ); + private static final Set<String> ALLOWED_CONTENT_TYPES_STR = + Set.of(MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE); @Override public Mono<Asset> getById(String id) { @@ -62,11 +59,11 @@ private Boolean checkImageTypeValidation(DataBuffer dataBuffer, MediaType conten dataBuffer.readPosition(0); if (bufferedImage == null) { /* - This is true for SVG and ICO images. - If ImageIO.read returns bufferedImage as null and the contentType file extension is .png or .jpeg which - means the file is not an image type file rather any other corrupted file but the extension has been - changed to .png or .jpeg to upload the flawed file. This is a security vulnerability hence reject - */ + This is true for SVG and ICO images. + If ImageIO.read returns bufferedImage as null and the contentType file extension is .png or .jpeg which + means the file is not an image type file rather any other corrupted file but the extension has been + changed to .png or .jpeg to upload the flawed file. This is a security vulnerability hence reject + */ if (ALLOWED_CONTENT_TYPES_STR.contains(contentType.toString())) { return false; } @@ -90,11 +87,11 @@ public Mono<Asset> upload(List<Part> fileParts, int maxFileSizeKB, boolean isThu if (contentType == null || !ALLOWED_CONTENT_TYPES.contains(contentType)) { return Mono.error(new AppsmithException( AppsmithError.VALIDATION_FAILURE, - "Please upload a valid image. Only JPEG, PNG, SVG and ICO are allowed." - )); + "Please upload a valid image. Only JPEG, PNG, SVG and ICO are allowed.")); } - final Flux<DataBuffer> contentCache = Flux.fromIterable(fileParts).flatMap(Part::content).cache(); + final Flux<DataBuffer> contentCache = + Flux.fromIterable(fileParts).flatMap(Part::content).cache(); return contentCache .map(DataBuffer::readableByteCount) @@ -128,16 +125,20 @@ public Mono<Asset> upload(List<Part> fileParts, int maxFileSizeKB, boolean isThu public Mono<Void> remove(String assetId) { final Asset tempAsset = new Asset(); tempAsset.setId(assetId); - return repository.deleteById(assetId) + return repository + .deleteById(assetId) .then(analyticsService.sendDeleteEvent(tempAsset)) .then(); } - private Asset createAsset(DataBuffer dataBuffer, MediaType srcContentType, boolean createThumbnail) throws IOException { + private Asset createAsset(DataBuffer dataBuffer, MediaType srcContentType, boolean createThumbnail) + throws IOException { MediaType contentType = srcContentType; Boolean isValidImage = checkImageTypeValidation(dataBuffer, contentType); if (isValidImage != true) { - throw new AppsmithException(AppsmithError.VALIDATION_FAILURE, "Please upload a valid image. Only JPEG, PNG, SVG and ICO are allowed."); + throw new AppsmithException( + AppsmithError.VALIDATION_FAILURE, + "Please upload a valid image. Only JPEG, PNG, SVG and ICO are allowed."); } byte[] imageData = null; @@ -146,7 +147,8 @@ private Asset createAsset(DataBuffer dataBuffer, MediaType srcContentType, boole try { imageData = resizeImage(dataBuffer); } finally { - // The `resizeImage` function, calls `ImageIO.read` which changes the read position of this `dataBuffer`. + // The `resizeImage` function, calls `ImageIO.read` which changes the read position of this + // `dataBuffer`. // This becomes a problem for us, since we attempt to read it ourselves, if the image is not resized. dataBuffer.readPosition(0); } @@ -184,19 +186,17 @@ private byte[] resizeImage(DataBuffer dataBuffer) throws IOException { @Override public Mono<Void> makeImageResponse(ServerWebExchange exchange, String assetId) { - return getById(assetId) - .flatMap(asset -> { - final String contentType = asset.getContentType(); - final ServerHttpResponse response = exchange.getResponse(); + return getById(assetId).flatMap(asset -> { + final String contentType = asset.getContentType(); + final ServerHttpResponse response = exchange.getResponse(); - response.setStatusCode(HttpStatus.OK); + response.setStatusCode(HttpStatus.OK); - if (contentType != null) { - response.getHeaders().set(HttpHeaders.CONTENT_TYPE, contentType); - } + if (contentType != null) { + response.getHeaders().set(HttpHeaders.CONTENT_TYPE, contentType); + } - return response.writeWith(Mono.just(new DefaultDataBufferFactory().wrap(asset.getData()))); - }); + return response.writeWith(Mono.just(new DefaultDataBufferFactory().wrap(asset.getData()))); + }); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AstServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AstServiceCE.java index 7fdc1059211d..b4a9f6f7cdc8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AstServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AstServiceCE.java @@ -22,7 +22,13 @@ public interface AstServiceCE { * @param evalVersion : The evaluated value version of the current app to be used while AST parsing * @return A mono of list of strings that represent all valid global references in the binding string */ - Flux<Tuple2<String, Set<String>>> getPossibleReferencesFromDynamicBinding(List<String> bindingValues, int evalVersion); + Flux<Tuple2<String, Set<String>>> getPossibleReferencesFromDynamicBinding( + List<String> bindingValues, int evalVersion); - Mono<Map<MustacheBindingToken, String>> refactorNameInDynamicBindings(Set<MustacheBindingToken> bindingValues, String oldName, String newName, int evalVersion, boolean isJSObject); + Mono<Map<MustacheBindingToken, String>> refactorNameInDynamicBindings( + Set<MustacheBindingToken> bindingValues, + String oldName, + String newName, + int evalVersion, + boolean isJSObject); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AstServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AstServiceCEImpl.java index 0e04c4a41f73..810cdbdb234c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AstServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AstServiceCEImpl.java @@ -48,17 +48,18 @@ public class AstServiceCEImpl implements AstServiceCE { .pendingAcquireMaxCount(-1) .build()); - private final static long MAX_API_RESPONSE_TIME_IN_MS = 50; + private static final long MAX_API_RESPONSE_TIME_IN_MS = 50; @Override - public Flux<Tuple2<String, Set<String>>> getPossibleReferencesFromDynamicBinding(List<String> bindingValues, int evalVersion) { - if (bindingValues == null || bindingValues.size() == 0) { + public Flux<Tuple2<String, Set<String>>> getPossibleReferencesFromDynamicBinding( + List<String> bindingValues, int evalVersion) { + if (bindingValues == null || bindingValues.isEmpty()) { return Flux.empty(); } /* - For the binding value which starts with "appsmith.theme" can be directly served - without calling the AST API or the calling the method for non-AST implementation - */ + For the binding value which starts with "appsmith.theme" can be directly served + without calling the AST API or the calling the method for non-AST implementation + */ if (bindingValues.size() == 1 && bindingValues.get(0).startsWith("appsmith.theme.")) { return Flux.just(Tuples.of(bindingValues.get(0), new HashSet<>(bindingValues))); } @@ -66,12 +67,11 @@ public Flux<Tuple2<String, Set<String>>> getPossibleReferencesFromDynamicBinding // If RTS server is not accessible for this instance, it means that this is a slim container set up // Proceed with assuming that all words need to be processed as possible entity references if (Boolean.FALSE.equals(instanceConfig.getIsRtsAccessible())) { - return Flux.fromIterable(bindingValues) - .flatMap( - bindingValue -> { - return Mono.zip(Mono.just(bindingValue), Mono.just(new HashSet<>(MustacheHelper.getPossibleParentsOld(bindingValue)))); - } - ); + return Flux.fromIterable(bindingValues).flatMap(bindingValue -> { + return Mono.zip( + Mono.just(bindingValue), + Mono.just(new HashSet<>(MustacheHelper.getPossibleParentsOld(bindingValue)))); + }); } return webClient .post() @@ -92,14 +92,20 @@ public Flux<Tuple2<String, Set<String>>> getPossibleReferencesFromDynamicBinding } @Override - public Mono<Map<MustacheBindingToken, String>> refactorNameInDynamicBindings(Set<MustacheBindingToken> bindingValues, String oldName, String newName, int evalVersion, boolean isJSObject) { + public Mono<Map<MustacheBindingToken, String>> refactorNameInDynamicBindings( + Set<MustacheBindingToken> bindingValues, + String oldName, + String newName, + int evalVersion, + boolean isJSObject) { if (bindingValues == null || bindingValues.isEmpty()) { return Mono.empty(); } return Flux.fromIterable(bindingValues) .flatMap(bindingValue -> { - EntityRefactorRequest entityRefactorRequest = new EntityRefactorRequest(bindingValue.getValue(), oldName, newName, evalVersion, isJSObject); + EntityRefactorRequest entityRefactorRequest = new EntityRefactorRequest( + bindingValue.getValue(), oldName, newName, evalVersion, isJSObject); return webClient .post() .uri(commonConfig.getRtsBaseUrl() + "/rts-api/v1/ast/entity-refactor") @@ -109,9 +115,12 @@ public Mono<Map<MustacheBindingToken, String>> refactorNameInDynamicBindings(Set .toEntity(EntityRefactorResponse.class) .flatMap(entityRefactorResponseResponseEntity -> { if (HttpStatus.OK.equals(entityRefactorResponseResponseEntity.getStatusCode())) { - return Mono.just(Objects.requireNonNull(entityRefactorResponseResponseEntity.getBody())); + return Mono.just( + Objects.requireNonNull(entityRefactorResponseResponseEntity.getBody())); } - return Mono.error(new AppsmithException(AppsmithError.RTS_SERVER_ERROR, entityRefactorResponseResponseEntity.getStatusCodeValue())); + return Mono.error(new AppsmithException( + AppsmithError.RTS_SERVER_ERROR, + entityRefactorResponseResponseEntity.getStatusCodeValue())); }) .elapsed() .map(tuple -> { @@ -126,7 +135,8 @@ public Mono<Map<MustacheBindingToken, String>> refactorNameInDynamicBindings(Set .flatMap(response -> Mono.just(bindingValue).zipWith(Mono.just(response.script))) .onErrorResume(error -> { var temp = bindingValue; - // If there is a problem with parsing and refactoring this binding, we just ignore it and move ahead + // If there is a problem with parsing and refactoring this binding, we just ignore it + // and move ahead // The expectation is that this binding would error out during eval anyway return Mono.empty(); }); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AuthenticationValidatorCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AuthenticationValidatorCE.java index 201012451c71..5fb4ae788a4b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AuthenticationValidatorCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AuthenticationValidatorCE.java @@ -3,9 +3,7 @@ import com.appsmith.external.models.DatasourceStorage; import reactor.core.publisher.Mono; - public interface AuthenticationValidatorCE { Mono<DatasourceStorage> validateAuthentication(DatasourceStorage datasourceStorage); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AuthenticationValidatorCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AuthenticationValidatorCEImpl.java index 9fb364c76158..a96b97accfee 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AuthenticationValidatorCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AuthenticationValidatorCEImpl.java @@ -15,11 +15,14 @@ public class AuthenticationValidatorCEImpl implements AuthenticationValidatorCE private final AuthenticationService authenticationService; public Mono<DatasourceStorage> validateAuthentication(DatasourceStorage datasourceStorage) { - if (datasourceStorage.getDatasourceConfiguration() == null || datasourceStorage.getDatasourceConfiguration().getAuthentication() == null) { + if (datasourceStorage.getDatasourceConfiguration() == null + || datasourceStorage.getDatasourceConfiguration().getAuthentication() == null) { return Mono.just(datasourceStorage); } - AuthenticationDTO authentication = datasourceStorage.getDatasourceConfiguration().getAuthentication(); - return authentication.hasExpired() + AuthenticationDTO authentication = + datasourceStorage.getDatasourceConfiguration().getAuthentication(); + return authentication + .hasExpired() .filter(expired -> expired) .flatMap(expired -> { if (authentication instanceof OAuth2) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/BaseApiImporterCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/BaseApiImporterCE.java index ce7381ad0f95..3e618e0c1055 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/BaseApiImporterCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/BaseApiImporterCE.java @@ -5,6 +5,6 @@ public abstract class BaseApiImporterCE implements ApiImporterCE { - public abstract Mono<ActionDTO> importAction(Object input, String pageId, String name, String workspaceId, String branchName); - + public abstract Mono<ActionDTO> importAction( + Object input, String pageId, String name, String workspaceId, String branchName); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CacheableFeatureFlagHelperCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CacheableFeatureFlagHelperCEImpl.java index a3252bd3fe19..0ebbbcae9a50 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CacheableFeatureFlagHelperCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CacheableFeatureFlagHelperCEImpl.java @@ -28,8 +28,8 @@ public class CacheableFeatureFlagHelperCEImpl implements CacheableFeatureFlagHel private final CloudServicesConfig cloudServicesConfig; - public CacheableFeatureFlagHelperCEImpl(TenantService tenantService, ConfigService configService, - CloudServicesConfig cloudServicesConfig) { + public CacheableFeatureFlagHelperCEImpl( + TenantService tenantService, ConfigService configService, CloudServicesConfig cloudServicesConfig) { this.tenantService = tenantService; this.configService = configService; this.cloudServicesConfig = cloudServicesConfig; @@ -59,10 +59,7 @@ private Mono<Map<String, Boolean>> forceAllRemoteFeatureFlagsForUser(String user return Mono.zip(instanceIdMono, defaultTenantIdMono) .flatMap(tuple2 -> { return this.getRemoteFeatureFlagsByIdentity( - new FeatureFlagIdentities( - tuple2.getT1(), - tuple2.getT2(), - Set.of(userIdentifier))); + new FeatureFlagIdentities(tuple2.getT1(), tuple2.getT2(), Set.of(userIdentifier))); }) .map(newValue -> newValue.get(userIdentifier)); } @@ -74,9 +71,8 @@ private Mono<Map<String, Map<String, Boolean>>> getRemoteFeatureFlagsByIdentity( .body(BodyInserters.fromValue(identity)) .exchangeToMono(clientResponse -> { if (clientResponse.statusCode().is2xxSuccessful()) { - return clientResponse.bodyToMono(new ParameterizedTypeReference<ResponseDTO<Map<String, - Map<String, Boolean>>>>() { - }); + return clientResponse.bodyToMono( + new ParameterizedTypeReference<ResponseDTO<Map<String, Map<String, Boolean>>>>() {}); } else { return clientResponse.createError(); } @@ -85,8 +81,7 @@ private Mono<Map<String, Map<String, Boolean>>> getRemoteFeatureFlagsByIdentity( .onErrorMap( // Only map errors if we haven't already wrapped them into an AppsmithException e -> !(e instanceof AppsmithException), - e -> new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, e.getMessage()) - ) + e -> new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, e.getMessage())) .onErrorResume(error -> { // We're gobbling up errors here so that all feature flags are turned off by default // This will be problematic if we do not maintain code to reflect validity of flags diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CaptchaServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CaptchaServiceCE.java index fbf2ad5de4d4..aaddcbd46979 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CaptchaServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CaptchaServiceCE.java @@ -5,5 +5,4 @@ public interface CaptchaServiceCE { Mono<Boolean> verify(String recaptchaResponse); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CollectionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CollectionServiceCEImpl.java index 639c3f2bb05c..fe56d49015a2 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CollectionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CollectionServiceCEImpl.java @@ -21,14 +21,16 @@ import java.util.ListIterator; @Slf4j -public class CollectionServiceCEImpl extends BaseService<CollectionRepository, Collection, String> implements CollectionServiceCE { +public class CollectionServiceCEImpl extends BaseService<CollectionRepository, Collection, String> + implements CollectionServiceCE { - public CollectionServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - CollectionRepository repository, - AnalyticsService analyticsService) { + public CollectionServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + CollectionRepository repository, + AnalyticsService analyticsService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); } @@ -41,7 +43,6 @@ public Mono<Collection> findById(String id) { public Mono<Collection> addActionsToCollection(Collection collection, List<NewAction> actions) { collection.setActions(actions); return repository.save(collection); - } @Override @@ -55,7 +56,8 @@ public Mono<ActionDTO> addSingleActionToCollection(String collectionId, ActionDT return repository .findById(collectionId) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.COLLECTION_ID))) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.COLLECTION_ID))) .flatMap(collection1 -> { List<NewAction> actions = collection1.getActions(); if (actions == null) { @@ -87,7 +89,8 @@ public Mono<NewAction> removeSingleActionFromCollection(String collectionId, Mon return repository .findById(collectionId) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.COLLECTION_ID))) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.COLLECTION_ID))) .zipWith(actionMono) .flatMap(tuple -> { Collection collection = tuple.getT1(); @@ -99,7 +102,9 @@ public Mono<NewAction> removeSingleActionFromCollection(String collectionId, Mon List<NewAction> actions = collection.getActions(); if (actions == null || actions.isEmpty()) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ACTION_ID + " or " + FieldName.COLLECTION_ID)); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_PARAMETER, + FieldName.ACTION_ID + " or " + FieldName.COLLECTION_ID)); } ListIterator<NewAction> actionIterator = actions.listIterator(); while (actionIterator.hasNext()) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCEImpl.java index c353fdd594f3..e20f0d75a419 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCEImpl.java @@ -34,9 +34,10 @@ public class ConfigServiceCEImpl implements ConfigServiceCE { // This is permanently cached through the life of the JVM process as this is not intended to change at runtime ever. private String instanceId = null; - public ConfigServiceCEImpl(ConfigRepository repository, - ApplicationRepository applicationRepository, - DatasourceRepository datasourceRepository) { + public ConfigServiceCEImpl( + ConfigRepository repository, + ApplicationRepository applicationRepository, + DatasourceRepository datasourceRepository) { this.applicationRepository = applicationRepository; this.datasourceRepository = datasourceRepository; @@ -45,15 +46,19 @@ public ConfigServiceCEImpl(ConfigRepository repository, @Override public Mono<Config> getByName(String name) { - return repository.findByName(name) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.CONFIG, name))); + return repository + .findByName(name) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.CONFIG, name))); } @Override public Mono<Config> updateByName(Config config) { final String name = config.getName(); - return repository.findByName(name) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.CONFIG, name))) + return repository + .findByName(name) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.CONFIG, name))) .flatMap(dbConfig -> { log.debug("Found config with name: {} and id: {}", name, dbConfig.getId()); dbConfig.setConfig(config.getConfig()); @@ -63,7 +68,8 @@ public Mono<Config> updateByName(Config config) { @Override public Mono<Config> save(Config config) { - return repository.findByName(config.getName()) + return repository + .findByName(config.getName()) .flatMap(dbConfig -> { dbConfig.setConfig(config.getConfig()); return repository.save(dbConfig); @@ -82,16 +88,16 @@ public Mono<String> getInstanceId() { return Mono.just(instanceId); } - return getByName("instance-id") - .map(config -> { - instanceId = config.getConfig().getAsString("value"); - return instanceId; - }); + return getByName("instance-id").map(config -> { + instanceId = config.getConfig().getAsString("value"); + return instanceId; + }); } @Override public Mono<String> getTemplateWorkspaceId() { - return repository.findByName(TEMPLATE_WORKSPACE_CONFIG_NAME) + return repository + .findByName(TEMPLATE_WORKSPACE_CONFIG_NAME) .filter(config -> config.getConfig() != null) .flatMap(config -> Mono.justOrEmpty(config.getConfig().getAsString(FieldName.WORKSPACE_ID))) .doOnError(error -> log.warn("Error getting template workspace ID", error)); @@ -99,12 +105,11 @@ public Mono<String> getTemplateWorkspaceId() { @Override public Flux<Application> getTemplateApplications() { - return repository.findByName(TEMPLATE_WORKSPACE_CONFIG_NAME) + return repository + .findByName(TEMPLATE_WORKSPACE_CONFIG_NAME) .filter(config -> config.getConfig() != null) - .map(config -> defaultIfNull( - config.getConfig().getOrDefault("applicationIds", null), - Collections.emptyList() - )) + .map(config -> + defaultIfNull(config.getConfig().getOrDefault("applicationIds", null), Collections.emptyList())) .cast(List.class) .onErrorReturn(Collections.emptyList()) .flatMapMany(applicationRepository::findByIdIn); @@ -112,12 +117,11 @@ public Flux<Application> getTemplateApplications() { @Override public Flux<Datasource> getTemplateDatasources() { - return repository.findByName(TEMPLATE_WORKSPACE_CONFIG_NAME) + return repository + .findByName(TEMPLATE_WORKSPACE_CONFIG_NAME) .filter(config -> config.getConfig() != null) - .map(config -> defaultIfNull( - config.getConfig().getOrDefault("datasourceIds", null), - Collections.emptyList() - )) + .map(config -> + defaultIfNull(config.getConfig().getOrDefault("datasourceIds", null), Collections.emptyList())) .cast(List.class) .onErrorReturn(Collections.emptyList()) .flatMapMany(datasourceRepository::findByIdIn); @@ -125,8 +129,10 @@ public Flux<Datasource> getTemplateDatasources() { @Override public Mono<Void> delete(String name) { - return repository.findByName(name) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.CONFIG, name))) + return repository + .findByName(name) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.CONFIG, name))) .flatMap(repository::delete); } @@ -139,5 +145,4 @@ public Mono<Config> getByName(String name, AclPermission permission) { public Mono<Config> getByNameAsUser(String name, User user, AclPermission permission) { return repository.findByNameAsUser(name, user, permission); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCE.java index 39a25fd99b28..63a1cbb43a2d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCE.java @@ -16,5 +16,4 @@ public interface CurlImporterServiceCE extends ApiImporterCE { List<String> normalize(List<String> tokens); ActionDTO parse(List<String> tokens) throws AppsmithException; - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java index bb936b9c9461..7f7d4eb1e9ca 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java @@ -67,8 +67,7 @@ public CurlImporterServiceCEImpl( NewPageService newPageService, ResponseUtils responseUtils, ObjectMapper objectMapper, - PagePermission pagePermission - ) { + PagePermission pagePermission) { this.pluginService = pluginService; this.layoutActionService = layoutActionService; this.newPageService = newPageService; @@ -78,7 +77,8 @@ public CurlImporterServiceCEImpl( } @Override - public Mono<ActionDTO> importAction(Object input, String pageId, String name, String workspaceId, String branchName) { + public Mono<ActionDTO> importAction( + Object input, String pageId, String name, String workspaceId, String branchName) { ActionDTO action; try { @@ -94,7 +94,8 @@ public Mono<ActionDTO> importAction(Object input, String pageId, String name, St return Mono.error(new AppsmithException(AppsmithError.INVALID_CURL_COMMAND)); } - Mono<NewPage> pageMono = newPageService.findByBranchNameAndDefaultPageId(branchName, pageId, pagePermission.getActionCreatePermission()); + Mono<NewPage> pageMono = newPageService.findByBranchNameAndDefaultPageId( + branchName, pageId, pagePermission.getActionCreatePermission()); // Set the default values for datasource (plugin, name) and then create the action // with embedded datasource @@ -163,7 +164,8 @@ public List<String> lex(String text) { if (isDollarSubshellPossible) { if (currentChar == '(') { - throw new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); + throw new AppsmithException( + AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); } } @@ -178,7 +180,8 @@ public List<String> lex(String text) { isDollarSubshellPossible = true; } else if (currentChar == '`' && quote != '\'') { - throw new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); + throw new AppsmithException( + AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); } else if (currentChar == '\\' && quote != '\'') { isEscaped = true; @@ -188,7 +191,6 @@ public List<String> lex(String text) { } else { currentToken.append(currentChar); - } } else { @@ -205,7 +207,8 @@ public List<String> lex(String text) { isDollarSubshellPossible = true; } else if (currentChar == '`') { - throw new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); + throw new AppsmithException( + AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); } else if (currentChar == '\\') { // This is a backslash that will escape the next character. @@ -228,11 +231,8 @@ public List<String> lex(String text) { } else { currentToken.append(currentChar); - } - } - } if (currentToken.length() > 0) { @@ -253,9 +253,7 @@ public List<String> normalize(List<String> tokens) { final List<String> normalizedTokens = new ArrayList<>(); for (String token : tokens) { - if ("-d".equals(token) - || "--data-ascii".equals(token) - || "--data-raw".equals(token)) { + if ("-d".equals(token) || "--data-ascii".equals(token) || "--data-raw".equals(token)) { normalizedTokens.add(ARG_DATA); } else if (token.startsWith("-d")) { @@ -301,9 +299,7 @@ public List<String> normalize(List<String> tokens) { // We skip the `--url` argument since it's superfluous and URLs are directly sniffed out of the argument // list. The `--url` argument holds no special significance in cURL. normalizedTokens.add(token); - } - } return normalizedTokens; @@ -356,22 +352,24 @@ public ActionDTO parse(List<String> tokens) throws AppsmithException { } if ("content-type".equalsIgnoreCase(parts[0])) { contentType = parts[1]; - // part[0] is already set to content-type, however, it might not have consistent casing. hence resetting it to a HTTP standard. + // part[0] is already set to content-type, however, it might not have consistent casing. hence + // resetting it to a HTTP standard. parts[0] = HttpHeaders.CONTENT_TYPE; - //Setting the apiContentType to the content-type detected in the header with the key word content-type. + // Setting the apiContentType to the content-type detected in the header with the key word + // content-type. // required for RestAPI calls with GET method having body. actionConfiguration.setFormData(Map.of(API_CONTENT_TYPE_KEY, contentType)); } headers.add(new Property(parts[0], parts[1])); - } else if (ARG_DATA.equals(state)) { // The `token` is next to `--data`. dataParts.add(token); } else if ("--data-urlencode".equals(state)) { // The `token` is next to `--data-urlencode`. - // ignore the '=' at the start as the curl document says https://curl.se/docs/manpage.html#--data-urlencode + // ignore the '=' at the start as the curl document says + // https://curl.se/docs/manpage.html#--data-urlencode if (token.startsWith("=")) { dataParts.add(token.substring(1)); } else { @@ -389,9 +387,7 @@ public ActionDTO parse(List<String> tokens) throws AppsmithException { } else if (ARG_USER.equals(state)) { // The `token` is next to `--user`. headers.add(new Property( - "Authorization", - "Basic " + Base64.getEncoder().encodeToString(token.getBytes()) - )); + "Authorization", "Basic " + Base64.getEncoder().encodeToString(token.getBytes()))); } else if (ARG_USER_AGENT.equals(state)) { // The `token` is next to `--user-agent`. @@ -414,14 +410,14 @@ public ActionDTO parse(List<String> tokens) throws AppsmithException { if (isStateProcessed) { state = null; } - } if (contentType == null) { contentType = guessTheContentType(dataParts, formParts); if (contentType != null) { headers.add(new Property(HttpHeaders.CONTENT_TYPE, contentType)); - // Setting the apiContentType to the content type detected by guessing the elements from -f/ --form flag or -d/ --data flag + // Setting the apiContentType to the content type detected by guessing the elements from -f/ --form + // flag or -d/ --data flag // required for RestAPI calls with GET method having body. actionConfiguration.setFormData(Map.of(API_CONTENT_TYPE_KEY, contentType)); } @@ -440,7 +436,6 @@ public ActionDTO parse(List<String> tokens) throws AppsmithException { } else { actionConfiguration.setBody(StringUtils.join(dataParts, '&')); - } } if (!formParts.isEmpty()) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CustomJSLibServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CustomJSLibServiceCE.java index 25b1a14fa98c..e7eba7bd5f74 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CustomJSLibServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CustomJSLibServiceCE.java @@ -10,22 +10,21 @@ import java.util.Set; public interface CustomJSLibServiceCE extends CrudService<CustomJSLib, String> { - Mono<Boolean> addJSLibToApplication(@NotNull String applicationId, @NotNull CustomJSLib jsLib, - String branchName, Boolean isForceInstall); + Mono<Boolean> addJSLibToApplication( + @NotNull String applicationId, @NotNull CustomJSLib jsLib, String branchName, Boolean isForceInstall); - Mono<Boolean> removeJSLibFromApplication(@NotNull String applicationId, @NotNull CustomJSLib jsLib, - String branchName, Boolean isForceRemove); + Mono<Boolean> removeJSLibFromApplication( + @NotNull String applicationId, @NotNull CustomJSLib jsLib, String branchName, Boolean isForceRemove); - Mono<List<CustomJSLib>> getAllJSLibsInApplication(@NotNull String applicationId, String branchName, - Boolean isViewMode); + Mono<List<CustomJSLib>> getAllJSLibsInApplication( + @NotNull String applicationId, String branchName, Boolean isViewMode); - Mono<List<CustomJSLib>> getAllJSLibsInApplicationForExport(@NotNull String applicationId, String branchName, - Boolean isViewMode); + Mono<List<CustomJSLib>> getAllJSLibsInApplicationForExport( + @NotNull String applicationId, String branchName, Boolean isViewMode); - Mono<Set<CustomJSLibApplicationDTO>> getAllJSLibApplicationDTOFromApplication(@NotNull String applicationId, - String branchName, - Boolean isViewMode); + Mono<Set<CustomJSLibApplicationDTO>> getAllJSLibApplicationDTOFromApplication( + @NotNull String applicationId, String branchName, Boolean isViewMode); - Mono<CustomJSLibApplicationDTO> persistCustomJSLibMetaDataIfDoesNotExistAndGetDTO(CustomJSLib jsLib, - Boolean isForceInstall); -} \ No newline at end of file + Mono<CustomJSLibApplicationDTO> persistCustomJSLibMetaDataIfDoesNotExistAndGetDTO( + CustomJSLib jsLib, Boolean isForceInstall); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CustomJSLibServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CustomJSLibServiceCEImpl.java index f8d865f169d2..228781d00337 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CustomJSLibServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CustomJSLibServiceCEImpl.java @@ -27,24 +27,26 @@ import static com.appsmith.server.dtos.CustomJSLibApplicationDTO.getDTOFromCustomJSLib; @Slf4j -public class CustomJSLibServiceCEImpl extends BaseService<CustomJSLibRepository, CustomJSLib, String> implements CustomJSLibServiceCE { +public class CustomJSLibServiceCEImpl extends BaseService<CustomJSLibRepository, CustomJSLib, String> + implements CustomJSLibServiceCE { ApplicationService applicationService; - public CustomJSLibServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - CustomJSLibRepository repository, - ApplicationService applicationService, - AnalyticsService analyticsService) { + public CustomJSLibServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + CustomJSLibRepository repository, + ApplicationService applicationService, + AnalyticsService analyticsService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.applicationService = applicationService; } @Override - public Mono<Boolean> addJSLibToApplication(@NotNull String applicationId, @NotNull CustomJSLib jsLib, - String branchName, Boolean isForceInstall) { + public Mono<Boolean> addJSLibToApplication( + @NotNull String applicationId, @NotNull CustomJSLib jsLib, String branchName, Boolean isForceInstall) { return getAllJSLibApplicationDTOFromApplication(applicationId, branchName, false) .zipWith(persistCustomJSLibMetaDataIfDoesNotExistAndGetDTO(jsLib, isForceInstall)) .map(tuple -> { @@ -61,38 +63,40 @@ public Mono<Boolean> addJSLibToApplication(@NotNull String applicationId, @NotNu return jsLibDTOsInApplication; }) .flatMap(updatedJSLibDTOList -> { - Map<String, Object> fieldNameValueMap = Map.of(FieldName.UNPUBLISHED_JS_LIBS_IDENTIFIER_IN_APPLICATION_CLASS, updatedJSLibDTOList); + Map<String, Object> fieldNameValueMap = + Map.of(FieldName.UNPUBLISHED_JS_LIBS_IDENTIFIER_IN_APPLICATION_CLASS, updatedJSLibDTOList); return applicationService.update(applicationId, fieldNameValueMap, branchName); }) .map(updateResult -> updateResult.getModifiedCount() > 0); } @Override - public Mono<CustomJSLibApplicationDTO> persistCustomJSLibMetaDataIfDoesNotExistAndGetDTO(CustomJSLib jsLib, - Boolean isForceInstall) { - return repository.findByUidString(jsLib.getUidString()) + public Mono<CustomJSLibApplicationDTO> persistCustomJSLibMetaDataIfDoesNotExistAndGetDTO( + CustomJSLib jsLib, Boolean isForceInstall) { + return repository + .findByUidString(jsLib.getUidString()) .flatMap(foundJSLib -> { /* - The first check is to make sure that we are able to detect any previously truncated data and overwrite it the next time we receive valid data. - The second check provides us with a backdoor to overwrite any faulty data that would have come in any time earlier. - Currently, once a custom JS lib data gets persisted there is no way to update it - the isForceInstall flag will allow a way to update this data. - */ + The first check is to make sure that we are able to detect any previously truncated data and overwrite it the next time we receive valid data. + The second check provides us with a backdoor to overwrite any faulty data that would have come in any time earlier. + Currently, once a custom JS lib data gets persisted there is no way to update it - the isForceInstall flag will allow a way to update this data. + */ if ((jsLib.getDefs().length() > foundJSLib.getDefs().length()) || isForceInstall) { jsLib.setId(foundJSLib.getId()); - return repository.save(jsLib) - .then(Mono.just(getDTOFromCustomJSLib(jsLib))); + return repository.save(jsLib).then(Mono.just(getDTOFromCustomJSLib(jsLib))); } return Mono.just(getDTOFromCustomJSLib(foundJSLib)); }) - //Read more why Mono.defer is used here. https://stackoverflow.com/questions/54373920/mono-switchifempty-is-always-called - .switchIfEmpty(Mono.defer(() -> repository.save(jsLib).map(savedJsLib -> getDTOFromCustomJSLib(savedJsLib)))); + // Read more why Mono.defer is used here. + // https://stackoverflow.com/questions/54373920/mono-switchifempty-is-always-called + .switchIfEmpty( + Mono.defer(() -> repository.save(jsLib).map(savedJsLib -> getDTOFromCustomJSLib(savedJsLib)))); } @Override - public Mono<Boolean> removeJSLibFromApplication(@NotNull String applicationId, - @NotNull CustomJSLib jsLib, String branchName, - Boolean isForceRemove) { + public Mono<Boolean> removeJSLibFromApplication( + @NotNull String applicationId, @NotNull CustomJSLib jsLib, String branchName, Boolean isForceRemove) { return getAllJSLibApplicationDTOFromApplication(applicationId, branchName, false) .map(jsLibDTOSet -> { @@ -106,39 +110,39 @@ public Mono<Boolean> removeJSLibFromApplication(@NotNull String applicationId, return jsLibDTOSet; }) .flatMap(updatedJSLibDTOList -> { - Map<String, Object> fieldNameValueMap = Map.of(FieldName.UNPUBLISHED_JS_LIBS_IDENTIFIER_IN_APPLICATION_CLASS, updatedJSLibDTOList); + Map<String, Object> fieldNameValueMap = + Map.of(FieldName.UNPUBLISHED_JS_LIBS_IDENTIFIER_IN_APPLICATION_CLASS, updatedJSLibDTOList); return applicationService.update(applicationId, fieldNameValueMap, branchName); }) .map(updateResult -> updateResult.getModifiedCount() > 0); } @Override - public Mono<List<CustomJSLib>> getAllJSLibsInApplication(@NotNull String applicationId, String branchName, - Boolean isViewMode) { + public Mono<List<CustomJSLib>> getAllJSLibsInApplication( + @NotNull String applicationId, String branchName, Boolean isViewMode) { return getAllCustomJSLibsFromApplication(applicationId, branchName, isViewMode); } @Override - public Mono<List<CustomJSLib>> getAllJSLibsInApplicationForExport(String applicationId, String branchName, Boolean isViewMode) { + public Mono<List<CustomJSLib>> getAllJSLibsInApplicationForExport( + String applicationId, String branchName, Boolean isViewMode) { return getAllCustomJSLibsFromApplication(applicationId, branchName, isViewMode) .map(jsLibList -> { - jsLibList - .forEach(jsLib -> { - jsLib.setId(null); - jsLib.setCreatedAt(null); - jsLib.setUpdatedAt(null); - }); + jsLibList.forEach(jsLib -> { + jsLib.setId(null); + jsLib.setCreatedAt(null); + jsLib.setUpdatedAt(null); + }); return jsLibList; }); } - private Mono<List<CustomJSLib>> getAllCustomJSLibsFromApplication(String applicationId, String branchName, boolean isViewMode) { + private Mono<List<CustomJSLib>> getAllCustomJSLibsFromApplication( + String applicationId, String branchName, boolean isViewMode) { return getAllJSLibApplicationDTOFromApplication(applicationId, branchName, isViewMode) - .map(jsLibDTOSet -> jsLibDTOSet.stream() - .map(dto -> dto.getUidString()) - .collect(Collectors.toList()) - ) + .map(jsLibDTOSet -> + jsLibDTOSet.stream().map(dto -> dto.getUidString()).collect(Collectors.toList())) .flatMapMany(Flux::fromIterable) .flatMap(uidString -> repository.findByUidString(uidString)) .collectList() @@ -149,20 +153,26 @@ private Mono<List<CustomJSLib>> getAllCustomJSLibsFromApplication(String applica } @Override - public Mono<Set<CustomJSLibApplicationDTO>> getAllJSLibApplicationDTOFromApplication(@NotNull String applicationId, - String branchName, - Boolean isViewMode) { - return applicationService.findByIdAndBranchName(applicationId, - List.of(isViewMode ? FieldName.PUBLISHED_JS_LIBS_IDENTIFIER_IN_APPLICATION_CLASS : - FieldName.UNPUBLISHED_JS_LIBS_IDENTIFIER_IN_APPLICATION_CLASS), branchName) + public Mono<Set<CustomJSLibApplicationDTO>> getAllJSLibApplicationDTOFromApplication( + @NotNull String applicationId, String branchName, Boolean isViewMode) { + return applicationService + .findByIdAndBranchName( + applicationId, + List.of( + isViewMode + ? FieldName.PUBLISHED_JS_LIBS_IDENTIFIER_IN_APPLICATION_CLASS + : FieldName.UNPUBLISHED_JS_LIBS_IDENTIFIER_IN_APPLICATION_CLASS), + branchName) .map(application -> { if (isViewMode) { - return application.getPublishedCustomJSLibs() == null ? new HashSet<>() : - application.getPublishedCustomJSLibs(); + return application.getPublishedCustomJSLibs() == null + ? new HashSet<>() + : application.getPublishedCustomJSLibs(); } - return application.getUnpublishedCustomJSLibs() == null ? new HashSet<>() : - application.getUnpublishedCustomJSLibs(); + return application.getUnpublishedCustomJSLibs() == null + ? new HashSet<>() + : application.getUnpublishedCustomJSLibs(); }); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCE.java index ca8909020897..95be7557a01b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCE.java @@ -26,8 +26,7 @@ public interface DatasourceContextServiceCE { Mono<DatasourceContext<?>> getRemoteDatasourceContext(Plugin plugin, DatasourceStorage datasourceStorage); - <T> Mono<T> retryOnce(DatasourceStorage datasourceStorage, - Function<DatasourceContext<?>, Mono<T>> task); + <T> Mono<T> retryOnce(DatasourceStorage datasourceStorage, Function<DatasourceContext<?>, Mono<T>> task); Mono<DatasourceContext<?>> deleteDatasourceContext(DatasourceStorage datasourceStorage); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCEImpl.java index bd42792e48d1..3ae2df532ecc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCEImpl.java @@ -26,7 +26,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; - @Slf4j public class DatasourceContextServiceCEImpl implements DatasourceContextServiceCE { @@ -42,12 +41,13 @@ public class DatasourceContextServiceCEImpl implements DatasourceContextServiceC private final DatasourcePermission datasourcePermission; @Autowired - public DatasourceContextServiceCEImpl(@Lazy DatasourceService datasourceService, - DatasourceStorageService datasourceStorageService, - PluginService pluginService, - PluginExecutorHelper pluginExecutorHelper, - ConfigService configService, - DatasourcePermission datasourcePermission) { + public DatasourceContextServiceCEImpl( + @Lazy DatasourceService datasourceService, + DatasourceStorageService datasourceStorageService, + PluginService pluginService, + PluginExecutorHelper pluginExecutorHelper, + ConfigService configService, + DatasourcePermission datasourcePermission) { this.datasourceService = datasourceService; this.datasourceStorageService = datasourceStorageService; this.pluginService = pluginService; @@ -76,17 +76,19 @@ public DatasourceContextServiceCEImpl(@Lazy DatasourceService datasourceService, * @return a cached source publisher which upon subscription produces / returns the latest datasource context / * connection. */ - public Mono<? extends DatasourceContext<?>> getCachedDatasourceContextMono(DatasourceStorage datasourceStorage, - PluginExecutor<Object> pluginExecutor, - Object monitor, - DatasourceContextIdentifier datasourceContextIdentifier) { + public Mono<? extends DatasourceContext<?>> getCachedDatasourceContextMono( + DatasourceStorage datasourceStorage, + PluginExecutor<Object> pluginExecutor, + Object monitor, + DatasourceContextIdentifier datasourceContextIdentifier) { synchronized (monitor) { /* Destroy any connection that is stale or in error state to free up resource */ final boolean isStale = getIsStale(datasourceStorage, datasourceContextIdentifier); final boolean isInErrorState = getIsInErrorState(datasourceContextIdentifier); if (isStale || isInErrorState) { - final Object connection = datasourceContextMap.get(datasourceContextIdentifier).getConnection(); + final Object connection = + datasourceContextMap.get(datasourceContextIdentifier).getConnection(); if (connection != null) { try { // Basically remove entry from both cache maps @@ -113,12 +115,14 @@ public Mono<? extends DatasourceContext<?>> getCachedDatasourceContextMono(Datas /* Create a fresh datasource context */ DatasourceContext<Object> datasourceContext = new DatasourceContext<>(); if (datasourceContextIdentifier.isKeyValid()) { - /* For this datasource, either the context doesn't exist, or the context is stale. Replace (or add) with - the new connection in the context map. */ + /* For this datasource, either the context doesn't exist, or the context is stale. Replace (or add) with + the new connection in the context map. */ datasourceContextMap.put(datasourceContextIdentifier, datasourceContext); } - Mono<Object> connectionMonoCache = pluginExecutor.datasourceCreate(datasourceStorage.getDatasourceConfiguration()).cache(); + Mono<Object> connectionMonoCache = pluginExecutor + .datasourceCreate(datasourceStorage.getDatasourceConfiguration()) + .cache(); Mono<DatasourceContext<Object>> datasourceContextMonoCache = connectionMonoCache .flatMap(connection -> updateDatasourceAndSetAuthentication(connection, datasourceStorage)) @@ -129,8 +133,8 @@ public Mono<? extends DatasourceContext<?>> getCachedDatasourceContextMono(Datas return datasourceContext; }) .defaultIfEmpty( - /* When a connection object doesn't make sense for the plugin, we get an empty mono - and we just return the context object as is. */ + /* When a connection object doesn't make sense for the plugin, we get an empty mono + and we just return the context object as is. */ datasourceContext) .cache(); /* Cache the value so that further evaluations don't result in new connections */ @@ -147,51 +151,58 @@ public Mono<Object> updateDatasourceAndSetAuthentication(Object connection, Data datasourceStorage.setUpdatedAt(Instant.now()); datasourceStorage .getDatasourceConfiguration() - .setAuthentication( - ((UpdatableConnection) connection).getAuthenticationDTO( - datasourceStorage.getDatasourceConfiguration().getAuthentication())); + .setAuthentication(((UpdatableConnection) connection) + .getAuthenticationDTO(datasourceStorage + .getDatasourceConfiguration() + .getAuthentication())); datasourceStorageMono = datasourceStorageService.save(datasourceStorage); } return datasourceStorageMono.thenReturn(connection); } - protected Mono<DatasourceContext<?>> createNewDatasourceContext(DatasourceStorage datasourceStorage, - DatasourceContextIdentifier datasourceContextIdentifier) { + protected Mono<DatasourceContext<?>> createNewDatasourceContext( + DatasourceStorage datasourceStorage, DatasourceContextIdentifier datasourceContextIdentifier) { log.debug("Datasource context doesn't exist. Creating connection."); Mono<Plugin> pluginMono = pluginService.findById(datasourceStorage.getPluginId()); - return pluginExecutorHelper.getPluginExecutor(pluginMono) - .flatMap(pluginExecutor -> { - - /** - * Keep one monitor object against each datasource id. The synchronized method - * `getCachedDatasourceContextMono` would then acquire lock on the monitor object which is unique - * for each datasourceId hence ensuring that if competing threads want to create datasource context - * on different datasource id then they are not blocked on each other and can run concurrently. - * Only threads that want to create a new datasource context on the same datasource id would be - * synchronized. - */ - Object monitor = new Object(); - if (datasourceContextIdentifier.isKeyValid()) { - if (datasourceContextSynchronizationMonitorMap.get(datasourceContextIdentifier) == null) { - synchronized (this) { - datasourceContextSynchronizationMonitorMap.computeIfAbsent(datasourceContextIdentifier, k -> new Object()); - } - } - - monitor = datasourceContextSynchronizationMonitorMap.get(datasourceContextIdentifier); + return pluginExecutorHelper.getPluginExecutor(pluginMono).flatMap(pluginExecutor -> { + + /** + * Keep one monitor object against each datasource id. The synchronized method + * `getCachedDatasourceContextMono` would then acquire lock on the monitor object which is unique + * for each datasourceId hence ensuring that if competing threads want to create datasource context + * on different datasource id then they are not blocked on each other and can run concurrently. + * Only threads that want to create a new datasource context on the same datasource id would be + * synchronized. + */ + Object monitor = new Object(); + if (datasourceContextIdentifier.isKeyValid()) { + if (datasourceContextSynchronizationMonitorMap.get(datasourceContextIdentifier) == null) { + synchronized (this) { + datasourceContextSynchronizationMonitorMap.computeIfAbsent( + datasourceContextIdentifier, k -> new Object()); } + } - return getCachedDatasourceContextMono(datasourceStorage, pluginExecutor, monitor, datasourceContextIdentifier); - }); + monitor = datasourceContextSynchronizationMonitorMap.get(datasourceContextIdentifier); + } + + return getCachedDatasourceContextMono( + datasourceStorage, pluginExecutor, monitor, datasourceContextIdentifier); + }); } - public boolean getIsStale(DatasourceStorage datasourceStorage, DatasourceContextIdentifier datasourceContextIdentifier) { + public boolean getIsStale( + DatasourceStorage datasourceStorage, DatasourceContextIdentifier datasourceContextIdentifier) { String datasourceId = datasourceStorage.getDatasourceId(); return datasourceId != null && datasourceContextMap.get(datasourceContextIdentifier) != null && datasourceStorage.getUpdatedAt() != null - && datasourceStorage.getUpdatedAt().isAfter(datasourceContextMap.get(datasourceContextIdentifier).getCreationTime()); + && datasourceStorage + .getUpdatedAt() + .isAfter(datasourceContextMap + .get(datasourceContextIdentifier) + .getCreationTime()); } /** @@ -202,11 +213,14 @@ public boolean getIsStale(DatasourceStorage datasourceStorage, DatasourceContext */ private boolean getIsInErrorState(DatasourceContextIdentifier datasourceContextIdentifier) { return datasourceContextMonoMap.get(datasourceContextIdentifier) != null - && datasourceContextMonoMap.get(datasourceContextIdentifier).toFuture().isCompletedExceptionally(); + && datasourceContextMonoMap + .get(datasourceContextIdentifier) + .toFuture() + .isCompletedExceptionally(); } - public boolean isValidDatasourceContextAvailable(DatasourceStorage datasourceStorage, - DatasourceContextIdentifier datasourceContextIdentifier) { + public boolean isValidDatasourceContextAvailable( + DatasourceStorage datasourceStorage, DatasourceContextIdentifier datasourceContextIdentifier) { boolean isStale = getIsStale(datasourceStorage, datasourceContextIdentifier); boolean isInErrorState = getIsInErrorState(datasourceContextIdentifier); return datasourceContextMap.get(datasourceContextIdentifier) != null @@ -223,8 +237,9 @@ public Mono<DatasourceContext<?>> getDatasourceContext(DatasourceStorage datasou DatasourceContextIdentifier datasourceContextIdentifier = this.initializeDatasourceContextIdentifier(datasourceStorage); if (datasourceId == null) { - log.debug("This is a dry run or an embedded datasourceStorage. The datasourceStorage context would not exist in this " + - "scenario"); + log.debug( + "This is a dry run or an embedded datasourceStorage. The datasourceStorage context would not exist in this " + + "scenario"); } else { if (isValidDatasourceContextAvailable(datasourceStorage, datasourceContextIdentifier)) { log.debug("Resource context exists. Returning the same."); @@ -235,26 +250,24 @@ public Mono<DatasourceContext<?>> getDatasourceContext(DatasourceStorage datasou } @Override - public <T> Mono<T> retryOnce(DatasourceStorage datasourceStorage, - Function<DatasourceContext<?>, Mono<T>> task) { + public <T> Mono<T> retryOnce(DatasourceStorage datasourceStorage, Function<DatasourceContext<?>, Mono<T>> task) { final Mono<T> taskRunnerMono = Mono.justOrEmpty(datasourceStorage) .flatMap(this::getDatasourceContext) // Now that we have the context (connection details), call the task. .flatMap(task); - return taskRunnerMono - .onErrorResume(StaleConnectionException.class, error -> { - log.info("Looks like the connection is stale. Retrying with a fresh context."); - return deleteDatasourceContext(datasourceStorage) - .then(taskRunnerMono); - }); + return taskRunnerMono.onErrorResume(StaleConnectionException.class, error -> { + log.info("Looks like the connection is stale. Retrying with a fresh context."); + return deleteDatasourceContext(datasourceStorage).then(taskRunnerMono); + }); } @Override public Mono<DatasourceContext<?>> deleteDatasourceContext(DatasourceStorage datasourceStorage) { - DatasourceContextIdentifier datasourceContextIdentifier = initializeDatasourceContextIdentifier(datasourceStorage); + DatasourceContextIdentifier datasourceContextIdentifier = + initializeDatasourceContextIdentifier(datasourceStorage); if (!datasourceContextIdentifier.isKeyValid()) { return Mono.empty(); } @@ -264,7 +277,8 @@ public Mono<DatasourceContext<?>> deleteDatasourceContext(DatasourceStorage data // No resource context exists for this resource. Return void. return Mono.empty(); } - return pluginExecutorHelper.getPluginExecutor(pluginService.findById(datasourceStorage.getPluginId())) + return pluginExecutorHelper + .getPluginExecutor(pluginService.findById(datasourceStorage.getPluginId())) .map(pluginExecutor -> { log.info("Clearing datasource context for datasource storage ID {}.", datasourceStorage.getId()); pluginExecutor.datasourceDestroy(datasourceContext.getConnection()); @@ -293,22 +307,19 @@ public Mono<DatasourceContext<?>> getDatasourceContext(DatasourceStorage datasou public Mono<DatasourceContext<?>> getRemoteDatasourceContext(Plugin plugin, DatasourceStorage datasourceStorage) { final DatasourceContext<ExecutePluginDTO> datasourceContext = new DatasourceContext<>(); - return configService.getInstanceId() - .map(instanceId -> { - ExecutePluginDTO executePluginDTO = new ExecutePluginDTO(); - executePluginDTO.setInstallationKey(instanceId); - executePluginDTO.setPluginName(plugin.getPluginName()); - executePluginDTO.setPluginVersion(plugin.getVersion()); - executePluginDTO.setDatasource(new RemoteDatasourceDTO( - datasourceStorage.getDatasourceId(), - datasourceStorage.getDatasourceConfiguration())); - datasourceContext.setConnection(executePluginDTO); - - return datasourceContext; - }); + return configService.getInstanceId().map(instanceId -> { + ExecutePluginDTO executePluginDTO = new ExecutePluginDTO(); + executePluginDTO.setInstallationKey(instanceId); + executePluginDTO.setPluginName(plugin.getPluginName()); + executePluginDTO.setPluginVersion(plugin.getVersion()); + executePluginDTO.setDatasource(new RemoteDatasourceDTO( + datasourceStorage.getDatasourceId(), datasourceStorage.getDatasourceConfiguration())); + datasourceContext.setConnection(executePluginDTO); + + return datasourceContext; + }); } - /** * Generates the custom key that is used in: * datasourceContextMap diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCE.java index 9d222c383742..e488b5bbb243 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCE.java @@ -69,9 +69,11 @@ public interface DatasourceServiceCE { Mono<Datasource> createWithoutPermissions(Datasource datasource); - Mono<Datasource> updateDatasourceStorage(DatasourceStorageDTO datasourceStorageDTO, String activeEnvironmentId, Boolean IsUserRefreshedUpdate); + Mono<Datasource> updateDatasourceStorage( + DatasourceStorageDTO datasourceStorageDTO, String activeEnvironmentId, Boolean IsUserRefreshedUpdate); - Mono<Datasource> updateDatasource(String id, Datasource datasource, String activeEnvironmentId, Boolean isUserRefreshedUpdate); + Mono<Datasource> updateDatasource( + String id, Datasource datasource, String activeEnvironmentId, Boolean isUserRefreshedUpdate); Mono<Datasource> archiveById(String id); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java index 2ae2d131f1c2..e44c0a96a752 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java @@ -86,23 +86,24 @@ public class DatasourceServiceCEImpl implements DatasourceServiceCE { private final AnalyticsService analyticsService; @Autowired - public DatasourceServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - DatasourceRepository repository, - WorkspaceService workspaceService, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - PluginService pluginService, - PluginExecutorHelper pluginExecutorHelper, - PolicyGenerator policyGenerator, - SequenceService sequenceService, - NewActionRepository newActionRepository, - DatasourceContextService datasourceContextService, - DatasourcePermission datasourcePermission, - WorkspacePermission workspacePermission, - DatasourceStorageService datasourceStorageService) { + public DatasourceServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + DatasourceRepository repository, + WorkspaceService workspaceService, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + PluginService pluginService, + PluginExecutorHelper pluginExecutorHelper, + PolicyGenerator policyGenerator, + SequenceService sequenceService, + NewActionRepository newActionRepository, + DatasourceContextService datasourceContextService, + DatasourcePermission datasourcePermission, + WorkspacePermission workspacePermission, + DatasourceStorageService datasourceStorageService) { this.workspaceService = workspaceService; this.sessionUserService = sessionUserService; @@ -176,36 +177,35 @@ private Mono<Datasource> createEx(@NotNull Datasource datasource, Optional<AclPe }) .flatMap(this::validateAndSaveDatasourceToRepository) .flatMap(savedDatasource -> - analyticsService.sendCreateEvent(savedDatasource, getAnalyticsProperties(savedDatasource)) - ); + analyticsService.sendCreateEvent(savedDatasource, getAnalyticsProperties(savedDatasource))); } else { - log.debug("datasource with name: {} already exists, Only configuration(s) will be created", datasource.getName()); - datasourceMono = datasourceMono - .flatMap(datasource1 -> findById(datasource1.getId(), datasourcePermission.getEditPermission()) - .map(datasource2 -> { - datasource2.setDatasourceStorages(datasource1.getDatasourceStorages()); - return datasource2; - }) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE))) - ); + log.debug( + "datasource with name: {} already exists, Only configuration(s) will be created", + datasource.getName()); + datasourceMono = datasourceMono.flatMap( + datasource1 -> findById(datasource1.getId(), datasourcePermission.getEditPermission()) + .map(datasource2 -> { + datasource2.setDatasourceStorages(datasource1.getDatasourceStorages()); + return datasource2; + }) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE)))); } - return datasourceMono - .flatMap(savedDatasource -> this.organiseDatasourceStorages(savedDatasource) - .flatMap(datasourceStorage -> { - // Make sure that we are creating entries only if the id is not already populated - if (datasourceStorage.getId() == null) { - return datasourceStorageService.create(datasourceStorage); - } - return Mono.just(datasourceStorage); - }) - .map(DatasourceStorageDTO::new) - .collectMap(DatasourceStorageDTO::getEnvironmentId) - .map(savedStorages -> { - savedDatasource.setDatasourceStorages(savedStorages); - return savedDatasource; - }) - ); + return datasourceMono.flatMap(savedDatasource -> this.organiseDatasourceStorages(savedDatasource) + .flatMap(datasourceStorage -> { + // Make sure that we are creating entries only if the id is not already populated + if (datasourceStorage.getId() == null) { + return datasourceStorageService.create(datasourceStorage); + } + return Mono.just(datasourceStorage); + }) + .map(DatasourceStorageDTO::new) + .collectMap(DatasourceStorageDTO::getEnvironmentId) + .map(savedStorages -> { + savedDatasource.setDatasourceStorages(savedStorages); + return savedDatasource; + })); } // this requires an EE override multiple environments @@ -213,44 +213,51 @@ protected Flux<DatasourceStorage> organiseDatasourceStorages(@NotNull Datasource Map<String, DatasourceStorageDTO> storages = savedDatasource.getDatasourceStorages(); int datasourceStorageDTOsAllowed = 1; if (storages.size() > datasourceStorageDTOsAllowed) { - //ideally an error should be thrown; however, since datasource has already been created, it needs be returned. - log.debug("datasource has got {} configurations, which is more than: {} for datasourceId: {}", - storages.size(), datasourceStorageDTOsAllowed, savedDatasource.getId()); + // ideally an error should be thrown; however, since datasource has already been created, it needs be + // returned. + log.debug( + "datasource has got {} configurations, which is more than: {} for datasourceId: {}", + storages.size(), + datasourceStorageDTOsAllowed, + savedDatasource.getId()); } Map<String, DatasourceStorage> storagesToBeSaved = new HashMap<>(); return Flux.fromIterable(storages.values()) - .flatMap(datasourceStorageDTO -> - this.getTrueEnvironmentId(savedDatasource.getWorkspaceId(), datasourceStorageDTO.getEnvironmentId()) - .map(trueEnvironmentId -> { - datasourceStorageDTO.setEnvironmentId(trueEnvironmentId); - DatasourceStorage datasourceStorage = new DatasourceStorage(datasourceStorageDTO); - datasourceStorage.prepareTransientFields(savedDatasource); - storagesToBeSaved.put(trueEnvironmentId, datasourceStorage); - return datasourceStorage; - }) - ) + .flatMap(datasourceStorageDTO -> this.getTrueEnvironmentId( + savedDatasource.getWorkspaceId(), datasourceStorageDTO.getEnvironmentId()) + .map(trueEnvironmentId -> { + datasourceStorageDTO.setEnvironmentId(trueEnvironmentId); + DatasourceStorage datasourceStorage = new DatasourceStorage(datasourceStorageDTO); + datasourceStorage.prepareTransientFields(savedDatasource); + storagesToBeSaved.put(trueEnvironmentId, datasourceStorage); + return datasourceStorage; + })) .thenMany(Flux.fromIterable(storagesToBeSaved.values())); } - private Mono<Datasource> generateAndSetDatasourcePolicies(Mono<User> userMono, Datasource datasource, Optional<AclPermission> permission) { - return userMono - .flatMap(user -> { - Mono<Workspace> workspaceMono = workspaceService.findById(datasource.getWorkspaceId(), permission) - .log() - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, datasource.getWorkspaceId()))); - - return workspaceMono.map(workspace -> { - Set<Policy> documentPolicies = policyGenerator.getAllChildPolicies(workspace.getPolicies(), Workspace.class, Datasource.class); - datasource.setPolicies(documentPolicies); - return datasource; - }); - }); + private Mono<Datasource> generateAndSetDatasourcePolicies( + Mono<User> userMono, Datasource datasource, Optional<AclPermission> permission) { + return userMono.flatMap(user -> { + Mono<Workspace> workspaceMono = workspaceService + .findById(datasource.getWorkspaceId(), permission) + .log() + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, datasource.getWorkspaceId()))); + + return workspaceMono.map(workspace -> { + Set<Policy> documentPolicies = + policyGenerator.getAllChildPolicies(workspace.getPolicies(), Workspace.class, Datasource.class); + datasource.setPolicies(documentPolicies); + return datasource; + }); + }); } @Override - public Mono<Datasource> updateDatasource(String id, Datasource datasource, String activeEnvironmentId, Boolean isUserRefreshedUpdate) { + public Mono<Datasource> updateDatasource( + String id, Datasource datasource, String activeEnvironmentId, Boolean isUserRefreshedUpdate) { if (!hasText(id)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ID)); } @@ -261,8 +268,10 @@ public Mono<Datasource> updateDatasource(String id, Datasource datasource, Strin // check method docstring for description datasource.nullifyStorageReplicaFields(); - Mono<Datasource> datasourceMono = repository.findById(id, datasourcePermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, id))); + Mono<Datasource> datasourceMono = repository + .findById(id, datasourcePermission.getEditPermission()) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, id))); // This is meant to be an update for just the datasource - like a rename return datasourceMono @@ -272,21 +281,24 @@ public Mono<Datasource> updateDatasource(String id, Datasource datasource, Strin }) .flatMap(this::validateAndSaveDatasourceToRepository) .map(savedDatasource -> { - //not required by client side in order to avoid updating it to a null storage, + // not required by client side in order to avoid updating it to a null storage, // one alternative is that we find and send datasourceStorages along, but that is an expensive call savedDatasource.setDatasourceStorages(null); return savedDatasource; }) .flatMap(savedDatasource -> { Map<String, Object> analyticsProperties = getAnalyticsProperties(savedDatasource); - Boolean userInvokedUpdate = TRUE.equals(isUserRefreshedUpdate) ? TRUE: FALSE; + Boolean userInvokedUpdate = TRUE.equals(isUserRefreshedUpdate) ? TRUE : FALSE; analyticsProperties.put(FieldName.IS_DATASOURCE_UPDATE_USER_INVOKED_KEY, userInvokedUpdate); return analyticsService.sendUpdateEvent(savedDatasource, analyticsProperties); }); } @Override - public Mono<Datasource> updateDatasourceStorage(@NotNull DatasourceStorageDTO datasourceStorageDTO, String activeEnvironmentId, Boolean isUserRefreshedUpdate) { + public Mono<Datasource> updateDatasourceStorage( + @NotNull DatasourceStorageDTO datasourceStorageDTO, + String activeEnvironmentId, + Boolean isUserRefreshedUpdate) { String datasourceId = datasourceStorageDTO.getDatasourceId(); String environmentId = datasourceStorageDTO.getEnvironmentId(); @@ -296,58 +308,57 @@ public Mono<Datasource> updateDatasourceStorage(@NotNull DatasourceStorageDTO da } if (!hasText(environmentId)) { - //ideally the error would be thrown, but we would only throw error when complete client side changes + // ideally the error would be thrown, but we would only throw error when complete client side changes // have been done for multiple-environments. For now this call will go through log.debug("environmentId not found while updating datasource storage with datasourceId : {}", datasourceId); } // querying for each of the datasource Mono<Datasource> datasourceMonoCached = findById(datasourceId, datasourcePermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))); - - Mono<String> trueEnvironmentIdMono = datasourceMonoCached - .flatMap(datasource -> getTrueEnvironmentId(datasource.getWorkspaceId(), environmentId)); - - return datasourceMonoCached - .zipWith(trueEnvironmentIdMono) - .flatMap(tuple2 -> { - Datasource dbDatasource = tuple2.getT1(); - String trueEnvironmentId = tuple2.getT2(); - - datasourceStorageDTO.setEnvironmentId(trueEnvironmentId); - DatasourceStorage datasourceStorage = new DatasourceStorage(datasourceStorageDTO); - datasourceStorage.prepareTransientFields(dbDatasource); - - return datasourceStorageService.updateDatasourceStorage(datasourceStorage, activeEnvironmentId, Boolean.TRUE) - .map(DatasourceStorageDTO::new) - .map(datasourceStorageDTO1 -> { - dbDatasource.getDatasourceStorages().put(trueEnvironmentId, datasourceStorageDTO1); - return dbDatasource; - }); - }); + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))); + + Mono<String> trueEnvironmentIdMono = datasourceMonoCached.flatMap( + datasource -> getTrueEnvironmentId(datasource.getWorkspaceId(), environmentId)); + + return datasourceMonoCached.zipWith(trueEnvironmentIdMono).flatMap(tuple2 -> { + Datasource dbDatasource = tuple2.getT1(); + String trueEnvironmentId = tuple2.getT2(); + + datasourceStorageDTO.setEnvironmentId(trueEnvironmentId); + DatasourceStorage datasourceStorage = new DatasourceStorage(datasourceStorageDTO); + datasourceStorage.prepareTransientFields(dbDatasource); + + return datasourceStorageService + .updateDatasourceStorage(datasourceStorage, activeEnvironmentId, Boolean.TRUE) + .map(DatasourceStorageDTO::new) + .map(datasourceStorageDTO1 -> { + dbDatasource.getDatasourceStorages().put(trueEnvironmentId, datasourceStorageDTO1); + return dbDatasource; + }); + }); } @Override public Mono<Datasource> save(Datasource datasource) { if (datasource.getGitSyncId() == null) { - datasource.setGitSyncId(datasource.getWorkspaceId() + "_" + Instant.now().toString()); + datasource.setGitSyncId( + datasource.getWorkspaceId() + "_" + Instant.now().toString()); } return repository.save(datasource); } - private Mono<Datasource> validateAndSaveDatasourceToRepository(Datasource datasource) { return Mono.just(datasource) .flatMap(this::validateDatasource) .flatMap(unsavedDatasource -> { - return repository.save(unsavedDatasource) - .map(savedDatasource -> { - // datasource.pluginName is a transient field. It was set by validateDatasource method - // object from db will have pluginName=null so set it manually from the unsaved datasource obj - savedDatasource.setPluginName(unsavedDatasource.getPluginName()); - return savedDatasource; - }); + return repository.save(unsavedDatasource).map(savedDatasource -> { + // datasource.pluginName is a transient field. It was set by validateDatasource method + // object from db will have pluginName=null so set it manually from the unsaved datasource obj + savedDatasource.setPluginName(unsavedDatasource.getPluginName()); + return savedDatasource; + }); }) .flatMap(repository::setUserPermissionsInObject); } @@ -377,10 +388,12 @@ public Mono<Datasource> validateDatasource(Datasource datasource) { invalids.add(AppsmithError.PLUGIN_NOT_INSTALLED.getMessage(datasource.getPluginId())); return Mono.just(new Workspace()); })); - final Mono<Plugin> pluginMono = pluginService.findById(datasource.getPluginId()).cache(); - Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper.getPluginExecutor(pluginMono) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, - FieldName.PLUGIN, datasource.getPluginId()))); + final Mono<Plugin> pluginMono = + pluginService.findById(datasource.getPluginId()).cache(); + Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper + .getPluginExecutor(pluginMono) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasource.getPluginId()))); return checkPluginInstallationAndThenReturnWorkspaceMono .then(pluginExecutorMono) @@ -399,7 +412,8 @@ public Mono<Datasource> validateDatasource(Datasource datasource) { * the password from the db if its a saved datasource before testing. */ @Override - public Mono<DatasourceTestResult> testDatasource(DatasourceStorageDTO datasourceStorageDTO, String activeEnvironmentId) { + public Mono<DatasourceTestResult> testDatasource( + DatasourceStorageDTO datasourceStorageDTO, String activeEnvironmentId) { DatasourceStorage datasourceStorage = new DatasourceStorage(datasourceStorageDTO); Mono<DatasourceStorage> datasourceStorageMono; @@ -414,15 +428,18 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceStorageDTO datasource return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); } - datasourceStorageMono = getTrueEnvironmentId(datasourceStorage.getWorkspaceId(), datasourceStorage.getEnvironmentId()) + datasourceStorageMono = getTrueEnvironmentId( + datasourceStorage.getWorkspaceId(), datasourceStorage.getEnvironmentId()) .map(trueEnvironmentId -> { datasourceStorage.setEnvironmentId(trueEnvironmentId); return datasourceStorage; }); } else { - datasourceStorageMono = findById(datasourceStorage.getDatasourceId(), datasourcePermission.getExecutePermission()) - .zipWhen(dbDatasource -> getTrueEnvironmentId(dbDatasource.getWorkspaceId(), datasourceStorage.getEnvironmentId())) + datasourceStorageMono = findById( + datasourceStorage.getDatasourceId(), datasourcePermission.getExecutePermission()) + .zipWhen(dbDatasource -> + getTrueEnvironmentId(dbDatasource.getWorkspaceId(), datasourceStorage.getEnvironmentId())) .map(tuple2 -> { Datasource datasource = tuple2.getT1(); String trueEnvironmentId = tuple2.getT2(); @@ -432,24 +449,28 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceStorageDTO datasource return datasourceStorage; }) .flatMap(datasourceStorage1 -> { - - DatasourceConfiguration datasourceConfiguration = datasourceStorage1.getDatasourceConfiguration(); + DatasourceConfiguration datasourceConfiguration = + datasourceStorage1.getDatasourceConfiguration(); if (datasourceConfiguration == null || datasourceConfiguration.getAuthentication() == null) { return Mono.just(datasourceStorage); } String datasourceId = datasourceStorage1.getDatasourceId(); String trueEnvironmentId = datasourceStorage1.getEnvironmentId(); - // Fetch any fields that maybe encrypted from the db if the datasource being tested does not have those fields set. - // This scenario would happen whenever an existing datasource is being tested and no changes are present in the - // encrypted field (because encrypted fields are not sent over the network after encryption back to the client + // Fetch any fields that maybe encrypted from the db if the datasource being tested does not + // have those fields set. + // This scenario would happen whenever an existing datasource is being tested and no changes are + // present in the + // encrypted field (because encrypted fields are not sent over the network after encryption back + // to the client if (!hasText(datasourceStorage.getId())) { return Mono.just(datasourceStorage); } - return datasourceStorageService.findStrictlyByDatasourceIdAndEnvironmentId(datasourceId, trueEnvironmentId) - .map(dbDatasourceStorage -> { + return datasourceStorageService + .findStrictlyByDatasourceIdAndEnvironmentId(datasourceId, trueEnvironmentId) + .map(dbDatasourceStorage -> { copyNestedNonNullProperties(datasourceStorage, dbDatasourceStorage); return dbDatasourceStorage; }); @@ -476,35 +497,44 @@ protected Mono<DatasourceTestResult> verifyDatasourceAndTest(DatasourceStorage d return datasourceTestResultMono .flatMap(datasourceTestResult -> { if (!CollectionUtils.isEmpty(datasourceTestResult.getInvalids())) { - return analyticsService.sendObjectEvent(AnalyticsEvents.DS_TEST_EVENT_FAILED, - datasourceStorage, getAnalyticsPropertiesForTestEventStatus(datasourceStorage, - datasourceTestResult)).thenReturn(datasourceTestResult); + return analyticsService + .sendObjectEvent( + AnalyticsEvents.DS_TEST_EVENT_FAILED, + datasourceStorage, + getAnalyticsPropertiesForTestEventStatus( + datasourceStorage, datasourceTestResult)) + .thenReturn(datasourceTestResult); } else { - return analyticsService.sendObjectEvent(AnalyticsEvents.DS_TEST_EVENT_SUCCESS, - datasourceStorage, getAnalyticsPropertiesForTestEventStatus(datasourceStorage, - datasourceTestResult)).thenReturn(datasourceTestResult); + return analyticsService + .sendObjectEvent( + AnalyticsEvents.DS_TEST_EVENT_SUCCESS, + datasourceStorage, + getAnalyticsPropertiesForTestEventStatus( + datasourceStorage, datasourceTestResult)) + .thenReturn(datasourceTestResult); } }) .map(datasourceTestResult -> { datasourceTestResult.setMessages(storage.getMessages()); return datasourceTestResult; }); - }); } protected Mono<DatasourceTestResult> testDatasourceViaPlugin(DatasourceStorage datasourceStorage) { - Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper.getPluginExecutor(pluginService.findById(datasourceStorage.getPluginId())) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasourceStorage.getPluginId()))); + Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper + .getPluginExecutor(pluginService.findById(datasourceStorage.getPluginId())) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasourceStorage.getPluginId()))); - return pluginExecutorMono - .flatMap(pluginExecutor -> ((PluginExecutor<Object>) pluginExecutor) - .testDatasource(datasourceStorage.getDatasourceConfiguration())); + return pluginExecutorMono.flatMap(pluginExecutor -> ((PluginExecutor<Object>) pluginExecutor) + .testDatasource(datasourceStorage.getDatasourceConfiguration())); } @Override - public Mono<Datasource> findByNameAndWorkspaceId(String name, String workspaceId, Optional<AclPermission> permission) { + public Mono<Datasource> findByNameAndWorkspaceId( + String name, String workspaceId, Optional<AclPermission> permission) { return repository.findByNameAndWorkspaceId(name, workspaceId, permission); } @@ -515,30 +545,31 @@ public Mono<Datasource> findById(String id, AclPermission aclPermission) { @Override public Mono<Datasource> findByIdWithStorages(String id) { - return repository.findById(id) - .flatMap(datasource -> { - return datasourceStorageService.findByDatasource(datasource) - .collectMap(datasourceStorage -> datasourceStorage.getEnvironmentId(), - datasourceStorage -> new DatasourceStorageDTO(datasourceStorage)) - .map(storages -> { - datasource.setDatasourceStorages(storages); - return datasource; - }); - }); + return repository.findById(id).flatMap(datasource -> { + return datasourceStorageService + .findByDatasource(datasource) + .collectMap( + datasourceStorage -> datasourceStorage.getEnvironmentId(), + datasourceStorage -> new DatasourceStorageDTO(datasourceStorage)) + .map(storages -> { + datasource.setDatasourceStorages(storages); + return datasource; + }); + }); } @Override public Mono<Datasource> findByIdAndEnvironmentId(String id, String environmentId) { - return repository.findById(id) - .flatMap(datasource -> { - return datasourceStorageService.findByDatasourceAndEnvironmentId(datasource, environmentId) - .map(storage -> { - HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(environmentId, new DatasourceStorageDTO(storage)); - datasource.setDatasourceStorages(storages); - return datasource; - }); - }); + return repository.findById(id).flatMap(datasource -> { + return datasourceStorageService + .findByDatasourceAndEnvironmentId(datasource, environmentId) + .map(storage -> { + HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); + storages.put(environmentId, new DatasourceStorageDTO(storage)); + datasource.setDatasourceStorages(storages); + return datasource; + }); + }); } @Override @@ -559,7 +590,8 @@ public Set<MustacheBindingToken> extractKeysFromDatasource(Datasource datasource public Flux<Datasource> getAllWithStorages(MultiValueMap<String, String> params) { String workspaceId = params.getFirst(fieldName(QDatasource.datasource.workspaceId)); if (workspaceId != null) { - return this.getAllByWorkspaceIdWithStorages(workspaceId, Optional.of(datasourcePermission.getReadPermission())); + return this.getAllByWorkspaceIdWithStorages( + workspaceId, Optional.of(datasourcePermission.getReadPermission())); } return Flux.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); @@ -573,7 +605,8 @@ public Flux<Datasource> getAllByWorkspaceIdWithoutStorages(String workspaceId, O @Override public Flux<Datasource> getAllByWorkspaceIdWithStorages(String workspaceId, Optional<AclPermission> permission) { - return repository.findAllByWorkspaceId(workspaceId, permission) + return repository + .findAllByWorkspaceId(workspaceId, permission) .publishOn(Schedulers.boundedElastic()) .flatMap(datasource -> datasourceStorageService .findByDatasource(datasource) @@ -590,15 +623,14 @@ public Flux<Datasource> getAllByWorkspaceIdWithStorages(String workspaceId, Opti markRecentlyUsed(datasourceList, 3); return Flux.fromIterable(datasourceList); }); - } @Override public Flux<Datasource> saveAll(List<Datasource> datasourceList) { - datasourceList - .stream() + datasourceList.stream() .filter(datasource -> datasource.getGitSyncId() == null) - .forEach(datasource -> datasource.setGitSyncId(datasource.getWorkspaceId() + "_" + Instant.now().toString())); + .forEach(datasource -> datasource.setGitSyncId( + datasource.getWorkspaceId() + "_" + Instant.now().toString())); return repository.saveAll(datasourceList); } @@ -606,7 +638,8 @@ public Flux<Datasource> saveAll(List<Datasource> datasourceList) { public Mono<Datasource> archiveById(String id) { return repository .findById(id, datasourcePermission.getDeletePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, id))) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, id))) .zipWhen(datasource -> newActionRepository.countByDatasourceId(datasource.getId())) .flatMap(objects -> { final Long actionsCount = objects.getT2(); @@ -616,23 +649,23 @@ public Mono<Datasource> archiveById(String id) { return Mono.just(objects.getT1()); }) .flatMap(toDelete -> { - return datasourceStorageService.findStrictlyByDatasourceId(toDelete.getId()) + return datasourceStorageService + .findStrictlyByDatasourceId(toDelete.getId()) .publishOn(Schedulers.boundedElastic()) .map(datasourceStorage -> { datasourceStorage.prepareTransientFields(toDelete); return datasourceStorage; }) .flatMap(datasourceStorage -> { - return datasourceContextService.deleteDatasourceContext(datasourceStorage) + return datasourceContextService + .deleteDatasourceContext(datasourceStorage) .then(datasourceStorageService.archive(datasourceStorage)); }) .then(repository.archive(toDelete)) .thenReturn(toDelete); }) .flatMap(datasource -> { - Map<String, String> eventData = Map.of( - FieldName.WORKSPACE_ID, datasource.getWorkspaceId() - ); + Map<String, String> eventData = Map.of(FieldName.WORKSPACE_ID, datasource.getWorkspaceId()); Map<String, Object> analyticsProperties = getAnalyticsProperties(datasource); analyticsProperties.put(FieldName.EVENT_DATA, eventData); return analyticsService.sendDeleteEvent(datasource, analyticsProperties); @@ -650,7 +683,6 @@ public Map<String, Object> getAnalyticsProperties(Datasource datasource) { return analyticsProperties; } - /** * Sets isRecentlyCreated flag to the datasources that were created recently. * It finds the most recent `recentlyUsedCount` numbers of datasources based on the `createdAt` field and set @@ -706,7 +738,8 @@ public Mono<DatasourceDTO> convertToDatasourceDTO(Datasource datasource) { datasourceDTO.setIsMock(datasource.getIsMock()); datasourceDTO.setPolicies(datasource.getPolicies()); - return workspaceService.getDefaultEnvironmentId(datasource.getWorkspaceId()) + return workspaceService + .getDefaultEnvironmentId(datasource.getWorkspaceId()) .flatMap(environmentId -> { Map<String, DatasourceStorageDTO> storages = datasource.getDatasourceStorages(); if (storages == null) { @@ -753,20 +786,22 @@ public Mono<Datasource> convertToDatasource(DatasourceDTO datasourceDTO, String .flatMap(datasource1 -> getTrueEnvironmentId(datasource1.getWorkspaceId(), environmentId)); } else { if (!StringUtils.hasText(environmentId)) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_DATASOURCE, FieldName.DATASOURCE, "Please provide valid metadata for datasource object")); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_DATASOURCE, + FieldName.DATASOURCE, + "Please provide valid metadata for datasource object")); } trueEnvironmentIdMono = Mono.just(environmentId); } - return trueEnvironmentIdMono - .map(trueEnvironmentId -> { - if (datasourceDTO.getDatasourceConfiguration() != null) { - storages.put(trueEnvironmentId, new DatasourceStorageDTO(datasourceDTO, trueEnvironmentId)); - } + return trueEnvironmentIdMono.map(trueEnvironmentId -> { + if (datasourceDTO.getDatasourceConfiguration() != null) { + storages.put(trueEnvironmentId, new DatasourceStorageDTO(datasourceDTO, trueEnvironmentId)); + } - return datasource; - }); + return datasource; + }); } @Override @@ -790,7 +825,8 @@ public Datasource createDatasourceFromDatasourceStorage(DatasourceStorage dataso datasource.setGitSyncId(datasourceStorage.getGitSyncId()); if (hasText(datasourceStorage.getEnvironmentId())) { - datasource.getDatasourceStorages() + datasource + .getDatasourceStorages() .put(datasourceStorage.getEnvironmentId(), new DatasourceStorageDTO(datasourceStorage)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStorageServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStorageServiceCE.java index dd07136de97b..8430ceb0117b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStorageServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStorageServiceCE.java @@ -16,11 +16,9 @@ public interface DatasourceStorageServiceCE { Mono<DatasourceStorage> archive(DatasourceStorage datasourceStorage); - Mono<DatasourceStorage> findByDatasourceAndEnvironmentId(Datasource datasource, - String environmentId); + Mono<DatasourceStorage> findByDatasourceAndEnvironmentId(Datasource datasource, String environmentId); - Mono<DatasourceStorage> findByDatasourceAndEnvironmentIdForExecution(Datasource datasource, - String environmentId); + Mono<DatasourceStorage> findByDatasourceAndEnvironmentIdForExecution(Datasource datasource, String environmentId); Flux<DatasourceStorage> findByDatasource(Datasource datasource); @@ -28,11 +26,11 @@ Mono<DatasourceStorage> findByDatasourceAndEnvironmentIdForExecution(Datasource Mono<DatasourceStorage> findStrictlyByDatasourceIdAndEnvironmentId(String datasourceId, String environmentId); - Mono<DatasourceStorage> updateDatasourceStorage(DatasourceStorage datasourceStorage, - String activeEnvironmentId, - Boolean IsUserRefreshedUpdate); + Mono<DatasourceStorage> updateDatasourceStorage( + DatasourceStorage datasourceStorage, String activeEnvironmentId, Boolean IsUserRefreshedUpdate); Mono<DatasourceStorage> validateDatasourceStorage(DatasourceStorage datasourceStorage, Boolean onlyConfiguration); + Mono<DatasourceStorage> validateDatasourceConfiguration(DatasourceStorage datasourceStorage); Mono<DatasourceStorage> checkEnvironment(DatasourceStorage datasourceStorage); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStorageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStorageServiceCEImpl.java index 6d2543819e2d..911d8d3ad347 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStorageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStorageServiceCEImpl.java @@ -34,6 +34,7 @@ import static com.appsmith.external.helpers.AppsmithBeanUtils.copyNestedNonNullProperties; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; + @Slf4j public class DatasourceStorageServiceCEImpl implements DatasourceStorageServiceCE { @@ -44,12 +45,13 @@ public class DatasourceStorageServiceCEImpl implements DatasourceStorageServiceC private final PluginExecutorHelper pluginExecutorHelper; private final AnalyticsService analyticsService; - public DatasourceStorageServiceCEImpl(DatasourceStorageRepository repository, - DatasourceStorageTransferSolution datasourceStorageTransferSolution, - DatasourcePermission datasourcePermission, - PluginService pluginService, - PluginExecutorHelper pluginExecutorHelper, - AnalyticsService analyticsService) { + public DatasourceStorageServiceCEImpl( + DatasourceStorageRepository repository, + DatasourceStorageTransferSolution datasourceStorageTransferSolution, + DatasourcePermission datasourcePermission, + PluginService pluginService, + PluginExecutorHelper pluginExecutorHelper, + AnalyticsService analyticsService) { this.repository = repository; this.datasourceStorageTransferSolution = datasourceStorageTransferSolution; this.datasourcePermission = datasourcePermission; @@ -61,12 +63,9 @@ public DatasourceStorageServiceCEImpl(DatasourceStorageRepository repository, @Override public Mono<DatasourceStorage> create(DatasourceStorage datasourceStorage) { return this.validateAndSaveDatasourceStorageToRepository(datasourceStorage) - .flatMap(this::populateHintMessages) // For REST API datasource create flow. - .flatMap(savedDatasourceStorage -> - analyticsService.sendCreateEvent( - savedDatasourceStorage, - getAnalyticsProperties(savedDatasourceStorage)) - ); + .flatMap(this::populateHintMessages) // For REST API datasource create flow. + .flatMap(savedDatasourceStorage -> analyticsService.sendCreateEvent( + savedDatasourceStorage, getAnalyticsProperties(savedDatasourceStorage))); } @Override @@ -80,17 +79,17 @@ public Mono<DatasourceStorage> archive(DatasourceStorage datasourceStorage) { } @Override - public Mono<DatasourceStorage> findByDatasourceAndEnvironmentId(Datasource datasource, - String environmentId) { + public Mono<DatasourceStorage> findByDatasourceAndEnvironmentId(Datasource datasource, String environmentId) { return this.findByDatasourceIdAndEnvironmentId(datasource.getId(), environmentId) .map(datasourceStorage -> { datasourceStorage.prepareTransientFields(datasource); return datasourceStorage; }) // TODO: This is a temporary call being made till storage transfer migrations are done - .switchIfEmpty(Mono.defer(() -> datasourceStorageTransferSolution - .transferAndGetDatasourceStorage(datasource, environmentId))) - .onErrorResume(e -> e instanceof DuplicateKeyException + .switchIfEmpty(Mono.defer(() -> + datasourceStorageTransferSolution.transferAndGetDatasourceStorage(datasource, environmentId))) + .onErrorResume( + e -> e instanceof DuplicateKeyException || e instanceof MongoServerException || e instanceof UncategorizedMongoDbException, error -> { @@ -104,8 +103,8 @@ public Mono<DatasourceStorage> findByDatasourceAndEnvironmentId(Datasource datas } @Override - public Mono<DatasourceStorage> findByDatasourceAndEnvironmentIdForExecution(Datasource datasource, - String environmentId) { + public Mono<DatasourceStorage> findByDatasourceAndEnvironmentIdForExecution( + Datasource datasource, String environmentId) { return this.findByDatasourceAndEnvironmentId(datasource, environmentId); } @@ -113,9 +112,11 @@ public Mono<DatasourceStorage> findByDatasourceAndEnvironmentIdForExecution(Data public Flux<DatasourceStorage> findByDatasource(Datasource datasource) { return this.findByDatasourceId(datasource.getId()) // TODO: This is a temporary call being made till storage transfer migrations are done - .switchIfEmpty(Mono.defer(() -> datasourceStorageTransferSolution - .transferToFallbackEnvironmentAndGetDatasourceStorage(datasource))) - .onErrorResume(e -> e instanceof DuplicateKeyException + .switchIfEmpty(Mono.defer( + () -> datasourceStorageTransferSolution.transferToFallbackEnvironmentAndGetDatasourceStorage( + datasource))) + .onErrorResume( + e -> e instanceof DuplicateKeyException || e instanceof MongoServerException || e instanceof UncategorizedMongoDbException, error -> { @@ -142,14 +143,14 @@ public Flux<DatasourceStorage> findStrictlyByDatasourceId(String datasourceId) { } @Override - public Mono<DatasourceStorage> findStrictlyByDatasourceIdAndEnvironmentId(String datasourceId, String environmentId) { + public Mono<DatasourceStorage> findStrictlyByDatasourceIdAndEnvironmentId( + String datasourceId, String environmentId) { return repository.findByDatasourceIdAndEnvironmentId(datasourceId, environmentId); } @Override - public Mono<DatasourceStorage> updateDatasourceStorage(DatasourceStorage datasourceStorage, - String activeEnvironmentId, - Boolean isUserRefreshedUpdate) { + public Mono<DatasourceStorage> updateDatasourceStorage( + DatasourceStorage datasourceStorage, String activeEnvironmentId, Boolean isUserRefreshedUpdate) { String datasourceId = datasourceStorage.getDatasourceId(); String environmentId = datasourceStorage.getEnvironmentId(); @@ -169,7 +170,7 @@ public Mono<DatasourceStorage> updateDatasourceStorage(DatasourceStorage datasou .flatMap(this::validateAndSaveDatasourceStorageToRepository) .flatMap(savedDatasourceStorage -> { Map<String, Object> analyticsProperties = getAnalyticsProperties(savedDatasourceStorage); - Boolean isUserInvokedUpdate = TRUE.equals(isUserRefreshedUpdate) ? TRUE : FALSE; + Boolean isUserInvokedUpdate = TRUE.equals(isUserRefreshedUpdate) ? TRUE : FALSE; analyticsProperties.put(FieldName.IS_DATASOURCE_UPDATE_USER_INVOKED_KEY, isUserInvokedUpdate); return analyticsService.sendUpdateEvent(savedDatasourceStorage, analyticsProperties); @@ -178,7 +179,8 @@ public Mono<DatasourceStorage> updateDatasourceStorage(DatasourceStorage datasou } @Override - public Mono<DatasourceStorage> validateDatasourceStorage(DatasourceStorage datasourceStorage, Boolean onlyConfiguration) { + public Mono<DatasourceStorage> validateDatasourceStorage( + DatasourceStorage datasourceStorage, Boolean onlyConfiguration) { Set<String> invalids = new HashSet<>(); datasourceStorage.setInvalids(invalids); @@ -198,17 +200,19 @@ public Mono<DatasourceStorage> validateDatasourceStorage(DatasourceStorage datas } final Mono<Plugin> pluginMono = pluginService.findById(datasourceStorage.getPluginId()); - Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper.getPluginExecutor(pluginMono) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, - FieldName.PLUGIN, datasourceStorage.getPluginId()))); + Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper + .getPluginExecutor(pluginMono) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasourceStorage.getPluginId()))); return pluginExecutorMono .map(pluginExecutor -> { DatasourceConfiguration datasourceConfiguration = datasourceStorage.getDatasourceConfiguration(); - if (datasourceConfiguration != null && !pluginExecutor.isDatasourceValid(datasourceConfiguration, - datasourceStorage.isEmbedded())) { - invalids.addAll(pluginExecutor.validateDatasource(datasourceConfiguration, - datasourceStorage.isEmbedded())); + if (datasourceConfiguration != null + && !pluginExecutor.isDatasourceValid( + datasourceConfiguration, datasourceStorage.isEmbedded())) { + invalids.addAll(pluginExecutor.validateDatasource( + datasourceConfiguration, datasourceStorage.isEmbedded())); } return datasourceStorage; @@ -230,13 +234,13 @@ private Mono<DatasourceStorage> validateAndSaveDatasourceStorageToRepository(Dat .map(this::sanitizeDatasourceStorage) .flatMap(datasourceStorage1 -> validateDatasourceStorage(datasourceStorage1, false)) .flatMap(unsavedDatasourceStorage -> { - return repository.save(unsavedDatasourceStorage) - .map(datasourceStorage1 -> { - // datasourceStorage.pluginName is a transient field. It was set by validateDatasource method - // object from db will have pluginName=null so set it manually from the unsaved datasourceStorage obj - datasourceStorage1.setPluginName(unsavedDatasourceStorage.getPluginName()); - return datasourceStorage1; - }); + return repository.save(unsavedDatasourceStorage).map(datasourceStorage1 -> { + // datasourceStorage.pluginName is a transient field. It was set by validateDatasource method + // object from db will have pluginName=null so set it manually from the unsaved + // datasourceStorage obj + datasourceStorage1.setPluginName(unsavedDatasourceStorage.getPluginName()); + return datasourceStorage1; + }); }); } @@ -248,8 +252,10 @@ public Mono<DatasourceStorage> checkEnvironment(DatasourceStorage datasourceStor private DatasourceStorage sanitizeDatasourceStorage(DatasourceStorage datasourceStorage) { if (datasourceStorage.getDatasourceConfiguration() != null - && !CollectionUtils.isEmpty(datasourceStorage.getDatasourceConfiguration().getEndpoints())) { - for (final Endpoint endpoint : datasourceStorage.getDatasourceConfiguration().getEndpoints()) { + && !CollectionUtils.isEmpty( + datasourceStorage.getDatasourceConfiguration().getEndpoints())) { + for (final Endpoint endpoint : + datasourceStorage.getDatasourceConfiguration().getEndpoints()) { if (endpoint != null && endpoint.getHost() != null) { endpoint.setHost(endpoint.getHost().trim()); } @@ -279,9 +285,10 @@ public Mono<DatasourceStorage> populateHintMessages(DatasourceStorage datasource } final Mono<Plugin> pluginMono = pluginService.findById(datasourceStorage.getPluginId()); - Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper.getPluginExecutor(pluginMono) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, - datasourceStorage.getPluginId()))); + Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper + .getPluginExecutor(pluginMono) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasourceStorage.getPluginId()))); /** * Delegate the task of generating hint messages to the concerned plugin, since only the @@ -305,7 +312,9 @@ public Map<String, Object> getAnalyticsProperties(DatasourceStorage datasourceSt analyticsProperties.put("dsId", datasourceStorage.getDatasourceId()); analyticsProperties.put("envId", datasourceStorage.getEnvironmentId()); DatasourceConfiguration dsConfig = datasourceStorage.getDatasourceConfiguration(); - if (dsConfig != null && dsConfig.getAuthentication() != null && dsConfig.getAuthentication() instanceof OAuth2) { + if (dsConfig != null + && dsConfig.getAuthentication() != null + && dsConfig.getAuthentication() instanceof OAuth2) { analyticsProperties.put("oAuthStatus", dsConfig.getAuthentication().getAuthenticationStatus()); } return analyticsProperties; @@ -324,11 +333,11 @@ public DatasourceStorage getDatasourceStorageFromDatasource(Datasource datasourc if (datasource == null || datasource.getDatasourceStorages() == null) { return null; } - DatasourceStorageDTO datasourceStorageDTO = this.getDatasourceStorageDTOFromDatasource(datasource, environmentId); + DatasourceStorageDTO datasourceStorageDTO = + this.getDatasourceStorageDTOFromDatasource(datasource, environmentId); DatasourceStorage datasourceStorage = new DatasourceStorage(datasourceStorageDTO); datasourceStorage.prepareTransientFields(datasource); return datasourceStorage; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStructureServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStructureServiceCEImpl.java index 880af54e829e..bc29114b875c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStructureServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceStructureServiceCEImpl.java @@ -15,7 +15,8 @@ public class DatasourceStructureServiceCEImpl implements DatasourceStructureServ protected final DatasourceStructureRepository repository; @Override - public Mono<DatasourceStorageStructure> getByDatasourceIdAndEnvironmentId(String datasourceId, String environmentId) { + public Mono<DatasourceStorageStructure> getByDatasourceIdAndEnvironmentId( + String datasourceId, String environmentId) { return repository.findByDatasourceIdAndEnvironmentId(datasourceId, environmentId); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/EncryptionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/EncryptionServiceCEImpl.java index 673c3db41c3e..0f7d61c5cdc1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/EncryptionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/EncryptionServiceCEImpl.java @@ -7,7 +7,6 @@ import org.springframework.security.crypto.encrypt.Encryptors; import org.springframework.security.crypto.encrypt.TextEncryptor; - public class EncryptionServiceCEImpl implements EncryptionServiceCE { private final EncryptionConfig encryptionConfig; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/FeatureFlagServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/FeatureFlagServiceCE.java index 07e8faafc20a..771584a80cba 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/FeatureFlagServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/FeatureFlagServiceCE.java @@ -1,7 +1,6 @@ package com.appsmith.server.services.ce; import com.appsmith.server.domains.User; -import com.appsmith.server.featureflags.CachedFlags; import com.appsmith.server.featureflags.FeatureFlagEnum; import com.appsmith.server.featureflags.FeatureFlagTrait; import reactor.core.publisher.Mono; @@ -40,5 +39,4 @@ public interface FeatureFlagServiceCE { Mono<Map<String, Boolean>> getAllFeatureFlagsForUser(); Mono<Void> remoteSetUserTraits(List<FeatureFlagTrait> featureFlagTraits); - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/FeatureFlagServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/FeatureFlagServiceCEImpl.java index 74e34cf4a756..a6c75a78ad10 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/FeatureFlagServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/FeatureFlagServiceCEImpl.java @@ -29,7 +29,6 @@ import java.util.List; import java.util.Map; - @Slf4j public class FeatureFlagServiceCEImpl implements FeatureFlagServiceCE { @@ -50,13 +49,14 @@ public class FeatureFlagServiceCEImpl implements FeatureFlagServiceCE { private final CacheableFeatureFlagHelper cacheableFeatureFlagHelper; @Autowired - public FeatureFlagServiceCEImpl(SessionUserService sessionUserService, - FF4j ff4j, - TenantService tenantService, - ConfigService configService, - CloudServicesConfig cloudServicesConfig, - UserIdentifierService userIdentifierService, - CacheableFeatureFlagHelper cacheableFeatureFlagHelper) { + public FeatureFlagServiceCEImpl( + SessionUserService sessionUserService, + FF4j ff4j, + TenantService tenantService, + ConfigService configService, + CloudServicesConfig cloudServicesConfig, + UserIdentifierService userIdentifierService, + CacheableFeatureFlagHelper cacheableFeatureFlagHelper) { this.sessionUserService = sessionUserService; this.ff4j = ff4j; this.tenantService = tenantService; @@ -66,7 +66,6 @@ public FeatureFlagServiceCEImpl(SessionUserService sessionUserService, this.cacheableFeatureFlagHelper = cacheableFeatureFlagHelper; } - private Mono<Boolean> checkAll(String featureName, User user) { Boolean check = check(featureName, user); @@ -89,8 +88,7 @@ public Mono<Boolean> check(FeatureFlagEnum featureEnum, User user) { @Override public Mono<Boolean> check(FeatureFlagEnum featureEnum) { - return sessionUserService.getCurrentUser() - .flatMap(user -> check(featureEnum, user)); + return sessionUserService.getCurrentUser().flatMap(user -> check(featureEnum, user)); } @Override @@ -101,15 +99,13 @@ public Boolean check(String featureName, User user) { @Override public Mono<Map<String, Boolean>> getAllFeatureFlagsForUser() { Mono<User> currentUser = sessionUserService.getCurrentUser().cache(); - Flux<Tuple2<String, User>> featureUserTuple = Flux.fromIterable(ff4j.getFeatures().keySet()) + Flux<Tuple2<String, User>> featureUserTuple = Flux.fromIterable( + ff4j.getFeatures().keySet()) .flatMap(featureName -> Mono.just(featureName).zipWith(currentUser)); Mono<Map<String, Boolean>> localFlagsForUser = featureUserTuple .filter(objects -> !objects.getT2().isAnonymous()) - .collectMap( - Tuple2::getT1, - tuple -> check(tuple.getT1(), tuple.getT2()) - ); + .collectMap(Tuple2::getT1, tuple -> check(tuple.getT1(), tuple.getT2())); return Mono.zip(localFlagsForUser, this.getAllRemoteFeatureFlagsForUser()) .map(tuple -> { @@ -125,22 +121,24 @@ public Mono<Map<String, Boolean>> getAllFeatureFlagsForUser() { */ private Mono<Map<String, Boolean>> getAllRemoteFeatureFlagsForUser() { Mono<User> userMono = sessionUserService.getCurrentUser().cache(); - return userMono - .flatMap(user -> { - String userIdentifier = userIdentifierService.getUserIdentifier(user); - // Checks for flags present in cache and if the cache is not expired - return cacheableFeatureFlagHelper.fetchUserCachedFlags(userIdentifier) - .flatMap(cachedFlags -> { - if (cachedFlags.getRefreshedAt().until(Instant.now(), ChronoUnit.MINUTES) < this.featureFlagCacheTimeMin) { - return Mono.just(cachedFlags.getFlags()); - } else { - // empty the cache for the userIdentifier as expired - return cacheableFeatureFlagHelper.evictUserCachedFlags(userIdentifier) - .then(cacheableFeatureFlagHelper.fetchUserCachedFlags(userIdentifier)) - .flatMap(cachedFlagsUpdated -> Mono.just(cachedFlagsUpdated.getFlags())); - } - }); - }); + return userMono.flatMap(user -> { + String userIdentifier = userIdentifierService.getUserIdentifier(user); + // Checks for flags present in cache and if the cache is not expired + return cacheableFeatureFlagHelper + .fetchUserCachedFlags(userIdentifier) + .flatMap(cachedFlags -> { + if (cachedFlags.getRefreshedAt().until(Instant.now(), ChronoUnit.MINUTES) + < this.featureFlagCacheTimeMin) { + return Mono.just(cachedFlags.getFlags()); + } else { + // empty the cache for the userIdentifier as expired + return cacheableFeatureFlagHelper + .evictUserCachedFlags(userIdentifier) + .then(cacheableFeatureFlagHelper.fetchUserCachedFlags(userIdentifier)) + .flatMap(cachedFlagsUpdated -> Mono.just(cachedFlagsUpdated.getFlags())); + } + }); + }); } @Override @@ -152,8 +150,7 @@ public Mono<Void> remoteSetUserTraits(List<FeatureFlagTrait> featureFlagTraits) .body(BodyInserters.fromValue(featureFlagTraits)) .exchangeToMono(clientResponse -> { if (clientResponse.statusCode().is2xxSuccessful()) { - return clientResponse.bodyToMono(new ParameterizedTypeReference<ResponseDTO<Void>>() { - }); + return clientResponse.bodyToMono(new ParameterizedTypeReference<ResponseDTO<Void>>() {}); } else { return clientResponse.createError(); } @@ -162,8 +159,7 @@ public Mono<Void> remoteSetUserTraits(List<FeatureFlagTrait> featureFlagTraits) .onErrorMap( // Only map errors if we haven't already wrapped them into an AppsmithException e -> !(e instanceof AppsmithException), - e -> new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, e.getMessage()) - ) + e -> new AppsmithException(AppsmithError.CLOUD_SERVICES_ERROR, e.getMessage())) .onErrorResume(error -> { // We're gobbling up errors here so that all feature flags are turned off by default // This will be problematic if we do not maintain code to reflect validity of flags @@ -171,4 +167,4 @@ public Mono<Void> remoteSetUserTraits(List<FeatureFlagTrait> featureFlagTraits) return Mono.empty(); }); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCE.java index 51659ed8f210..24e9e6b93fad 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCE.java @@ -8,15 +8,14 @@ import com.appsmith.server.domains.GitApplicationMetadata; import com.appsmith.server.domains.GitAuth; import com.appsmith.server.domains.GitProfile; +import com.appsmith.server.dtos.ApplicationImportDTO; import com.appsmith.server.dtos.GitCommitDTO; import com.appsmith.server.dtos.GitConnectDTO; -import com.appsmith.server.dtos.ApplicationImportDTO; import com.appsmith.server.dtos.GitDocsDTO; import com.appsmith.server.dtos.GitMergeDTO; import com.appsmith.server.dtos.GitPullDTO; import reactor.core.publisher.Mono; -import java.util.EnumSet; import java.util.List; import java.util.Map; @@ -24,7 +23,8 @@ public interface GitServiceCE { Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser(GitProfile gitProfile); - Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser(GitProfile gitProfile, String defaultApplicationId); + Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser( + GitProfile gitProfile, String defaultApplicationId); Mono<GitProfile> getDefaultGitProfileOrCreateIfEmpty(); @@ -34,7 +34,8 @@ public interface GitServiceCE { Mono<Application> updateGitMetadata(String applicationId, GitApplicationMetadata gitApplicationMetadata); - Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApplicationId, String branchName, boolean doAmend); + Mono<String> commitApplication( + GitCommitDTO commitDTO, String defaultApplicationId, String branchName, boolean doAmend); Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApplicationId, String branchName); @@ -50,7 +51,8 @@ public interface GitServiceCE { Mono<GitPullDTO> pullApplication(String defaultApplicationId, String branchName); - Mono<List<GitBranchDTO>> listBranchForApplication(String defaultApplicationId, Boolean pruneBranches, String currentBranch); + Mono<List<GitBranchDTO>> listBranchForApplication( + String defaultApplicationId, Boolean pruneBranches, String currentBranch); Mono<GitApplicationMetadata> getGitApplicationMetadata(String defaultApplicationId); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java index ac29832cb266..72d6c02a3555 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java @@ -113,7 +113,6 @@ * not take subscription cancellations into account. This means that even if the subscriber has cancelled its * subscription, the create method still generates its event. */ - @Slf4j @RequiredArgsConstructor @Import({GitExecutorImpl.class}) @@ -145,19 +144,21 @@ public class GitServiceCEImpl implements GitServiceCE { private final RedisUtils redisUtils; private final ExecutionTimeLogging executionTimeLogging; - private final static Duration RETRY_DELAY = Duration.ofSeconds(1); - private final static Integer MAX_RETRIES = 20; + private static final Duration RETRY_DELAY = Duration.ofSeconds(1); + private static final Integer MAX_RETRIES = 20; @Override public Mono<Application> updateGitMetadata(String applicationId, GitApplicationMetadata gitApplicationMetadata) { if (Optional.ofNullable(gitApplicationMetadata).isEmpty()) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "Git metadata values cannot be null")); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_PARAMETER, "Git metadata values cannot be null")); } // For default application we expect a GitAuth to be a part of gitMetadata. We are using save method to leverage // @Encrypted annotation used for private SSH keys - return applicationService.findById(applicationId, applicationPermission.getEditPermission()) + return applicationService + .findById(applicationId, applicationPermission.getEditPermission()) .flatMap(application -> { application.setGitApplicationMetadata(gitApplicationMetadata); return applicationService.save(application); @@ -192,7 +193,8 @@ public Mono<GitApplicationMetadata> getGitApplicationMetadata(String defaultAppl } @Override - public Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser(GitProfile gitProfile, String defaultApplicationId) { + public Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser( + GitProfile gitProfile, String defaultApplicationId) { // Throw error in following situations: // 1. Updating or creating global git profile (defaultApplicationId = "default") and update is made with empty @@ -201,12 +203,10 @@ public Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser(GitP // values for authorName and email if ((DEFAULT.equals(defaultApplicationId) || Boolean.FALSE.equals(gitProfile.getUseGlobalProfile())) - && StringUtils.isEmptyOrNull(gitProfile.getAuthorName()) - ) { + && StringUtils.isEmptyOrNull(gitProfile.getAuthorName())) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "Author Name")); } else if ((DEFAULT.equals(defaultApplicationId) || Boolean.FALSE.equals(gitProfile.getUseGlobalProfile())) - && StringUtils.isEmptyOrNull(gitProfile.getAuthorEmail()) - ) { + && StringUtils.isEmptyOrNull(gitProfile.getAuthorEmail())) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "Author Email")); } else if (StringUtils.isEmptyOrNull(defaultApplicationId)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID)); @@ -218,9 +218,11 @@ public Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser(GitP gitProfile.setUseGlobalProfile(Boolean.FALSE); } - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .flatMap(user -> userService.findByEmail(user.getEmail())) - .flatMap(user -> userDataService.getForUser(user.getId()) + .flatMap(user -> userDataService + .getForUser(user.getId()) .flatMap(userData -> { // GitProfiles will be null if the user has not created any git profile. GitProfile savedProfile = userData.getGitProfileByKey(defaultApplicationId); @@ -244,27 +246,29 @@ public Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser(GitP // Update userData here UserData requiredUpdates = new UserData(); requiredUpdates.setGitProfiles(userData.getGitProfiles()); - return userDataService.updateForUser(user, requiredUpdates) + return userDataService + .updateForUser(user, requiredUpdates) .map(UserData::getGitProfiles); } return Mono.just(userData.getGitProfiles()); }) .switchIfEmpty(Mono.defer(() -> { - // If profiles are empty use Appsmith's user profile as git default profile - GitProfile profile = new GitProfile(); - String authorName = StringUtils.isEmptyOrNull(user.getName()) ? user.getUsername().split("@")[0] : user.getName(); - - profile.setAuthorName(authorName); - profile.setAuthorEmail(user.getEmail()); - - UserData requiredUpdates = new UserData(); - requiredUpdates.setGitProfiles(Map.of(DEFAULT, gitProfile)); - return userDataService.updateForUser(user, requiredUpdates) - .map(UserData::getGitProfiles); - }) - ) - .filter(profiles -> !CollectionUtils.isNullOrEmpty(profiles)) - ); + // If profiles are empty use Appsmith's user profile as git default profile + GitProfile profile = new GitProfile(); + String authorName = StringUtils.isEmptyOrNull(user.getName()) + ? user.getUsername().split("@")[0] + : user.getName(); + + profile.setAuthorName(authorName); + profile.setAuthorEmail(user.getEmail()); + + UserData requiredUpdates = new UserData(); + requiredUpdates.setGitProfiles(Map.of(DEFAULT, gitProfile)); + return userDataService + .updateForUser(user, requiredUpdates) + .map(UserData::getGitProfiles); + })) + .filter(profiles -> !CollectionUtils.isNullOrEmpty(profiles))); } @Override @@ -276,37 +280,37 @@ public Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser(GitP @Override public Mono<GitProfile> getDefaultGitProfileOrCreateIfEmpty() { // Get default git profile if the default is empty then use Appsmith profile as a fallback value - return getGitProfileForUser(DEFAULT) - .flatMap(gitProfile -> { - if (StringUtils.isEmptyOrNull(gitProfile.getAuthorName()) || StringUtils.isEmptyOrNull(gitProfile.getAuthorEmail())) { - return updateGitProfileWithAppsmithProfile(DEFAULT); - } - gitProfile.setUseGlobalProfile(null); - return Mono.just(gitProfile); - }); + return getGitProfileForUser(DEFAULT).flatMap(gitProfile -> { + if (StringUtils.isEmptyOrNull(gitProfile.getAuthorName()) + || StringUtils.isEmptyOrNull(gitProfile.getAuthorEmail())) { + return updateGitProfileWithAppsmithProfile(DEFAULT); + } + gitProfile.setUseGlobalProfile(null); + return Mono.just(gitProfile); + }); } @Override public Mono<GitProfile> getGitProfileForUser(String defaultApplicationId) { - return userDataService.getForCurrentUser() - .map(userData -> { - GitProfile gitProfile = userData.getGitProfileByKey(defaultApplicationId); - if (gitProfile != null && gitProfile.getUseGlobalProfile() == null) { - gitProfile.setUseGlobalProfile(true); - } else if (gitProfile == null) { - // If the profile is requested for repo specific using the applicationId - GitProfile gitProfile1 = new GitProfile(); - gitProfile1.setAuthorName(""); - gitProfile1.setAuthorEmail(""); - gitProfile1.setUseGlobalProfile(true); - return gitProfile1; - } - return gitProfile; - }); + return userDataService.getForCurrentUser().map(userData -> { + GitProfile gitProfile = userData.getGitProfileByKey(defaultApplicationId); + if (gitProfile != null && gitProfile.getUseGlobalProfile() == null) { + gitProfile.setUseGlobalProfile(true); + } else if (gitProfile == null) { + // If the profile is requested for repo specific using the applicationId + GitProfile gitProfile1 = new GitProfile(); + gitProfile1.setAuthorName(""); + gitProfile1.setAuthorEmail(""); + gitProfile1.setUseGlobalProfile(true); + return gitProfile1; + } + return gitProfile; + }); } private Mono<GitProfile> updateGitProfileWithAppsmithProfile(String key) { - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .flatMap(user -> userService.findByEmail(user.getEmail())) .flatMap(currentUser -> { GitProfile gitProfile = new GitProfile(); @@ -316,18 +320,18 @@ private Mono<GitProfile> updateGitProfileWithAppsmithProfile(String key) { gitProfile.setAuthorEmail(currentUser.getEmail()); gitProfile.setAuthorName(authorName); gitProfile.setUseGlobalProfile(null); - return userDataService.getForUser(currentUser) - .flatMap(userData -> { - UserData updates = new UserData(); - if (CollectionUtils.isNullOrEmpty(userData.getGitProfiles())) { - updates.setGitProfiles(Map.of(key, gitProfile)); - } else { - userData.getGitProfiles().put(key, gitProfile); - updates.setGitProfiles(userData.getGitProfiles()); - } - return userDataService.updateForUser(currentUser, updates) - .thenReturn(gitProfile); - }); + return userDataService.getForUser(currentUser).flatMap(userData -> { + UserData updates = new UserData(); + if (CollectionUtils.isNullOrEmpty(userData.getGitProfiles())) { + updates.setGitProfiles(Map.of(key, gitProfile)); + } else { + userData.getGitProfiles().put(key, gitProfile); + updates.setGitProfiles(userData.getGitProfiles()); + } + return userDataService + .updateForUser(currentUser, updates) + .thenReturn(gitProfile); + }); }); } @@ -341,7 +345,8 @@ private Mono<GitProfile> updateGitProfileWithAppsmithProfile(String key) { * @return success message */ @Override - public Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApplicationId, String branchName, boolean doAmend) { + public Mono<String> commitApplication( + GitCommitDTO commitDTO, String defaultApplicationId, String branchName, boolean doAmend) { return this.commitApplication(commitDTO, defaultApplicationId, branchName, doAmend, true); } @@ -365,7 +370,12 @@ public Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultAppl * @param isFileLock boolean value indicates whether the file lock is needed to complete the operation * @return success message */ - private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApplicationId, String branchName, boolean doAmend, boolean isFileLock) { + private Mono<String> commitApplication( + GitCommitDTO commitDTO, + String defaultApplicationId, + String branchName, + boolean doAmend, + boolean isFileLock) { /* 1. Check if application exists and user have sufficient permissions 2. Check if branch name exists in git metadata @@ -388,14 +398,19 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp isSystemGeneratedTemp = true; } - Mono<UserData> currentUserMono = executionTimeLogging.measureTask("getForCurrentUser", userDataService.getForCurrentUser()) + Mono<UserData> currentUserMono = executionTimeLogging + .measureTask("getForCurrentUser", userDataService.getForCurrentUser()) .flatMap(userData -> { - if (CollectionUtils.isNullOrEmpty(userData.getGitProfiles()) || userData.getGitProfileByKey(DEFAULT) == null) { - return executionTimeLogging.measureTask("getCurrentUser", sessionUserService - .getCurrentUser()) + if (CollectionUtils.isNullOrEmpty(userData.getGitProfiles()) + || userData.getGitProfileByKey(DEFAULT) == null) { + return executionTimeLogging + .measureTask("getCurrentUser", sessionUserService.getCurrentUser()) .flatMap(user -> { GitProfile gitProfile = new GitProfile(); - gitProfile.setAuthorName(StringUtils.isEmptyOrNull(user.getName()) ? user.getUsername().split("@")[0] : user.getName()); + gitProfile.setAuthorName( + StringUtils.isEmptyOrNull(user.getName()) + ? user.getUsername().split("@")[0] + : user.getName()); gitProfile.setAuthorEmail(user.getEmail()); Map<String, GitProfile> updateProfiles = userData.getGitProfiles(); if (CollectionUtils.isNullOrEmpty(updateProfiles)) { @@ -405,18 +420,21 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp } userData.setGitProfiles(updateProfiles); - return executionTimeLogging.measureTask("updateForCurrentUser", userDataService.updateForCurrentUser(userData)); + return executionTimeLogging.measureTask( + "updateForCurrentUser", userDataService.updateForCurrentUser(userData)); }); } return Mono.just(userData); }); boolean isSystemGenerated = isSystemGeneratedTemp; - Mono<String> commitMono = executionTimeLogging.measureTask("getApplicationById", this.getApplicationById(defaultApplicationId)) + Mono<String> commitMono = executionTimeLogging + .measureTask("getApplicationById", this.getApplicationById(defaultApplicationId)) .flatMap(application -> { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); - if(Boolean.TRUE.equals(isFileLock)) { - return executionTimeLogging.measureTask("addFileLock", addFileLock(gitData.getDefaultApplicationId())) + if (Boolean.TRUE.equals(isFileLock)) { + return executionTimeLogging + .measureTask("addFileLock", addFileLock(gitData.getDefaultApplicationId())) .then(Mono.just(application)); } return Mono.just(application); @@ -424,7 +442,8 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp .flatMap(defaultApplication -> { GitApplicationMetadata defaultGitMetadata = defaultApplication.getGitApplicationMetadata(); if (Optional.ofNullable(defaultGitMetadata).isEmpty()) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); } // Check if the repo is public for current application and if the user have changed the access after // the connection @@ -432,12 +451,17 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp return GitUtils.isRepoPrivate(defaultGitMetadata.getBrowserSupportedRemoteUrl()) .flatMap(isPrivate -> { // Check the repo limit if the visibility status is updated, or it is private - if (!isPrivate.equals(defaultGitMetadata.getIsRepoPrivate()) || isPrivate.equals(Boolean.TRUE)) { + if (!isPrivate.equals(defaultGitMetadata.getIsRepoPrivate()) + || isPrivate.equals(Boolean.TRUE)) { defaultGitMetadata.setIsRepoPrivate(isPrivate); defaultApplication.setGitApplicationMetadata(defaultGitMetadata); - return executionTimeLogging.measureTask("applicationService.save", applicationService.save(defaultApplication)) + return executionTimeLogging + .measureTask( + "applicationService.save", + applicationService.save(defaultApplication)) // Check if the private repo count is less than the allowed repo count - .flatMap(application -> executionTimeLogging.measureTask("isRepoLimitReached", isRepoLimitReached(workspaceId, false))) + .flatMap(application -> executionTimeLogging.measureTask( + "isRepoLimitReached", isRepoLimitReached(workspaceId, false))) .flatMap(isRepoLimitReached -> { if (Boolean.FALSE.equals(isRepoLimitReached)) { return Mono.just(defaultApplication); @@ -449,11 +473,15 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp } }); }) - .then(executionTimeLogging.measureTask("findByBranchNameAndDefaultApplicationId", applicationService.findByBranchNameAndDefaultApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()))) + .then(executionTimeLogging.measureTask( + "findByBranchNameAndDefaultApplicationId", + applicationService.findByBranchNameAndDefaultApplicationId( + branchName, defaultApplicationId, applicationPermission.getEditPermission()))) .flatMap((branchedApplication) -> { GitApplicationMetadata gitApplicationMetadata = branchedApplication.getGitApplicationMetadata(); if (gitApplicationMetadata == null) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); } String errorEntity = ""; if (StringUtils.isEmptyOrNull(gitApplicationMetadata.getBranchName())) { @@ -465,40 +493,46 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp } if (!errorEntity.isEmpty()) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, "Unable to find " + errorEntity)); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, "Unable to find " + errorEntity)); } return Mono.zip( - executionTimeLogging.measureTask("exportApplicationById", importExportApplicationService - .exportApplicationById(branchedApplication.getId(), SerialiseApplicationObjective.VERSION_CONTROL)), - Mono.just(branchedApplication) - ); + executionTimeLogging.measureTask( + "exportApplicationById", + importExportApplicationService.exportApplicationById( + branchedApplication.getId(), + SerialiseApplicationObjective.VERSION_CONTROL)), + Mono.just(branchedApplication)); }) .flatMap(tuple -> { ApplicationJson applicationJson = tuple.getT1(); Application childApplication = tuple.getT2(); GitApplicationMetadata gitData = childApplication.getGitApplicationMetadata(); - Path baseRepoSuffix = - Paths.get(childApplication.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); + Path baseRepoSuffix = Paths.get( + childApplication.getWorkspaceId(), + gitData.getDefaultApplicationId(), + gitData.getRepoName()); Mono<Path> repoPathMono; try { - repoPathMono = executionTimeLogging.measureTask("saveApplicationToLocalRepo", fileUtils.saveApplicationToLocalRepo(baseRepoSuffix, applicationJson, gitData.getBranchName())); + repoPathMono = executionTimeLogging.measureTask( + "saveApplicationToLocalRepo", + fileUtils.saveApplicationToLocalRepo( + baseRepoSuffix, applicationJson, gitData.getBranchName())); } catch (IOException | GitAPIException e) { return Mono.error(e); } gitData.setLastCommittedAt(Instant.now()); - Mono<Application> branchedApplicationMono = executionTimeLogging.measureTask("updateGitMetadata", updateGitMetadata(childApplication.getId(), gitData)); + Mono<Application> branchedApplicationMono = executionTimeLogging.measureTask( + "updateGitMetadata", updateGitMetadata(childApplication.getId(), gitData)); return Mono.zip( - repoPathMono, - currentUserMono, - branchedApplicationMono, - Mono.just(childApplication) - ); + repoPathMono, currentUserMono, branchedApplicationMono, Mono.just(childApplication)); }) .onErrorResume(e -> { log.error("Error in commit flow: ", e); if (e instanceof RepositoryNotFoundException) { - return Mono.error(new AppsmithException(AppsmithError.REPOSITORY_NOT_FOUND, defaultApplicationId)); + return Mono.error( + new AppsmithException(AppsmithError.REPOSITORY_NOT_FOUND, defaultApplicationId)); } else if (e instanceof AppsmithException) { return Mono.error(e); } @@ -510,7 +544,8 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp Application childApplication = tuple.getT3(); GitApplicationMetadata gitApplicationData = childApplication.getGitApplicationMetadata(); - GitProfile authorProfile = currentUserData.getGitProfileByKey(gitApplicationData.getDefaultApplicationId()); + GitProfile authorProfile = + currentUserData.getGitProfileByKey(gitApplicationData.getDefaultApplicationId()); if (authorProfile == null || StringUtils.isEmptyOrNull(authorProfile.getAuthorName()) @@ -523,32 +558,44 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp } if (authorProfile == null || StringUtils.isEmptyOrNull(authorProfile.getAuthorName())) { - String errorMessage = "Unable to find git author configuration for logged-in user. You can set " + - "up a git profile from the user profile section."; + String errorMessage = "Unable to find git author configuration for logged-in user. You can set " + + "up a git profile from the user profile section."; return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_COMMIT.getEventName(), - childApplication, - AppsmithError.INVALID_GIT_CONFIGURATION.getErrorType(), - AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(errorMessage), - childApplication.getGitApplicationMetadata().getIsRepoPrivate() - ) - .flatMap(user -> Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, errorMessage))); + AnalyticsEvents.GIT_COMMIT.getEventName(), + childApplication, + AppsmithError.INVALID_GIT_CONFIGURATION.getErrorType(), + AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(errorMessage), + childApplication + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .flatMap(user -> Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, errorMessage))); } result.append("Commit Result : "); - Mono<String> gitCommitMono = executionTimeLogging.measureTask("commitApplication", gitExecutor - .commitApplication(baseRepoPath, commitMessage, authorProfile.getAuthorName(), authorProfile.getAuthorEmail(), false, doAmend)) + Mono<String> gitCommitMono = executionTimeLogging + .measureTask( + "commitApplication", + gitExecutor.commitApplication( + baseRepoPath, + commitMessage, + authorProfile.getAuthorName(), + authorProfile.getAuthorEmail(), + false, + doAmend)) .onErrorResume(error -> { if (error instanceof EmptyCommitException) { return Mono.just(EMPTY_COMMIT_ERROR_MESSAGE); } return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_COMMIT.getEventName(), - childApplication, - error.getClass().getName(), - error.getMessage(), - childApplication.getGitApplicationMetadata().getIsRepoPrivate() - ) - .then(Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "commit", error.getMessage()))); + AnalyticsEvents.GIT_COMMIT.getEventName(), + childApplication, + error.getClass().getName(), + error.getMessage(), + childApplication + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .then(Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "commit", error.getMessage()))); }); return Mono.zip(gitCommitMono, Mono.just(childApplication)); @@ -561,7 +608,8 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp if (Boolean.TRUE.equals(commitDTO.getDoPush())) { // Push flow result.append(".\nPush Result : "); - return executionTimeLogging.measureTask("pushApplication", pushApplication(childApplication.getId(), false)) + return executionTimeLogging + .measureTask("pushApplication", pushApplication(childApplication.getId(), false)) .map(pushResult -> result.append(pushResult).toString()) .zipWith(Mono.just(childApplication)); } @@ -570,24 +618,36 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp .flatMap(tuple -> { Application childApplication = tuple.getT2(); String status = tuple.getT1(); - return Mono.zip(Mono.just(status), executionTimeLogging.measureTask("publishAndOrGetApplication", publishAndOrGetApplication(childApplication.getId(), commitDTO.getDoPush()))); + return Mono.zip( + Mono.just(status), + executionTimeLogging.measureTask( + "publishAndOrGetApplication", + publishAndOrGetApplication(childApplication.getId(), commitDTO.getDoPush()))); }) // Add BE analytics .flatMap(tuple -> { String status = tuple.getT1(); Application childApplication = tuple.getT2(); - // Update json schema versions so that we can detect if the next update was made by DB migration or by the user + // Update json schema versions so that we can detect if the next update was made by DB migration or + // by the user Application update = new Application(); // Reset migration related fields before commit to detect the updates correctly between the commits update.setClientSchemaVersion(JsonSchemaVersions.clientVersion); update.setServerSchemaVersion(JsonSchemaVersions.serverVersion); update.setIsManualUpdate(false); - return executionTimeLogging.measureTask("applicationService.update", applicationService.update(childApplication.getId(), update)) + return executionTimeLogging + .measureTask( + "applicationService.update", + applicationService.update(childApplication.getId(), update)) // Release the file lock on git repo .flatMap(application -> { - if(Boolean.TRUE.equals(isFileLock)) { - return executionTimeLogging.measureTask("releaseFileLock", releaseFileLock(childApplication.getGitApplicationMetadata().getDefaultApplicationId())); + if (Boolean.TRUE.equals(isFileLock)) { + return executionTimeLogging.measureTask( + "releaseFileLock", + releaseFileLock(childApplication + .getGitApplicationMetadata() + .getDefaultApplicationId())); } return Mono.just(application); }) @@ -597,16 +657,17 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp "", "", childApplication.getGitApplicationMetadata().getIsRepoPrivate(), - isSystemGenerated - )) + isSystemGenerated)) .thenReturn(status); }); return Mono.create(sink -> { - commitMono.map(t -> { - log.debug("Time take, {}\n", executionTimeLogging.print()); - return t; - }).subscribe(sink::success, sink::error, null, sink.currentContext()); + commitMono + .map(t -> { + log.debug("Time take, {}\n", executionTimeLogging.print()); + return t; + }) + .subscribe(sink::success, sink::error, null, sink.currentContext()); }); } @@ -620,32 +681,36 @@ private Mono<String> commitApplication(GitCommitDTO commitDTO, String defaultApp public Mono<List<GitLogDTO>> getCommitHistory(String defaultApplicationId, String branchName) { Mono<List<GitLogDTO>> commitHistoryMono = applicationService - .findByBranchNameAndDefaultApplicationId(branchName, defaultApplicationId, applicationPermission.getReadPermission()) + .findByBranchNameAndDefaultApplicationId( + branchName, defaultApplicationId, applicationPermission.getReadPermission()) .flatMap(application -> { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); - if (gitData == null || StringUtils.isEmptyOrNull(application.getGitApplicationMetadata().getBranchName())) { - return Mono.error(new AppsmithException( - AppsmithError.INVALID_GIT_CONFIGURATION, - GIT_CONFIG_ERROR - )); + if (gitData == null + || StringUtils.isEmptyOrNull( + application.getGitApplicationMetadata().getBranchName())) { + return Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); } - Path baseRepoSuffix = Paths.get(application.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); + Path baseRepoSuffix = Paths.get( + application.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); // Checkout to branch return Mono.zip( - gitExecutor.checkoutToBranch(baseRepoSuffix, gitData.getBranchName()) - .onErrorResume(e -> Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "checkout", e.getMessage()))), - Mono.just(baseRepoSuffix) - ); + gitExecutor + .checkoutToBranch(baseRepoSuffix, gitData.getBranchName()) + .onErrorResume(e -> Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "checkout", e.getMessage()))), + Mono.just(baseRepoSuffix)); }) .flatMap(tuple -> { Path baseRepoSuffix = tuple.getT2(); - return gitExecutor.getCommitHistory(baseRepoSuffix) - .onErrorResume(e -> Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "log", e.getMessage()))); + return gitExecutor + .getCommitHistory(baseRepoSuffix) + .onErrorResume(e -> Mono.error( + new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "log", e.getMessage()))); }); - return Mono.create(sink -> commitHistoryMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> commitHistoryMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } /** @@ -659,7 +724,8 @@ public Mono<List<GitLogDTO>> getCommitHistory(String defaultApplicationId, Strin * @return Application object with the updated data */ @Override - public Mono<Application> connectApplicationToGit(String defaultApplicationId, GitConnectDTO gitConnectDTO, String originHeader) { + public Mono<Application> connectApplicationToGit( + String defaultApplicationId, GitConnectDTO gitConnectDTO, String originHeader) { /* * Connecting the application for the first time * The ssh keys is already present in application object from generate SSH key step @@ -674,17 +740,21 @@ public Mono<Application> connectApplicationToGit(String defaultApplicationId, Gi return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ORIGIN)); } - Mono<UserData> currentUserMono = userDataService.getForCurrentUser() + Mono<UserData> currentUserMono = userDataService + .getForCurrentUser() .filter(userData -> !CollectionUtils.isNullOrEmpty(userData.getGitProfiles())) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_PROFILE_ERROR))); + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_PROFILE_ERROR))); - Mono<Map<String, GitProfile>> profileMono = updateOrCreateGitProfileForCurrentUser(gitConnectDTO.getGitProfile(), defaultApplicationId) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_PROFILE_ERROR))); + Mono<Map<String, GitProfile>> profileMono = updateOrCreateGitProfileForCurrentUser( + gitConnectDTO.getGitProfile(), defaultApplicationId) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_PROFILE_ERROR))); final String browserSupportedUrl = GitUtils.convertSshUrlToBrowserSupportedUrl(gitConnectDTO.getRemoteUrl()); - Mono<Boolean> isPrivateRepoMono = GitUtils.isRepoPrivate(browserSupportedUrl).cache(); - + Mono<Boolean> isPrivateRepoMono = + GitUtils.isRepoPrivate(browserSupportedUrl).cache(); Mono<Application> connectApplicationMono = profileMono .then(getApplicationById(defaultApplicationId).zipWith(isPrivateRepoMono)) @@ -695,19 +765,20 @@ public Mono<Application> connectApplicationToGit(String defaultApplicationId, Gi if (!isRepoPrivate) { return Mono.just(application); } - //Check the limit for number of private repo + // Check the limit for number of private repo return isRepoLimitReached(application.getWorkspaceId(), true) .flatMap(isRepoLimitReached -> { if (Boolean.FALSE.equals(isRepoLimitReached)) { return Mono.just(application); } return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_PRIVATE_REPO_LIMIT_EXCEEDED.getEventName(), - application, - AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getErrorType(), - AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getMessage(), - true - ).flatMap(ignore -> Mono.error(new AppsmithException(AppsmithError.GIT_APPLICATION_LIMIT_ERROR))); + AnalyticsEvents.GIT_PRIVATE_REPO_LIMIT_EXCEEDED.getEventName(), + application, + AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getErrorType(), + AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getMessage(), + true) + .flatMap(ignore -> Mono.error( + new AppsmithException(AppsmithError.GIT_APPLICATION_LIMIT_ERROR))); }); }) .flatMap(application -> { @@ -717,47 +788,52 @@ public Mono<Application> connectApplicationToGit(String defaultApplicationId, Gi } else { String repoName = GitUtils.getRepoName(gitConnectDTO.getRemoteUrl()); Path repoSuffix = Paths.get(application.getWorkspaceId(), defaultApplicationId, repoName); - Mono<String> defaultBranchMono = gitExecutor.cloneApplication( + Mono<String> defaultBranchMono = gitExecutor + .cloneApplication( repoSuffix, gitConnectDTO.getRemoteUrl(), gitApplicationMetadata.getGitAuth().getPrivateKey(), - gitApplicationMetadata.getGitAuth().getPublicKey() - ) + gitApplicationMetadata.getGitAuth().getPublicKey()) .onErrorResume(error -> { log.error("Error while cloning the remote repo, ", error); - return fileUtils.deleteLocalRepo(repoSuffix) + return fileUtils + .deleteLocalRepo(repoSuffix) .then(addAnalyticsForGitOperation( AnalyticsEvents.GIT_CONNECT.getEventName(), application, error.getClass().getName(), error.getMessage(), - application.getGitApplicationMetadata().getIsRepoPrivate() - )) + application + .getGitApplicationMetadata() + .getIsRepoPrivate())) .flatMap(app -> { if (error instanceof TransportException) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); } if (error instanceof InvalidRemoteException) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, error.getMessage())); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, + error.getMessage())); } if (error instanceof TimeoutException) { - return Mono.error(new AppsmithException(AppsmithError.GIT_EXECUTION_TIMEOUT)); + return Mono.error( + new AppsmithException(AppsmithError.GIT_EXECUTION_TIMEOUT)); } if (error instanceof ClassCastException) { - // To catch TransportHttp cast error in case HTTP URL is passed instead of SSH URL + // To catch TransportHttp cast error in case HTTP URL is passed + // instead of SSH URL if (error.getMessage().contains("TransportHttp")) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_URL)); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_SSH_URL)); } } - return Mono.error(new AppsmithException(AppsmithError.GIT_GENERIC_ERROR, error.getMessage())); + return Mono.error(new AppsmithException( + AppsmithError.GIT_GENERIC_ERROR, error.getMessage())); }); }); return Mono.zip( - Mono.just(application), - defaultBranchMono, - Mono.just(repoName), - Mono.just(repoSuffix) - ); + Mono.just(application), defaultBranchMono, Mono.just(repoName), Mono.just(repoSuffix)); } }) .flatMap(tuple -> { @@ -768,21 +844,24 @@ public Mono<Application> connectApplicationToGit(String defaultApplicationId, Gi final String applicationId = application.getId(); final String workspaceId = application.getWorkspaceId(); try { - return fileUtils.checkIfDirectoryIsEmpty(repoPath).zipWith(isPrivateRepoMono) + return fileUtils + .checkIfDirectoryIsEmpty(repoPath) + .zipWith(isPrivateRepoMono) .flatMap(objects -> { boolean isEmpty = objects.getT1(); boolean isRepoPrivate = objects.getT2(); if (!isEmpty) { return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_CONNECT.getEventName(), - application, - AppsmithError.INVALID_GIT_REPO.getErrorType(), - AppsmithError.INVALID_GIT_REPO.getMessage(), - isRepoPrivate - ) - .then(Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_REPO))); + AnalyticsEvents.GIT_CONNECT.getEventName(), + application, + AppsmithError.INVALID_GIT_REPO.getErrorType(), + AppsmithError.INVALID_GIT_REPO.getMessage(), + isRepoPrivate) + .then(Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_REPO))); } else { - GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); + GitApplicationMetadata gitApplicationMetadata = + application.getGitApplicationMetadata(); gitApplicationMetadata.setDefaultApplicationId(applicationId); gitApplicationMetadata.setBranchName(defaultBranch); gitApplicationMetadata.setDefaultBranchName(defaultBranch); @@ -794,17 +873,26 @@ public Mono<Application> connectApplicationToGit(String defaultApplicationId, Gi gitApplicationMetadata.setLastCommittedAt(Instant.now()); // Set branchName for each application resource - return importExportApplicationService.exportApplicationById(applicationId, SerialiseApplicationObjective.VERSION_CONTROL) + return importExportApplicationService + .exportApplicationById( + applicationId, SerialiseApplicationObjective.VERSION_CONTROL) .flatMap(applicationJson -> { - applicationJson.getExportedApplication().setGitApplicationMetadata(gitApplicationMetadata); + applicationJson + .getExportedApplication() + .setGitApplicationMetadata(gitApplicationMetadata); return importExportApplicationService - .importApplicationInWorkspaceFromGit(workspaceId, applicationJson, applicationId, defaultBranch); + .importApplicationInWorkspaceFromGit( + workspaceId, + applicationJson, + applicationId, + defaultBranch); }); } }) .onErrorResume(e -> { if (e instanceof IOException) { - return Mono.error(new AppsmithException(AppsmithError.GIT_FILE_SYSTEM_ERROR, e.getMessage())); + return Mono.error(new AppsmithException( + AppsmithError.GIT_FILE_SYSTEM_ERROR, e.getMessage())); } return Mono.error(e); }); @@ -817,34 +905,38 @@ public Mono<Application> connectApplicationToGit(String defaultApplicationId, Gi String repoName = GitUtils.getRepoName(gitConnectDTO.getRemoteUrl()); String defaultPageId = ""; if (!application.getPages().isEmpty()) { - defaultPageId = application.getPages() - .stream() - .filter(applicationPage -> applicationPage.getIsDefault().equals(Boolean.TRUE)) + defaultPageId = application.getPages().stream() + .filter(applicationPage -> + applicationPage.getIsDefault().equals(Boolean.TRUE)) .collect(Collectors.toList()) .get(0) .getId(); } - String viewModeUrl = Paths.get("/", Entity.APPLICATIONS, "/", application.getId(), - Entity.PAGES, defaultPageId).toString(); + String viewModeUrl = Paths.get( + "/", Entity.APPLICATIONS, "/", application.getId(), Entity.PAGES, defaultPageId) + .toString(); String editModeUrl = Paths.get(viewModeUrl, "edit").toString(); - //Initialize the repo with readme file + // Initialize the repo with readme file try { return Mono.zip( - fileUtils.initializeReadme( - Paths.get(application.getWorkspaceId(), defaultApplicationId, repoName, "README.md"), - originHeader + viewModeUrl, - originHeader + editModeUrl - ).onErrorMap(throwable -> { - log.error("Error while initialising git repo, {0}", throwable); - return new AppsmithException( - AppsmithError.GIT_FILE_SYSTEM_ERROR, - Exceptions.unwrap(throwable).getMessage() - ); - }), - currentUserMono - ) + fileUtils + .initializeReadme( + Paths.get( + application.getWorkspaceId(), + defaultApplicationId, + repoName, + "README.md"), + originHeader + viewModeUrl, + originHeader + editModeUrl) + .onErrorMap(throwable -> { + log.error("Error while initialising git repo, {0}", throwable); + return new AppsmithException( + AppsmithError.GIT_FILE_SYSTEM_ERROR, + Exceptions.unwrap(throwable) + .getMessage()); + }), + currentUserMono) .flatMap(tuple -> { - UserData userData = tuple.getT2(); GitProfile profile = userData.getGitProfileByKey(defaultApplicationId); if (profile == null @@ -859,42 +951,52 @@ public Mono<Application> connectApplicationToGit(String defaultApplicationId, Gi profile.getAuthorName(), profile.getAuthorEmail(), false, - false - ); + false); }) .flatMap(ignore -> { // Commit and push application to check if the SSH key has the write access GitCommitDTO commitDTO = new GitCommitDTO(); commitDTO.setDoPush(true); - commitDTO.setCommitMessage(DEFAULT_COMMIT_MESSAGE + GitDefaultCommitMessage.CONNECT_FLOW.getReason()); - - - return this.commitApplication(commitDTO, defaultApplicationId, application.getGitApplicationMetadata().getBranchName(), true) + commitDTO.setCommitMessage( + DEFAULT_COMMIT_MESSAGE + GitDefaultCommitMessage.CONNECT_FLOW.getReason()); + + return this.commitApplication( + commitDTO, + defaultApplicationId, + application + .getGitApplicationMetadata() + .getBranchName(), + true) .onErrorResume(error -> // If the push fails remove all the cloned files from local repo this.detachRemote(defaultApplicationId) .flatMap(isDeleted -> { if (error instanceof TransportException) { return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_CONNECT.getEventName(), - application, - error.getClass().getName(), - error.getMessage(), - application.getGitApplicationMetadata().getIsRepoPrivate() - ) + AnalyticsEvents.GIT_CONNECT + .getEventName(), + application, + error.getClass() + .getName(), + error.getMessage(), + application + .getGitApplicationMetadata() + .getIsRepoPrivate()) .then(Mono.error(new AppsmithException( - AppsmithError.INVALID_GIT_SSH_CONFIGURATION, error.getMessage())) - ); + AppsmithError + .INVALID_GIT_SSH_CONFIGURATION, + error.getMessage()))); } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "push", error.getMessage())); - }) - ); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "push", + error.getMessage())); + })); }) .then(addAnalyticsForGitOperation( AnalyticsEvents.GIT_CONNECT.getEventName(), application, - application.getGitApplicationMetadata().getIsRepoPrivate() - )) + application.getGitApplicationMetadata().getIsRepoPrivate())) .map(responseUtils::updateApplicationWithDefaultResources); } catch (IOException e) { log.error("Error while cloning the remote repo, {}", e.getMessage()); @@ -902,9 +1004,8 @@ public Mono<Application> connectApplicationToGit(String defaultApplicationId, Gi } }); - return Mono.create(sink -> connectApplicationMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> connectApplicationMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override @@ -913,7 +1014,8 @@ public Mono<String> pushApplication(String defaultApplicationId, String branchNa if (StringUtils.isEmptyOrNull(branchName)) { throw new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.BRANCH_NAME); } - return applicationService.findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) + return applicationService + .findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) .flatMap(applicationId -> pushApplication(applicationId, true)); } @@ -927,12 +1029,18 @@ private Mono<String> pushApplication(String applicationId, boolean doPublish) { Mono<String> pushStatusMono = publishAndOrGetApplication(applicationId, doPublish) .flatMap(application -> { - if (applicationId.equals(application.getGitApplicationMetadata().getDefaultApplicationId())) { + if (applicationId.equals( + application.getGitApplicationMetadata().getDefaultApplicationId())) { return Mono.just(application); } - return applicationService.findById(application.getGitApplicationMetadata().getDefaultApplicationId()) + return applicationService + .findById(application.getGitApplicationMetadata().getDefaultApplicationId()) .map(defaultApp -> { - application.getGitApplicationMetadata().setGitAuth(defaultApp.getGitApplicationMetadata().getGitAuth()); + application + .getGitApplicationMetadata() + .setGitAuth(defaultApp + .getGitApplicationMetadata() + .getGitAuth()); return application; }); }) @@ -944,37 +1052,41 @@ private Mono<String> pushApplication(String applicationId, boolean doPublish) { || StringUtils.isEmptyOrNull(gitData.getDefaultApplicationId()) || StringUtils.isEmptyOrNull(gitData.getGitAuth().getPrivateKey())) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); } - Path baseRepoSuffix = - Paths.get(application.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); + Path baseRepoSuffix = Paths.get( + application.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); GitAuth gitAuth = gitData.getGitAuth(); - return gitExecutor.checkoutToBranch(baseRepoSuffix, application.getGitApplicationMetadata().getBranchName()) - .then(gitExecutor.pushApplication( - baseRepoSuffix, - gitData.getRemoteUrl(), - gitAuth.getPublicKey(), - gitAuth.getPrivateKey(), - gitData.getBranchName() - ) - .zipWith(Mono.just(application)) - ) - .onErrorResume(error -> - addAnalyticsForGitOperation( + return gitExecutor + .checkoutToBranch( + baseRepoSuffix, + application.getGitApplicationMetadata().getBranchName()) + .then(gitExecutor + .pushApplication( + baseRepoSuffix, + gitData.getRemoteUrl(), + gitAuth.getPublicKey(), + gitAuth.getPrivateKey(), + gitData.getBranchName()) + .zipWith(Mono.just(application))) + .onErrorResume(error -> addAnalyticsForGitOperation( AnalyticsEvents.GIT_PUSH.getEventName(), application, error.getClass().getName(), error.getMessage(), - application.getGitApplicationMetadata().getIsRepoPrivate() - ) - .flatMap(application1 -> { - if (error instanceof TransportException) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); - } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "push", error.getMessage())); - }) - ); + application + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .flatMap(application1 -> { + if (error instanceof TransportException) { + return Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); + } + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "push", error.getMessage())); + })); }) .flatMap(tuple -> { String pushResult = tuple.getT1(); @@ -982,22 +1094,36 @@ private Mono<String> pushApplication(String applicationId, boolean doPublish) { if (pushResult.contains("REJECTED_NONFASTFORWARD")) { return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_PUSH.getEventName(), - application, - AppsmithError.GIT_UPSTREAM_CHANGES.getErrorType(), - AppsmithError.GIT_UPSTREAM_CHANGES.getMessage(), - application.getGitApplicationMetadata().getIsRepoPrivate() - ).flatMap(application1 -> Mono.error(new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES))); - } else if (pushResult.contains("REJECTED_OTHERREASON") || pushResult.contains("pre-receive hook declined")) { - // Mostly happens when the remote branch is protected or any specific rules in place on the branch - // Since the users will be in a bad state where the changes are committed locally but they are not able to + AnalyticsEvents.GIT_PUSH.getEventName(), + application, + AppsmithError.GIT_UPSTREAM_CHANGES.getErrorType(), + AppsmithError.GIT_UPSTREAM_CHANGES.getMessage(), + application.getGitApplicationMetadata().getIsRepoPrivate()) + .flatMap(application1 -> + Mono.error(new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES))); + } else if (pushResult.contains("REJECTED_OTHERREASON") + || pushResult.contains("pre-receive hook declined")) { + // Mostly happens when the remote branch is protected or any specific rules in place on the + // branch + // Since the users will be in a bad state where the changes are committed locally but they are + // not able to // push them changes or revert the changes either. // TODO Support protected branch flow within Appsmith - Path path = Paths.get(application.getWorkspaceId(), application.getGitApplicationMetadata().getDefaultApplicationId(), application.getGitApplicationMetadata().getRepoName()); - return gitExecutor.resetHard(path, application.getGitApplicationMetadata().getBranchName()) - .then(Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "push", + Path path = Paths.get( + application.getWorkspaceId(), + application.getGitApplicationMetadata().getDefaultApplicationId(), + application.getGitApplicationMetadata().getRepoName()); + return gitExecutor + .resetHard( + path, + application.getGitApplicationMetadata().getBranchName()) + .then(Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "push", "Unable to push changes as pre-receive hook declined. Please make sure that you don't have any rules enabled on the branch " - + application.getGitApplicationMetadata().getBranchName()))); + + application + .getGitApplicationMetadata() + .getBranchName()))); } return Mono.just(pushResult).zipWith(Mono.just(tuple.getT2())); }) @@ -1006,16 +1132,13 @@ private Mono<String> pushApplication(String applicationId, boolean doPublish) { String pushStatus = tuple.getT1(); Application application = tuple.getT2(); return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_PUSH.getEventName(), - application, - application.getGitApplicationMetadata().getIsRepoPrivate() - ) + AnalyticsEvents.GIT_PUSH.getEventName(), + application, + application.getGitApplicationMetadata().getIsRepoPrivate()) .thenReturn(pushStatus); }); - return Mono.create(sink -> pushStatusMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create(sink -> pushStatusMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } /** @@ -1031,26 +1154,26 @@ public Mono<Application> detachRemote(String defaultApplicationId) { Mono<Application> disconnectMono = getApplicationById(defaultApplicationId) .flatMap(defaultApplication -> { - if (Optional.ofNullable(defaultApplication.getGitApplicationMetadata()).isEmpty() + if (Optional.ofNullable(defaultApplication.getGitApplicationMetadata()) + .isEmpty() || isInvalidDefaultApplicationGitMetadata(defaultApplication.getGitApplicationMetadata())) { - return Mono.error( - new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, "Please reconfigure the application to connect to git repo") - ); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, + "Please reconfigure the application to connect to git repo")); } - //Remove the git contents from file system + // Remove the git contents from file system GitApplicationMetadata gitApplicationMetadata = defaultApplication.getGitApplicationMetadata(); String repoName = gitApplicationMetadata.getRepoName(); - Path repoSuffix = Paths.get(defaultApplication.getWorkspaceId(), gitApplicationMetadata.getDefaultApplicationId(), repoName); + Path repoSuffix = Paths.get( + defaultApplication.getWorkspaceId(), + gitApplicationMetadata.getDefaultApplicationId(), + repoName); String defaultApplicationBranchName = gitApplicationMetadata.getBranchName(); String remoteUrl = gitApplicationMetadata.getRemoteUrl(); String privateKey = gitApplicationMetadata.getGitAuth().getPrivateKey(); String publicKey = gitApplicationMetadata.getGitAuth().getPublicKey(); return Mono.zip( - gitExecutor.listBranches(repoSuffix, - remoteUrl, - privateKey, - publicKey, - false), + gitExecutor.listBranches(repoSuffix, remoteUrl, privateKey, publicKey, false), Mono.just(defaultApplication), Mono.just(repoSuffix), Mono.just(defaultApplicationBranchName)); @@ -1058,27 +1181,24 @@ public Mono<Application> detachRemote(String defaultApplicationId) { .flatMap(tuple -> { Application defaultApplication = tuple.getT2(); Path repoSuffix = tuple.getT3(); - List<String> branch = tuple.getT1() - .stream() + List<String> branch = tuple.getT1().stream() .map(GitBranchDTO::getBranchName) .filter(branchName -> !branchName.startsWith("origin")) .collect(Collectors.toList()); - //Remove the parent application branch name from the list + // Remove the parent application branch name from the list branch.remove(tuple.getT4()); defaultApplication.setGitApplicationMetadata(null); defaultApplication.getPages().forEach(page -> page.setDefaultPageId(page.getId())); if (!CollectionUtils.isNullOrEmpty(defaultApplication.getPublishedPages())) { defaultApplication.getPublishedPages().forEach(page -> page.setDefaultPageId(page.getId())); } - return fileUtils.deleteLocalRepo(repoSuffix) - .flatMap(status -> Flux.fromIterable(branch) - .flatMap(gitBranch -> - applicationService - .findByBranchNameAndDefaultApplicationId(gitBranch, defaultApplicationId, applicationPermission.getEditPermission()) - .flatMap(applicationPageService::deleteApplicationByResource) - ) - .then(applicationService.save(defaultApplication))); + return fileUtils.deleteLocalRepo(repoSuffix).flatMap(status -> Flux.fromIterable(branch) + .flatMap(gitBranch -> applicationService + .findByBranchNameAndDefaultApplicationId( + gitBranch, defaultApplicationId, applicationPermission.getEditPermission()) + .flatMap(applicationPageService::deleteApplicationByResource)) + .then(applicationService.save(defaultApplication))); }) .flatMap(application -> // Update all the resources to replace defaultResource Ids with the resource Ids as branchName @@ -1091,7 +1211,8 @@ public Mono<Application> detachRemote(String defaultApplicationId) { }) .collectList() .flatMapMany(newPageService::saveAll) - .flatMap(newPage -> newActionService.findByPageId(newPage.getId(), Optional.empty()) + .flatMap(newPage -> newActionService + .findByPageId(newPage.getId(), Optional.empty()) .map(newAction -> { newAction.setDefaultResources(null); if (newAction.getUnpublishedAction() != null) { @@ -1108,23 +1229,24 @@ public Mono<Application> detachRemote(String defaultApplicationId) { .map(actionCollection -> { actionCollection.setDefaultResources(null); if (actionCollection.getUnpublishedCollection() != null) { - actionCollection.getUnpublishedCollection().setDefaultResources(null); + actionCollection + .getUnpublishedCollection() + .setDefaultResources(null); } if (actionCollection.getPublishedCollection() != null) { - actionCollection.getPublishedCollection().setDefaultResources(null); + actionCollection + .getPublishedCollection() + .setDefaultResources(null); } return createDefaultIdsOrUpdateWithGivenResourceIds(actionCollection, null); }) .collectList() - .flatMapMany(actionCollectionService::saveAll) - ) - .then(addAnalyticsForGitOperation(AnalyticsEvents.GIT_DISCONNECT.getEventName(), application, false)) - .map(responseUtils::updateApplicationWithDefaultResources) - ); - - return Mono.create(sink -> disconnectMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + .flatMapMany(actionCollectionService::saveAll)) + .then(addAnalyticsForGitOperation( + AnalyticsEvents.GIT_DISCONNECT.getEventName(), application, false)) + .map(responseUtils::updateApplicationWithDefaultResources)); + + return Mono.create(sink -> disconnectMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } public Mono<Application> createBranch(String defaultApplicationId, GitBranchDTO branchDTO, String srcBranch) { @@ -1142,13 +1264,16 @@ public Mono<Application> createBranch(String defaultApplicationId, GitBranchDTO } Mono<Application> createBranchMono = applicationService - .findByBranchNameAndDefaultApplicationId(srcBranch, defaultApplicationId, applicationPermission.getEditPermission()) + .findByBranchNameAndDefaultApplicationId( + srcBranch, defaultApplicationId, applicationPermission.getEditPermission()) .zipWhen(srcApplication -> { GitApplicationMetadata gitData = srcApplication.getGitApplicationMetadata(); if (gitData.getDefaultApplicationId().equals(srcApplication.getId())) { - return Mono.just(srcApplication.getGitApplicationMetadata().getGitAuth()); + return Mono.just( + srcApplication.getGitApplicationMetadata().getGitAuth()); } - return applicationService.getSshKey(gitData.getDefaultApplicationId()) + return applicationService + .getSshKey(gitData.getDefaultApplicationId()) .map(gitAuthDTO -> { GitAuth gitAuth = new GitAuth(); gitAuth.setPrivateKey(gitAuthDTO.getPrivateKey()); @@ -1164,25 +1289,45 @@ public Mono<Application> createBranch(String defaultApplicationId, GitBranchDTO if (srcBranchGitData == null || StringUtils.isEmptyOrNull(srcBranchGitData.getDefaultApplicationId()) || StringUtils.isEmptyOrNull(srcBranchGitData.getRepoName())) { - return Mono.error(new AppsmithException( - AppsmithError.INVALID_GIT_CONFIGURATION, - "Unable to find the parent branch. Please create a branch from other available branches" - )); + return Mono.error( + new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, + "Unable to find the parent branch. Please create a branch from other available branches")); } - Path repoSuffix = Paths.get(srcApplication.getWorkspaceId(), srcBranchGitData.getDefaultApplicationId(), srcBranchGitData.getRepoName()); + Path repoSuffix = Paths.get( + srcApplication.getWorkspaceId(), + srcBranchGitData.getDefaultApplicationId(), + srcBranchGitData.getRepoName()); // Create a new branch from the parent checked out branch return addFileLock(srcBranchGitData.getDefaultApplicationId()) .flatMap(status -> gitExecutor.checkoutToBranch(repoSuffix, srcBranch)) - .onErrorResume(error -> Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "checkout", "Unable to find " + srcBranch))) - .zipWhen(isCheckedOut -> gitExecutor.fetchRemote(repoSuffix, defaultGitAuth.getPublicKey(), defaultGitAuth.getPrivateKey(), false, srcBranch, true) - .onErrorResume(error -> Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "fetch", error)))) - .flatMap(ignore -> gitExecutor.listBranches(repoSuffix, srcBranchGitData.getRemoteUrl(), defaultGitAuth.getPrivateKey(), defaultGitAuth.getPublicKey(), false) + .onErrorResume(error -> Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "checkout", "Unable to find " + srcBranch))) + .zipWhen(isCheckedOut -> gitExecutor + .fetchRemote( + repoSuffix, + defaultGitAuth.getPublicKey(), + defaultGitAuth.getPrivateKey(), + false, + srcBranch, + true) + .onErrorResume(error -> Mono.error( + new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "fetch", error)))) + .flatMap(ignore -> gitExecutor + .listBranches( + repoSuffix, + srcBranchGitData.getRemoteUrl(), + defaultGitAuth.getPrivateKey(), + defaultGitAuth.getPublicKey(), + false) .flatMap(branchList -> { boolean isDuplicateName = branchList.stream() // We are only supporting origin as the remote name so this is safe - // but needs to be altered if we start supporting user defined remote names - .anyMatch(branch -> branch.getBranchName().replaceFirst("origin/", "") + // but needs to be altered if we start supporting user defined remote + // names + .anyMatch(branch -> branch.getBranchName() + .replaceFirst("origin/", "") .equals(branchDTO.getBranchName())); if (isDuplicateName) { @@ -1191,7 +1336,8 @@ public Mono<Application> createBranch(String defaultApplicationId, GitBranchDTO "remotes/origin/" + branchDTO.getBranchName(), FieldName.BRANCH_NAME)); } - return gitExecutor.createAndCheckoutToBranch(repoSuffix, branchDTO.getBranchName()); + return gitExecutor.createAndCheckoutToBranch( + repoSuffix, branchDTO.getBranchName()); })) .flatMap(branchName -> { final String srcApplicationId = srcApplication.getId(); @@ -1208,41 +1354,44 @@ public Mono<Application> createBranch(String defaultApplicationId, GitBranchDTO srcApplication.setGitApplicationMetadata(srcBranchGitData); return Mono.zip( applicationService.save(srcApplication), - importExportApplicationService.exportApplicationById(srcApplicationId, SerialiseApplicationObjective.VERSION_CONTROL) - ); + importExportApplicationService.exportApplicationById( + srcApplicationId, SerialiseApplicationObjective.VERSION_CONTROL)); }) - .onErrorResume(error -> Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "branch", error.getMessage()))); + .onErrorResume(error -> Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "branch", error.getMessage()))); }) .flatMap(tuple -> { Application savedApplication = tuple.getT1(); - return importExportApplicationService.importApplicationInWorkspaceFromGit( + return importExportApplicationService + .importApplicationInWorkspaceFromGit( savedApplication.getWorkspaceId(), tuple.getT2(), savedApplication.getId(), - branchDTO.getBranchName() - ) + branchDTO.getBranchName()) .flatMap(application -> { - // Commit and push for new branch created this is to avoid issues when user tries to create a + // Commit and push for new branch created this is to avoid issues when user tries to + // create a // new branch from uncommitted branch GitApplicationMetadata gitData = application.getGitApplicationMetadata(); GitCommitDTO commitDTO = new GitCommitDTO(); - commitDTO.setCommitMessage(DEFAULT_COMMIT_MESSAGE + GitDefaultCommitMessage.BRANCH_CREATED.getReason() + gitData.getBranchName()); + commitDTO.setCommitMessage(DEFAULT_COMMIT_MESSAGE + + GitDefaultCommitMessage.BRANCH_CREATED.getReason() + + gitData.getBranchName()); commitDTO.setDoPush(true); - return commitApplication(commitDTO, gitData.getDefaultApplicationId(), gitData.getBranchName()) + return commitApplication( + commitDTO, gitData.getDefaultApplicationId(), gitData.getBranchName()) .thenReturn(application); }); }) - .flatMap(application -> releaseFileLock(application.getGitApplicationMetadata().getDefaultApplicationId()) + .flatMap(application -> releaseFileLock( + application.getGitApplicationMetadata().getDefaultApplicationId()) .then(addAnalyticsForGitOperation( AnalyticsEvents.GIT_CREATE_BRANCH.getEventName(), application, - application.getGitApplicationMetadata().getIsRepoPrivate()) - ) - ).map(responseUtils::updateApplicationWithDefaultResources); + application.getGitApplicationMetadata().getIsRepoPrivate()))) + .map(responseUtils::updateApplicationWithDefaultResources); - return Mono.create(sink -> createBranchMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create(sink -> createBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } public Mono<Application> checkoutBranch(String defaultApplicationId, String branchName) { @@ -1251,20 +1400,23 @@ public Mono<Application> checkoutBranch(String defaultApplicationId, String bran return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.BRANCH_NAME)); } - //If the user is trying to check out remote branch, create a new branch if the branch does not exist already + // If the user is trying to check out remote branch, create a new branch if the branch does not exist already if (branchName.startsWith("origin/")) { String finalBranchName = branchName.replaceFirst("origin/", ""); return listBranchForApplication(defaultApplicationId, false, branchName) .flatMap(gitBranchDTOList -> { - long branchMatchCount = gitBranchDTOList - .stream() - .filter(gitBranchDTO -> gitBranchDTO.getBranchName() - .equals(finalBranchName)).count(); + long branchMatchCount = gitBranchDTOList.stream() + .filter(gitBranchDTO -> + gitBranchDTO.getBranchName().equals(finalBranchName)) + .count(); if (branchMatchCount == 0) { return checkoutRemoteBranch(defaultApplicationId, finalBranchName); } else { - return Mono.error( - new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "checkout", branchName + " already exists in local - " + branchName.replaceFirst("origin/", ""))); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "checkout", + branchName + " already exists in local - " + + branchName.replaceFirst("origin/", ""))); } }); } @@ -1275,14 +1427,12 @@ public Mono<Application> checkoutBranch(String defaultApplicationId, String bran return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); } return applicationService.findByBranchNameAndDefaultApplicationId( - branchName, defaultApplicationId, applicationPermission.getReadPermission() - ); + branchName, defaultApplicationId, applicationPermission.getReadPermission()); }) .flatMap(application -> addAnalyticsForGitOperation( AnalyticsEvents.GIT_CHECKOUT_BRANCH.getEventName(), application, - application.getGitApplicationMetadata().getIsRepoPrivate() - )) + application.getGitApplicationMetadata().getIsRepoPrivate())) .map(responseUtils::updateApplicationWithDefaultResources); } @@ -1293,14 +1443,19 @@ private Mono<Application> checkoutRemoteBranch(String defaultApplicationId, Stri String repoName = gitApplicationMetadata.getRepoName(); Path repoPath = Paths.get(application.getWorkspaceId(), defaultApplicationId, repoName); - return gitExecutor.fetchRemote(repoPath, - gitApplicationMetadata.getGitAuth().getPublicKey(), - gitApplicationMetadata.getGitAuth().getPrivateKey(), - false, - branchName, - true - ).flatMap(fetchStatus -> gitExecutor.checkoutRemoteBranch(repoPath, branchName).zipWith(Mono.just(application)) - .onErrorResume(error -> Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "checkout branch", error.getMessage())))); + return gitExecutor + .fetchRemote( + repoPath, + gitApplicationMetadata.getGitAuth().getPublicKey(), + gitApplicationMetadata.getGitAuth().getPrivateKey(), + false, + branchName, + true) + .flatMap(fetchStatus -> gitExecutor + .checkoutRemoteBranch(repoPath, branchName) + .zipWith(Mono.just(application)) + .onErrorResume(error -> Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "checkout branch", error.getMessage())))); }) .flatMap(tuple -> { /* @@ -1311,7 +1466,7 @@ private Mono<Application> checkoutRemoteBranch(String defaultApplicationId, Stri * */ Application srcApplication = tuple.getT2(); - //Create a new Application + // Create a new Application GitApplicationMetadata srcBranchGitData = srcApplication.getGitApplicationMetadata(); srcBranchGitData.setBranchName(branchName); srcBranchGitData.setDefaultApplicationId(defaultApplicationId); @@ -1324,23 +1479,39 @@ private Mono<Application> checkoutRemoteBranch(String defaultApplicationId, Stri srcApplication.setPublishedPages(null); srcApplication.setGitApplicationMetadata(srcBranchGitData); - return applicationService.save(srcApplication) - .flatMap(application1 -> - fileUtils.reconstructApplicationJsonFromGitRepo(srcApplication.getWorkspaceId(), defaultApplicationId, srcApplication.getGitApplicationMetadata().getRepoName(), branchName) - .zipWith(Mono.just(application1)) - ) + return applicationService + .save(srcApplication) + .flatMap(application1 -> fileUtils + .reconstructApplicationJsonFromGitRepo( + srcApplication.getWorkspaceId(), + defaultApplicationId, + srcApplication + .getGitApplicationMetadata() + .getRepoName(), + branchName) + .zipWith(Mono.just(application1))) // We need to handle the case specifically for default branch of Appsmith - // if user switches default branch and tries to delete the default branch we do not delete resource from db - // This is an exception only for the above case and in such case if the user tries to check out the branch again + // if user switches default branch and tries to delete the default branch we do not delete + // resource from db + // This is an exception only for the above case and in such case if the user tries to check + // out the branch again // It results in an error as the resources are already present in db // So we just rehydrate from the file system to the existing resource on the db .onErrorResume(throwable -> { if (throwable instanceof DuplicateKeyException) { - return fileUtils.reconstructApplicationJsonFromGitRepo(srcApplication.getWorkspaceId(), defaultApplicationId, srcApplication.getGitApplicationMetadata().getRepoName(), branchName) + return fileUtils + .reconstructApplicationJsonFromGitRepo( + srcApplication.getWorkspaceId(), + defaultApplicationId, + srcApplication + .getGitApplicationMetadata() + .getRepoName(), + branchName) .zipWith(Mono.just(tuple.getT2())); } log.error(" Git checkout remote branch failed {}", throwable.getMessage()); - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, " --checkout", throwable.getMessage())); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, " --checkout", throwable.getMessage())); }); }) .flatMap(tuple -> { @@ -1348,23 +1519,25 @@ private Mono<Application> checkoutRemoteBranch(String defaultApplicationId, Stri ApplicationJson applicationJson = tuple.getT1(); Application application = tuple.getT2(); return importExportApplicationService - .importApplicationInWorkspaceFromGit(application.getWorkspaceId(), applicationJson, application.getId(), branchName) + .importApplicationInWorkspaceFromGit( + application.getWorkspaceId(), applicationJson, application.getId(), branchName) .flatMap(application1 -> addAnalyticsForGitOperation( AnalyticsEvents.GIT_CHECKOUT_REMOTE_BRANCH.getEventName(), application1, - Boolean.TRUE.equals(application1.getGitApplicationMetadata().getIsRepoPrivate()) - )) + Boolean.TRUE.equals(application1 + .getGitApplicationMetadata() + .getIsRepoPrivate()))) .map(responseUtils::updateApplicationWithDefaultResources); }); - return Mono.create(sink -> checkoutRemoteBranchMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> checkoutRemoteBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } private Mono<Application> publishAndOrGetApplication(String applicationId, boolean publish) { if (Boolean.TRUE.equals(publish)) { - return applicationPageService.publish(applicationId, true) + return applicationPageService + .publish(applicationId, true) // Get application here to decrypt the git private key if present .then(getApplicationById(applicationId)); } @@ -1372,8 +1545,10 @@ private Mono<Application> publishAndOrGetApplication(String applicationId, boole } Mono<Application> getApplicationById(String applicationId) { - return applicationService.findById(applicationId, applicationPermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION_ID, applicationId))); + return applicationService + .findById(applicationId, applicationPermission.getEditPermission()) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION_ID, applicationId))); } /** @@ -1398,47 +1573,54 @@ public Mono<GitPullDTO> pullApplication(String defaultApplicationId, String bran Mono<GitPullDTO> pullMono = getApplicationById(defaultApplicationId) .flatMap(application -> { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); - return addFileLock(gitData.getDefaultApplicationId()) - .then(Mono.just(application)); + return addFileLock(gitData.getDefaultApplicationId()).then(Mono.just(application)); }) .flatMap(defaultApplication -> { GitApplicationMetadata defaultGitMetadata = defaultApplication.getGitApplicationMetadata(); - return Mono.zip(Mono.just(defaultApplication), getStatus(defaultGitMetadata.getDefaultApplicationId(), branchName, false)); + return Mono.zip( + Mono.just(defaultApplication), + getStatus(defaultGitMetadata.getDefaultApplicationId(), branchName, false)); }) .flatMap(tuple -> { Application defaultApplication = tuple.getT1(); GitStatusDTO status = tuple.getT2(); // Check if the repo is clean if (!CollectionUtils.isNullOrEmpty(status.getModified())) { - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "pull", "There are uncommitted changes present in your local. Please commit them first and then try git pull")); + return Mono.error( + new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "pull", + "There are uncommitted changes present in your local. Please commit them first and then try git pull")); } return pullAndRehydrateApplication(defaultApplication, branchName) // Release file lock after the pull operation - .flatMap(gitPullDTO -> releaseFileLock(defaultApplicationId) - .then(Mono.just(gitPullDTO))); + .flatMap(gitPullDTO -> + releaseFileLock(defaultApplicationId).then(Mono.just(gitPullDTO))); }); - return Mono.create(sink -> pullMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create(sink -> pullMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override - public Mono<List<GitBranchDTO>> listBranchForApplication(String defaultApplicationId, Boolean pruneBranches, String currentBranch) { + public Mono<List<GitBranchDTO>> listBranchForApplication( + String defaultApplicationId, Boolean pruneBranches, String currentBranch) { Mono<List<GitBranchDTO>> branchMono = getApplicationById(defaultApplicationId) .flatMap(application -> { GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); if (gitApplicationMetadata == null || gitApplicationMetadata.getDefaultApplicationId() == null) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); } - Path repoPath = Paths.get(application.getWorkspaceId(), + Path repoPath = Paths.get( + application.getWorkspaceId(), gitApplicationMetadata.getDefaultApplicationId(), gitApplicationMetadata.getRepoName()); Mono<List<GitBranchDTO>> gitBranchDTOMono; // Fetch remote first if the prune branch is valid if (Boolean.TRUE.equals(pruneBranches)) { - gitBranchDTOMono = gitExecutor.fetchRemote( + gitBranchDTOMono = gitExecutor + .fetchRemote( repoPath, gitApplicationMetadata.getGitAuth().getPublicKey(), gitApplicationMetadata.getGitAuth().getPrivateKey(), @@ -1460,31 +1642,26 @@ public Mono<List<GitBranchDTO>> listBranchForApplication(String defaultApplicati gitApplicationMetadata.getGitAuth().getPublicKey(), false); } - return Mono.zip(gitBranchDTOMono, Mono.just(application)) - .onErrorResume(error -> { - if (error instanceof RepositoryNotFoundException) { - Mono<List<GitBranchDTO>> branchListMono = handleRepoNotFoundException(defaultApplicationId); - return Mono.zip(branchListMono, Mono.just(application), Mono.just(repoPath)); - } - return Mono.error(new AppsmithException( - AppsmithError.GIT_ACTION_FAILED, - "branch --list", - error.getMessage())); - } - ); - + return Mono.zip(gitBranchDTOMono, Mono.just(application)).onErrorResume(error -> { + if (error instanceof RepositoryNotFoundException) { + Mono<List<GitBranchDTO>> branchListMono = handleRepoNotFoundException(defaultApplicationId); + return Mono.zip(branchListMono, Mono.just(application), Mono.just(repoPath)); + } + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "branch --list", error.getMessage())); + }); }) .flatMap(tuple -> { List<GitBranchDTO> gitBranchListDTOS = tuple.getT1(); Application application = tuple.getT2(); GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); - final String dbDefaultBranch = StringUtils.isEmptyOrNull(gitApplicationMetadata.getDefaultBranchName()) - ? gitApplicationMetadata.getBranchName() - : gitApplicationMetadata.getDefaultBranchName(); + final String dbDefaultBranch = + StringUtils.isEmptyOrNull(gitApplicationMetadata.getDefaultBranchName()) + ? gitApplicationMetadata.getBranchName() + : gitApplicationMetadata.getDefaultBranchName(); if (Boolean.TRUE.equals(pruneBranches)) { - String defaultBranchRemote = gitBranchListDTOS - .stream() + String defaultBranchRemote = gitBranchListDTOS.stream() .filter(GitBranchDTO::isDefault) .map(GitBranchDTO::getBranchName) .findFirst() @@ -1494,22 +1671,31 @@ public Mono<List<GitBranchDTO>> listBranchForApplication(String defaultApplicati return Mono.just(gitBranchListDTOS).zipWith(Mono.just(application)); } else { // Get the application from DB by new defaultBranch name - return applicationService.findByBranchNameAndDefaultApplicationId(defaultBranchRemote, defaultApplicationId, applicationPermission.getEditPermission()) + return applicationService + .findByBranchNameAndDefaultApplicationId( + defaultBranchRemote, + defaultApplicationId, + applicationPermission.getEditPermission()) // Check if the branch is already present, If not follow checkout remote flow - .onErrorResume(throwable -> checkoutRemoteBranch(defaultApplicationId, defaultBranchRemote)) + .onErrorResume(throwable -> + checkoutRemoteBranch(defaultApplicationId, defaultBranchRemote)) // Update the default branch name in all the child applications - .flatMapMany(application1 -> applicationService.findAllApplicationsByDefaultApplicationId(defaultApplicationId, applicationPermission.getEditPermission()) + .flatMapMany(application1 -> applicationService + .findAllApplicationsByDefaultApplicationId( + defaultApplicationId, applicationPermission.getEditPermission()) .flatMap(application2 -> { - application2.getGitApplicationMetadata().setDefaultBranchName(defaultBranchRemote); + application2 + .getGitApplicationMetadata() + .setDefaultBranchName(defaultBranchRemote); return applicationService.save(application2); })) // Return the deleted branches .then(Mono.just(gitBranchListDTOS).zipWith(Mono.just(application))); } } else { - gitBranchListDTOS - .stream() - .filter(branchDTO -> StringUtils.equalsIgnoreCase(branchDTO.getBranchName(), dbDefaultBranch)) + gitBranchListDTOS.stream() + .filter(branchDTO -> + StringUtils.equalsIgnoreCase(branchDTO.getBranchName(), dbDefaultBranch)) .findFirst() .ifPresent(branchDTO -> branchDTO.setDefault(true)); return Mono.just(gitBranchListDTOS).zipWith(Mono.just(application)); @@ -1522,16 +1708,15 @@ public Mono<List<GitBranchDTO>> listBranchForApplication(String defaultApplicati return Boolean.FALSE.equals(pruneBranches) ? Mono.just(gitBranchDTOList) : addAnalyticsForGitOperation( - AnalyticsEvents.GIT_PRUNE.getEventName(), - application, - application.getGitApplicationMetadata().getIsRepoPrivate() - ) - .thenReturn(gitBranchDTOList); + AnalyticsEvents.GIT_PRUNE.getEventName(), + application, + application + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .thenReturn(gitBranchDTOList); }); - return Mono.create(sink -> branchMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create(sink -> branchMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } /** @@ -1551,31 +1736,44 @@ private Mono<GitStatusDTO> getStatus(String defaultApplicationId, String branchN final String finalBranchName = branchName.replaceFirst("origin/", ""); /* - 1. Copy resources from DB to local repo - 2. Fetch the current status from local repo - */ + 1. Copy resources from DB to local repo + 2. Fetch the current status from local repo + */ - Mono<GitStatusDTO> statusMono = executionTimeLogging.measureTask("getGitApplicationMetadata", getGitApplicationMetadata(defaultApplicationId)) + Mono<GitStatusDTO> statusMono = executionTimeLogging + .measureTask("getGitApplicationMetadata", getGitApplicationMetadata(defaultApplicationId)) .flatMap(gitApplicationMetadata -> { - - Mono<Tuple2<Application, ApplicationJson>> applicationJsonTuple = executionTimeLogging.measureTask("findByBranchNameAndDefaultApplicationId", applicationService.findByBranchNameAndDefaultApplicationId(finalBranchName, defaultApplicationId, applicationPermission.getEditPermission())) + Mono<Tuple2<Application, ApplicationJson>> applicationJsonTuple = executionTimeLogging + .measureTask( + "findByBranchNameAndDefaultApplicationId", + applicationService.findByBranchNameAndDefaultApplicationId( + finalBranchName, + defaultApplicationId, + applicationPermission.getEditPermission())) .onErrorResume(error -> { - //if the branch does not exist in local, checkout remote branch - return executionTimeLogging.measureTask("checkoutBranch", checkoutBranch(defaultApplicationId, finalBranchName)); + // if the branch does not exist in local, checkout remote branch + return executionTimeLogging.measureTask( + "checkoutBranch", checkoutBranch(defaultApplicationId, finalBranchName)); }) - .zipWhen(application -> executionTimeLogging.measureTask( "getStatus->exportApplicationById", importExportApplicationService.exportApplicationById(application.getId(), SerialiseApplicationObjective.VERSION_CONTROL))); + .zipWhen(application -> executionTimeLogging.measureTask( + "getStatus->exportApplicationById", + importExportApplicationService.exportApplicationById( + application.getId(), SerialiseApplicationObjective.VERSION_CONTROL))); if (Boolean.TRUE.equals(isFileLock)) { // Add file lock for the status API call to avoid sending wrong info on the status - return executionTimeLogging.measureTask("addFileLock", redisUtils.addFileLock(gitApplicationMetadata.getDefaultApplicationId())) - .retryWhen(Retry.fixedDelay(MAX_RETRIES, RETRY_DELAY).jitter(0.75) + return executionTimeLogging + .measureTask( + "addFileLock", + redisUtils.addFileLock(gitApplicationMetadata.getDefaultApplicationId())) + .retryWhen(Retry.fixedDelay(MAX_RETRIES, RETRY_DELAY) + .jitter(0.75) .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> { throw new AppsmithException(AppsmithError.GIT_FILE_IN_USE); })) .then(Mono.zip(Mono.just(gitApplicationMetadata), applicationJsonTuple)); } return Mono.zip(Mono.just(gitApplicationMetadata), applicationJsonTuple); - }) .flatMap(tuple -> { GitApplicationMetadata defaultApplicationMetadata = tuple.getT1(); @@ -1583,44 +1781,68 @@ private Mono<GitStatusDTO> getStatus(String defaultApplicationId, String branchN ApplicationJson applicationJson = tuple.getT2().getT2(); GitApplicationMetadata gitData = application.getGitApplicationMetadata(); gitData.setGitAuth(defaultApplicationMetadata.getGitAuth()); - Path repoSuffix = - Paths.get(application.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); + Path repoSuffix = Paths.get( + application.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); try { return Mono.zip( - executionTimeLogging.measureTask("getStatus->saveApplicationToLocalRepo", fileUtils.saveApplicationToLocalRepo(repoSuffix, applicationJson, finalBranchName)), + executionTimeLogging.measureTask( + "getStatus->saveApplicationToLocalRepo", + fileUtils.saveApplicationToLocalRepo( + repoSuffix, applicationJson, finalBranchName)), Mono.just(gitData.getGitAuth()), - Mono.just(repoSuffix) - ); + Mono.just(repoSuffix)); } catch (IOException | GitAPIException e) { - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "status", e.getMessage())); + return Mono.error( + new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "status", e.getMessage())); } }) .flatMap(tuple -> { - Mono<GitStatusDTO> branchedStatusMono = executionTimeLogging.measureTask("getStatus->gitExecutor.getStatus", gitExecutor.getStatus(tuple.getT1(), finalBranchName).cache()); + Mono<GitStatusDTO> branchedStatusMono = executionTimeLogging.measureTask( + "getStatus->gitExecutor.getStatus", + gitExecutor + .getStatus(tuple.getT1(), finalBranchName) + .cache()); try { - return executionTimeLogging.measureTask("getStatus->gitExecutor.fetchRemote", gitExecutor.fetchRemote(tuple.getT1(), tuple.getT2().getPublicKey(), tuple.getT2().getPrivateKey(), true, branchName, false)) + return executionTimeLogging + .measureTask( + "getStatus->gitExecutor.fetchRemote", + gitExecutor.fetchRemote( + tuple.getT1(), + tuple.getT2().getPublicKey(), + tuple.getT2().getPrivateKey(), + true, + branchName, + false)) .then(branchedStatusMono) // Remove any files which are copied by hard resetting the repo - .then(executionTimeLogging.measureTask("getStatus->gitExecutor.resetToLastCommit", gitExecutor.resetToLastCommit(tuple.getT3(), branchName))) + .then(executionTimeLogging.measureTask( + "getStatus->gitExecutor.resetToLastCommit", + gitExecutor.resetToLastCommit(tuple.getT3(), branchName))) .flatMap(gitStatusDTO -> { if (Boolean.TRUE.equals(isFileLock)) { - return executionTimeLogging.measureTask("getStatus->releaseFileLock", releaseFileLock(defaultApplicationId)) + return executionTimeLogging + .measureTask( + "getStatus->releaseFileLock", + releaseFileLock(defaultApplicationId)) .then(branchedStatusMono); } return branchedStatusMono; }) - .onErrorResume(error -> Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "status", error.getMessage()))); + .onErrorResume(error -> Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "status", error.getMessage()))); } catch (GitAPIException | IOException e) { return Mono.error(new AppsmithException(AppsmithError.GIT_GENERIC_ERROR, e.getMessage())); } }); return Mono.create(sink -> { - statusMono.map(t -> { - log.debug("Time take, {}\n", executionTimeLogging.print()); - return t; - }).subscribe(sink::success, sink::error, null, sink.currentContext()); + statusMono + .map(t -> { + log.debug("Time take, {}\n", executionTimeLogging.print()); + return t; + }) + .subscribe(sink::success, sink::error, null, sink.currentContext()); }); } @@ -1645,54 +1867,64 @@ public Mono<MergeStatusDTO> mergeBranch(String defaultApplicationId, GitMergeDTO if (StringUtils.isEmptyOrNull(sourceBranch) || StringUtils.isEmptyOrNull(destinationBranch)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.BRANCH_NAME)); } else if (sourceBranch.startsWith("origin/")) { - return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH, sourceBranch)); + return Mono.error( + new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH, sourceBranch)); } else if (destinationBranch.startsWith("origin/")) { - return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH, destinationBranch)); + return Mono.error( + new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH, destinationBranch)); } Mono<MergeStatusDTO> mergeMono = getApplicationById(defaultApplicationId) .flatMap(application -> { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); - return addFileLock(gitData.getDefaultApplicationId()) - .then(Mono.just(application)); + return addFileLock(gitData.getDefaultApplicationId()).then(Mono.just(application)); }) .flatMap(defaultApplication -> { GitApplicationMetadata gitApplicationMetadata = defaultApplication.getGitApplicationMetadata(); if (isInvalidDefaultApplicationGitMetadata(defaultApplication.getGitApplicationMetadata())) { return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); } - Path repoSuffix = Paths.get(defaultApplication.getWorkspaceId(), + Path repoSuffix = Paths.get( + defaultApplication.getWorkspaceId(), gitApplicationMetadata.getDefaultApplicationId(), gitApplicationMetadata.getRepoName()); - //1. Hydrate from db to file system for both branch Applications + // 1. Hydrate from db to file system for both branch Applications Mono<Path> pathToFile = this.getStatus(defaultApplicationId, sourceBranch, false) .flatMap(status -> { if (!Integer.valueOf(0).equals(status.getBehindCount())) { - return Mono.error(new AppsmithException(AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES, status.getBehindCount(), sourceBranch)); + return Mono.error(new AppsmithException( + AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES, + status.getBehindCount(), + sourceBranch)); } else if (!CollectionUtils.isNullOrEmpty(status.getModified())) { - return Mono.error(new AppsmithException(AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES, sourceBranch)); + return Mono.error(new AppsmithException( + AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES, sourceBranch)); } return this.getStatus(defaultApplicationId, destinationBranch, false) .map(status1 -> { if (!Integer.valueOf(0).equals(status.getBehindCount())) { - return Mono.error(new AppsmithException(AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES, status.getBehindCount(), destinationBranch)); + return Mono.error(new AppsmithException( + AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES, + status.getBehindCount(), + destinationBranch)); } else if (!CollectionUtils.isNullOrEmpty(status.getModified())) { - return Mono.error(new AppsmithException(AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES, destinationBranch)); + return Mono.error(new AppsmithException( + AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES, + destinationBranch)); } return status1; }); }) .thenReturn(repoSuffix); - return Mono.zip(Mono.just(defaultApplication), pathToFile) - .onErrorResume(error -> { - log.error("Error in repo status check for application " + defaultApplicationId, error); - if (error instanceof AppsmithException) { - return Mono.error(error); - } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "status", error)); - }); + return Mono.zip(Mono.just(defaultApplication), pathToFile).onErrorResume(error -> { + log.error("Error in repo status check for application " + defaultApplicationId, error); + if (error instanceof AppsmithException) { + return Mono.error(error); + } + return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "status", error)); + }); }) .flatMap(tuple -> { Application defaultApplication = tuple.getT1(); @@ -1701,28 +1933,29 @@ public Mono<MergeStatusDTO> mergeBranch(String defaultApplicationId, GitMergeDTO // 2. git checkout destinationBranch ---> git merge sourceBranch return Mono.zip( gitExecutor.mergeBranch(repoSuffix, sourceBranch, destinationBranch), - Mono.just(defaultApplication) - ) + Mono.just(defaultApplication)) .onErrorResume(error -> addAnalyticsForGitOperation( AnalyticsEvents.GIT_MERGE.getEventName(), defaultApplication, error.getClass().getName(), error.getMessage(), - defaultApplication.getGitApplicationMetadata().getIsRepoPrivate() - ) - .flatMap(application -> { - if (error instanceof GitAPIException) { - return Mono.error(new AppsmithException(AppsmithError.GIT_MERGE_CONFLICTS, error.getMessage())); - } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "merge", error.getMessage())); - }) - ); + defaultApplication + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .flatMap(application -> { + if (error instanceof GitAPIException) { + return Mono.error(new AppsmithException( + AppsmithError.GIT_MERGE_CONFLICTS, error.getMessage())); + } + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "merge", error.getMessage())); + })); }) .flatMap(mergeStatusTuple -> { Application defaultApplication = mergeStatusTuple.getT2(); String mergeStatus = mergeStatusTuple.getT1(); - //3. rehydrate from file system to db + // 3. rehydrate from file system to db Mono<ApplicationJson> applicationJson = fileUtils.reconstructApplicationJsonFromGitRepo( defaultApplication.getWorkspaceId(), defaultApplication.getGitApplicationMetadata().getDefaultApplicationId(), @@ -1730,10 +1963,9 @@ public Mono<MergeStatusDTO> mergeBranch(String defaultApplicationId, GitMergeDTO destinationBranch); return Mono.zip( Mono.just(mergeStatus), - applicationService - .findByBranchNameAndDefaultApplicationId(destinationBranch, defaultApplicationId, applicationPermission.getEditPermission()), - applicationJson - ); + applicationService.findByBranchNameAndDefaultApplicationId( + destinationBranch, defaultApplicationId, applicationPermission.getEditPermission()), + applicationJson); }) .flatMap(tuple -> { Application destApplication = tuple.getT2(); @@ -1742,13 +1974,19 @@ public Mono<MergeStatusDTO> mergeBranch(String defaultApplicationId, GitMergeDTO mergeStatusDTO.setStatus(tuple.getT1()); mergeStatusDTO.setMergeAble(Boolean.TRUE); - //4. Get the latest application mono with all the changes + // 4. Get the latest application mono with all the changes return importExportApplicationService - .importApplicationInWorkspaceFromGit(destApplication.getWorkspaceId(), applicationJson, destApplication.getId(), destinationBranch.replaceFirst("origin/", "")) + .importApplicationInWorkspaceFromGit( + destApplication.getWorkspaceId(), + applicationJson, + destApplication.getId(), + destinationBranch.replaceFirst("origin/", "")) .flatMap(application1 -> { GitCommitDTO commitDTO = new GitCommitDTO(); commitDTO.setDoPush(true); - commitDTO.setCommitMessage(DEFAULT_COMMIT_MESSAGE + GitDefaultCommitMessage.SYNC_REMOTE_AFTER_MERGE.getReason() + sourceBranch); + commitDTO.setCommitMessage(DEFAULT_COMMIT_MESSAGE + + GitDefaultCommitMessage.SYNC_REMOTE_AFTER_MERGE.getReason() + + sourceBranch); return this.commitApplication(commitDTO, defaultApplicationId, destinationBranch) .map(commitStatus -> mergeStatusDTO) .zipWith(Mono.just(application1)); @@ -1758,17 +1996,14 @@ public Mono<MergeStatusDTO> mergeBranch(String defaultApplicationId, GitMergeDTO MergeStatusDTO mergeStatusDTO = tuple.getT1(); Application application = tuple.getT2(); // Send analytics event - return releaseFileLock(defaultApplicationId) - .flatMap(status -> addAnalyticsForGitOperation( + return releaseFileLock(defaultApplicationId).flatMap(status -> addAnalyticsForGitOperation( AnalyticsEvents.GIT_MERGE.getEventName(), application, application.getGitApplicationMetadata().getIsRepoPrivate()) - .thenReturn(mergeStatusDTO)); + .thenReturn(mergeStatusDTO)); }); - return Mono.create(sink -> mergeMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create(sink -> mergeMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override @@ -1780,9 +2015,11 @@ public Mono<MergeStatusDTO> isBranchMergeable(String defaultApplicationId, GitMe if (StringUtils.isEmptyOrNull(sourceBranch) || StringUtils.isEmptyOrNull(destinationBranch)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.BRANCH_NAME)); } else if (sourceBranch.startsWith("origin/")) { - return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH, sourceBranch)); + return Mono.error( + new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH, sourceBranch)); } else if (destinationBranch.startsWith("origin/")) { - return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH, destinationBranch)); + return Mono.error( + new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION_FOR_REMOTE_BRANCH, destinationBranch)); } Mono<MergeStatusDTO> mergeableStatusMono = getApplicationById(defaultApplicationId) @@ -1791,41 +2028,61 @@ public Mono<MergeStatusDTO> isBranchMergeable(String defaultApplicationId, GitMe if (isInvalidDefaultApplicationGitMetadata(application.getGitApplicationMetadata())) { return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); } - Path repoSuffix = Paths.get(application.getWorkspaceId(), + Path repoSuffix = Paths.get( + application.getWorkspaceId(), gitApplicationMetadata.getDefaultApplicationId(), gitApplicationMetadata.getRepoName()); - //1. Hydrate from db to file system for both branch Applications - return redisUtils.addFileLock(gitApplicationMetadata.getDefaultApplicationId()) - .retryWhen(Retry.fixedDelay(MAX_RETRIES, RETRY_DELAY).jitter(0.75) + // 1. Hydrate from db to file system for both branch Applications + return redisUtils + .addFileLock(gitApplicationMetadata.getDefaultApplicationId()) + .retryWhen(Retry.fixedDelay(MAX_RETRIES, RETRY_DELAY) + .jitter(0.75) .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> { throw new AppsmithException(AppsmithError.GIT_FILE_IN_USE); })) .flatMap(status -> this.getStatus(defaultApplicationId, sourceBranch, false)) .flatMap(srcBranchStatus -> { if (!Integer.valueOf(0).equals(srcBranchStatus.getBehindCount())) { - return Mono.error(Exceptions.propagate(new AppsmithException(AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES, srcBranchStatus.getBehindCount(), sourceBranch))); + return Mono.error(Exceptions.propagate(new AppsmithException( + AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES, + srcBranchStatus.getBehindCount(), + sourceBranch))); } else if (!CollectionUtils.isNullOrEmpty(srcBranchStatus.getModified())) { - return Mono.error(Exceptions.propagate(new AppsmithException(AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES, sourceBranch))); + return Mono.error(Exceptions.propagate(new AppsmithException( + AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES, sourceBranch))); } return this.getStatus(defaultApplicationId, destinationBranch, false) .map(destBranchStatus -> { if (!Integer.valueOf(0).equals(destBranchStatus.getBehindCount())) { return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_MERGE.getEventName(), - application, - AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES.name(), - AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES.getMessage(destBranchStatus.getBehindCount(), destinationBranch), - application.getGitApplicationMetadata().getIsRepoPrivate() - ).then(Mono.error(Exceptions.propagate(new AppsmithException(AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES, destBranchStatus.getBehindCount(), destinationBranch)))); + AnalyticsEvents.GIT_MERGE.getEventName(), + application, + AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES.name(), + AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES + .getMessage( + destBranchStatus.getBehindCount(), + destinationBranch), + application + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .then(Mono.error(Exceptions.propagate(new AppsmithException( + AppsmithError.GIT_MERGE_FAILED_REMOTE_CHANGES, + destBranchStatus.getBehindCount(), + destinationBranch)))); } else if (!CollectionUtils.isNullOrEmpty(destBranchStatus.getModified())) { return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_MERGE.getEventName(), - application, - AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES.name(), - AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES.getMessage(destinationBranch), - application.getGitApplicationMetadata().getIsRepoPrivate() - ).then(Mono.error(Exceptions.propagate(new AppsmithException(AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES, destinationBranch)))); + AnalyticsEvents.GIT_MERGE.getEventName(), + application, + AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES.name(), + AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES.getMessage( + destinationBranch), + application + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .then(Mono.error(Exceptions.propagate(new AppsmithException( + AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES, + destinationBranch)))); } return destBranchStatus; }); @@ -1835,32 +2092,34 @@ public Mono<MergeStatusDTO> isBranchMergeable(String defaultApplicationId, GitMe if (error instanceof AppsmithException) { return Mono.error(error); } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "status", error)); + return Mono.error( + new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "status", error)); }) - .then(gitExecutor.isMergeBranch(repoSuffix, sourceBranch, destinationBranch) + .then(gitExecutor + .isMergeBranch(repoSuffix, sourceBranch, destinationBranch) .flatMap(mergeStatusDTO -> releaseFileLock(defaultApplicationId) .flatMap(mergeStatus -> addAnalyticsForGitOperation( AnalyticsEvents.GIT_MERGE_CHECK.getEventName(), application, - application.getGitApplicationMetadata().getIsRepoPrivate()) - ) - .then(Mono.just(mergeStatusDTO) - ) - ) - ) + application + .getGitApplicationMetadata() + .getIsRepoPrivate())) + .then(Mono.just(mergeStatusDTO)))) .onErrorResume(error -> { try { - return gitExecutor.resetToLastCommit(repoSuffix, destinationBranch) + return gitExecutor + .resetToLastCommit(repoSuffix, destinationBranch) .map(reset -> { MergeStatusDTO mergeStatus = new MergeStatusDTO(); mergeStatus.setMergeAble(false); mergeStatus.setStatus("Merge check failed!"); mergeStatus.setMessage(error.getMessage()); if (error instanceof CheckoutConflictException) { - mergeStatus.setConflictingFiles(((CheckoutConflictException) error) - .getConflictingPaths()); + mergeStatus.setConflictingFiles( + ((CheckoutConflictException) error).getConflictingPaths()); } - mergeStatus.setReferenceDoc(ErrorReferenceDocUrl.GIT_MERGE_CONFLICT.getDocUrl()); + mergeStatus.setReferenceDoc( + ErrorReferenceDocUrl.GIT_MERGE_CONFLICT.getDocUrl()); return mergeStatus; }) .flatMap(mergeStatusDTO -> { @@ -1869,20 +2128,21 @@ public Mono<MergeStatusDTO> isBranchMergeable(String defaultApplicationId, GitMe application, error.getClass().getName(), error.getMessage(), - application.getGitApplicationMetadata().getIsRepoPrivate() - ); + application + .getGitApplicationMetadata() + .getIsRepoPrivate()); return Mono.just(mergeStatusDTO); }); } catch (GitAPIException | IOException e) { log.error("Error while resetting to last commit", e); - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "reset --hard HEAD", e.getMessage())); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "reset --hard HEAD", e.getMessage())); } }); }); - return Mono.create(sink -> mergeableStatusMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> mergeableStatusMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override @@ -1893,42 +2153,47 @@ public Mono<String> createConflictedBranch(String defaultApplicationId, String b Mono<String> conflictedBranchMono = Mono.zip( getGitApplicationMetadata(defaultApplicationId), - applicationService.findByBranchNameAndDefaultApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) - .zipWhen(application -> importExportApplicationService.exportApplicationById(application.getId(), SerialiseApplicationObjective.VERSION_CONTROL))) + applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, defaultApplicationId, applicationPermission.getEditPermission()) + .zipWhen(application -> importExportApplicationService.exportApplicationById( + application.getId(), SerialiseApplicationObjective.VERSION_CONTROL))) .flatMap(tuple -> { GitApplicationMetadata defaultApplicationMetadata = tuple.getT1(); Application application = tuple.getT2().getT1(); ApplicationJson applicationJson = tuple.getT2().getT2(); GitApplicationMetadata gitData = application.getGitApplicationMetadata(); gitData.setGitAuth(defaultApplicationMetadata.getGitAuth()); - Path repoSuffix = - Paths.get(application.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); + Path repoSuffix = Paths.get( + application.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); try { return Mono.zip( fileUtils.saveApplicationToLocalRepo(repoSuffix, applicationJson, branchName), Mono.just(gitData), - Mono.just(repoSuffix) - ); + Mono.just(repoSuffix)); } catch (IOException | GitAPIException e) { - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "checkout", e.getMessage())); + return Mono.error( + new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "checkout", e.getMessage())); } }) .flatMap(tuple -> { GitApplicationMetadata gitData = tuple.getT2(); Path repoSuffix = tuple.getT3(); - return gitExecutor.createAndCheckoutToBranch(repoSuffix, branchName + MERGE_CONFLICT_BRANCH_NAME) - .flatMap(conflictedBranchName -> - commitAndPushWithDefaultCommit(repoSuffix, gitData.getGitAuth(), gitData, GitDefaultCommitMessage.CONFLICT_STATE) - .flatMap(successMessage -> gitExecutor.checkoutToBranch(repoSuffix, branchName)) - .flatMap(isCheckedOut -> gitExecutor.deleteBranch(repoSuffix, conflictedBranchName)) - .thenReturn(conflictedBranchName + CONFLICTED_SUCCESS_MESSAGE) - ); + return gitExecutor + .createAndCheckoutToBranch(repoSuffix, branchName + MERGE_CONFLICT_BRANCH_NAME) + .flatMap(conflictedBranchName -> commitAndPushWithDefaultCommit( + repoSuffix, + gitData.getGitAuth(), + gitData, + GitDefaultCommitMessage.CONFLICT_STATE) + .flatMap(successMessage -> gitExecutor.checkoutToBranch(repoSuffix, branchName)) + .flatMap(isCheckedOut -> gitExecutor.deleteBranch(repoSuffix, conflictedBranchName)) + .thenReturn(conflictedBranchName + CONFLICTED_SUCCESS_MESSAGE)); }); - return Mono.create(sink -> conflictedBranchMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> conflictedBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override @@ -1948,16 +2213,24 @@ public Mono<ApplicationImportDTO> importApplicationFromGit(String workspaceId, G return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "Invalid workspace id")); } - Mono<Workspace> workspaceMono = workspaceService.findById(workspaceId, AclPermission.WORKSPACE_CREATE_APPLICATION) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); + Mono<Workspace> workspaceMono = workspaceService + .findById(workspaceId, AclPermission.WORKSPACE_CREATE_APPLICATION) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); final String repoName = GitUtils.getRepoName(gitConnectDTO.getRemoteUrl()); - Mono<Boolean> isPrivateRepoMono = GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl(gitConnectDTO.getRemoteUrl())).cache(); - Mono<ApplicationImportDTO> importedApplicationMono = workspaceMono.then(getSSHKeyForCurrentUser()) + Mono<Boolean> isPrivateRepoMono = GitUtils.isRepoPrivate( + GitUtils.convertSshUrlToBrowserSupportedUrl(gitConnectDTO.getRemoteUrl())) + .cache(); + Mono<ApplicationImportDTO> importedApplicationMono = workspaceMono + .then(getSSHKeyForCurrentUser()) .zipWith(isPrivateRepoMono) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, - "Unable to find git configuration for logged-in user. Please contact Appsmith team for support"))) - //Check the limit for number of private repo + .switchIfEmpty( + Mono.error( + new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, + "Unable to find git configuration for logged-in user. Please contact Appsmith team for support"))) + // Check the limit for number of private repo .flatMap(tuple -> { // Check if the repo is public Application newApplication = new Application(); @@ -1966,94 +2239,109 @@ public Mono<ApplicationImportDTO> importApplicationFromGit(String workspaceId, G newApplication.setGitApplicationMetadata(new GitApplicationMetadata()); GitAuth gitAuth = tuple.getT1(); boolean isRepoPrivate = tuple.getT2(); - Mono<Application> applicationMono = applicationPageService - .createOrUpdateSuffixedApplication(newApplication, newApplication.getName(), 0); + Mono<Application> applicationMono = applicationPageService.createOrUpdateSuffixedApplication( + newApplication, newApplication.getName(), 0); if (!isRepoPrivate) { return Mono.just(gitAuth).zipWith(applicationMono); } - return isRepoLimitReached(workspaceId, true) - .flatMap(isRepoLimitReached -> { - if (Boolean.FALSE.equals(isRepoLimitReached)) { - return Mono.just(gitAuth).zipWith(applicationMono); - } - return addAnalyticsForGitOperation( + return isRepoLimitReached(workspaceId, true).flatMap(isRepoLimitReached -> { + if (Boolean.FALSE.equals(isRepoLimitReached)) { + return Mono.just(gitAuth).zipWith(applicationMono); + } + return addAnalyticsForGitOperation( AnalyticsEvents.GIT_IMPORT.getEventName(), newApplication, AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getErrorType(), AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getMessage(), - true - ).flatMap(user -> Mono.error(new AppsmithException(AppsmithError.GIT_APPLICATION_LIMIT_ERROR))); - }); + true) + .flatMap(user -> + Mono.error(new AppsmithException(AppsmithError.GIT_APPLICATION_LIMIT_ERROR))); + }); }) .flatMap(tuple -> { GitAuth gitAuth = tuple.getT1(); Application application = tuple.getT2(); Path repoSuffix = Paths.get(application.getWorkspaceId(), application.getId(), repoName); - Mono<Map<String, GitProfile>> profileMono = updateOrCreateGitProfileForCurrentUser(gitConnectDTO.getGitProfile(), application.getId()); + Mono<Map<String, GitProfile>> profileMono = + updateOrCreateGitProfileForCurrentUser(gitConnectDTO.getGitProfile(), application.getId()); - Mono<String> defaultBranchMono = gitExecutor.cloneApplication( - repoSuffix, - gitConnectDTO.getRemoteUrl(), - gitAuth.getPrivateKey(), - gitAuth.getPublicKey() - ).onErrorResume(error -> { - log.error("Error while cloning the remote repo, {}", error.getMessage()); - return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_IMPORT.getEventName(), - application, - error.getClass().getName(), - error.getMessage(), - false) - .flatMap(user -> fileUtils.deleteLocalRepo(repoSuffix) - .then(applicationPageService.deleteApplication(application.getId()))) - .flatMap(application1 -> { - if (error instanceof TransportException) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); - } else if (error instanceof InvalidRemoteException) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "remote url")); - } else if (error instanceof TimeoutException) { - return Mono.error(new AppsmithException(AppsmithError.GIT_EXECUTION_TIMEOUT)); - } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "clone", error)); - }); - }); - - return defaultBranchMono - .zipWith(isPrivateRepoMono) - .flatMap(tuple2 -> { - String defaultBranch = tuple2.getT1(); - boolean isRepoPrivate = tuple2.getT2(); - GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); - gitApplicationMetadata.setGitAuth(gitAuth); - gitApplicationMetadata.setDefaultApplicationId(application.getId()); - gitApplicationMetadata.setBranchName(defaultBranch); - gitApplicationMetadata.setDefaultBranchName(defaultBranch); - gitApplicationMetadata.setRemoteUrl(gitConnectDTO.getRemoteUrl()); - gitApplicationMetadata.setRepoName(repoName); - gitApplicationMetadata.setBrowserSupportedRemoteUrl( - GitUtils.convertSshUrlToBrowserSupportedUrl(gitConnectDTO.getRemoteUrl()) - ); - gitApplicationMetadata.setIsRepoPrivate(isRepoPrivate); - gitApplicationMetadata.setLastCommittedAt(Instant.now()); - - application.setGitApplicationMetadata(gitApplicationMetadata); - return Mono.just(application).zipWith(profileMono); + Mono<String> defaultBranchMono = gitExecutor + .cloneApplication( + repoSuffix, + gitConnectDTO.getRemoteUrl(), + gitAuth.getPrivateKey(), + gitAuth.getPublicKey()) + .onErrorResume(error -> { + log.error("Error while cloning the remote repo, {}", error.getMessage()); + return addAnalyticsForGitOperation( + AnalyticsEvents.GIT_IMPORT.getEventName(), + application, + error.getClass().getName(), + error.getMessage(), + false) + .flatMap(user -> fileUtils + .deleteLocalRepo(repoSuffix) + .then(applicationPageService.deleteApplication(application.getId()))) + .flatMap(application1 -> { + if (error instanceof TransportException) { + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); + } else if (error instanceof InvalidRemoteException) { + return Mono.error(new AppsmithException( + AppsmithError.INVALID_PARAMETER, "remote url")); + } else if (error instanceof TimeoutException) { + return Mono.error( + new AppsmithException(AppsmithError.GIT_EXECUTION_TIMEOUT)); + } + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "clone", error)); + }); }); + + return defaultBranchMono.zipWith(isPrivateRepoMono).flatMap(tuple2 -> { + String defaultBranch = tuple2.getT1(); + boolean isRepoPrivate = tuple2.getT2(); + GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); + gitApplicationMetadata.setGitAuth(gitAuth); + gitApplicationMetadata.setDefaultApplicationId(application.getId()); + gitApplicationMetadata.setBranchName(defaultBranch); + gitApplicationMetadata.setDefaultBranchName(defaultBranch); + gitApplicationMetadata.setRemoteUrl(gitConnectDTO.getRemoteUrl()); + gitApplicationMetadata.setRepoName(repoName); + gitApplicationMetadata.setBrowserSupportedRemoteUrl( + GitUtils.convertSshUrlToBrowserSupportedUrl(gitConnectDTO.getRemoteUrl())); + gitApplicationMetadata.setIsRepoPrivate(isRepoPrivate); + gitApplicationMetadata.setLastCommittedAt(Instant.now()); + + application.setGitApplicationMetadata(gitApplicationMetadata); + return Mono.just(application).zipWith(profileMono); + }); }) .flatMap(objects -> { Application application = objects.getT1(); GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); String defaultBranch = gitApplicationMetadata.getDefaultBranchName(); - - Mono<List<Datasource>> datasourceMono = datasourceService.getAllByWorkspaceIdWithStorages(workspaceId, Optional.of(datasourcePermission.getEditPermission())).collectList(); - Mono<List<Plugin>> pluginMono = pluginService.getDefaultPlugins().collectList(); + Mono<List<Datasource>> datasourceMono = datasourceService + .getAllByWorkspaceIdWithStorages( + workspaceId, Optional.of(datasourcePermission.getEditPermission())) + .collectList(); + Mono<List<Plugin>> pluginMono = + pluginService.getDefaultPlugins().collectList(); Mono<ApplicationJson> applicationJsonMono = fileUtils - .reconstructApplicationJsonFromGitRepo(workspaceId, application.getId(), gitApplicationMetadata.getRepoName(), defaultBranch) + .reconstructApplicationJsonFromGitRepo( + workspaceId, + application.getId(), + gitApplicationMetadata.getRepoName(), + defaultBranch) .onErrorResume(error -> { log.error("Error while constructing application from git repo", error); - return deleteApplicationCreatedFromGitImport(application.getId(), application.getWorkspaceId(), gitApplicationMetadata.getRepoName()) - .flatMap(application1 -> Mono.error(new AppsmithException(AppsmithError.GIT_FILE_SYSTEM_ERROR, error.getMessage()))); + return deleteApplicationCreatedFromGitImport( + application.getId(), + application.getWorkspaceId(), + gitApplicationMetadata.getRepoName()) + .flatMap(application1 -> Mono.error(new AppsmithException( + AppsmithError.GIT_FILE_SYSTEM_ERROR, error.getMessage()))); }); return Mono.zip(applicationJsonMono, datasourceMono, pluginMono) @@ -2062,49 +2350,62 @@ public Mono<ApplicationImportDTO> importApplicationFromGit(String workspaceId, G List<Datasource> datasourceList = data.getT2(); List<Plugin> pluginList = data.getT3(); - if (Optional.ofNullable(applicationJson.getExportedApplication()).isEmpty() + if (Optional.ofNullable(applicationJson.getExportedApplication()) + .isEmpty() || applicationJson.getPageList().isEmpty()) { - return deleteApplicationCreatedFromGitImport(application.getId(), application.getWorkspaceId(), gitApplicationMetadata.getRepoName()) - .then(Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "import", "Cannot import app from an empty repo"))); + return deleteApplicationCreatedFromGitImport( + application.getId(), + application.getWorkspaceId(), + gitApplicationMetadata.getRepoName()) + .then(Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "import", + "Cannot import app from an empty repo"))); } - // If there is an existing datasource with the same name but a different type from that in the repo, the import api should fail - if (checkIsDatasourceNameConflict(datasourceList, applicationJson.getDatasourceList(), pluginList)) { - return deleteApplicationCreatedFromGitImport(application.getId(), application.getWorkspaceId(), gitApplicationMetadata.getRepoName()) - .then(Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, + // If there is an existing datasource with the same name but a different type from that + // in the repo, the import api should fail + if (checkIsDatasourceNameConflict( + datasourceList, applicationJson.getDatasourceList(), pluginList)) { + return deleteApplicationCreatedFromGitImport( + application.getId(), + application.getWorkspaceId(), + gitApplicationMetadata.getRepoName()) + .then(Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "import", - "Datasource already exists with the same name")) - ); + "Datasource already exists with the same name"))); } - applicationJson.getExportedApplication().setGitApplicationMetadata(gitApplicationMetadata); + applicationJson + .getExportedApplication() + .setGitApplicationMetadata(gitApplicationMetadata); return importExportApplicationService - .importApplicationInWorkspaceFromGit(workspaceId, applicationJson, application.getId(), defaultBranch) - .onErrorResume(throwable -> - deleteApplicationCreatedFromGitImport(application.getId(), application.getWorkspaceId(), gitApplicationMetadata.getRepoName()) - .flatMap(application1 -> Mono.error(new AppsmithException(AppsmithError.GIT_FILE_SYSTEM_ERROR, throwable.getMessage()))) - ); + .importApplicationInWorkspaceFromGit( + workspaceId, applicationJson, application.getId(), defaultBranch) + .onErrorResume(throwable -> deleteApplicationCreatedFromGitImport( + application.getId(), + application.getWorkspaceId(), + gitApplicationMetadata.getRepoName()) + .flatMap(application1 -> Mono.error(new AppsmithException( + AppsmithError.GIT_FILE_SYSTEM_ERROR, throwable.getMessage())))); }); }) // Add un-configured datasource to the list to response - .flatMap(application -> importExportApplicationService - .getApplicationImportDTO(application.getId(), - application.getWorkspaceId(), - application - )) + .flatMap(application -> importExportApplicationService.getApplicationImportDTO( + application.getId(), application.getWorkspaceId(), application)) // Add analytics event .flatMap(applicationImportDTO -> { Application application = applicationImportDTO.getApplication(); return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_IMPORT.getEventName(), - application, - application.getGitApplicationMetadata().getIsRepoPrivate() - ).thenReturn(applicationImportDTO); + AnalyticsEvents.GIT_IMPORT.getEventName(), + application, + application.getGitApplicationMetadata().getIsRepoPrivate()) + .thenReturn(applicationImportDTO); }); - return Mono.create(sink -> importedApplicationMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> importedApplicationMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override @@ -2114,10 +2415,12 @@ public Mono<GitAuth> generateSSHKey(String keyType) { GitDeployKeys gitDeployKeys = new GitDeployKeys(); gitDeployKeys.setGitAuth(gitAuth); - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .flatMap(user -> { gitDeployKeys.setEmail(user.getEmail()); - return gitDeployKeysRepository.findByEmail(user.getEmail()) + return gitDeployKeysRepository + .findByEmail(user.getEmail()) .switchIfEmpty(gitDeployKeysRepository.save(gitDeployKeys)) .flatMap(gitDeployKeys1 -> { if (gitDeployKeys.equals(gitDeployKeys1)) { @@ -2139,41 +2442,50 @@ public Mono<Boolean> testConnection(String defaultApplicationId) { if (isInvalidDefaultApplicationGitMetadata(gitApplicationMetadata)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); } - return gitExecutor.testConnection( + return gitExecutor + .testConnection( gitApplicationMetadata.getGitAuth().getPublicKey(), gitApplicationMetadata.getGitAuth().getPrivateKey(), - gitApplicationMetadata.getRemoteUrl() - ).zipWith(Mono.just(application)) + gitApplicationMetadata.getRemoteUrl()) + .zipWith(Mono.just(application)) .onErrorResume(error -> { - log.error("Error while testing the connection to th remote repo " + gitApplicationMetadata.getRemoteUrl() + " ", error); + log.error( + "Error while testing the connection to th remote repo " + + gitApplicationMetadata.getRemoteUrl() + " ", + error); return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_TEST_CONNECTION.getEventName(), - application, - error.getClass().getName(), - error.getMessage(), - application.getGitApplicationMetadata().getIsRepoPrivate() - ).flatMap(application1 -> { - if (error instanceof TransportException) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); - } - if (error instanceof InvalidRemoteException) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, error.getMessage())); - } - if (error instanceof TimeoutException) { - return Mono.error(new AppsmithException(AppsmithError.GIT_EXECUTION_TIMEOUT)); - } - return Mono.error(new AppsmithException(AppsmithError.GIT_GENERIC_ERROR, error.getMessage())); - }); - + AnalyticsEvents.GIT_TEST_CONNECTION.getEventName(), + application, + error.getClass().getName(), + error.getMessage(), + application + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .flatMap(application1 -> { + if (error instanceof TransportException) { + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); + } + if (error instanceof InvalidRemoteException) { + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, error.getMessage())); + } + if (error instanceof TimeoutException) { + return Mono.error( + new AppsmithException(AppsmithError.GIT_EXECUTION_TIMEOUT)); + } + return Mono.error(new AppsmithException( + AppsmithError.GIT_GENERIC_ERROR, error.getMessage())); + }); }); }) .flatMap(objects -> { Application application = objects.getT2(); return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_TEST_CONNECTION.getEventName(), - application, - application.getGitApplicationMetadata().getIsRepoPrivate() - ).thenReturn(objects.getT1()); + AnalyticsEvents.GIT_TEST_CONNECTION.getEventName(), + application, + application.getGitApplicationMetadata().getIsRepoPrivate()) + .thenReturn(objects.getT1()); }); } @@ -2182,25 +2494,42 @@ public Mono<Application> deleteBranch(String defaultApplicationId, String branch Mono<Application> deleteBranchMono = getApplicationById(defaultApplicationId) .flatMap(application -> { GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); - Path repoPath = Paths.get(application.getWorkspaceId(), defaultApplicationId, gitApplicationMetadata.getRepoName()); + Path repoPath = Paths.get( + application.getWorkspaceId(), defaultApplicationId, gitApplicationMetadata.getRepoName()); if (branchName.equals(gitApplicationMetadata.getDefaultBranchName())) { - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "delete branch", " Cannot delete default branch")); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "delete branch", " Cannot delete default branch")); } - return gitExecutor.deleteBranch(repoPath, branchName) + return gitExecutor + .deleteBranch(repoPath, branchName) .onErrorResume(throwable -> { log.error("Delete branch failed {}", throwable.getMessage()); if (throwable instanceof CannotDeleteCurrentBranchException) { - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "delete branch", "Cannot delete current checked out branch")); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "delete branch", + "Cannot delete current checked out branch")); } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "delete branch", throwable.getMessage())); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "delete branch", throwable.getMessage())); }) .flatMap(isBranchDeleted -> { if (Boolean.FALSE.equals(isBranchDeleted)) { - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, " delete branch. Branch does not exists in the repo")); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + " delete branch. Branch does not exists in the repo")); } - return applicationService.findByBranchNameAndDefaultApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) + return applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, + defaultApplicationId, + applicationPermission.getEditPermission()) .flatMap(application1 -> { - if (application1.getId().equals(application1.getGitApplicationMetadata().getDefaultApplicationId())) { + if (application1 + .getId() + .equals(application1 + .getGitApplicationMetadata() + .getDefaultApplicationId())) { return Mono.just(application1); } return applicationPageService.deleteApplicationByResource(application1); @@ -2208,21 +2537,22 @@ public Mono<Application> deleteBranch(String defaultApplicationId, String branch .onErrorResume(throwable -> { log.warn("Unable to find branch with name ", throwable); return addAnalyticsForGitOperation( - AnalyticsEvents.GIT_DELETE_BRANCH.getEventName(), - application, - throwable.getClass().getName(), - throwable.getMessage(), - gitApplicationMetadata.getIsRepoPrivate() - ).flatMap(application1 -> Mono.just(application1)); + AnalyticsEvents.GIT_DELETE_BRANCH.getEventName(), + application, + throwable.getClass().getName(), + throwable.getMessage(), + gitApplicationMetadata.getIsRepoPrivate()) + .flatMap(application1 -> Mono.just(application1)); }); }); }) - .flatMap(application -> addAnalyticsForGitOperation(AnalyticsEvents.GIT_DELETE_BRANCH.getEventName(), application, application.getGitApplicationMetadata().getIsRepoPrivate())) + .flatMap(application -> addAnalyticsForGitOperation( + AnalyticsEvents.GIT_DELETE_BRANCH.getEventName(), + application, + application.getGitApplicationMetadata().getIsRepoPrivate())) .map(responseUtils::updateApplicationWithDefaultResources); - return Mono.create(sink -> deleteBranchMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create(sink -> deleteBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override @@ -2232,7 +2562,8 @@ public Mono<Application> discardChanges(String defaultApplicationId, String bran return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID)); } Mono<Application> branchedApplicationMono = applicationService - .findByBranchNameAndDefaultApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) + .findByBranchNameAndDefaultApplicationId( + branchName, defaultApplicationId, applicationPermission.getEditPermission()) .cache(); Mono<Application> defaultApplicationMono = this.getApplicationById(defaultApplicationId); @@ -2245,34 +2576,48 @@ public Mono<Application> discardChanges(String defaultApplicationId, String bran .flatMap(branchedApplication -> { GitApplicationMetadata gitData = branchedApplication.getGitApplicationMetadata(); if (gitData == null || StringUtils.isEmptyOrNull(gitData.getDefaultApplicationId())) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); } - Path repoSuffix = Paths.get(branchedApplication.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); - return gitExecutor.rebaseBranch(repoSuffix, branchName) + Path repoSuffix = Paths.get( + branchedApplication.getWorkspaceId(), + gitData.getDefaultApplicationId(), + gitData.getRepoName()); + return gitExecutor + .rebaseBranch(repoSuffix, branchName) .flatMap(rebaseStatus -> { return fileUtils.reconstructApplicationJsonFromGitRepo( branchedApplication.getWorkspaceId(), - branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(), - branchedApplication.getGitApplicationMetadata().getRepoName(), + branchedApplication + .getGitApplicationMetadata() + .getDefaultApplicationId(), + branchedApplication + .getGitApplicationMetadata() + .getRepoName(), branchName); }) .onErrorResume(throwable -> { log.error("Git Discard & Rebase failed {}", throwable.getMessage()); - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "discard changes", "Please create a new branch and resolve the conflicts on remote repository before proceeding ahead.")); + return Mono.error( + new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "discard changes", + "Please create a new branch and resolve the conflicts on remote repository before proceeding ahead.")); }) .flatMap(applicationJson -> - importExportApplicationService - .importApplicationInWorkspaceFromGit(branchedApplication.getWorkspaceId(), applicationJson, branchedApplication.getId(), branchName) - ); + importExportApplicationService.importApplicationInWorkspaceFromGit( + branchedApplication.getWorkspaceId(), + applicationJson, + branchedApplication.getId(), + branchName)); }) .flatMap(application -> releaseFileLock(defaultApplicationId) - .then(this.addAnalyticsForGitOperation(AnalyticsEvents.GIT_DISCARD_CHANGES.getEventName(), application, null))) + .then(this.addAnalyticsForGitOperation( + AnalyticsEvents.GIT_DISCARD_CHANGES.getEventName(), application, null))) .map(responseUtils::updateApplicationWithDefaultResources); - - return Mono.create(sink -> discardChangeMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> discardChangeMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } /** @@ -2295,28 +2640,29 @@ public Mono<List<GitDocsDTO>> getGitDocUrls() { return Mono.just(gitDocsDTOList); } - private Mono<Application> deleteApplicationCreatedFromGitImport(String applicationId, String workspaceId, String repoName) { + private Mono<Application> deleteApplicationCreatedFromGitImport( + String applicationId, String workspaceId, String repoName) { Path repoSuffix = Paths.get(workspaceId, applicationId, repoName); - return fileUtils.deleteLocalRepo(repoSuffix) - .then(applicationPageService.deleteApplication(applicationId)); + return fileUtils.deleteLocalRepo(repoSuffix).then(applicationPageService.deleteApplication(applicationId)); } - private Mono<GitAuth> getSSHKeyForCurrentUser() { - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .flatMap(user -> gitDeployKeysRepository.findByEmail(user.getEmail())) .map(GitDeployKeys::getGitAuth); } - private boolean checkIsDatasourceNameConflict(List<Datasource> existingDatasources, - List<DatasourceStorage> importedDatasources, - List<Plugin> pluginList) { - // If we have an existing datasource with the same name but a different type from that in the repo, the import api should fail + private boolean checkIsDatasourceNameConflict( + List<Datasource> existingDatasources, + List<DatasourceStorage> importedDatasources, + List<Plugin> pluginList) { + // If we have an existing datasource with the same name but a different type from that in the repo, the import + // api should fail for (DatasourceStorage datasourceStorage : importedDatasources) { // Collect the datasource(existing in workspace) which has same as of imported datasource // As names are unique we will need filter first element to check if the plugin id is matched - Datasource filteredDatasource = existingDatasources - .stream() + Datasource filteredDatasource = existingDatasources.stream() .filter(datasource1 -> datasource1.getName().equals(datasourceStorage.getName())) .findFirst() .orElse(null); @@ -2325,7 +2671,8 @@ private boolean checkIsDatasourceNameConflict(List<Datasource> existingDatasourc if (filteredDatasource != null) { long matchCount = pluginList.stream() .filter(plugin -> { - final String pluginReference = plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName(); + final String pluginReference = + plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName(); return plugin.getId().equals(filteredDatasource.getPluginId()) && !datasourceStorage.getPluginId().equals(pluginReference); @@ -2335,7 +2682,6 @@ private boolean checkIsDatasourceNameConflict(List<Datasource> existingDatasourc return true; } } - } return false; } @@ -2347,31 +2693,39 @@ private boolean isInvalidDefaultApplicationGitMetadata(GitApplicationMetadata gi || StringUtils.isEmptyOrNull(gitApplicationMetadata.getGitAuth().getPublicKey()); } - private Mono<String> commitAndPushWithDefaultCommit(Path repoSuffix, - GitAuth auth, - GitApplicationMetadata gitApplicationMetadata, - GitDefaultCommitMessage reason) { - return gitExecutor.commitApplication(repoSuffix, DEFAULT_COMMIT_MESSAGE + reason.getReason(), APPSMITH_BOT_USERNAME, emailConfig.getSupportEmailAddress(), true, false) + private Mono<String> commitAndPushWithDefaultCommit( + Path repoSuffix, + GitAuth auth, + GitApplicationMetadata gitApplicationMetadata, + GitDefaultCommitMessage reason) { + return gitExecutor + .commitApplication( + repoSuffix, + DEFAULT_COMMIT_MESSAGE + reason.getReason(), + APPSMITH_BOT_USERNAME, + emailConfig.getSupportEmailAddress(), + true, + false) .onErrorResume(error -> { if (error instanceof EmptyCommitException) { return Mono.just(EMPTY_COMMIT_ERROR_MESSAGE); } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "commit", error.getMessage())); + return Mono.error( + new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "commit", error.getMessage())); }) - .flatMap(commitMessage -> - gitExecutor.pushApplication( - repoSuffix, - gitApplicationMetadata.getRemoteUrl(), - auth.getPublicKey(), - auth.getPrivateKey(), - gitApplicationMetadata.getBranchName()) - .map(pushResult -> { - if (pushResult.contains("REJECTED")) { - throw new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES); - } - return pushResult; - }) - ); + .flatMap(commitMessage -> gitExecutor + .pushApplication( + repoSuffix, + gitApplicationMetadata.getRemoteUrl(), + auth.getPublicKey(), + auth.getPrivateKey(), + gitApplicationMetadata.getBranchName()) + .map(pushResult -> { + if (pushResult.contains("REJECTED")) { + throw new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES); + } + return pushResult; + })); } public Mono<List<GitBranchDTO>> handleRepoNotFoundException(String defaultApplicationId) { @@ -2379,42 +2733,53 @@ public Mono<List<GitBranchDTO>> handleRepoNotFoundException(String defaultApplic // clone application to the local filesystem again and update the defaultBranch for the application // list branch and compare with branch applications and checkout if not exists - return getApplicationById(defaultApplicationId) - .flatMap(application -> { - GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); - Path repoPath = Paths.get(application.getWorkspaceId(), application.getId(), gitApplicationMetadata.getRepoName()); - GitAuth gitAuth = gitApplicationMetadata.getGitAuth(); - return gitExecutor.cloneApplication(repoPath, gitApplicationMetadata.getRemoteUrl(), gitAuth.getPrivateKey(), gitAuth.getPublicKey()) - .flatMap(defaultBranch -> gitExecutor.listBranches( - repoPath, - gitApplicationMetadata.getRemoteUrl(), - gitAuth.getPrivateKey(), - gitAuth.getPublicKey(), - false)) - .flatMap(gitBranchDTOList -> { - List<String> branchList = gitBranchDTOList.stream() - .filter(gitBranchDTO -> gitBranchDTO.getBranchName().contains("origin")) - .map(gitBranchDTO -> gitBranchDTO.getBranchName().replace("origin/", "")) - .collect(Collectors.toList()); - // Remove the default branch of Appsmith - branchList.remove(gitApplicationMetadata.getBranchName()); - - return Flux.fromIterable(branchList) - .flatMap(branchName -> applicationService.findByBranchNameAndDefaultApplicationId(branchName, application.getId(), applicationPermission.getReadPermission()) - // checkout the branch locally - .flatMap(application1 -> { - // Add the locally checked out branch to the branchList - GitBranchDTO gitBranchDTO = new GitBranchDTO(); - gitBranchDTO.setBranchName(branchName); - gitBranchDTO.setDefault(false); - gitBranchDTOList.add(gitBranchDTO); - return gitExecutor.checkoutRemoteBranch(repoPath, branchName); - }) - // Return empty mono when the branched application is not in db - .onErrorResume(throwable -> Mono.empty())) - .then(Mono.just(gitBranchDTOList)); - }); - }); + return getApplicationById(defaultApplicationId).flatMap(application -> { + GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); + Path repoPath = + Paths.get(application.getWorkspaceId(), application.getId(), gitApplicationMetadata.getRepoName()); + GitAuth gitAuth = gitApplicationMetadata.getGitAuth(); + return gitExecutor + .cloneApplication( + repoPath, + gitApplicationMetadata.getRemoteUrl(), + gitAuth.getPrivateKey(), + gitAuth.getPublicKey()) + .flatMap(defaultBranch -> gitExecutor.listBranches( + repoPath, + gitApplicationMetadata.getRemoteUrl(), + gitAuth.getPrivateKey(), + gitAuth.getPublicKey(), + false)) + .flatMap(gitBranchDTOList -> { + List<String> branchList = gitBranchDTOList.stream() + .filter(gitBranchDTO -> + gitBranchDTO.getBranchName().contains("origin")) + .map(gitBranchDTO -> + gitBranchDTO.getBranchName().replace("origin/", "")) + .collect(Collectors.toList()); + // Remove the default branch of Appsmith + branchList.remove(gitApplicationMetadata.getBranchName()); + + return Flux.fromIterable(branchList) + .flatMap(branchName -> applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, + application.getId(), + applicationPermission.getReadPermission()) + // checkout the branch locally + .flatMap(application1 -> { + // Add the locally checked out branch to the branchList + GitBranchDTO gitBranchDTO = new GitBranchDTO(); + gitBranchDTO.setBranchName(branchName); + gitBranchDTO.setDefault(false); + gitBranchDTOList.add(gitBranchDTO); + return gitExecutor.checkoutRemoteBranch(repoPath, branchName); + }) + // Return empty mono when the branched application is not in db + .onErrorResume(throwable -> Mono.empty())) + .then(Mono.just(gitBranchDTOList)); + }); + }); } @Override @@ -2442,45 +2807,50 @@ private Mono<GitPullDTO> pullAndRehydrateApplication(Application defaultApplicat if (isInvalidDefaultApplicationGitMetadata(gitData)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); } - Path repoSuffix = Paths.get(defaultApplication.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); + Path repoSuffix = Paths.get( + defaultApplication.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); - Mono<Application> branchedApplicationMono = applicationService - .findByBranchNameAndDefaultApplicationId(branchName, defaultApplication.getId(), applicationPermission.getEditPermission()); + Mono<Application> branchedApplicationMono = applicationService.findByBranchNameAndDefaultApplicationId( + branchName, defaultApplication.getId(), applicationPermission.getEditPermission()); return branchedApplicationMono .flatMap(branchedApplication -> { // git checkout and pull origin branchName try { - Mono<MergeStatusDTO> pullStatusMono = gitExecutor.checkoutToBranch(repoSuffix, branchName) + Mono<MergeStatusDTO> pullStatusMono = gitExecutor + .checkoutToBranch(repoSuffix, branchName) .then(gitExecutor.pullApplication( repoSuffix, gitData.getRemoteUrl(), branchName, gitData.getGitAuth().getPrivateKey(), - gitData.getGitAuth().getPublicKey() - )) + gitData.getGitAuth().getPublicKey())) .onErrorResume(error -> { if (error.getMessage().contains("conflict")) { - return Mono.error(new AppsmithException(AppsmithError.GIT_PULL_CONFLICTS, error.getMessage())); + return Mono.error(new AppsmithException( + AppsmithError.GIT_PULL_CONFLICTS, error.getMessage())); } else if (error.getMessage().contains("Nothing to fetch")) { MergeStatusDTO mergeStatus = new MergeStatusDTO(); - mergeStatus.setStatus("Nothing to fetch from remote. All changes are up to date."); + mergeStatus.setStatus( + "Nothing to fetch from remote. All changes are up to date."); mergeStatus.setMergeAble(true); return Mono.just(mergeStatus); } - return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "pull", error.getMessage())); + return Mono.error(new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, "pull", error.getMessage())); }) .cache(); // Rehydrate the application from file system - Mono<ApplicationJson> applicationJsonMono = pullStatusMono - .flatMap(status -> - fileUtils.reconstructApplicationJsonFromGitRepo( - branchedApplication.getWorkspaceId(), - branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(), - branchedApplication.getGitApplicationMetadata().getRepoName(), - branchName - ) - ); + Mono<ApplicationJson> applicationJsonMono = + pullStatusMono.flatMap(status -> fileUtils.reconstructApplicationJsonFromGitRepo( + branchedApplication.getWorkspaceId(), + branchedApplication + .getGitApplicationMetadata() + .getDefaultApplicationId(), + branchedApplication + .getGitApplicationMetadata() + .getRepoName(), + branchName)); return Mono.zip(pullStatusMono, Mono.just(branchedApplication), applicationJsonMono); } catch (IOException e) { @@ -2495,48 +2865,58 @@ private Mono<GitPullDTO> pullAndRehydrateApplication(Application defaultApplicat // Get the latest application with all the changes // Commit and push changes to sync with remote return importExportApplicationService - .importApplicationInWorkspaceFromGit(branchedApplication.getWorkspaceId(), applicationJson, branchedApplication.getId(), branchName) + .importApplicationInWorkspaceFromGit( + branchedApplication.getWorkspaceId(), + applicationJson, + branchedApplication.getId(), + branchName) .flatMap(application -> addAnalyticsForGitOperation( AnalyticsEvents.GIT_PULL.getEventName(), application, - application.getGitApplicationMetadata().getIsRepoPrivate() - ) - .thenReturn(application) - ) + application + .getGitApplicationMetadata() + .getIsRepoPrivate()) + .thenReturn(application)) .flatMap(application -> { GitCommitDTO commitDTO = new GitCommitDTO(); - commitDTO.setCommitMessage(DEFAULT_COMMIT_MESSAGE + GitDefaultCommitMessage.SYNC_WITH_REMOTE_AFTER_PULL.getReason()); + commitDTO.setCommitMessage(DEFAULT_COMMIT_MESSAGE + + GitDefaultCommitMessage.SYNC_WITH_REMOTE_AFTER_PULL.getReason()); commitDTO.setDoPush(true); GitPullDTO gitPullDTO = new GitPullDTO(); gitPullDTO.setMergeStatus(status); - gitPullDTO.setApplication(responseUtils.updateApplicationWithDefaultResources(application)); + gitPullDTO.setApplication( + responseUtils.updateApplicationWithDefaultResources(application)); // Make commit and push after pull is successful to have a clean repo - return this.commitApplication(commitDTO, application.getGitApplicationMetadata().getDefaultApplicationId(), branchName) + return this.commitApplication( + commitDTO, + application + .getGitApplicationMetadata() + .getDefaultApplicationId(), + branchName) .thenReturn(gitPullDTO); }); }); } - private Mono<Application> addAnalyticsForGitOperation(String eventName, Application application, Boolean isRepoPrivate) { + private Mono<Application> addAnalyticsForGitOperation( + String eventName, Application application, Boolean isRepoPrivate) { return addAnalyticsForGitOperation(eventName, application, "", "", isRepoPrivate, false); } - private Mono<Application> addAnalyticsForGitOperation(String eventName, - Application application, - String errorType, - String errorMessage, - Boolean isRepoPrivate) { + private Mono<Application> addAnalyticsForGitOperation( + String eventName, Application application, String errorType, String errorMessage, Boolean isRepoPrivate) { return addAnalyticsForGitOperation(eventName, application, errorType, errorMessage, isRepoPrivate, false); } - private Mono<Application> addAnalyticsForGitOperation(String eventName, - Application application, - String errorType, - String errorMessage, - Boolean isRepoPrivate, - Boolean isSystemGenerated) { + private Mono<Application> addAnalyticsForGitOperation( + String eventName, + Application application, + String errorType, + String errorMessage, + Boolean isRepoPrivate, + Boolean isSystemGenerated) { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); Map<String, Object> analyticsProps = new HashMap<>(); if (gitData != null) { @@ -2551,23 +2931,27 @@ private Mono<Application> addAnalyticsForGitOperation(String eventName, analyticsProps.put("errorType", errorType); } analyticsProps.putAll(Map.of( - FieldName.ORGANIZATION_ID, defaultIfNull(application.getWorkspaceId(), ""), - "orgId", defaultIfNull(application.getWorkspaceId(), ""), - "branchApplicationId", defaultIfNull(application.getId(), ""), - "isRepoPrivate", defaultIfNull(isRepoPrivate, ""), - "isSystemGenerated", defaultIfNull(isSystemGenerated, "") - )); - final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.APPLICATION, application - ); + FieldName.ORGANIZATION_ID, + defaultIfNull(application.getWorkspaceId(), ""), + "orgId", + defaultIfNull(application.getWorkspaceId(), ""), + "branchApplicationId", + defaultIfNull(application.getId(), ""), + "isRepoPrivate", + defaultIfNull(isRepoPrivate, ""), + "isSystemGenerated", + defaultIfNull(isSystemGenerated, ""))); + final Map<String, Object> eventData = + Map.of(FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.APPLICATION, application); analyticsProps.put(FieldName.EVENT_DATA, eventData); - return sessionUserService.getCurrentUser() - .flatMap(user -> analyticsService.sendEvent(eventName, user.getUsername(), analyticsProps).thenReturn(application)); + return sessionUserService.getCurrentUser().flatMap(user -> analyticsService + .sendEvent(eventName, user.getUsername(), analyticsProps) + .thenReturn(application)); } private Mono<Boolean> addFileLock(String defaultApplicationId) { - return redisUtils.addFileLock(defaultApplicationId) + return redisUtils + .addFileLock(defaultApplicationId) .retryWhen(Retry.fixedDelay(MAX_RETRIES, RETRY_DELAY) .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> { throw new AppsmithException(AppsmithError.GIT_FILE_IN_USE); @@ -2580,26 +2964,26 @@ private Mono<Boolean> releaseFileLock(String defaultApplicationId) { @Override public Mono<Boolean> isRepoLimitReached(String workspaceId, Boolean isClearCache) { - return gitCloudServicesUtils.getPrivateRepoLimitForOrg(workspaceId, isClearCache) + return gitCloudServicesUtils + .getPrivateRepoLimitForOrg(workspaceId, isClearCache) .flatMap(limit -> { if (limit == -1) { return Mono.just(Boolean.FALSE); } - return this.getApplicationCountWithPrivateRepo(workspaceId) - .map(privateRepoCount -> { - // isClearCache is false for the commit flow - // isClearCache is true for the connect & import flow - if (!isClearCache) { - if (privateRepoCount <= limit) { - return Boolean.FALSE; - } - } else { - if (privateRepoCount < limit) { - return Boolean.FALSE; - } - } - return Boolean.TRUE; - }); + return this.getApplicationCountWithPrivateRepo(workspaceId).map(privateRepoCount -> { + // isClearCache is false for the commit flow + // isClearCache is true for the connect & import flow + if (!isClearCache) { + if (privateRepoCount <= limit) { + return Boolean.FALSE; + } + } else { + if (privateRepoCount < limit) { + return Boolean.FALSE; + } + } + return Boolean.TRUE; + }); }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GoogleRecaptchaServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GoogleRecaptchaServiceCEImpl.java index 437f0d715c09..c2d744eb7ff7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GoogleRecaptchaServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GoogleRecaptchaServiceCEImpl.java @@ -28,9 +28,10 @@ public class GoogleRecaptchaServiceCEImpl implements CaptchaServiceCE { private static final Long TIMEOUT_IN_MILLIS = 10000L; @Autowired - public GoogleRecaptchaServiceCEImpl(WebClient.Builder webClientBuilder, - GoogleRecaptchaConfig googleRecaptchaConfig, - ObjectMapper objectMapper) { + public GoogleRecaptchaServiceCEImpl( + WebClient.Builder webClientBuilder, + GoogleRecaptchaConfig googleRecaptchaConfig, + ObjectMapper objectMapper) { this.webClient = webClientBuilder.baseUrl(BASE_URL).build(); this.googleRecaptchaConfig = googleRecaptchaConfig; this.objectMapper = objectMapper; @@ -46,11 +47,11 @@ public Mono<Boolean> verify(String recaptchaResponse) { // API Docs: https://developers.google.com/recaptcha/docs/v3 return webClient .get() - .uri(uriBuilder -> uriBuilder.path(VERIFY_PATH) + .uri(uriBuilder -> uriBuilder + .path(VERIFY_PATH) .queryParam("response", recaptchaResponse) .queryParam("secret", googleRecaptchaConfig.getSecretKey()) - .build() - ) + .build()) .retrieve() .bodyToMono(String.class) .flatMap(stringBody -> { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GroupServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GroupServiceCEImpl.java index f45cd6677700..d1e532e723e0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GroupServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GroupServiceCEImpl.java @@ -22,7 +22,6 @@ import java.util.Set; import java.util.stream.Collectors; - @Slf4j public class GroupServiceCEImpl extends BaseService<GroupRepository, Group, String> implements GroupServiceCE { @@ -30,13 +29,14 @@ public class GroupServiceCEImpl extends BaseService<GroupRepository, Group, Stri private final SessionUserService sessionUserService; @Autowired - public GroupServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - GroupRepository repository, - AnalyticsService analyticsService, - SessionUserService sessionUserService) { + public GroupServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + GroupRepository repository, + AnalyticsService analyticsService, + SessionUserService sessionUserService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.repository = repository; this.sessionUserService = sessionUserService; @@ -50,10 +50,12 @@ public Flux<Group> get(MultiValueMap<String, String> params) { // Add conditions to the query if there are any filter params provided if (params != null && !params.isEmpty()) { params.entrySet().stream() - .forEach(entry -> query.addCriteria(Criteria.where(entry.getKey()).in(entry.getValue()))); + .forEach(entry -> + query.addCriteria(Criteria.where(entry.getKey()).in(entry.getValue()))); } - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .map(user -> { // Filtering the groups by the user's current workspace String workspaceId = user.getCurrentWorkspaceId(); @@ -89,22 +91,20 @@ public Flux<Group> getAllById(Set<String> ids) { public Flux<Group> createDefaultGroupsForWorkspace(String workspaceId) { log.debug("Going to create default groups for workspace: {}", workspaceId); - return this.repository.getAllByWorkspaceId(AclConstants.DEFAULT_ORG_ID) - .flatMap(group -> { - Group newGroup = new Group(); - newGroup.setName(group.getName()); - newGroup.setDisplayName(group.getDisplayName()); - newGroup.setWorkspaceId(workspaceId); - newGroup.setPermissions(group.getPermissions()); - newGroup.setIsDefault(group.getIsDefault()); - log.debug("Creating group {} for org: {}", group.getName(), workspaceId); - return create(newGroup); - }); + return this.repository.getAllByWorkspaceId(AclConstants.DEFAULT_ORG_ID).flatMap(group -> { + Group newGroup = new Group(); + newGroup.setName(group.getName()); + newGroup.setDisplayName(group.getDisplayName()); + newGroup.setWorkspaceId(workspaceId); + newGroup.setPermissions(group.getPermissions()); + newGroup.setIsDefault(group.getIsDefault()); + log.debug("Creating group {} for org: {}", group.getName(), workspaceId); + return create(newGroup); + }); } @Override public Flux<Group> getByWorkspaceId(String workspaceId) { return this.repository.getAllByWorkspaceId(workspaceId); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/HealthCheckServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/HealthCheckServiceCEImpl.java index 92ba2b0564df..4c3bc7242f0c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/HealthCheckServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/HealthCheckServiceCEImpl.java @@ -15,23 +15,22 @@ import java.util.concurrent.TimeoutException; import java.util.function.Function; - @Slf4j public class HealthCheckServiceCEImpl implements HealthCheckServiceCE { private final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory; private final ReactiveMongoTemplate reactiveMongoTemplate; - public HealthCheckServiceCEImpl(ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, - ReactiveMongoTemplate reactiveMongoTemplate) { + public HealthCheckServiceCEImpl( + ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, + ReactiveMongoTemplate reactiveMongoTemplate) { this.reactiveRedisConnectionFactory = reactiveRedisConnectionFactory; this.reactiveMongoTemplate = reactiveMongoTemplate; } @Override public Mono<String> getHealth() { - return Mono.zip(getRedisHealth(), getMongoHealth()) - .map(tuple -> "All systems are Up"); + return Mono.zip(getRedisHealth(), getMongoHealth()).map(tuple -> "All systems are Up"); } @Override @@ -40,8 +39,12 @@ public Mono<Health> getRedisHealth() { log.warn("Redis health check timed out: {}", error.getMessage()); return new AppsmithException(AppsmithError.HEALTHCHECK_TIMEOUT, "Redis"); }; - RedisReactiveHealthIndicator redisReactiveHealthIndicator = new RedisReactiveHealthIndicator(reactiveRedisConnectionFactory); - return redisReactiveHealthIndicator.health().timeout(Duration.ofSeconds(3)).onErrorMap(TimeoutException.class, healthTimeout); + RedisReactiveHealthIndicator redisReactiveHealthIndicator = + new RedisReactiveHealthIndicator(reactiveRedisConnectionFactory); + return redisReactiveHealthIndicator + .health() + .timeout(Duration.ofSeconds(3)) + .onErrorMap(TimeoutException.class, healthTimeout); } @Override @@ -50,8 +53,12 @@ public Mono<Health> getMongoHealth() { log.warn("MongoDB health check timed out: {}", error.getMessage()); return new AppsmithException(AppsmithError.HEALTHCHECK_TIMEOUT, "Mongo"); }; - MongoReactiveHealthIndicator mongoReactiveHealthIndicator = new MongoReactiveHealthIndicator(reactiveMongoTemplate); - return mongoReactiveHealthIndicator.health().timeout(Duration.ofSeconds(1)).onErrorMap(TimeoutException.class, healthTimeout); + MongoReactiveHealthIndicator mongoReactiveHealthIndicator = + new MongoReactiveHealthIndicator(reactiveMongoTemplate); + return mongoReactiveHealthIndicator + .health() + .timeout(Duration.ofSeconds(1)) + .onErrorMap(TimeoutException.class, healthTimeout); } private boolean isUp(Health health) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ItemServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ItemServiceCE.java index 5d33763a8dc5..cf6758ff8cc4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ItemServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ItemServiceCE.java @@ -12,5 +12,4 @@ public interface ItemServiceCE { Flux<ItemDTO> get(MultiValueMap<String, String> params); Mono<ActionDTO> addItemToPage(AddItemToPageDTO addItemToPageDTO); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ItemServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ItemServiceCEImpl.java index 84fbab02b5c4..13951b3c6bc7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ItemServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ItemServiceCEImpl.java @@ -20,7 +20,6 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; - @Slf4j public class ItemServiceCEImpl implements ItemServiceCE { @@ -31,11 +30,12 @@ public class ItemServiceCEImpl implements ItemServiceCE { private final LayoutActionService layoutActionService; private static final String RAPID_API_PLUGIN = "rapidapi-plugin"; - public ItemServiceCEImpl(ApiTemplateService apiTemplateService, - PluginService pluginService, - MarketplaceService marketplaceService, - NewActionService newActionService, - LayoutActionService layoutActionService) { + public ItemServiceCEImpl( + ApiTemplateService apiTemplateService, + PluginService pluginService, + MarketplaceService marketplaceService, + NewActionService newActionService, + LayoutActionService layoutActionService) { this.apiTemplateService = apiTemplateService; this.pluginService = pluginService; this.marketplaceService = marketplaceService; @@ -53,15 +53,13 @@ public Flux<ItemDTO> get(MultiValueMap<String, String> params) { } else if (params.getFirst(FieldName.APPLICATION_ID) != null) { return Flux.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION)); } else if (params.getFirst(FieldName.PROVIDER_ID) != null) { - return apiTemplateService - .get(params) - .map(apiTemplate -> { - ItemDTO itemDTO = new ItemDTO(); - itemDTO.setItem(apiTemplate); - itemDTO.setType(ItemType.TEMPLATE); - - return itemDTO; - }); + return apiTemplateService.get(params).map(apiTemplate -> { + ItemDTO itemDTO = new ItemDTO(); + itemDTO.setItem(apiTemplate); + itemDTO.setType(ItemType.TEMPLATE); + + return itemDTO; + }); } return Flux.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION)); @@ -93,9 +91,13 @@ public Mono<ActionDTO> addItemToPage(AddItemToPageDTO addItemToPageDTO) { // Set Action Fields action.setActionConfiguration(apiTemplate.getActionConfiguration()); - if (apiTemplate.getApiTemplateConfiguration().getSampleResponse() != null && - apiTemplate.getApiTemplateConfiguration().getSampleResponse().getBody() != null) { - action.setCacheResponse(apiTemplate.getApiTemplateConfiguration().getSampleResponse().getBody().toString()); + if (apiTemplate.getApiTemplateConfiguration().getSampleResponse() != null + && apiTemplate.getApiTemplateConfiguration().getSampleResponse().getBody() != null) { + action.setCacheResponse(apiTemplate + .getApiTemplateConfiguration() + .getSampleResponse() + .getBody() + .toString()); } log.debug("Going to subscribe marketplace provider : {} and then create action", apiTemplate.getProviderId()); @@ -106,7 +108,7 @@ public Mono<ActionDTO> addItemToPage(AddItemToPageDTO addItemToPageDTO) { // Assume that we are only adding rapid api templates right now. Set the package to rapid-api forcibly .then(pluginService.findByPackageName(RAPID_API_PLUGIN)) .map(plugin -> { - //Set Datasource + // Set Datasource Datasource datasource = new Datasource(); datasource.setDatasourceConfiguration(apiTemplate.getDatasourceConfiguration()); datasource.setName(apiTemplate.getDatasourceConfiguration().getUrl()); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCE.java index b8d586cf4fff..72c9380c0fe6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCE.java @@ -13,9 +13,11 @@ public interface LayoutActionServiceCE { Mono<LayoutDTO> updateLayout(String pageId, String applicationId, String layoutId, Layout layout); - Mono<LayoutDTO> updateLayout(String defaultPageId, String defaultApplicationId, String layoutId, Layout layout, String branchName); + Mono<LayoutDTO> updateLayout( + String defaultPageId, String defaultApplicationId, String layoutId, Layout layout, String branchName); - Mono<Integer> updateMultipleLayouts(String defaultApplicationId, String branchName, UpdateMultiplePageLayoutDTO updateMultiplePageLayoutDTO); + Mono<Integer> updateMultipleLayouts( + String defaultApplicationId, String branchName, UpdateMultiplePageLayoutDTO updateMultiplePageLayoutDTO); Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO); @@ -48,5 +50,4 @@ public interface LayoutActionServiceCE { Mono<ActionDTO> deleteUnpublishedAction(String id); Mono<ActionDTO> deleteUnpublishedAction(String id, String branchName); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java index 10eb7c772819..f91268c69044 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java @@ -70,7 +70,6 @@ import static java.lang.Boolean.FALSE; import static java.util.stream.Collectors.toSet; - @Slf4j @RequiredArgsConstructor public class LayoutActionServiceCEImpl implements LayoutActionServiceCE { @@ -89,9 +88,8 @@ public class LayoutActionServiceCEImpl implements LayoutActionServiceCE { private final PagePermission pagePermission; private final ActionPermission actionPermission; - - private final String layoutOnLoadActionErrorToastMessage = "A cyclic dependency error has been encountered on current page, \nqueries on page load will not run. \n Please check debugger and Appsmith documentation for more information"; - + private final String layoutOnLoadActionErrorToastMessage = + "A cyclic dependency error has been encountered on current page, \nqueries on page load will not run. \n Please check debugger and Appsmith documentation for more information"; /** * Called by Action controller to create Action @@ -103,7 +101,8 @@ public Mono<ActionDTO> createAction(ActionDTO action) { } return this.createSingleAction(action, Boolean.FALSE) - .flatMap(savedAction -> collectionService.addSingleActionToCollection(action.getCollectionId(), savedAction)); + .flatMap(savedAction -> + collectionService.addSingleActionToCollection(action.getCollectionId(), savedAction)); } @Override @@ -112,31 +111,34 @@ public Mono<ActionDTO> updateAction(String id, ActionDTO action) { // Since the policies are server only concept, we should first set this to null. action.setPolicies(null); - //The change was not in CollectionId, just go ahead and update normally + // The change was not in CollectionId, just go ahead and update normally if (action.getCollectionId() == null) { return this.updateSingleAction(id, action) - .flatMap(updatedAction -> this.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); + .flatMap(updatedAction -> this.updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); } else if (action.getCollectionId().length() == 0) { - //The Action has been removed from existing collection. + // The Action has been removed from existing collection. return newActionService .getById(id) - .flatMap(action1 -> collectionService.removeSingleActionFromCollection(action1.getUnpublishedAction().getCollectionId(), - Mono.just(action1))) + .flatMap(action1 -> collectionService.removeSingleActionFromCollection( + action1.getUnpublishedAction().getCollectionId(), Mono.just(action1))) .flatMap(action1 -> { log.debug("Action {} has been removed from its collection.", action1.getId()); action.setCollectionId(null); return this.updateSingleAction(id, action) - .flatMap(updatedAction -> this.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); + .flatMap(updatedAction -> this.updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); }); } else { - //If the code flow has reached this point, that means that the collectionId has been changed to another collection. - //Remove the action from previous collection and add it to the new collection. + // If the code flow has reached this point, that means that the collectionId has been changed to another + // collection. + // Remove the action from previous collection and add it to the new collection. return newActionService .getById(id) .flatMap(action1 -> { if (action1.getUnpublishedAction().getCollectionId() != null) { - return collectionService.removeSingleActionFromCollection(action1.getUnpublishedAction().getCollectionId(), - Mono.just(action1)); + return collectionService.removeSingleActionFromCollection( + action1.getUnpublishedAction().getCollectionId(), Mono.just(action1)); } return Mono.just(newActionService.generateActionByViewMode(action1, false)); }) @@ -144,12 +146,16 @@ public Mono<ActionDTO> updateAction(String id, ActionDTO action) { .flatMap(action1 -> { ActionDTO unpublishedAction = action1.getUnpublishedAction(); unpublishedAction.setId(action1.getId()); - return collectionService.addSingleActionToCollection(action.getCollectionId(), unpublishedAction); + return collectionService.addSingleActionToCollection( + action.getCollectionId(), unpublishedAction); }) .flatMap(action1 -> { - log.debug("Action {} removed from its previous collection and added to the new collection", action1.getId()); + log.debug( + "Action {} removed from its previous collection and added to the new collection", + action1.getId()); return this.updateSingleAction(id, action) - .flatMap(updatedAction -> this.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); + .flatMap(updatedAction -> this.updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); }); } } @@ -161,8 +167,10 @@ public Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO) { final String destinationPageId = actionMoveDTO.getDestinationPageId(); action.setPageId(destinationPageId); - Mono<NewPage> destinationPageMono = newPageService.findById(destinationPageId, pagePermission.getActionCreatePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, destinationPageId))); + Mono<NewPage> destinationPageMono = newPageService + .findById(destinationPageId, pagePermission.getActionCreatePermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, destinationPageId))); /* * The following steps are followed here : @@ -178,14 +186,18 @@ public Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO) { if (action.getDefaultResources() == null) { log.debug("Default resource should not be empty for move action: {}", action.getId()); DefaultResources defaultResources = new DefaultResources(); - defaultResources.setPageId(destinationPage.getDefaultResources().getPageId()); + defaultResources.setPageId( + destinationPage.getDefaultResources().getPageId()); action.setDefaultResources(defaultResources); } else { - action.getDefaultResources().setPageId(destinationPage.getDefaultResources().getPageId()); + action.getDefaultResources() + .setPageId(destinationPage.getDefaultResources().getPageId()); } return newActionService .updateUnpublishedAction(action.getId(), action) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, actionMoveDTO.getAction().getId()))); + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + actionMoveDTO.getAction().getId()))); }) .flatMap(savedAction -> // fetch the unpublished source page @@ -200,12 +212,16 @@ public Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO) { return Flux.fromIterable(page.getLayouts()) .flatMap(layout -> { layout.setDsl(this.unescapeMongoSpecialCharacters(layout)); - return updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout); + return updateLayout( + page.getId(), page.getApplicationId(), layout.getId(), layout); }) .collect(toSet()); }) // fetch the unpublished destination page - .then(newPageService.findPageById(actionMoveDTO.getDestinationPageId(), pagePermission.getActionCreatePermission(), false)) + .then(newPageService.findPageById( + actionMoveDTO.getDestinationPageId(), + pagePermission.getActionCreatePermission(), + false)) .flatMap(page -> { if (page.getLayouts() == null) { return Mono.empty(); @@ -215,7 +231,8 @@ public Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO) { return Flux.fromIterable(page.getLayouts()) .flatMap(layout -> { layout.setDsl(this.unescapeMongoSpecialCharacters(layout)); - return updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout); + return updateLayout( + page.getId(), page.getApplicationId(), layout.getId(), layout); }) .collect(toSet()); }) @@ -228,11 +245,12 @@ public Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO, String branchName // As client only have default page Id it will be sent under action and not the action.defaultResources Mono<String> toPageMono = newPageService - .findByBranchNameAndDefaultPageId(branchName, actionMoveDTO.getDestinationPageId(), pagePermission.getActionCreatePermission()) + .findByBranchNameAndDefaultPageId( + branchName, actionMoveDTO.getDestinationPageId(), pagePermission.getActionCreatePermission()) .map(NewPage::getId); - Mono<NewAction> branchedActionMono = newActionService - .findByBranchNameAndDefaultActionId(branchName, actionMoveDTO.getAction().getId(), actionPermission.getEditPermission()); + Mono<NewAction> branchedActionMono = newActionService.findByBranchNameAndDefaultActionId( + branchName, actionMoveDTO.getAction().getId(), actionPermission.getEditPermission()); return Mono.zip(toPageMono, branchedActionMono) .flatMap(tuple -> { @@ -242,7 +260,8 @@ public Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO, String branchName actionMoveDTO.setDestinationPageId(toPageId); moveAction.setPageId(branchedAction.getUnpublishedAction().getPageId()); moveAction.setId(branchedAction.getId()); - moveAction.setDefaultResources(branchedAction.getUnpublishedAction().getDefaultResources()); + moveAction.setDefaultResources( + branchedAction.getUnpublishedAction().getDefaultResources()); return moveAction(actionMoveDTO); }) .map(responseUtils::updateActionDTOWithDefaultResources); @@ -263,12 +282,14 @@ public Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO, String branchName * @param escapedWidgetNames * @return */ - private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL(JSONObject dsl, - Set<String> widgetNames, - Map<String, Set<String>> widgetDynamicBindingsMap, - String pageId, - String layoutId, - Set<String> escapedWidgetNames) throws AppsmithException { + private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL( + JSONObject dsl, + Set<String> widgetNames, + Map<String, Set<String>> widgetDynamicBindingsMap, + String pageId, + String layoutId, + Set<String> escapedWidgetNames) + throws AppsmithException { if (dsl.get(FieldName.WIDGET_NAME) == null) { // This isn't a valid widget configuration. No need to traverse this. return dsl; @@ -293,10 +314,13 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL(JSONObject dsl String[] fields = fieldPath.split("[].\\[]"); // For nested fields, the parent dsl to search in would shift by one level every iteration Object parent = dsl; - Iterator<String> fieldsIterator = Arrays.stream(fields).filter(fieldToken -> !fieldToken.isBlank()).iterator(); + Iterator<String> fieldsIterator = Arrays.stream(fields) + .filter(fieldToken -> !fieldToken.isBlank()) + .iterator(); boolean isLeafNode = false; Object oldParent; - // This loop will end at either a leaf node, or the last identified JSON field (by throwing an exception) + // This loop will end at either a leaf node, or the last identified JSON field (by throwing an + // exception) // Valid forms of the fieldPath for this search could be: // root.field.list[index].childField.anotherList.indexWithDotOperator.multidimensionalList[index1][index2] while (fieldsIterator.hasNext()) { @@ -312,18 +336,45 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL(JSONObject dsl parent = ((List) parent).get(Integer.parseInt(nextKey)); } catch (IndexOutOfBoundsException e) { // The index being referred does not exist. Hence the path would not exist. - throw new AppsmithException(AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE, widgetType, - widgetName, widgetId, fieldPath, pageId, layoutId, oldParent, nextKey, "Index out of bounds for list"); + throw new AppsmithException( + AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE, + widgetType, + widgetName, + widgetId, + fieldPath, + pageId, + layoutId, + oldParent, + nextKey, + "Index out of bounds for list"); } } else { - throw new AppsmithException(AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE, widgetType, - widgetName, widgetId, fieldPath, pageId, layoutId, oldParent, nextKey, "Child of list is not in an indexed path"); + throw new AppsmithException( + AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE, + widgetType, + widgetName, + widgetId, + fieldPath, + pageId, + layoutId, + oldParent, + nextKey, + "Child of list is not in an indexed path"); } } // After updating the parent, check for the types if (parent == null) { - throw new AppsmithException(AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE, widgetType, - widgetName, widgetId, fieldPath, pageId, layoutId, oldParent, nextKey, "New element is null"); + throw new AppsmithException( + AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE, + widgetType, + widgetName, + widgetId, + fieldPath, + pageId, + layoutId, + oldParent, + nextKey, + "New element is null"); } else if (parent instanceof String) { // If we get String value, then this is a leaf node isLeafNode = true; @@ -336,15 +387,27 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL(JSONObject dsl if (!MustacheHelper.laxIsBindingPresentInString((String) parent)) { try { String bindingAsString = objectMapper.writeValueAsString(parent); - throw new AppsmithException(AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE, widgetType, - widgetName, widgetId, fieldPath, pageId, layoutId, bindingAsString, nextKey, "Binding path has no mustache bindings"); + throw new AppsmithException( + AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE, + widgetType, + widgetName, + widgetId, + fieldPath, + pageId, + layoutId, + bindingAsString, + nextKey, + "Binding path has no mustache bindings"); } catch (JsonProcessingException e) { throw new AppsmithException(AppsmithError.JSON_PROCESSING_ERROR, parent); } } // Stricter extraction of dynamic bindings - Set<String> mustacheKeysFromFields = MustacheHelper.extractMustacheKeysFromFields(parent).stream().map(token -> token.getValue()).collect(Collectors.toSet()); + Set<String> mustacheKeysFromFields = + MustacheHelper.extractMustacheKeysFromFields(parent).stream() + .map(token -> token.getValue()) + .collect(Collectors.toSet()); String completePath = widgetName + "." + fieldPath; if (widgetDynamicBindingsMap.containsKey(completePath)) { @@ -370,7 +433,8 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL(JSONObject dsl // If the children tag exists and there are entries within it if (!CollectionUtils.isEmpty(data)) { object.putAll(data); - JSONObject child = extractAllWidgetNamesAndDynamicBindingsFromDSL(object, widgetNames, widgetDynamicBindingsMap, pageId, layoutId, escapedWidgetNames); + JSONObject child = extractAllWidgetNamesAndDynamicBindingsFromDSL( + object, widgetNames, widgetDynamicBindingsMap, pageId, layoutId, escapedWidgetNames); newChildren.add(child); } } @@ -412,23 +476,25 @@ public Mono<Boolean> isNameAllowed(String pageId, String layoutId, String newNam Mono<Set<String>> actionNamesInPageMono = newActionService .getUnpublishedActions(params) - .flatMap( - actionDTO -> { - /* - This is unexpected. Every action inside a JS collection should have a collectionId. - But there are a few documents found for plugin type JS inside newAction collection that don't have any collectionId. - The reason could be due to the lack of transactional behaviour when multiple inserts/updates that take place - during JS action creation. A detailed RCA is documented here - https://www.notion.so/appsmith/RCA-JSObject-name-already-exists-Please-use-a-different-name-e09c407f0ddb4653bd3974f3703408e6 - */ - if (actionDTO.getPluginType().equals(PluginType.JS) && !StringUtils.hasLength(actionDTO.getCollectionId())) { - log.debug("JS Action with Id: {} doesn't have any collection Id under pageId: {}", actionDTO.getId(), pageId); - return Mono.empty(); - } else { - return Mono.just(actionDTO); - } - } - ) + .flatMap(actionDTO -> { + /* + This is unexpected. Every action inside a JS collection should have a collectionId. + But there are a few documents found for plugin type JS inside newAction collection that don't have any collectionId. + The reason could be due to the lack of transactional behaviour when multiple inserts/updates that take place + during JS action creation. A detailed RCA is documented here + https://www.notion.so/appsmith/RCA-JSObject-name-already-exists-Please-use-a-different-name-e09c407f0ddb4653bd3974f3703408e6 + */ + if (actionDTO.getPluginType().equals(PluginType.JS) + && !StringUtils.hasLength(actionDTO.getCollectionId())) { + log.debug( + "JS Action with Id: {} doesn't have any collection Id under pageId: {}", + actionDTO.getId(), + pageId); + return Mono.empty(); + } else { + return Mono.just(actionDTO); + } + }) .map(ActionDTO::getValidName) .collect(toSet()); @@ -439,7 +505,6 @@ public Mono<Boolean> isNameAllowed(String pageId, String layoutId, String newNam Mono<Set<String>> widgetNamesMono = Mono.just(Set.of()); Mono<Set<String>> actionCollectionNamesMono = Mono.just(Set.of()); - // Widget and collection names cannot collide with FQNs because of the dot operator // Hence we can avoid unnecessary DB calls if (!isFQN) { @@ -450,16 +515,19 @@ public Mono<Boolean> isNameAllowed(String pageId, String layoutId, String newNam List<Layout> layouts = page.getLayouts(); for (Layout layout : layouts) { if (layoutId.equals(layout.getId())) { - if (layout.getWidgetNames() != null && layout.getWidgetNames().size() > 0) { + if (layout.getWidgetNames() != null + && layout.getWidgetNames().size() > 0) { return Mono.just(layout.getWidgetNames()); } // In case of no widget names (which implies that there is no DSL), return an empty set. return Mono.just(new HashSet<>()); } } - return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.LAYOUT_ID, layoutId)); + return Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.LAYOUT_ID, layoutId)); }); - actionCollectionNamesMono = actionCollectionService.getActionCollectionsByViewMode(params, false) + actionCollectionNamesMono = actionCollectionService + .getActionCollectionsByViewMode(params, false) .map(ActionCollectionDTO::getName) .collect(toSet()) .switchIfEmpty(Mono.just(Set.of())); @@ -503,30 +571,35 @@ public Mono<ActionDTO> updateSingleAction(String id, ActionDTO action) { .updateUnpublishedAction(id, action) .flatMap(newActionService::populateHintMessages) .cache(); - } @Override - public Mono<ActionDTO> updateSingleActionWithBranchName(String defaultActionId, ActionDTO action, String branchName) { + public Mono<ActionDTO> updateSingleActionWithBranchName( + String defaultActionId, ActionDTO action, String branchName) { String pageId = action.getPageId(); action.setApplicationId(null); action.setPageId(null); - return newActionService.findByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getEditPermission()) + return newActionService + .findByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getEditPermission()) .flatMap(newAction -> updateSingleAction(newAction.getId(), action)) .flatMap(updatedAction -> this.updatePageLayoutsByPageId(pageId).thenReturn(updatedAction)) .map(responseUtils::updateActionDTOWithDefaultResources) - .zipWith(newPageService.findPageById(pageId, pagePermission.getEditPermission(), false), (actionDTO, pageDTO) -> { - // redundant check - if (pageDTO.getLayouts().size() > 0) { - actionDTO.setErrorReports(pageDTO.getLayouts().get(0).getLayoutOnLoadActionErrors()); - } - return actionDTO; - }); + .zipWith( + newPageService.findPageById(pageId, pagePermission.getEditPermission(), false), + (actionDTO, pageDTO) -> { + // redundant check + if (pageDTO.getLayouts().size() > 0) { + actionDTO.setErrorReports( + pageDTO.getLayouts().get(0).getLayoutOnLoadActionErrors()); + } + return actionDTO; + }); } @Override public Mono<ActionDTO> setExecuteOnLoad(String id, Boolean isExecuteOnLoad) { - return newActionService.findById(id, actionPermission.getEditPermission()) + return newActionService + .findById(id, actionPermission.getEditPermission()) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))) .flatMap(newAction -> { ActionDTO action = newAction.getUnpublishedAction(); @@ -536,16 +609,16 @@ public Mono<ActionDTO> setExecuteOnLoad(String id, Boolean isExecuteOnLoad) { newAction.setUnpublishedAction(action); - return newActionService.save(newAction) - .flatMap(savedAction -> updatePageLayoutsByPageId(savedAction.getUnpublishedAction().getPageId()) - .then(newActionService.generateActionByViewMode(savedAction, false))); - + return newActionService.save(newAction).flatMap(savedAction -> updatePageLayoutsByPageId( + savedAction.getUnpublishedAction().getPageId()) + .then(newActionService.generateActionByViewMode(savedAction, false))); }); } @Override public Mono<ActionDTO> setExecuteOnLoad(String defaultActionId, String branchName, Boolean isExecuteOnLoad) { - return newActionService.findByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getEditPermission()) + return newActionService + .findByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getEditPermission()) .flatMap(branchedAction -> setExecuteOnLoad(branchedAction.getId(), isExecuteOnLoad)) .map(responseUtils::updateActionDTOWithDefaultResources); } @@ -555,9 +628,9 @@ public Mono<ActionDTO> setExecuteOnLoad(String defaultActionId, String branchNam * - Update page layout since a deleted action cannot be marked as on page load. */ public Mono<ActionDTO> deleteUnpublishedAction(String id) { - return newActionService.deleteUnpublishedAction(id) - .flatMap(actionDTO -> Mono.zip(Mono.just(actionDTO), - updatePageLayoutsByPageId(actionDTO.getPageId()))) + return newActionService + .deleteUnpublishedAction(id) + .flatMap(actionDTO -> Mono.zip(Mono.just(actionDTO), updatePageLayoutsByPageId(actionDTO.getPageId()))) .flatMap(tuple -> { ActionDTO actionDTO = tuple.getT1(); return Mono.just(actionDTO); @@ -565,7 +638,8 @@ public Mono<ActionDTO> deleteUnpublishedAction(String id) { } public Mono<ActionDTO> deleteUnpublishedAction(String defaultActionId, String branchName) { - return newActionService.findByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getDeletePermission()) + return newActionService + .findByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getDeletePermission()) .flatMap(branchedAction -> deleteUnpublishedAction(branchedAction.getId())) .map(responseUtils::updateActionDTOWithDefaultResources); } @@ -579,41 +653,44 @@ public Mono<String> updatePageLayoutsByPageId(String pageId) { if (page.getLayouts() == null) { return Mono.empty(); } - return Flux.fromIterable(page.getLayouts()) - .flatMap(layout -> { - layout.setDsl(this.unescapeMongoSpecialCharacters(layout)); - return updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout); - }); + return Flux.fromIterable(page.getLayouts()).flatMap(layout -> { + layout.setDsl(this.unescapeMongoSpecialCharacters(layout)); + return updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout); + }); }) .collectList() .then(Mono.just(pageId)); } - private Mono<Boolean> sendUpdateLayoutAnalyticsEvent(String pageId, String layoutId, JSONObject dsl, boolean isSuccess, Throwable error) { - return Mono.zip( - sessionUserService.getCurrentUser(), - newPageService.getById(pageId) - ) + private Mono<Boolean> sendUpdateLayoutAnalyticsEvent( + String pageId, String layoutId, JSONObject dsl, boolean isSuccess, Throwable error) { + return Mono.zip(sessionUserService.getCurrentUser(), newPageService.getById(pageId)) .flatMap(tuple -> { User t1 = tuple.getT1(); NewPage t2 = tuple.getT2(); final Map<String, Object> data = Map.of( - "username", t1.getUsername(), - "appId", t2.getApplicationId(), - "pageId", pageId, - "layoutId", layoutId, - "isSuccessfulExecution", isSuccess, - "error", error == null ? "" : error.getMessage() - ); - - return analyticsService.sendObjectEvent(AnalyticsEvents.UPDATE_LAYOUT, t2, data).thenReturn(isSuccess); + "username", + t1.getUsername(), + "appId", + t2.getApplicationId(), + "pageId", + pageId, + "layoutId", + layoutId, + "isSuccessfulExecution", + isSuccess, + "error", + error == null ? "" : error.getMessage()); + + return analyticsService + .sendObjectEvent(AnalyticsEvents.UPDATE_LAYOUT, t2, data) + .thenReturn(isSuccess); }) .onErrorResume(e -> { log.warn("Error sending action execution data point", e); return Mono.just(isSuccess); }); - } private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout layout, Integer evaluatedVersion) { @@ -627,7 +704,8 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l Map<String, Set<String>> widgetDynamicBindingsMap = new HashMap<>(); Set<String> escapedWidgetNames = new HashSet<>(); try { - dsl = extractAllWidgetNamesAndDynamicBindingsFromDSL(dsl, widgetNames, widgetDynamicBindingsMap, pageId, layoutId, escapedWidgetNames); + dsl = extractAllWidgetNamesAndDynamicBindingsFromDSL( + dsl, widgetNames, widgetDynamicBindingsMap, pageId, layoutId, escapedWidgetNames); } catch (Throwable t) { return sendUpdateLayoutAnalyticsEvent(pageId, layoutId, dsl, false, t) .then(Mono.error(t)); @@ -652,16 +730,23 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l layout.setLayoutOnLoadActionErrors(new ArrayList<>()); Mono<List<Set<DslActionDTO>>> allOnLoadActionsMono = pageLoadActionsUtil - .findAllOnLoadActions(pageId, evaluatedVersion, widgetNames, edges, widgetDynamicBindingsMap, flatmapPageLoadActions, actionsUsedInDSL) + .findAllOnLoadActions( + pageId, + evaluatedVersion, + widgetNames, + edges, + widgetDynamicBindingsMap, + flatmapPageLoadActions, + actionsUsedInDSL) .onErrorResume(AppsmithException.class, error -> { log.info(error.getMessage()); validOnPageLoadActions.set(FALSE); - layout.setLayoutOnLoadActionErrors(List.of( - new ErrorDTO(error.getAppErrorCode(), - error.getErrorType(), - layoutOnLoadActionErrorToastMessage, - error.getMessage(), - error.getTitle()))); + layout.setLayoutOnLoadActionErrors(List.of(new ErrorDTO( + error.getAppErrorCode(), + error.getErrorType(), + layoutOnLoadActionErrorToastMessage, + error.getMessage(), + error.getTitle()))); return Mono.just(new ArrayList<>()); }); @@ -674,29 +759,36 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l if (!validOnPageLoadActions.get()) { return Mono.just(allOnLoadActions); } - // Update these actions to be executed on load, unless the user has touched the executeOnLoad setting for this + // Update these actions to be executed on load, unless the user has touched the executeOnLoad + // setting for this return newActionService .updateActionsExecuteOnLoad(flatmapPageLoadActions, pageId, actionUpdates, messages) .thenReturn(allOnLoadActions); }) - .zipWith(newPageService.findByIdAndLayoutsId(pageId, layoutId, pagePermission.getEditPermission(), false) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, - FieldName.PAGE_ID + " or " + FieldName.LAYOUT_ID, pageId + ", " + layoutId)))) + .zipWith(newPageService + .findByIdAndLayoutsId(pageId, layoutId, pagePermission.getEditPermission(), false) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.PAGE_ID + " or " + FieldName.LAYOUT_ID, + pageId + ", " + layoutId)))) // Now update the page layout with the page load actions and the graph. .flatMap(tuple -> { List<Set<DslActionDTO>> onLoadActions = tuple.getT1(); PageDTO page = tuple.getT2(); List<Layout> layoutList = page.getLayouts(); - //Because the findByIdAndLayoutsId call returned non-empty result, we are guaranteed to find the layoutId here. + // Because the findByIdAndLayoutsId call returned non-empty result, we are guaranteed to find the + // layoutId here. for (Layout storedLayout : layoutList) { if (storedLayout.getId().equals(layoutId)) { - // Now that all the on load actions have been computed, set the vertices, edges, actions in DSL + // Now that all the on load actions have been computed, set the vertices, edges, actions in + // DSL // in the layout for re-use to avoid computing DAG unnecessarily. layout.setLayoutOnLoadActions(onLoadActions); layout.setAllOnPageLoadActionNames(actionNames); layout.setActionsUsedInDynamicBindings(actionsUsedInDSL); - // The below field is to ensure that we record if the page load actions computation was valid + // The below field is to ensure that we record if the page load actions computation was + // valid // when last stored in the database. layout.setValidOnPageLoadActions(validOnPageLoadActions.get()); @@ -707,7 +799,8 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l } } page.setLayouts(layoutList); - return applicationService.saveLastEditInformation(page.getApplicationId()) + return applicationService + .saveLastEditInformation(page.getApplicationId()) .then(newPageService.saveUnpublishedPage(page)); }) .flatMap(page -> { @@ -737,8 +830,8 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l public Mono<LayoutDTO> updateLayout(String pageId, String applicationId, String layoutId, Layout layout) { return applicationService .findById(applicationId) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, - FieldName.APPLICATION_ID, applicationId))) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION_ID, applicationId))) .flatMap(application -> { Integer evaluationVersion = application.getEvaluationVersion(); if (evaluationVersion == null) { @@ -749,20 +842,30 @@ public Mono<LayoutDTO> updateLayout(String pageId, String applicationId, String } @Override - public Mono<LayoutDTO> updateLayout(String defaultPageId, String defaultApplicationId, String layoutId, Layout layout, String branchName) { + public Mono<LayoutDTO> updateLayout( + String defaultPageId, String defaultApplicationId, String layoutId, Layout layout, String branchName) { if (!StringUtils.hasLength(branchName)) { return updateLayout(defaultPageId, defaultApplicationId, layoutId, layout); } - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) - .flatMap(branchedPage -> updateLayout(branchedPage.getId(), branchedPage.getApplicationId(), layoutId, layout)) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) + .flatMap(branchedPage -> + updateLayout(branchedPage.getId(), branchedPage.getApplicationId(), layoutId, layout)) .map(responseUtils::updateLayoutDTOWithDefaultResources); } @Override - public Mono<Integer> updateMultipleLayouts(String defaultApplicationId, String branchName, UpdateMultiplePageLayoutDTO updateMultiplePageLayoutDTO) { + public Mono<Integer> updateMultipleLayouts( + String defaultApplicationId, String branchName, UpdateMultiplePageLayoutDTO updateMultiplePageLayoutDTO) { List<Mono<LayoutDTO>> monoList = new ArrayList<>(); - for (UpdateMultiplePageLayoutDTO.UpdatePageLayoutDTO pageLayout : updateMultiplePageLayoutDTO.getPageLayouts()) { - Mono<LayoutDTO> updatedLayoutMono = this.updateLayout(pageLayout.getPageId(), defaultApplicationId, pageLayout.getLayoutId(), pageLayout.getLayout(), branchName); + for (UpdateMultiplePageLayoutDTO.UpdatePageLayoutDTO pageLayout : + updateMultiplePageLayoutDTO.getPageLayouts()) { + Mono<LayoutDTO> updatedLayoutMono = this.updateLayout( + pageLayout.getPageId(), + defaultApplicationId, + pageLayout.getLayoutId(), + pageLayout.getLayout(), + branchName); monoList.add(updatedLayoutMono); } return Flux.merge(monoList).then(Mono.just(monoList.size())); @@ -812,7 +915,8 @@ private JSONObject unEscapeDslKeys(JSONObject dsl, Set<String> escapedWidgetName String widgetType = dsl.getAsString(FieldName.WIDGET_TYPE); if (widgetType.equals(FieldName.TABLE_WIDGET)) { // UnEscape Table widget keys - // Since this is a table widget, it wouldnt have children. We can safely return from here with updated dsl + // Since this is a table widget, it wouldnt have children. We can safely return from here with updated + // dsl return WidgetSpecificUtils.unEscapeTableWidgetPrimaryColumns(dsl); } } @@ -843,7 +947,9 @@ public Mono<ActionDTO> createSingleActionWithBranch(ActionDTO action, String bra DefaultResources defaultResources = new DefaultResources(); defaultResources.setBranchName(branchName); - return newPageService.findByBranchNameAndDefaultPageId(branchName, action.getPageId(), pagePermission.getActionCreatePermission()) + return newPageService + .findByBranchNameAndDefaultPageId( + branchName, action.getPageId(), pagePermission.getActionCreatePermission()) .flatMap(newPage -> { // Update the page and application id with branched resource action.setPageId(newPage.getId()); @@ -892,7 +998,8 @@ public Mono<ActionDTO> createAction(ActionDTO action, AppsmithEventContext event // If the action is a JS action, then we don't need to validate the page. Fetch the page with read. // Else fetch the page with create action permission to ensure that the user has the right to create an action - AclPermission aclPermission = isJsAction ? pagePermission.getReadPermission() : pagePermission.getActionCreatePermission(); + AclPermission aclPermission = + isJsAction ? pagePermission.getReadPermission() : pagePermission.getActionCreatePermission(); Mono<NewPage> pageMono = newPageService .findById(action.getPageId(), aclPermission) @@ -900,8 +1007,7 @@ public Mono<ActionDTO> createAction(ActionDTO action, AppsmithEventContext event new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, action.getPageId()))) .cache(); - return pageMono - .flatMap(page -> { + return pageMono.flatMap(page -> { Layout layout = page.getUnpublishedPage().getLayouts().get(0); String name = action.getValidName(); return isNameAllowed(page.getId(), layout.getId(), name); @@ -913,7 +1019,8 @@ public Mono<ActionDTO> createAction(ActionDTO action, AppsmithEventContext event } String name = action.getValidName(); // Throw an error since the new action's name matches an existing action or widget name. - return Mono.error(new AppsmithException(AppsmithError.DUPLICATE_KEY_USER_ERROR, name, FieldName.NAME)); + return Mono.error( + new AppsmithException(AppsmithError.DUPLICATE_KEY_USER_ERROR, name, FieldName.NAME)); }) .flatMap(page -> { // Inherit the action policies from the page. @@ -925,11 +1032,11 @@ public Mono<ActionDTO> createAction(ActionDTO action, AppsmithEventContext event newAction.setApplicationId(page.getApplicationId()); // If the datasource is embedded, check for workspaceId and set it in action - if (action.getDatasource() != null && - action.getDatasource().getId() == null) { + if (action.getDatasource() != null && action.getDatasource().getId() == null) { Datasource datasource = action.getDatasource(); if (datasource.getWorkspaceId() == null) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); } newAction.setWorkspaceId(datasource.getWorkspaceId()); } @@ -970,29 +1077,28 @@ public Mono<ActionDTO> createAction(ActionDTO action, AppsmithEventContext event return Mono.just(newAction); }) - .flatMap(savedNewAction -> newActionService.validateAndSaveActionToRepository(savedNewAction).zipWith(Mono.just(savedNewAction))) + .flatMap(savedNewAction -> newActionService + .validateAndSaveActionToRepository(savedNewAction) + .zipWith(Mono.just(savedNewAction))) .zipWith(Mono.defer(() -> { - if (action.getDatasource() != null && - action.getDatasource().getId() != null) { + if (action.getDatasource() != null && action.getDatasource().getId() != null) { return datasourceService.findById(action.getDatasource().getId()); } else { return Mono.justOrEmpty(action.getDatasource()); } })) .flatMap(zippedData -> { - final Tuple2<ActionDTO, NewAction> zippedActions = zippedData.getT1(); final Datasource datasource = zippedData.getT2(); final NewAction newAction1 = zippedActions.getT2(); - final Datasource embeddedDatasource = newAction1.getUnpublishedAction().getDatasource(); + final Datasource embeddedDatasource = + newAction1.getUnpublishedAction().getDatasource(); embeddedDatasource.setIsMock(datasource.getIsMock()); embeddedDatasource.setIsTemplate(datasource.getIsTemplate()); return analyticsService .sendCreateEvent(newAction1, newActionService.getAnalyticsProperties(newAction1)) .thenReturn(zippedActions.getT1()); - }); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCE.java index d8133be97067..5e0c60ddde5a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCE.java @@ -13,16 +13,18 @@ public interface LayoutCollectionServiceCE { Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection, String branchName); - Mono<LayoutDTO> refactorCollectionName(RefactorActionCollectionNameDTO refactorActionCollectionNameDTO, String branchName); + Mono<LayoutDTO> refactorCollectionName( + RefactorActionCollectionNameDTO refactorActionCollectionNameDTO, String branchName); Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCollectionMoveDTO); Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCollectionMoveDTO, String branchName); - Mono<ActionCollectionDTO> updateUnpublishedActionCollection(String id, ActionCollectionDTO actionCollectionDTO, String branchName); + Mono<ActionCollectionDTO> updateUnpublishedActionCollection( + String id, ActionCollectionDTO actionCollectionDTO, String branchName); Mono<LayoutDTO> refactorAction(RefactorActionNameInCollectionDTO refactorActionNameInCollectionDTO); - Mono<LayoutDTO> refactorAction(RefactorActionNameInCollectionDTO refactorActionNameInCollectionDTO, String branchName); - + Mono<LayoutDTO> refactorAction( + RefactorActionNameInCollectionDTO refactorActionNameInCollectionDTO, String branchName); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java index 8a49cc73dba9..927ec84e88c0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java @@ -48,7 +48,6 @@ import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; - @Slf4j @RequiredArgsConstructor public class LayoutCollectionServiceCEImpl implements LayoutCollectionServiceCE { @@ -76,9 +75,7 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection final Set<String> validationMessages = collection.validate(); if (!validationMessages.isEmpty()) { return Mono.error(new AppsmithException( - AppsmithError.INVALID_ACTION_COLLECTION, - collection.getName(), - validationMessages.toString())); + AppsmithError.INVALID_ACTION_COLLECTION, collection.getName(), validationMessages.toString())); } DefaultResources defaultResources = collection.getDefaultResources(); @@ -90,14 +87,13 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection final String pageId = collection.getPageId(); Mono<NewPage> pageMono = newPageService .findById(pageId, pagePermission.getActionCreatePermission()) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, pageId))) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, pageId))) .cache(); // First check if the collection name is allowed // If the collection name is unique, the action name will be guaranteed to be unique within that collection - return pageMono - .flatMap(page -> { + return pageMono.flatMap(page -> { Layout layout = page.getUnpublishedPage().getLayouts().get(0); // Check against widget names and action names return layoutActionService.isNameAllowed(page.getId(), layout.getId(), collection.getName()); @@ -107,11 +103,10 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection if (Boolean.TRUE.equals(isNameAllowed)) { return Mono.justOrEmpty(collection.getActions()).defaultIfEmpty(List.of()); } - // Throw an error since the new action collection's name matches an existing action, widget or collection name. + // Throw an error since the new action collection's name matches an existing action, widget or + // collection name. return Mono.error(new AppsmithException( - AppsmithError.DUPLICATE_KEY_USER_ERROR, - collection.getName(), - FieldName.NAME)); + AppsmithError.DUPLICATE_KEY_USER_ERROR, collection.getName(), FieldName.NAME)); }) .flatMapMany(Flux::fromIterable) .flatMap(action -> { @@ -130,12 +125,16 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection .createSingleAction(action, Boolean.TRUE) // return an empty action so that this action is disregarded from the list .onErrorResume(throwable -> { - log.debug("Failed to create action with name {} for collection: {}", action.getName(), collection.getName()); + log.debug( + "Failed to create action with name {} for collection: {}", + action.getName(), + collection.getName()); log.error(throwable.getMessage()); return Mono.empty(); }); } - // actionCollectionService would occur when the new collection is created by grouping existing actions + // actionCollectionService would occur when the new collection is created by grouping existing + // actions // actionCollectionService could be a future enhancement for js editor templates, // but is also useful for generic collections // We do not expect to have to update the action at actionCollectionService point @@ -157,7 +156,8 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection // Store the default resource ids // Only store defaultPageId for collectionDTO level resource DefaultResources defaultDTOResource = new DefaultResources(); - AppsmithBeanUtils.copyNewFieldValuesIntoOldObject(collection.getDefaultResources(), defaultDTOResource); + AppsmithBeanUtils.copyNewFieldValuesIntoOldObject( + collection.getDefaultResources(), defaultDTOResource); defaultDTOResource.setApplicationId(null); defaultDTOResource.setCollectionId(null); @@ -167,7 +167,8 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection } collection.setDefaultResources(defaultDTOResource); - // Only store branchName, defaultApplicationId and defaultActionCollectionId for ActionCollection level resource + // Only store branchName, defaultApplicationId and defaultActionCollectionId for ActionCollection + // level resource DefaultResources defaults = new DefaultResources(); AppsmithBeanUtils.copyNewFieldValuesIntoOldObject(actionCollection.getDefaultResources(), defaults); defaults.setPageId(null); @@ -176,9 +177,9 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection } actionCollection.setDefaultResources(defaults); - final Map<String, String> actionIds = actions - .stream() - .collect(toMap(actionDTO -> actionDTO.getDefaultResources().getActionId(), ActionDTO::getId)); + final Map<String, String> actionIds = actions.stream() + .collect(toMap( + actionDTO -> actionDTO.getDefaultResources().getActionId(), ActionDTO::getId)); collection.setDefaultToBranchedActionIdsMap(actionIds); if (actionCollection.getGitSyncId() == null) { @@ -189,8 +190,12 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection .create(actionCollection) .flatMap(savedActionCollection -> { // If the default collection is not set then current collection will be the default one - if (StringUtils.isEmpty(savedActionCollection.getDefaultResources().getCollectionId())) { - savedActionCollection.getDefaultResources().setCollectionId(savedActionCollection.getId()); + if (StringUtils.isEmpty(savedActionCollection + .getDefaultResources() + .getCollectionId())) { + savedActionCollection + .getDefaultResources() + .setCollectionId(savedActionCollection.getId()); } return actionCollectionService.save(savedActionCollection); }) @@ -200,9 +205,11 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection return actionCollectionMono .map(actionCollection1 -> { actions.forEach(actionDTO -> { - // Update all the actions in the list to belong to actionCollectionService collection + // Update all the actions in the list to belong to actionCollectionService + // collection actionDTO.setCollectionId(actionCollection1.getId()); - if (StringUtils.isEmpty(actionDTO.getDefaultResources().getCollectionId())) { + if (StringUtils.isEmpty( + actionDTO.getDefaultResources().getCollectionId())) { actionDTO.getDefaultResources().setCollectionId(actionCollection1.getId()); } }); @@ -215,14 +222,17 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection .flatMap(tuple1 -> { final List<ActionDTO> actionDTOList = tuple1.getT1(); final ActionCollection actionCollection1 = tuple1.getT2(); - return actionCollectionService.generateActionCollectionByViewMode(actionCollection, false) + return actionCollectionService + .generateActionCollectionByViewMode(actionCollection, false) .flatMap(actionCollectionDTO -> actionCollectionService.splitValidActionsByViewMode( actionCollection1.getUnpublishedCollection(), actionDTOList, false)); }) - .flatMap(updatedCollection -> layoutActionService.updatePageLayoutsByPageId(updatedCollection.getPageId()).thenReturn(updatedCollection)); + .flatMap(updatedCollection -> layoutActionService + .updatePageLayoutsByPageId(updatedCollection.getPageId()) + .thenReturn(updatedCollection)); }); } @@ -232,13 +242,15 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ID)); } - return newPageService.findById(collection.getPageId(), pagePermission.getActionCreatePermission()) + return newPageService + .findById(collection.getPageId(), pagePermission.getActionCreatePermission()) .flatMap(newPage -> { // Insert defaultPageId and defaultAppId from page DefaultResources defaultResources = newPage.getDefaultResources(); defaultResources.setBranchName(branchName); collection.setDefaultResources(defaultResources); - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultResources.getPageId(), pagePermission.getEditPermission()); + return newPageService.findByBranchNameAndDefaultPageId( + branchName, defaultResources.getPageId(), pagePermission.getEditPermission()); }) .flatMap(branchedPage -> { // Update the page and application id with branched resource @@ -250,7 +262,8 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection } @Override - public Mono<LayoutDTO> refactorCollectionName(RefactorActionCollectionNameDTO refactorActionCollectionNameDTO, String branchName) { + public Mono<LayoutDTO> refactorCollectionName( + RefactorActionCollectionNameDTO refactorActionCollectionNameDTO, String branchName) { String pageId = refactorActionCollectionNameDTO.getPageId(); String layoutId = refactorActionCollectionNameDTO.getLayoutId(); String oldName = refactorActionCollectionNameDTO.getOldName(); @@ -260,34 +273,32 @@ public Mono<LayoutDTO> refactorCollectionName(RefactorActionCollectionNameDTO re Mono<String> branchedPageIdMono = StringUtils.isEmpty(branchName) ? Mono.just(pageId) : newPageService - .findByBranchNameAndDefaultPageId(branchName, pageId, pagePermission.getReadPermission()) - .map(NewPage::getId) - .cache(); + .findByBranchNameAndDefaultPageId(branchName, pageId, pagePermission.getReadPermission()) + .map(NewPage::getId) + .cache(); Mono<String> branchedActionCollectionIdMono = StringUtils.isEmpty(branchName) ? Mono.just(actionCollectionId) : actionCollectionService - .findByBranchNameAndDefaultCollectionId(branchName, actionCollectionId, actionPermission.getEditPermission()) - .map(ActionCollection::getId); + .findByBranchNameAndDefaultCollectionId( + branchName, actionCollectionId, actionPermission.getEditPermission()) + .map(ActionCollection::getId); return branchedPageIdMono - .flatMap(branchedPageId -> - layoutActionService - .isNameAllowed(branchedPageId, layoutId, newName) - .flatMap(isNameAllowed -> { - // If the name is allowed, return list of actionDTOs for further processing - if (Boolean.TRUE.equals(isNameAllowed)) { - return branchedActionCollectionIdMono - .flatMap(collectionId -> actionCollectionService - .findActionCollectionDTObyIdAndViewMode(collectionId, false, actionPermission.getEditPermission())); - } - // Throw an error since the new action collection's name matches an existing action, widget or collection name. - return Mono.error(new AppsmithException( - AppsmithError.DUPLICATE_KEY_USER_ERROR, - newName, - FieldName.NAME)); - }) - ) + .flatMap(branchedPageId -> layoutActionService + .isNameAllowed(branchedPageId, layoutId, newName) + .flatMap(isNameAllowed -> { + // If the name is allowed, return list of actionDTOs for further processing + if (Boolean.TRUE.equals(isNameAllowed)) { + return branchedActionCollectionIdMono.flatMap( + collectionId -> actionCollectionService.findActionCollectionDTObyIdAndViewMode( + collectionId, false, actionPermission.getEditPermission())); + } + // Throw an error since the new action collection's name matches an existing action, widget + // or collection name. + return Mono.error(new AppsmithException( + AppsmithError.DUPLICATE_KEY_USER_ERROR, newName, FieldName.NAME)); + })) .flatMap(branchedActionCollection -> { final HashMap<String, String> actionIds = new HashMap<>(); if (branchedActionCollection.getDefaultToBranchedActionIdsMap() != null) { @@ -297,9 +308,9 @@ public Mono<LayoutDTO> refactorCollectionName(RefactorActionCollectionNameDTO re actionIds.putAll(branchedActionCollection.getDefaultToBranchedArchivedActionIdsMap()); } - Flux<ActionDTO> actionUpdatesFlux = Flux - .fromIterable(actionIds.values()) - .flatMap(actionId -> newActionService.findActionDTObyIdAndViewMode(actionId, false, actionPermission.getEditPermission())) + Flux<ActionDTO> actionUpdatesFlux = Flux.fromIterable(actionIds.values()) + .flatMap(actionId -> newActionService.findActionDTObyIdAndViewMode( + actionId, false, actionPermission.getEditPermission())) .flatMap(actionDTO -> { actionDTO.setFullyQualifiedName(newName + "." + actionDTO.getName()); return newActionService @@ -315,7 +326,8 @@ public Mono<LayoutDTO> refactorCollectionName(RefactorActionCollectionNameDTO re }); branchedActionCollection.setName(newName); return actionUpdatesFlux - .then(actionCollectionService.update(branchedActionCollection.getId(), branchedActionCollection)) + .then(actionCollectionService.update( + branchedActionCollection.getId(), branchedActionCollection)) .then(branchedPageIdMono) .flatMap(branchedPageId -> refactoringSolution.refactorActionCollectionName( branchedActionCollection.getApplicationId(), @@ -332,14 +344,16 @@ public Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCo final String collectionId = actionCollectionMoveDTO.getCollectionId(); final String destinationPageId = actionCollectionMoveDTO.getDestinationPageId(); - Mono<NewPage> destinationPageMono = newPageService.findById(actionCollectionMoveDTO.getDestinationPageId(), pagePermission.getActionCreatePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, destinationPageId))) + Mono<NewPage> destinationPageMono = newPageService + .findById(actionCollectionMoveDTO.getDestinationPageId(), pagePermission.getActionCreatePermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, destinationPageId))) .cache(); return Mono.zip( destinationPageMono, - actionCollectionService - .findActionCollectionDTObyIdAndViewMode(collectionId, false, actionPermission.getEditPermission())) + actionCollectionService.findActionCollectionDTObyIdAndViewMode( + collectionId, false, actionPermission.getEditPermission())) .flatMap(tuple -> { NewPage destinationPage = tuple.getT1(); ActionCollectionDTO actionCollectionDTO = tuple.getT2(); @@ -352,14 +366,23 @@ public Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCo } final Flux<ActionDTO> actionUpdatesFlux = Flux.fromIterable(actionIds.values()) - .flatMap(actionId -> newActionService.findActionDTObyIdAndViewMode(actionId, false, actionPermission.getEditPermission())) + .flatMap(actionId -> newActionService.findActionDTObyIdAndViewMode( + actionId, false, actionPermission.getEditPermission())) .flatMap(actionDTO -> { actionDTO.setPageId(destinationPageId); // Update default page ID in actions as per destination page object - actionDTO.getDefaultResources().setPageId(destinationPage.getDefaultResources().getPageId()); - return newActionService.updateUnpublishedAction(actionDTO.getId(), actionDTO) + actionDTO + .getDefaultResources() + .setPageId(destinationPage + .getDefaultResources() + .getPageId()); + return newActionService + .updateUnpublishedAction(actionDTO.getId(), actionDTO) .onErrorResume(throwable -> { - log.debug("Failed to update collection name for action {} for collection with id: {}", actionDTO.getName(), actionDTO.getCollectionId()); + log.debug( + "Failed to update collection name for action {} for collection with id: {}", + actionDTO.getName(), + actionDTO.getCollectionId()); log.error(throwable.getMessage()); return Mono.empty(); }); @@ -368,7 +391,8 @@ public Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCo final String oldPageId = actionCollectionDTO.getPageId(); actionCollectionDTO.setPageId(destinationPageId); DefaultResources defaultResources = new DefaultResources(); - defaultResources.setPageId(destinationPage.getDefaultResources().getPageId()); + defaultResources.setPageId( + destinationPage.getDefaultResources().getPageId()); actionCollectionDTO.setDefaultResources(defaultResources); actionCollectionDTO.setName(actionCollectionMoveDTO.getName()); @@ -392,12 +416,16 @@ public Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCo return Flux.fromIterable(page.getLayouts()) .flatMap(layout -> { layout.setDsl(layoutActionService.unescapeMongoSpecialCharacters(layout)); - return layoutActionService.updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout); + return layoutActionService.updateLayout( + page.getId(), page.getApplicationId(), layout.getId(), layout); }) .collect(toSet()); }) // fetch the unpublished destination page - .then(newPageService.findPageById(actionCollectionMoveDTO.getDestinationPageId(), pagePermission.getActionCreatePermission(), false)) + .then(newPageService.findPageById( + actionCollectionMoveDTO.getDestinationPageId(), + pagePermission.getActionCreatePermission(), + false)) .flatMap(page -> { if (page.getLayouts() == null) { return Mono.empty(); @@ -407,7 +435,8 @@ public Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCo return Flux.fromIterable(page.getLayouts()) .flatMap(layout -> { layout.setDsl(layoutActionService.unescapeMongoSpecialCharacters(layout)); - return layoutActionService.updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout); + return layoutActionService.updateLayout( + page.getId(), page.getApplicationId(), layout.getId(), layout); }) .collect(toSet()); }) @@ -417,14 +446,19 @@ public Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCo } @Override - public Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCollectionMoveDTO, String branchName) { + public Mono<ActionCollectionDTO> moveCollection( + ActionCollectionMoveDTO actionCollectionMoveDTO, String branchName) { Mono<String> destinationPageMono = newPageService - .findByBranchNameAndDefaultPageId(branchName, actionCollectionMoveDTO.getDestinationPageId(), pagePermission.getActionCreatePermission()) + .findByBranchNameAndDefaultPageId( + branchName, + actionCollectionMoveDTO.getDestinationPageId(), + pagePermission.getActionCreatePermission()) .map(NewPage::getId); Mono<String> branchedCollectionMono = actionCollectionService - .findByBranchNameAndDefaultCollectionId(branchName, actionCollectionMoveDTO.getCollectionId(), actionPermission.getEditPermission()) + .findByBranchNameAndDefaultCollectionId( + branchName, actionCollectionMoveDTO.getCollectionId(), actionPermission.getEditPermission()) .map(ActionCollection::getId); return Mono.zip(destinationPageMono, branchedCollectionMono) @@ -439,9 +473,8 @@ public Mono<ActionCollectionDTO> moveCollection(ActionCollectionMoveDTO actionCo } @Override - public Mono<ActionCollectionDTO> updateUnpublishedActionCollection(String id, - ActionCollectionDTO actionCollectionDTO, - String branchName) { + public Mono<ActionCollectionDTO> updateUnpublishedActionCollection( + String id, ActionCollectionDTO actionCollectionDTO, String branchName) { // new actions without ids are to be created // new actions with ids are to be updated and added to collection // old actions that are now missing are to be archived @@ -457,15 +490,11 @@ public Mono<ActionCollectionDTO> updateUnpublishedActionCollection(String id, .cache(); // It is expected that client will be aware of defaultActionIds and not the branched (actual) action ID - final Set<String> validDefaultActionIds = actionCollectionDTO - .getActions() - .stream() + final Set<String> validDefaultActionIds = actionCollectionDTO.getActions().stream() .map(ActionDTO::getId) .filter(Objects::nonNull) .collect(Collectors.toUnmodifiableSet()); - final Set<String> archivedDefaultActionIds = actionCollectionDTO - .getArchivedActions() - .stream() + final Set<String> archivedDefaultActionIds = actionCollectionDTO.getArchivedActions().stream() .map(ActionDTO::getId) .filter(Objects::nonNull) .collect(Collectors.toUnmodifiableSet()); @@ -473,80 +502,103 @@ public Mono<ActionCollectionDTO> updateUnpublishedActionCollection(String id, defaultActionIds.addAll(validDefaultActionIds); defaultActionIds.addAll(archivedDefaultActionIds); - final Mono<Map<String, String>> newValidActionIdsMono = branchedActionCollectionMono - .flatMap(branchedActionCollection -> Flux.fromIterable(actionCollectionDTO.getActions()) + final Mono<Map<String, String>> newValidActionIdsMono = branchedActionCollectionMono.flatMap( + branchedActionCollection -> Flux.fromIterable(actionCollectionDTO.getActions()) .flatMap(actionDTO -> { actionDTO.setDeletedAt(null); - actionDTO.setPageId(branchedActionCollection.getUnpublishedCollection().getPageId()); + actionDTO.setPageId(branchedActionCollection + .getUnpublishedCollection() + .getPageId()); actionDTO.setApplicationId(branchedActionCollection.getApplicationId()); if (actionDTO.getId() == null) { actionDTO.setCollectionId(branchedActionCollection.getId()); actionDTO.getDatasource().setWorkspaceId(actionCollectionDTO.getWorkspaceId()); actionDTO.getDatasource().setPluginId(actionCollectionDTO.getPluginId()); actionDTO.getDatasource().setName(FieldName.UNUSED_DATASOURCE); - actionDTO.setFullyQualifiedName(actionCollectionDTO.getName() + "." + actionDTO.getName()); + actionDTO.setFullyQualifiedName( + actionCollectionDTO.getName() + "." + actionDTO.getName()); actionDTO.setPluginType(actionCollectionDTO.getPluginType()); actionDTO.setPluginId(actionCollectionDTO.getPluginId()); actionDTO.setDefaultResources(branchedActionCollection.getDefaultResources()); actionDTO.getDefaultResources().setBranchName(branchName); - final String defaultPageId = branchedActionCollection.getUnpublishedCollection().getDefaultResources().getPageId(); + final String defaultPageId = branchedActionCollection + .getUnpublishedCollection() + .getDefaultResources() + .getPageId(); actionDTO.getDefaultResources().setPageId(defaultPageId); // actionCollectionService is a new action, we need to create one return layoutActionService.createSingleAction(actionDTO, Boolean.TRUE); } else { actionDTO.setCollectionId(null); - // Client only knows about the default action ID, fetch branched action id to update the action + // Client only knows about the default action ID, fetch branched action id to update the + // action Mono<String> branchedActionIdMono = StringUtils.isEmpty(branchName) ? Mono.just(actionDTO.getId()) : newActionService - .findByBranchNameAndDefaultActionId(branchName, actionDTO.getId(), actionPermission.getEditPermission()) - .map(NewAction::getId); + .findByBranchNameAndDefaultActionId( + branchName, + actionDTO.getId(), + actionPermission.getEditPermission()) + .map(NewAction::getId); actionDTO.setId(null); - return branchedActionIdMono - .flatMap(actionId -> layoutActionService.updateSingleAction(actionId, actionDTO)); + return branchedActionIdMono.flatMap( + actionId -> layoutActionService.updateSingleAction(actionId, actionDTO)); } }) - .collect(toMap(actionDTO -> actionDTO.getDefaultResources().getActionId(), ActionDTO::getId)) - ); + .collect(toMap( + actionDTO -> actionDTO.getDefaultResources().getActionId(), ActionDTO::getId))); - final Mono<Map<String, String>> newArchivedActionIdsMono = branchedActionCollectionMono - .flatMap(branchedActionCollection -> Flux.fromIterable(actionCollectionDTO.getArchivedActions()) + final Mono<Map<String, String>> newArchivedActionIdsMono = branchedActionCollectionMono.flatMap( + branchedActionCollection -> Flux.fromIterable(actionCollectionDTO.getArchivedActions()) .flatMap(actionDTO -> { actionDTO.setCollectionId(branchedActionCollection.getId()); actionDTO.setDeletedAt(Instant.now()); - actionDTO.setPageId(branchedActionCollection.getUnpublishedCollection().getPageId()); + actionDTO.setPageId(branchedActionCollection + .getUnpublishedCollection() + .getPageId()); if (actionDTO.getId() == null) { actionDTO.getDatasource().setWorkspaceId(actionCollectionDTO.getWorkspaceId()); actionDTO.getDatasource().setPluginId(actionCollectionDTO.getPluginId()); actionDTO.getDatasource().setName(FieldName.UNUSED_DATASOURCE); - actionDTO.setFullyQualifiedName(actionCollectionDTO.getName() + "." + actionDTO.getName()); + actionDTO.setFullyQualifiedName( + actionCollectionDTO.getName() + "." + actionDTO.getName()); actionDTO.setDefaultResources(branchedActionCollection.getDefaultResources()); actionDTO.getDefaultResources().setBranchName(branchName); - final String defaultPageId = branchedActionCollection.getUnpublishedCollection().getDefaultResources().getPageId(); + final String defaultPageId = branchedActionCollection + .getUnpublishedCollection() + .getDefaultResources() + .getPageId(); actionDTO.getDefaultResources().setPageId(defaultPageId); // actionCollectionService is a new action, we need to create one - return layoutActionService.createSingleAction(actionDTO, Boolean.TRUE) + return layoutActionService + .createSingleAction(actionDTO, Boolean.TRUE) // return an empty action so that the filter can remove it from the list .onErrorResume(throwable -> { - log.debug("Failed to create action with name {} for collection: {}", actionDTO.getName(), actionCollectionDTO.getName()); + log.debug( + "Failed to create action with name {} for collection: {}", + actionDTO.getName(), + actionCollectionDTO.getName()); log.error(throwable.getMessage()); return Mono.empty(); }); } else { - // Client only knows about the default action ID, fetch branched action id to update the action + // Client only knows about the default action ID, fetch branched action id to update the + // action Mono<String> branchedActionIdMono = StringUtils.isEmpty(branchName) ? Mono.just(actionDTO.getId()) : newActionService - .findByBranchNameAndDefaultActionId(branchName, actionDTO.getId(), actionPermission.getEditPermission()) - .map(NewAction::getId); + .findByBranchNameAndDefaultActionId( + branchName, + actionDTO.getId(), + actionPermission.getEditPermission()) + .map(NewAction::getId); actionDTO.setId(null); - return branchedActionIdMono - .flatMap(actionId -> layoutActionService.updateSingleAction(actionId, actionDTO)); + return branchedActionIdMono.flatMap( + actionId -> layoutActionService.updateSingleAction(actionId, actionDTO)); } }) - .collect(toMap(actionDTO -> actionDTO.getDefaultResources().getActionId(), ActionDTO::getId)) - ); - + .collect(toMap( + actionDTO -> actionDTO.getDefaultResources().getActionId(), ActionDTO::getId))); // First collect all valid action ids from before, and diff against incoming action ids return branchedActionCollectionMono @@ -554,31 +606,38 @@ public Mono<ActionCollectionDTO> updateUnpublishedActionCollection(String id, // From the existing collection, if an action id is not referenced at all anymore, // this means the action has been somehow deleted final Set<String> oldDefaultActionIds = new HashSet<>(); - if (branchedActionCollection.getUnpublishedCollection().getDefaultToBranchedActionIdsMap() != null) { + if (branchedActionCollection.getUnpublishedCollection().getDefaultToBranchedActionIdsMap() + != null) { oldDefaultActionIds.addAll(branchedActionCollection .getUnpublishedCollection() .getDefaultToBranchedActionIdsMap() .keySet()); } - if (branchedActionCollection.getUnpublishedCollection().getDefaultToBranchedArchivedActionIdsMap() != null) { + if (branchedActionCollection.getUnpublishedCollection().getDefaultToBranchedArchivedActionIdsMap() + != null) { oldDefaultActionIds.addAll(branchedActionCollection .getUnpublishedCollection() .getDefaultToBranchedArchivedActionIdsMap() .keySet()); } - return oldDefaultActionIds - .stream() + return oldDefaultActionIds.stream() .filter(Objects::nonNull) .filter(x -> !defaultActionIds.contains(x)) .collect(Collectors.toUnmodifiableSet()); }) .flatMapMany(Flux::fromIterable) - .flatMap(defaultActionId -> newActionService.findBranchedIdByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getEditPermission()) + .flatMap(defaultActionId -> newActionService + .findBranchedIdByBranchNameAndDefaultActionId( + branchName, defaultActionId, actionPermission.getEditPermission()) .flatMap(newActionService::deleteUnpublishedAction) // return an empty action so that the filter can remove it from the list .onErrorResume(throwable -> { - log.debug("Failed to delete action with id {}, branch {} for collection: {}", defaultActionId, branchName, actionCollectionDTO.getName()); + log.debug( + "Failed to delete action with id {}, branch {} for collection: {}", + defaultActionId, + branchName, + actionCollectionDTO.getName()); log.error(throwable.getMessage()); return Mono.empty(); })) @@ -586,29 +645,37 @@ public Mono<ActionCollectionDTO> updateUnpublishedActionCollection(String id, .flatMap(tuple -> { actionCollectionDTO.setDefaultToBranchedActionIdsMap(tuple.getT1()); actionCollectionDTO.setDefaultToBranchedArchivedActionIdsMap(tuple.getT2()); - return branchedActionCollectionMono - .map(dbActionCollection -> { - actionCollectionDTO.setId(null); - actionCollectionDTO.setPageId(null); - copyNewFieldValuesIntoOldObject(actionCollectionDTO, dbActionCollection.getUnpublishedCollection()); - return dbActionCollection; - }); + return branchedActionCollectionMono.map(dbActionCollection -> { + actionCollectionDTO.setId(null); + actionCollectionDTO.setPageId(null); + copyNewFieldValuesIntoOldObject( + actionCollectionDTO, dbActionCollection.getUnpublishedCollection()); + return dbActionCollection; + }); }) .flatMap(actionCollection -> actionCollectionService.update(actionCollection.getId(), actionCollection)) .flatMap(actionCollectionRepository::setUserPermissionsInObject) - .flatMap(savedActionCollection -> layoutActionService.updatePageLayoutsByPageId(savedActionCollection.getUnpublishedCollection().getPageId()).thenReturn(savedActionCollection)) - .flatMap(savedActionCollection -> analyticsService.sendUpdateEvent(savedActionCollection, actionCollectionService.getAnalyticsProperties(savedActionCollection))) - .flatMap(actionCollection -> actionCollectionService.generateActionCollectionByViewMode(actionCollection, false) + .flatMap(savedActionCollection -> layoutActionService + .updatePageLayoutsByPageId( + savedActionCollection.getUnpublishedCollection().getPageId()) + .thenReturn(savedActionCollection)) + .flatMap(savedActionCollection -> analyticsService.sendUpdateEvent( + savedActionCollection, actionCollectionService.getAnalyticsProperties(savedActionCollection))) + .flatMap(actionCollection -> actionCollectionService + .generateActionCollectionByViewMode(actionCollection, false) .flatMap(actionCollectionDTO1 -> actionCollectionService.populateActionCollectionByViewMode( - actionCollection.getUnpublishedCollection(), - false))) + actionCollection.getUnpublishedCollection(), false))) .map(responseUtils::updateCollectionDTOWithDefaultResources) - .zipWith(newPageService.findById(pageId, pagePermission.getEditPermission()), + .zipWith( + newPageService.findById(pageId, pagePermission.getEditPermission()), (branchedActionCollection, newPage) -> { - //redundant check + // redundant check if (newPage.getUnpublishedPage().getLayouts().size() > 0) { // redundant check as the collection lies inside a layout. Maybe required for testcases - branchedActionCollection.setErrorReports(newPage.getUnpublishedPage().getLayouts().get(0).getLayoutOnLoadActionErrors()); + branchedActionCollection.setErrorReports(newPage.getUnpublishedPage() + .getLayouts() + .get(0) + .getLayoutOnLoadActionErrors()); } return branchedActionCollection; @@ -623,35 +690,47 @@ public Mono<LayoutDTO> refactorAction(RefactorActionNameInCollectionDTO refactor .cache(); final ActionCollectionDTO actionCollectionDTO = refactorActionNameInCollectionDTO.getActionCollection(); - Mono<ActionCollection> actionCollectionMono = actionCollectionService.findById(actionCollectionDTO.getId(), actionPermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION_COLLECTION, actionCollectionDTO.getId()))); + Mono<ActionCollection> actionCollectionMono = actionCollectionService + .findById(actionCollectionDTO.getId(), actionPermission.getEditPermission()) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.ACTION_COLLECTION, + actionCollectionDTO.getId()))); return layoutDTOMono .then(actionCollectionMono) .map(dbActionCollection -> { // Make sure that the action related fields and name are not edited - actionCollectionDTO.setName(dbActionCollection.getUnpublishedCollection().getName()); - actionCollectionDTO.setDefaultToBranchedActionIdsMap(dbActionCollection.getUnpublishedCollection().getDefaultToBranchedActionIdsMap()); - actionCollectionDTO.setDefaultToBranchedArchivedActionIdsMap(dbActionCollection.getUnpublishedCollection().getDefaultToBranchedArchivedActionIdsMap()); + actionCollectionDTO.setName( + dbActionCollection.getUnpublishedCollection().getName()); + actionCollectionDTO.setDefaultToBranchedActionIdsMap( + dbActionCollection.getUnpublishedCollection().getDefaultToBranchedActionIdsMap()); + actionCollectionDTO.setDefaultToBranchedArchivedActionIdsMap( + dbActionCollection.getUnpublishedCollection().getDefaultToBranchedArchivedActionIdsMap()); copyNewFieldValuesIntoOldObject(actionCollectionDTO, dbActionCollection.getUnpublishedCollection()); return dbActionCollection; }) - .flatMap(actionCollection -> actionCollectionService.update(actionCollectionDTO.getId(), actionCollection)) + .flatMap(actionCollection -> + actionCollectionService.update(actionCollectionDTO.getId(), actionCollection)) .then(layoutDTOMono); } - public Mono<LayoutDTO> refactorAction(RefactorActionNameInCollectionDTO refactorActionNameInCollectionDTO, String branchName) { + public Mono<LayoutDTO> refactorAction( + RefactorActionNameInCollectionDTO refactorActionNameInCollectionDTO, String branchName) { RefactorActionNameDTO refactorActionNameDTO = refactorActionNameInCollectionDTO.getRefactorAction(); ActionCollectionDTO defaultActionCollection = refactorActionNameInCollectionDTO.getActionCollection(); Map<String, String> defaultToBranchedActionIdMap = new HashMap<>(); // Fetch branched action as client only knows about the default action IDs Mono<RefactorActionNameDTO> refactorBranchedActionMono = newActionService - .findByBranchNameAndDefaultActionId(branchName, refactorActionNameDTO.getActionId(), actionPermission.getEditPermission()) + .findByBranchNameAndDefaultActionId( + branchName, refactorActionNameDTO.getActionId(), actionPermission.getEditPermission()) .map(branchedAction -> { refactorActionNameDTO.setActionId(branchedAction.getId()); - refactorActionNameDTO.setPageId(branchedAction.getUnpublishedAction().getPageId()); - defaultActionCollection.setPageId(branchedAction.getUnpublishedAction().getPageId()); + refactorActionNameDTO.setPageId( + branchedAction.getUnpublishedAction().getPageId()); + defaultActionCollection.setPageId( + branchedAction.getUnpublishedAction().getPageId()); defaultActionCollection.setApplicationId(branchedAction.getApplicationId()); return refactorActionNameDTO; }); @@ -659,12 +738,16 @@ public Mono<LayoutDTO> refactorAction(RefactorActionNameInCollectionDTO refactor Mono<String> branchedCollectionIdMono = StringUtils.isEmpty(branchName) ? Mono.just(defaultActionCollection.getId()) : actionCollectionService - .findByBranchNameAndDefaultCollectionId(branchName, defaultActionCollection.getId(), actionPermission.getEditPermission()) - .map(actionCollection -> { - defaultToBranchedActionIdMap.putAll(actionCollection.getUnpublishedCollection().getDefaultToBranchedActionIdsMap()); - defaultToBranchedActionIdMap.putAll(actionCollection.getUnpublishedCollection().getDefaultToBranchedArchivedActionIdsMap()); - return actionCollection.getId(); - }); + .findByBranchNameAndDefaultCollectionId( + branchName, defaultActionCollection.getId(), actionPermission.getEditPermission()) + .map(actionCollection -> { + defaultToBranchedActionIdMap.putAll( + actionCollection.getUnpublishedCollection().getDefaultToBranchedActionIdsMap()); + defaultToBranchedActionIdMap.putAll(actionCollection + .getUnpublishedCollection() + .getDefaultToBranchedArchivedActionIdsMap()); + return actionCollection.getId(); + }); return Mono.zip(refactorBranchedActionMono, branchedCollectionIdMono) .flatMap(tuple -> { @@ -672,27 +755,22 @@ public Mono<LayoutDTO> refactorAction(RefactorActionNameInCollectionDTO refactor defaultActionCollection.setId(tuple.getT2()); // As client is not aware of branch specific action IDs, replace default action IDs within // actionCollection with the branch specific action IDs - defaultActionCollection - .getActions() - .forEach(actionDTO -> { - actionDTO.setPageId(defaultActionCollection.getPageId()); - actionDTO.setApplicationId(defaultActionCollection.getApplicationId()); - actionDTO.setCollectionId(defaultActionCollection.getId()); - actionDTO.setId(defaultToBranchedActionIdMap.get(actionDTO.getId())); - }); + defaultActionCollection.getActions().forEach(actionDTO -> { + actionDTO.setPageId(defaultActionCollection.getPageId()); + actionDTO.setApplicationId(defaultActionCollection.getApplicationId()); + actionDTO.setCollectionId(defaultActionCollection.getId()); + actionDTO.setId(defaultToBranchedActionIdMap.get(actionDTO.getId())); + }); if (!CollectionUtils.isNullOrEmpty(defaultActionCollection.getArchivedActions())) { - defaultActionCollection - .getArchivedActions() - .forEach(actionDTO -> { - actionDTO.setPageId(defaultActionCollection.getPageId()); - actionDTO.setApplicationId(defaultActionCollection.getApplicationId()); - actionDTO.setCollectionId(defaultActionCollection.getId()); - actionDTO.setId(defaultToBranchedActionIdMap.get(actionDTO.getId())); - }); + defaultActionCollection.getArchivedActions().forEach(actionDTO -> { + actionDTO.setPageId(defaultActionCollection.getPageId()); + actionDTO.setApplicationId(defaultActionCollection.getApplicationId()); + actionDTO.setCollectionId(defaultActionCollection.getId()); + actionDTO.setId(defaultToBranchedActionIdMap.get(actionDTO.getId())); + }); } return refactorAction(refactorActionNameInCollectionDTO); }) .map(responseUtils::updateLayoutDTOWithDefaultResources); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutServiceCE.java index e94e47f2f90f..9c3fa758a5ea 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutServiceCE.java @@ -12,5 +12,4 @@ public interface LayoutServiceCE { Mono<Layout> getLayout(String pageId, String layoutId, Boolean viewMode); Mono<Layout> getLayout(String defaultPageId, String layoutId, Boolean viewMode, String branchName); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutServiceCEImpl.java index 6ce8bff21c55..9cb365b038d9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutServiceCEImpl.java @@ -25,9 +25,8 @@ public class LayoutServiceCEImpl implements LayoutServiceCE { private final PagePermission pagePermission; @Autowired - public LayoutServiceCEImpl(NewPageService newPageService, - ResponseUtils responseUtils, - PagePermission pagePermission) { + public LayoutServiceCEImpl( + NewPageService newPageService, ResponseUtils responseUtils, PagePermission pagePermission) { this.newPageService = newPageService; this.responseUtils = responseUtils; this.pagePermission = pagePermission; @@ -44,14 +43,13 @@ public Mono<Layout> createLayout(String pageId, Layout layout) { .findPageById(pageId, pagePermission.getEditPermission(), false) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.PAGE_ID))); - return pageMono - .map(page -> { + return pageMono.map(page -> { List<Layout> layoutList = page.getLayouts(); if (layoutList == null) { - //no layouts exist for this page + // no layouts exist for this page layoutList = new ArrayList<Layout>(); } - //Adding an Id to the layout to ensure that a layout can be referred to by its ID as well. + // Adding an Id to the layout to ensure that a layout can be referred to by its ID as well. layout.setId(new ObjectId().toString()); layoutList.add(layout); @@ -67,19 +65,26 @@ public Mono<Layout> createLayout(String defaultPageId, Layout layout, String bra if (StringUtils.isEmpty(branchName)) { return createLayout(defaultPageId, layout); } - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) .flatMap(branchedPage -> createLayout(branchedPage.getId(), layout)) .map(responseUtils::updateLayoutWithDefaultResources); } @Override public Mono<Layout> getLayout(String pageId, String layoutId, Boolean viewMode) { - return newPageService.findByIdAndLayoutsId(pageId, layoutId, pagePermission.getReadPermission(), viewMode) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.PAGE_ID + " or " + FieldName.LAYOUT_ID))) + return newPageService + .findByIdAndLayoutsId(pageId, layoutId, pagePermission.getReadPermission(), viewMode) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.INVALID_PARAMETER, FieldName.PAGE_ID + " or " + FieldName.LAYOUT_ID))) .map(page -> { List<Layout> layoutList = page.getLayouts(); - //Because the findByIdAndLayoutsId call returned non-empty result, we are guaranteed to find the layoutId here. - Layout matchedLayout = layoutList.stream().filter(layout -> layout.getId().equals(layoutId)).findFirst().get(); + // Because the findByIdAndLayoutsId call returned non-empty result, we are guaranteed to find the + // layoutId here. + Layout matchedLayout = layoutList.stream() + .filter(layout -> layout.getId().equals(layoutId)) + .findFirst() + .get(); matchedLayout.setViewMode(viewMode); return matchedLayout; }); @@ -90,11 +95,9 @@ public Mono<Layout> getLayout(String defaultPageId, String layoutId, Boolean vie if (StringUtils.isEmpty(branchName)) { return getLayout(defaultPageId, layoutId, viewMode); } - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) .flatMap(branchedPage -> getLayout(branchedPage.getId(), layoutId, viewMode)) .map(responseUtils::updateLayoutWithDefaultResources); } - - } - diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/MarketplaceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/MarketplaceServiceCEImpl.java index 4e57d722ceac..9b3a9a13a027 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/MarketplaceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/MarketplaceServiceCEImpl.java @@ -44,12 +44,12 @@ public class MarketplaceServiceCEImpl implements MarketplaceServiceCE { private final Long timeoutInMillis = Long.valueOf(10000); @Autowired - public MarketplaceServiceCEImpl(WebClient.Builder webClientBuilder, - CloudServicesConfig cloudServicesConfig, ObjectMapper objectMapper) { + public MarketplaceServiceCEImpl( + WebClient.Builder webClientBuilder, CloudServicesConfig cloudServicesConfig, ObjectMapper objectMapper) { this.cloudServicesConfig = cloudServicesConfig; this.webClient = webClientBuilder - .defaultHeaders(header -> header.setBasicAuth(cloudServicesConfig.getUsername(), - cloudServicesConfig.getPassword())) + .defaultHeaders(header -> + header.setBasicAuth(cloudServicesConfig.getUsername(), cloudServicesConfig.getPassword())) .baseUrl(cloudServicesConfig.getBaseUrl()) .build(); this.objectMapper = objectMapper; @@ -143,11 +143,7 @@ public Mono<Boolean> subscribeAndUpdateStatisticsOfProvider(String providerId) { return Mono.error(new AppsmithException(AppsmithError.MARKETPLACE_NOT_CONFIGURED)); } - return webClient - .put() - .uri(uri) - .retrieve() - .bodyToMono(Boolean.class); + return webClient.put().uri(uri).retrieve().bodyToMono(Boolean.class); } @Override diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/MockDataServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/MockDataServiceCEImpl.java index 854f0523f5a1..943105fa7d7e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/MockDataServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/MockDataServiceCEImpl.java @@ -50,10 +50,11 @@ public class MockDataServiceCEImpl implements MockDataServiceCE { private Instant cacheExpiryTime = null; @Autowired - public MockDataServiceCEImpl(CloudServicesConfig cloudServicesConfig, - DatasourceService datasourceService, - AnalyticsService analyticsService, - SessionUserService sessionUserService) { + public MockDataServiceCEImpl( + CloudServicesConfig cloudServicesConfig, + DatasourceService datasourceService, + AnalyticsService analyticsService, + SessionUserService sessionUserService) { this.cloudServicesConfig = cloudServicesConfig; this.datasourceService = datasourceService; this.analyticsService = analyticsService; @@ -71,18 +72,17 @@ public Mono<MockDataDTO> getMockDataSet() { return Mono.justOrEmpty(mockData); } - return WebClientUtils - .create(baseUrl + "/api/v1/mocks") + return WebClientUtils.create(baseUrl + "/api/v1/mocks") .get() .exchange() .flatMap(response -> { if (response.statusCode().is2xxSuccessful()) { - return response.bodyToMono(new ParameterizedTypeReference<ResponseDTO<MockDataDTO>>() { - }); + return response.bodyToMono(new ParameterizedTypeReference<ResponseDTO<MockDataDTO>>() {}); } else { return Mono.error(new AppsmithException( AppsmithError.CLOUD_SERVICES_ERROR, - "Unable to connect to cloud-services with error status {0}", response.statusCode())); + "Unable to connect to cloud-services with error status {0}", + response.statusCode())); } }) .map(ResponseDTO::getData) @@ -92,7 +92,6 @@ public Mono<MockDataDTO> getMockDataSet() { return config; }) .doOnError(error -> log.error("Error fetching mock data sets config from cloud services", error)); - } @Override @@ -113,7 +112,8 @@ public Mono<Datasource> createMockDataSet(MockDataSource mockDataSource, String datasourceConfiguration = getPostgresDataSourceConfiguration(mockDataSource.getName(), mockDataDTO); } if (datasourceConfiguration.getAuthentication() == null) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, + return Mono.error(new AppsmithException( + AppsmithError.INVALID_PARAMETER, " Couldn't find any mock datasource with the given name - " + mockDataSource.getName())); } Datasource datasource = new Datasource(); @@ -124,9 +124,11 @@ public Mono<Datasource> createMockDataSet(MockDataSource mockDataSource, String HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - return datasourceService.getTrueEnvironmentId(mockDataSource.getWorkspaceId(), environmentId) + return datasourceService + .getTrueEnvironmentId(mockDataSource.getWorkspaceId(), environmentId) .flatMap(trueEnvironmentId -> { - storages.put(trueEnvironmentId, + storages.put( + trueEnvironmentId, new DatasourceStorageDTO(null, trueEnvironmentId, datasourceConfiguration)); datasource.setDatasourceStorages(storages); @@ -134,7 +136,6 @@ public Mono<Datasource> createMockDataSet(MockDataSource mockDataSource, String .then(createSuffixedDatasource(datasource, trueEnvironmentId)); }); }); - } private DatasourceConfiguration getMongoDataSourceConfiguration(String name, MockDataDTO mockDataSet) { @@ -146,7 +147,9 @@ private DatasourceConfiguration getMongoDataSourceConfiguration(String name, Moc List<Property> listProperty = new ArrayList<>(); SSLDetails sslDetails = new SSLDetails(); - Optional<MockDataCredentials> credentialsList = mockDataSet.getCredentials().stream().filter(cred -> cred.getDbname().equalsIgnoreCase(name)).findFirst(); + Optional<MockDataCredentials> credentialsList = mockDataSet.getCredentials().stream() + .filter(cred -> cred.getDbname().equalsIgnoreCase(name)) + .findFirst(); if (Boolean.TRUE.equals(credentialsList.isEmpty())) { return datasourceConfiguration; } @@ -174,7 +177,6 @@ private DatasourceConfiguration getMongoDataSourceConfiguration(String name, Moc datasourceConfiguration.setConnection(connection); datasourceConfiguration.setAuthentication(auth); return datasourceConfiguration; - } private DatasourceConfiguration getPostgresDataSourceConfiguration(String name, MockDataDTO mockDataSet) { @@ -185,7 +187,9 @@ private DatasourceConfiguration getPostgresDataSourceConfiguration(String name, Endpoint endpoint = new Endpoint(); List<Endpoint> endpointList = new ArrayList<>(); - Optional<MockDataCredentials> credentialsList = mockDataSet.getCredentials().stream().filter(cred -> cred.getDbname().equalsIgnoreCase(name)).findFirst(); + Optional<MockDataCredentials> credentialsList = mockDataSet.getCredentials().stream() + .filter(cred -> cred.getDbname().equalsIgnoreCase(name)) + .findFirst(); if (Boolean.TRUE.equals(credentialsList.isEmpty())) { return datasourceConfiguration; } @@ -197,7 +201,6 @@ private DatasourceConfiguration getPostgresDataSourceConfiguration(String name, endpoint.setHost(credentials.getHost()); endpointList.add(endpoint); - auth.setDatabaseName(credentials.getDbname()); auth.setPassword(credentials.getPassword()); auth.setUsername(credentials.getUsername()); @@ -221,25 +224,28 @@ private Mono<Datasource> createSuffixedDatasource(Datasource datasource, String * @param suffix Suffix used for appending, recursion artifact. Usually set to 0. * @return A Mono that yields the created datasource. */ - private Mono<Datasource> createSuffixedDatasource(Datasource datasource, String name, String environmentId, int suffix) { + private Mono<Datasource> createSuffixedDatasource( + Datasource datasource, String name, String environmentId, int suffix) { final String actualName = name + (suffix == 0 ? "" : " (" + suffix + ")"); datasource.setName(actualName); String password = null; - DatasourceStorageDTO datasourceStorageDTO = datasource.getDatasourceStorages().get(environmentId); + DatasourceStorageDTO datasourceStorageDTO = + datasource.getDatasourceStorages().get(environmentId); if (datasourceStorageDTO.getDatasourceConfiguration().getAuthentication() instanceof DBAuth) { - password = ((DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication()).getPassword(); + password = + ((DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication()).getPassword(); } final String finalPassword = password; - return datasourceService.create(datasource) - .onErrorResume(DuplicateKeyException.class, error -> { - if (error.getMessage() != null - && error.getMessage().contains("workspace_datasource_deleted_compound_index") - && datasourceStorageDTO.getDatasourceConfiguration().getAuthentication() instanceof DBAuth) { - ((DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication()).setPassword(finalPassword); - return createSuffixedDatasource(datasource, name, environmentId, 1 + suffix); - } - throw error; - }); + return datasourceService.create(datasource).onErrorResume(DuplicateKeyException.class, error -> { + if (error.getMessage() != null + && error.getMessage().contains("workspace_datasource_deleted_compound_index") + && datasourceStorageDTO.getDatasourceConfiguration().getAuthentication() instanceof DBAuth) { + ((DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication()) + .setPassword(finalPassword); + return createSuffixedDatasource(datasource, name, environmentId, 1 + suffix); + } + throw error; + }); } private Mono<User> addAnalyticsForMockDataCreation(String name, String workspaceId) { @@ -247,17 +253,13 @@ private Mono<User> addAnalyticsForMockDataCreation(String name, String workspace return Mono.empty(); } - return sessionUserService.getCurrentUser() - .flatMap(user -> - analyticsService.sendEvent( - AnalyticsEvents.CREATE.getEventName(), - user.getUsername(), - Map.of( - "MockDataSource", defaultIfNull(name, ""), - "orgId", defaultIfNull(workspaceId, "") - ) - ).thenReturn(user) - ); + return sessionUserService.getCurrentUser().flatMap(user -> analyticsService + .sendEvent( + AnalyticsEvents.CREATE.getEventName(), + user.getUsername(), + Map.of( + "MockDataSource", defaultIfNull(name, ""), + "orgId", defaultIfNull(workspaceId, ""))) + .thenReturn(user)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCE.java index ed2ba2de0b46..76931b2972ac 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCE.java @@ -59,9 +59,11 @@ public interface NewActionServiceCE extends CrudService<NewAction, String> { Flux<NewAction> findByPageIdAndViewMode(String pageId, Boolean viewMode, AclPermission permission); - Flux<NewAction> findAllByApplicationIdAndViewMode(String applicationId, Boolean viewMode, AclPermission permission, Sort sort); + Flux<NewAction> findAllByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, AclPermission permission, Sort sort); - Flux<NewAction> findAllByApplicationIdAndViewMode(String applicationId, Boolean viewMode, Optional<AclPermission> permission, Optional<Sort> sort); + Flux<NewAction> findAllByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, Optional<AclPermission> permission, Optional<Sort> sort); Flux<ActionViewDTO> getActionsForViewMode(String applicationId); @@ -71,7 +73,8 @@ public interface NewActionServiceCE extends CrudService<NewAction, String> { Flux<ActionDTO> getUnpublishedActions(MultiValueMap<String, String> params, Boolean includeJsActions); - Flux<ActionDTO> getUnpublishedActions(MultiValueMap<String, String> params, String branchName, Boolean includeJsActions); + Flux<ActionDTO> getUnpublishedActions( + MultiValueMap<String, String> params, String branchName, Boolean includeJsActions); Flux<ActionDTO> getUnpublishedActions(MultiValueMap<String, String> params); @@ -95,15 +98,18 @@ public interface NewActionServiceCE extends CrudService<NewAction, String> { String replaceMustacheWithQuestionMark(String query, List<String> mustacheBindings); - Mono<Boolean> updateActionsExecuteOnLoad(List<ActionDTO> actions, String pageId, List<LayoutActionUpdateDTO> actionUpdates, List<String> messages); + Mono<Boolean> updateActionsExecuteOnLoad( + List<ActionDTO> actions, String pageId, List<LayoutActionUpdateDTO> actionUpdates, List<String> messages); Flux<ActionDTO> getUnpublishedActionsExceptJs(MultiValueMap<String, String> params); Flux<ActionDTO> getUnpublishedActionsExceptJs(MultiValueMap<String, String> params, String branchName); - Mono<NewAction> findByBranchNameAndDefaultActionId(String branchName, String defaultActionId, AclPermission permission); + Mono<NewAction> findByBranchNameAndDefaultActionId( + String branchName, String defaultActionId, AclPermission permission); - Mono<String> findBranchedIdByBranchNameAndDefaultActionId(String branchName, String defaultActionId, AclPermission permission); + Mono<String> findBranchedIdByBranchNameAndDefaultActionId( + String branchName, String defaultActionId, AclPermission permission); Mono<NewAction> sanitizeAction(NewAction action); @@ -113,16 +119,16 @@ public interface NewActionServiceCE extends CrudService<NewAction, String> { void populateDefaultResources(NewAction newAction, NewAction branchedAction, String branchName); - Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActionList, - Application importedApplication, - String branchName, - Map<String, NewPage> pageNameMap, - Map<String, String> pluginMap, - Map<String, String> datasourceMap, - ImportApplicationPermissionProvider permissionProvider); + Mono<ImportActionResultDTO> importActions( + List<NewAction> importedNewActionList, + Application importedApplication, + String branchName, + Map<String, NewPage> pageNameMap, + Map<String, String> pluginMap, + Map<String, String> datasourceMap, + ImportApplicationPermissionProvider permissionProvider); Mono<ImportedActionAndCollectionMapsDTO> updateActionsWithImportedCollectionIds( ImportActionCollectionResultDTO importActionCollectionResultDTO, - ImportActionResultDTO importActionResultDTO - ); + ImportActionResultDTO importActionResultDTO); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java index ee1e834628a6..f8536847055e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java @@ -35,7 +35,6 @@ import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.server.helpers.PluginExecutorHelper; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.helpers.ResponseUtils; import com.appsmith.server.helpers.ce.ImportApplicationPermissionProvider; import com.appsmith.server.repositories.NewActionRepository; @@ -52,6 +51,7 @@ import com.appsmith.server.solutions.ApplicationPermission; import com.appsmith.server.solutions.DatasourcePermission; import com.appsmith.server.solutions.PagePermission; +import com.appsmith.server.solutions.PolicySolution; import io.micrometer.observation.ObservationRegistry; import jakarta.validation.Validator; import lombok.extern.slf4j.Slf4j; @@ -98,7 +98,8 @@ import static java.lang.Boolean.TRUE; @Slf4j -public class NewActionServiceCEImpl extends BaseService<NewActionRepository, NewAction, String> implements NewActionServiceCE { +public class NewActionServiceCEImpl extends BaseService<NewActionRepository, NewAction, String> + implements NewActionServiceCE { public static final String DATA = "data"; public static final String STATUS = "status"; @@ -109,7 +110,6 @@ public class NewActionServiceCEImpl extends BaseService<NewActionRepository, New public static final PluginType JS_PLUGIN_TYPE = PluginType.JS; public static final String JS_PLUGIN_PACKAGE_NAME = "js-plugin"; - private final NewActionRepository repository; private final DatasourceService datasourceService; private final PluginService pluginService; @@ -132,28 +132,29 @@ public class NewActionServiceCEImpl extends BaseService<NewActionRepository, New private final Map<String, Plugin> defaultPluginMap = new HashMap<>(); private final AtomicReference<Plugin> jsTypePluginReference = new AtomicReference<>(); - public NewActionServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - NewActionRepository repository, - AnalyticsService analyticsService, - DatasourceService datasourceService, - PluginService pluginService, - PluginExecutorHelper pluginExecutorHelper, - MarketplaceService marketplaceService, - PolicyGenerator policyGenerator, - NewPageService newPageService, - ApplicationService applicationService, - PolicySolution policySolution, - ConfigService configService, - ResponseUtils responseUtils, - PermissionGroupService permissionGroupService, - DatasourcePermission datasourcePermission, - ApplicationPermission applicationPermission, - PagePermission pagePermission, - ActionPermission actionPermission, - ObservationRegistry observationRegistry) { + public NewActionServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + NewActionRepository repository, + AnalyticsService analyticsService, + DatasourceService datasourceService, + PluginService pluginService, + PluginExecutorHelper pluginExecutorHelper, + MarketplaceService marketplaceService, + PolicyGenerator policyGenerator, + NewPageService newPageService, + ApplicationService applicationService, + PolicySolution policySolution, + ConfigService configService, + ResponseUtils responseUtils, + PermissionGroupService permissionGroupService, + DatasourcePermission datasourcePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission, + ObservationRegistry observationRegistry) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.repository = repository; @@ -226,14 +227,16 @@ public Mono<ActionDTO> generateActionByViewMode(NewAction newAction, Boolean vie if (newAction.getPublishedAction() != null) { action = newAction.getPublishedAction(); } else { - // We are trying to fetch published action but it doesn't exist because the action hasn't been published yet + // We are trying to fetch published action but it doesn't exist because the action hasn't been published + // yet return Mono.empty(); } } else { if (newAction.getUnpublishedAction() != null) { action = newAction.getUnpublishedAction(); } else { - return Mono.error(new AppsmithException(AppsmithError.INVALID_ACTION, newAction.getId(), "No unpublished action found for edit mode")); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_ACTION, newAction.getId(), "No unpublished action found for edit mode")); } } @@ -255,7 +258,8 @@ public void generateAndSetActionPolicies(NewPage page, NewAction action) { if (page == null) { throw new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR, "No page found to copy policies from."); } - Set<Policy> documentPolicies = policyGenerator.getAllChildPolicies(page.getPolicies(), Page.class, Action.class); + Set<Policy> documentPolicies = + policyGenerator.getAllChildPolicies(page.getPolicies(), Page.class, Action.class); action.setPolicies(documentPolicies); } @@ -269,7 +273,8 @@ public Mono<ActionDTO> validateAndSaveActionToRepository(NewAction newAction) { ActionDTO action = newAction.getUnpublishedAction(); if (action.getDefaultResources() == null) { - return Mono.error(new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "action", action.getName())); + return Mono.error( + new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "action", action.getName())); } // Remove default appId, branchName and actionId to avoid duplication these resources will be present in @@ -301,7 +306,9 @@ public Mono<ActionDTO> validateAndSaveActionToRepository(NewAction newAction) { invalids.add(AppsmithError.NO_CONFIGURATION_FOUND_IN_ACTION.getMessage()); } - if (action.getPluginType() == PluginType.JS && action.getActionConfiguration() != null && Boolean.FALSE.equals(action.getActionConfiguration().getIsValid())) { + if (action.getPluginType() == PluginType.JS + && action.getActionConfiguration() != null + && Boolean.FALSE.equals(action.getActionConfiguration().getIsValid())) { action.setIsValid(false); invalids.add(AppsmithError.INVALID_JS_ACTION.getMessage()); } @@ -309,14 +316,13 @@ public Mono<ActionDTO> validateAndSaveActionToRepository(NewAction newAction) { // Validate actionConfiguration ActionConfiguration actionConfig = action.getActionConfiguration(); if (actionConfig != null) { - validator.validate(actionConfig) - .stream() - .forEach(x -> invalids.add(x.getMessage())); + validator.validate(actionConfig).stream().forEach(x -> invalids.add(x.getMessage())); } if (action.getDatasource() == null || action.getDatasource().getIsAutoGenerated()) { if (action.getPluginType() != PluginType.JS) { - // This action isn't of type JS functions which requires that the pluginType be set by the client. Hence, + // This action isn't of type JS functions which requires that the pluginType be set by the client. + // Hence, // datasource is very much required for such an action. action.setIsValid(false); invalids.add(AppsmithError.DATASOURCE_NOT_GIVEN.getMessage()); @@ -324,7 +330,8 @@ public Mono<ActionDTO> validateAndSaveActionToRepository(NewAction newAction) { return super.create(newAction) .flatMap(savedAction -> { // If the default action is not set then current action will be the default one - if (!StringUtils.hasLength(savedAction.getDefaultResources().getActionId())) { + if (!StringUtils.hasLength( + savedAction.getDefaultResources().getActionId())) { savedAction.getDefaultResources().setActionId(savedAction.getId()); } return repository.save(savedAction); @@ -338,19 +345,21 @@ public Mono<ActionDTO> validateAndSaveActionToRepository(NewAction newAction) { if (action.getDatasource().getId() == null) { // This is a nested datasource. If the action is in bad state (aka without workspace id, add the same) - if (action.getDatasource().getWorkspaceId() == null && action.getDatasource().getOrganizationId() != null) { + if (action.getDatasource().getWorkspaceId() == null + && action.getDatasource().getOrganizationId() != null) { action.getDatasource().setWorkspaceId(action.getDatasource().getOrganizationId()); } - datasourceMono = Mono.just(action.getDatasource()) - .flatMap(datasourceService::validateDatasource); + datasourceMono = Mono.just(action.getDatasource()).flatMap(datasourceService::validateDatasource); } else { // TODO: check if datasource should be fetched with edit during action create or update. - //Data source already exists. Find the same. - datasourceMono = datasourceService.findById(action.getDatasource().getId()) + // Data source already exists. Find the same. + datasourceMono = datasourceService + .findById(action.getDatasource().getId()) .switchIfEmpty(Mono.defer(() -> { action.setIsValid(false); - invalids.add(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.DATASOURCE, action.getDatasource().getId())); + invalids.add(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.DATASOURCE, action.getDatasource().getId())); return Mono.just(action.getDatasource()); })) .map(datasource -> { @@ -367,17 +376,16 @@ public Mono<ActionDTO> validateAndSaveActionToRepository(NewAction newAction) { if (datasource.getPluginId() == null) { return Mono.error(new AppsmithException(AppsmithError.PLUGIN_ID_NOT_GIVEN)); } - return pluginService.findById(datasource.getPluginId()) - .switchIfEmpty(Mono.defer(() -> { - action.setIsValid(false); - invalids.add(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PLUGIN, datasource.getPluginId())); - return Mono.just(new Plugin()); - })); + return pluginService.findById(datasource.getPluginId()).switchIfEmpty(Mono.defer(() -> { + action.setIsValid(false); + invalids.add(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PLUGIN, datasource.getPluginId())); + return Mono.just(new Plugin()); + })); }); return pluginMono .zipWith(datasourceMono) - //Set plugin in the action before saving. + // Set plugin in the action before saving. .map(tuple -> { Plugin plugin = tuple.getT1(); Datasource datasource = tuple.getT2(); @@ -464,12 +472,18 @@ private Set<MustacheBindingToken> extractKeysFromAction(ActionDTO actionDTO) { @Override public NewAction extractAndSetJsonPathKeys(NewAction newAction) { ActionDTO action = newAction.getUnpublishedAction(); - Set<String> actionKeys = extractKeysFromAction(action).stream().map(token -> token.getValue()).collect(Collectors.toSet()); - Set<String> datasourceKeys = datasourceService.extractKeysFromDatasource(action.getDatasource()).stream().map(token -> token.getValue()).collect(Collectors.toSet()); - Set<String> keys = new HashSet<>() {{ - addAll(actionKeys); - addAll(datasourceKeys); - }}; + Set<String> actionKeys = extractKeysFromAction(action).stream() + .map(token -> token.getValue()) + .collect(Collectors.toSet()); + Set<String> datasourceKeys = datasourceService.extractKeysFromDatasource(action.getDatasource()).stream() + .map(token -> token.getValue()) + .collect(Collectors.toSet()); + Set<String> keys = new HashSet<>() { + { + addAll(actionKeys); + addAll(datasourceKeys); + } + }; action.setJsonPathKeys(keys); return newAction; @@ -484,7 +498,8 @@ private Mono<ActionDTO> setTransientFieldsInUnpublishedAction(NewAction newActio return Mono.empty(); } - // In case of an action which was imported from a 3P API, fill in the extra information of the provider required by the front end UI. + // In case of an action which was imported from a 3P API, fill in the extra information of the provider required + // by the front end UI. Mono<ActionDTO> providerUpdateMono; if ((action.getTemplateId() != null) && (action.getProviderId() != null)) { @@ -510,7 +525,8 @@ private Mono<ActionDTO> setTransientFieldsInUnpublishedAction(NewAction newActio .map(actionDTO -> { DefaultResources defaults = newAction.getDefaultResources(); if (defaults == null) { - throw new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "action", newAction.getId()); + throw new AppsmithException( + AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "action", newAction.getId()); } actionDTO.getDefaultResources().setActionId(defaults.getActionId()); actionDTO.getDefaultResources().setApplicationId(defaults.getApplicationId()); @@ -532,7 +548,8 @@ public Mono<ActionDTO> updateUnpublishedAction(String id, ActionDTO action) { // the update doesn't lead to resetting of this field. action.setUserSetOnLoad(null); - Mono<NewAction> updatedActionMono = repository.findById(id, actionPermission.getEditPermission()) + Mono<NewAction> updatedActionMono = repository + .findById(id, actionPermission.getEditPermission()) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))) .map(dbAction -> { final ActionDTO unpublishedAction = dbAction.getUnpublishedAction(); @@ -540,8 +557,8 @@ public Mono<ActionDTO> updateUnpublishedAction(String id, ActionDTO action) { // In case this update is for an action that represents a JS function, // perform a check to reset values for sync functions - final boolean isSyncJSFunction = PluginType.JS.equals(action.getPluginType()) && - FALSE.equals(action.getActionConfiguration().getIsAsync()); + final boolean isSyncJSFunction = PluginType.JS.equals(action.getPluginType()) + && FALSE.equals(action.getActionConfiguration().getIsAsync()); if (isSyncJSFunction) { unpublishedAction.setUserSetOnLoad(false); unpublishedAction.setConfirmBeforeExecute(false); @@ -553,40 +570,34 @@ public Mono<ActionDTO> updateUnpublishedAction(String id, ActionDTO action) { .cache(); return updatedActionMono - .flatMap(savedNewAction -> this.validateAndSaveActionToRepository(savedNewAction).zipWith(Mono.just(savedNewAction))) + .flatMap(savedNewAction -> + this.validateAndSaveActionToRepository(savedNewAction).zipWith(Mono.just(savedNewAction))) .zipWith(Mono.defer(() -> { - if (action.getDatasource() != null && - action.getDatasource().getId() != null) { + if (action.getDatasource() != null && action.getDatasource().getId() != null) { return datasourceService.findById(action.getDatasource().getId()); } else { return Mono.justOrEmpty(action.getDatasource()); } })) .flatMap(zippedData -> { - final Tuple2<ActionDTO, NewAction> zippedActions = zippedData.getT1(); final Datasource datasource = zippedData.getT2(); final NewAction newAction1 = zippedActions.getT2(); // This is being done in order to avoid any usage of datasource storages in client side. // the ideas is that datasourceStorages shouldn't be used for action's datasource configuration. - final ActionDTO savedActionDTO = zippedActions.getT1(); + final ActionDTO savedActionDTO = zippedActions.getT1(); if (savedActionDTO.getDatasource() != null) { savedActionDTO.getDatasource().setDatasourceStorages(null); } final Map<String, Object> data = this.getAnalyticsProperties(newAction1, datasource); - final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.ACTION, newAction1 - ); + final Map<String, Object> eventData = + Map.of(FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.ACTION, newAction1); data.put(FieldName.EVENT_DATA, eventData); - return analyticsService - .sendUpdateEvent(newAction1, data) - .thenReturn(savedActionDTO); - + return analyticsService.sendUpdateEvent(newAction1, data).thenReturn(savedActionDTO); }); } @@ -597,8 +608,7 @@ private Mono<NewAction> extractAndSetNativeQueryFromFormData(NewAction action) { return pluginExecutorMono .flatMap(pluginExecutor -> { pluginExecutor.extractAndSetNativeQueryFromFormData( - action.getUnpublishedAction().getActionConfiguration() - ); + action.getUnpublishedAction().getActionConfiguration()); return Mono.just(action); }) @@ -611,30 +621,32 @@ private Mono<NewAction> extractAndSetNativeQueryFromFormData(NewAction action) { * failure here would only cause a minor inconvenience to a beginner user since the form data would * not be auto translated to the raw query. */ - Map<String, Object> formData = action.getUnpublishedAction().getActionConfiguration().getFormData(); + Map<String, Object> formData = action.getUnpublishedAction() + .getActionConfiguration() + .getFormData(); setValueSafelyInFormData(formData, NATIVE_QUERY_PATH_STATUS, ERROR); setValueSafelyInFormData(formData, NATIVE_QUERY_PATH_DATA, e.getMessage()); return Mono.just(action); }); } - @Override public Mono<ActionDTO> findByUnpublishedNameAndPageId(String name, String pageId, AclPermission permission) { - return repository.findByUnpublishedNameAndPageId(name, pageId, permission) + return repository + .findByUnpublishedNameAndPageId(name, pageId, permission) .flatMap(action -> generateActionByViewMode(action, false)); } @Override public Mono<ActionDTO> findActionDTObyIdAndViewMode(String id, Boolean viewMode, AclPermission permission) { - return this.findById(id, permission) - .flatMap(action -> generateActionByViewMode(action, viewMode)); + return this.findById(id, permission).flatMap(action -> generateActionByViewMode(action, viewMode)); } @Override public Flux<NewAction> findUnpublishedOnLoadActionsExplicitSetByUserInPage(String pageId) { return repository - .findUnpublishedActionsByPageIdAndExecuteOnLoadSetByUserTrue(pageId, actionPermission.getEditPermission()) + .findUnpublishedActionsByPageIdAndExecuteOnLoadSetByUserTrue( + pageId, actionPermission.getEditPermission()) .flatMap(this::sanitizeAction); } @@ -654,52 +666,50 @@ public Flux<NewAction> findUnpublishedActionsInPageByNames(Set<String> names, St @Override public Mono<NewAction> findById(String id) { - return repository.findById(id) - .flatMap(this::sanitizeAction); + return repository.findById(id).flatMap(this::sanitizeAction); } @Override public Flux<NewAction> findAllById(Iterable<String> id) { - return repository.findAllById(id) - .flatMap(this::sanitizeAction); + return repository.findAllById(id).flatMap(this::sanitizeAction); } @Override public Mono<NewAction> findById(String id, AclPermission aclPermission) { - return repository.findById(id, aclPermission) - .flatMap(this::sanitizeAction); + return repository.findById(id, aclPermission).flatMap(this::sanitizeAction); } @Override public Flux<NewAction> findByPageId(String pageId, AclPermission permission) { - return repository.findByPageId(pageId, permission) - .flatMap(this::sanitizeAction); + return repository.findByPageId(pageId, permission).flatMap(this::sanitizeAction); } @Override public Flux<NewAction> findByPageId(String pageId, Optional<AclPermission> permission) { - return repository.findByPageId(pageId, permission) - .flatMap(this::sanitizeAction); + return repository.findByPageId(pageId, permission).flatMap(this::sanitizeAction); } @Override public Flux<NewAction> findByPageIdAndViewMode(String pageId, Boolean viewMode, AclPermission permission) { - return repository.findByPageIdAndViewMode(pageId, viewMode, permission) - .flatMap(this::sanitizeAction); + return repository.findByPageIdAndViewMode(pageId, viewMode, permission).flatMap(this::sanitizeAction); } @Override - public Flux<NewAction> findAllByApplicationIdAndViewMode(String applicationId, Boolean viewMode, AclPermission permission, Sort sort) { - return repository.findByApplicationId(applicationId, permission, sort) + public Flux<NewAction> findAllByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, AclPermission permission, Sort sort) { + return repository + .findByApplicationId(applicationId, permission, sort) // In case of view mode being true, filter out all the actions which haven't been published .flatMap(action -> { if (Boolean.TRUE.equals(viewMode)) { - // In case we are trying to fetch published actions but this action has not been published, do not return + // In case we are trying to fetch published actions but this action has not been published, do + // not return if (action.getPublishedAction() == null) { return Mono.empty(); } } - // No need to handle the edge case of unpublished action not being present. This is not possible because + // No need to handle the edge case of unpublished action not being present. This is not possible + // because // every created action starts from an unpublishedAction state. return Mono.just(action); @@ -708,17 +718,21 @@ public Flux<NewAction> findAllByApplicationIdAndViewMode(String applicationId, B } @Override - public Flux<NewAction> findAllByApplicationIdAndViewMode(String applicationId, Boolean viewMode, Optional<AclPermission> permission, Optional<Sort> sort) { - return repository.findByApplicationId(applicationId, permission, sort) + public Flux<NewAction> findAllByApplicationIdAndViewMode( + String applicationId, Boolean viewMode, Optional<AclPermission> permission, Optional<Sort> sort) { + return repository + .findByApplicationId(applicationId, permission, sort) // In case of view mode being true, filter out all the actions which haven't been published .flatMap(action -> { if (Boolean.TRUE.equals(viewMode)) { - // In case we are trying to fetch published actions but this action has not been published, do not return + // In case we are trying to fetch published actions but this action has not been published, do + // not return if (action.getPublishedAction() == null) { return Mono.empty(); } } - // No need to handle the edge case of unpublished action not being present. This is not possible because + // No need to handle the edge case of unpublished action not being present. This is not possible + // because // every created action starts from an unpublishedAction state. return Mono.just(action); @@ -729,7 +743,8 @@ public Flux<NewAction> findAllByApplicationIdAndViewMode(String applicationId, B @Override public Flux<ActionViewDTO> getActionsForViewMode(String defaultApplicationId, String branchName) { - return applicationService.findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getReadPermission()) + return applicationService + .findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getReadPermission()) .flatMapMany(this::getActionsForViewMode) .map(responseUtils::updateActionViewDTOWithDefaultResources) .name(GET_VIEW_MODE_ACTION) @@ -752,26 +767,34 @@ public Flux<ActionViewDTO> getActionsForViewMode(String applicationId) { actionViewDTO.setId(action.getDefaultResources().getActionId()); actionViewDTO.setName(action.getPublishedAction().getValidName()); actionViewDTO.setPageId(action.getPublishedAction().getPageId()); - actionViewDTO.setConfirmBeforeExecute(action.getPublishedAction().getConfirmBeforeExecute()); + actionViewDTO.setConfirmBeforeExecute( + action.getPublishedAction().getConfirmBeforeExecute()); // Update defaultResources DefaultResources defaults = action.getDefaultResources(); // Consider a situation when action is not published but user is viewing in deployed mode if (action.getPublishedAction().getDefaultResources() != null) { - defaults.setPageId(action.getPublishedAction().getDefaultResources().getPageId()); - defaults.setCollectionId(action.getPublishedAction().getDefaultResources().getCollectionId()); + defaults.setPageId(action.getPublishedAction() + .getDefaultResources() + .getPageId()); + defaults.setCollectionId(action.getPublishedAction() + .getDefaultResources() + .getCollectionId()); } else { defaults.setPageId(null); defaults.setCollectionId(null); } actionViewDTO.setDefaultResources(defaults); - if (action.getPublishedAction().getJsonPathKeys() != null && !action.getPublishedAction().getJsonPathKeys().isEmpty()) { + if (action.getPublishedAction().getJsonPathKeys() != null + && !action.getPublishedAction().getJsonPathKeys().isEmpty()) { Set<String> jsonPathKeys; jsonPathKeys = new HashSet<>(); jsonPathKeys.addAll(action.getPublishedAction().getJsonPathKeys()); actionViewDTO.setJsonPathKeys(jsonPathKeys); } if (action.getPublishedAction().getActionConfiguration() != null) { - actionViewDTO.setTimeoutInMillisecond(action.getPublishedAction().getActionConfiguration().getTimeoutInMillisecond()); + actionViewDTO.setTimeoutInMillisecond(action.getPublishedAction() + .getActionConfiguration() + .getTimeoutInMillisecond()); } return actionViewDTO; }); @@ -779,25 +802,27 @@ public Flux<ActionViewDTO> getActionsForViewMode(String applicationId) { @Override public Mono<ActionDTO> deleteUnpublishedAction(String id) { - Mono<NewAction> actionMono = repository.findById(id, actionPermission.getDeletePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))); + Mono<NewAction> actionMono = repository + .findById(id, actionPermission.getDeletePermission()) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))); return actionMono .flatMap(toDelete -> { - Mono<NewAction> newActionMono; // Using the name field to determine if the action was ever published. In case of never published // action, publishedAction would exist with empty datasource and default fields. - if (toDelete.getPublishedAction() != null && toDelete.getPublishedAction().getName() != null) { + if (toDelete.getPublishedAction() != null + && toDelete.getPublishedAction().getName() != null) { toDelete.getUnpublishedAction().setDeletedAt(Instant.now()); newActionMono = repository .save(toDelete) - .zipWith(Mono.defer(() -> { final ActionDTO action = toDelete.getUnpublishedAction(); - if (action.getDatasource() != null && - action.getDatasource().getId() != null) { - return datasourceService.findById(action.getDatasource().getId()); + if (action.getDatasource() != null + && action.getDatasource().getId() != null) { + return datasourceService.findById( + action.getDatasource().getId()); } else { return Mono.justOrEmpty(action.getDatasource()); } @@ -805,17 +830,18 @@ public Mono<ActionDTO> deleteUnpublishedAction(String id) { .flatMap(zippedActions -> { final Datasource datasource = zippedActions.getT2(); final NewAction newAction1 = zippedActions.getT1(); - final Map<String, Object> data = this.getAnalyticsProperties(newAction1, datasource); + final Map<String, Object> data = + this.getAnalyticsProperties(newAction1, datasource); final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.ACTION, newAction1 - ); + FieldName.APP_MODE, + ApplicationMode.EDIT.toString(), + FieldName.ACTION, + newAction1); data.put(FieldName.EVENT_DATA, eventData); return analyticsService .sendArchiveEvent(newAction1, data) .thenReturn(zippedActions.getT1()); - }) .thenReturn(toDelete); } else { @@ -824,9 +850,10 @@ public Mono<ActionDTO> deleteUnpublishedAction(String id) { .archive(toDelete) .zipWith(Mono.defer(() -> { final ActionDTO action = toDelete.getUnpublishedAction(); - if (action.getDatasource() != null && - action.getDatasource().getId() != null) { - return datasourceService.findById(action.getDatasource().getId()); + if (action.getDatasource() != null + && action.getDatasource().getId() != null) { + return datasourceService.findById( + action.getDatasource().getId()); } else { return Mono.justOrEmpty(action.getDatasource()); } @@ -834,17 +861,18 @@ public Mono<ActionDTO> deleteUnpublishedAction(String id) { .flatMap(zippedActions -> { final Datasource datasource = zippedActions.getT2(); final NewAction newAction1 = zippedActions.getT1(); - final Map<String, Object> data = this.getAnalyticsProperties(newAction1, datasource); + final Map<String, Object> data = + this.getAnalyticsProperties(newAction1, datasource); final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.ACTION, newAction1 - ); + FieldName.APP_MODE, + ApplicationMode.EDIT.toString(), + FieldName.ACTION, + newAction1); data.put(FieldName.EVENT_DATA, eventData); return analyticsService .sendDeleteEvent(newAction1, data) .thenReturn(zippedActions.getT1()); - }) .thenReturn(toDelete); } @@ -880,7 +908,8 @@ public Mono<ActionDTO> populateHintMessages(ActionDTO action) { if (action.getDatasource().getDatasourceConfiguration() != null) { dsConfigMono = Mono.just(action.getDatasource().getDatasourceConfiguration()); } else if (action.getDatasource().getId() != null) { - dsConfigMono = datasourceService.findById(action.getDatasource().getId()) + dsConfigMono = datasourceService + .findById(action.getDatasource().getId()) .flatMap(datasource -> { if (datasource.getDatasourceConfiguration() == null) { return Mono.just(new DatasourceConfiguration()); @@ -888,15 +917,10 @@ public Mono<ActionDTO> populateHintMessages(ActionDTO action) { return Mono.just(datasource.getDatasourceConfiguration()); }) - .switchIfEmpty( - Mono.error( - new AppsmithException( - AppsmithError.NO_RESOURCE_FOUND, - FieldName.DATASOURCE, - action.getDatasource().getId() - ) - ) - ); + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + FieldName.DATASOURCE, + action.getDatasource().getId()))); } else { dsConfigMono = Mono.just(new DatasourceConfiguration()); } @@ -946,26 +970,22 @@ public Flux<ActionDTO> getUnpublishedActions(MultiValueMap<String, String> param // function call is made which takes care of returning only the essential fields of an action if (FALSE.equals(includeJsActions)) { - actionsFromRepository = repository.findNonJsActionsByApplicationIdAndViewMode(params.getFirst(FieldName.APPLICATION_ID), - false, - actionPermission.getReadPermission()); + actionsFromRepository = repository.findNonJsActionsByApplicationIdAndViewMode( + params.getFirst(FieldName.APPLICATION_ID), false, actionPermission.getReadPermission()); } else { - actionsFromRepository = repository.findByApplicationIdAndViewMode(params.getFirst(FieldName.APPLICATION_ID), - false, - actionPermission.getReadPermission()); + actionsFromRepository = repository.findByApplicationIdAndViewMode( + params.getFirst(FieldName.APPLICATION_ID), false, actionPermission.getReadPermission()); } } else { if (FALSE.equals(includeJsActions)) { - actionsFromRepository = repository.findAllNonJsActionsByNameAndPageIdsAndViewMode(name, pageIds, false, - actionPermission.getReadPermission(), - sort); + actionsFromRepository = repository.findAllNonJsActionsByNameAndPageIdsAndViewMode( + name, pageIds, false, actionPermission.getReadPermission(), sort); } else { - actionsFromRepository = repository.findAllActionsByNameAndPageIdsAndViewMode(name, pageIds, false, - actionPermission.getReadPermission(), - sort); + actionsFromRepository = repository.findAllActionsByNameAndPageIdsAndViewMode( + name, pageIds, false, actionPermission.getReadPermission(), sort); } } @@ -974,24 +994,30 @@ public Flux<ActionDTO> getUnpublishedActions(MultiValueMap<String, String> param .flatMapMany(this::addMissingPluginDetailsIntoAllActions) .flatMap(this::setTransientFieldsInUnpublishedAction) // this generates four different tags, (ApplicationId, FieldId) *(True, False) - .tag("includeJsAction", (params.get(FieldName.APPLICATION_ID) == null ? FieldName.PAGE_ID : FieldName.APPLICATION_ID) + includeJsActions.toString()) + .tag( + "includeJsAction", + (params.get(FieldName.APPLICATION_ID) == null ? FieldName.PAGE_ID : FieldName.APPLICATION_ID) + + includeJsActions.toString()) .name(GET_ACTION_REPOSITORY_CALL) .tap(Micrometer.observation(observationRegistry)); } @Override - public Flux<ActionDTO> getUnpublishedActions(MultiValueMap<String, String> params, - String branchName, - Boolean includeJsActions) { + public Flux<ActionDTO> getUnpublishedActions( + MultiValueMap<String, String> params, String branchName, Boolean includeJsActions) { MultiValueMap<String, String> updatedParams = new LinkedMultiValueMap<>(params); // Get branched applicationId and pageId Mono<NewPage> branchedPageMono = !StringUtils.hasLength(params.getFirst(FieldName.PAGE_ID)) ? Mono.just(new NewPage()) - : newPageService.findByBranchNameAndDefaultPageId(branchName, params.getFirst(FieldName.PAGE_ID), pagePermission.getReadPermission()); + : newPageService.findByBranchNameAndDefaultPageId( + branchName, params.getFirst(FieldName.PAGE_ID), pagePermission.getReadPermission()); Mono<Application> branchedApplicationMono = !StringUtils.hasLength(params.getFirst(FieldName.APPLICATION_ID)) ? Mono.just(new Application()) - : applicationService.findByBranchNameAndDefaultApplicationId(branchName, params.getFirst(FieldName.APPLICATION_ID), applicationPermission.getReadPermission()); + : applicationService.findByBranchNameAndDefaultApplicationId( + branchName, + params.getFirst(FieldName.APPLICATION_ID), + applicationPermission.getReadPermission()); return Mono.zip(branchedApplicationMono, branchedPageMono) .flatMapMany(tuple -> { @@ -1000,7 +1026,8 @@ public Flux<ActionDTO> getUnpublishedActions(MultiValueMap<String, String> param if (!CollectionUtils.isEmpty(params.get(FieldName.PAGE_ID)) && StringUtils.hasLength(pageId)) { updatedParams.set(FieldName.PAGE_ID, pageId); } - if (!CollectionUtils.isEmpty(params.get(FieldName.APPLICATION_ID)) && StringUtils.hasLength(applicationId)) { + if (!CollectionUtils.isEmpty(params.get(FieldName.APPLICATION_ID)) + && StringUtils.hasLength(applicationId)) { updatedParams.set(FieldName.APPLICATION_ID, applicationId); } return getUnpublishedActions(updatedParams, includeJsActions); @@ -1059,13 +1086,13 @@ public Flux<NewAction> addMissingPluginDetailsIntoAllActions(List<NewAction> act */ if (CollectionUtils.isEmpty(defaultPluginMap)) { - pluginMapMono = pluginService.getDefaultPlugins() + pluginMapMono = pluginService + .getDefaultPlugins() .collectMap(Plugin::getId) .map(pluginMap -> { pluginMap.forEach((pluginId, plugin) -> { defaultPluginMap.put(pluginId, plugin); - if (JS_PLUGIN_PACKAGE_NAME - .equals(plugin.getPackageName())) { + if (JS_PLUGIN_PACKAGE_NAME.equals(plugin.getPackageName())) { jsTypePluginReference.set(plugin); } }); @@ -1073,14 +1100,12 @@ public Flux<NewAction> addMissingPluginDetailsIntoAllActions(List<NewAction> act }); } - return pluginMapMono - .thenMany(Flux.fromIterable(actionList)) - .flatMap(action -> { - if (!isPluginTypeOrPluginIdMissing(action)) { - return Mono.just(action); - } - return addMissingPluginDetailsToNewActionObjects(action); - }); + return pluginMapMono.thenMany(Flux.fromIterable(actionList)).flatMap(action -> { + if (!isPluginTypeOrPluginIdMissing(action)) { + return Mono.just(action); + } + return addMissingPluginDetailsToNewActionObjects(action); + }); } private Mono<NewAction> addMissingPluginDetailsToNewActionObjects(NewAction action) { @@ -1115,11 +1140,12 @@ public Mono<ActionDTO> fillSelfReferencingDataPaths(ActionDTO actionDTO) { Mono<Plugin> pluginMono = pluginService.getById(actionDTO.getPluginId()); Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper.getPluginExecutor(pluginMono); - return pluginExecutorMono - .map(pluginExecutor -> { - actionDTO.getActionConfiguration().setSelfReferencingDataPaths(pluginExecutor.getSelfReferencingDataPaths()); - return actionDTO; - }); + return pluginExecutorMono.map(pluginExecutor -> { + actionDTO + .getActionConfiguration() + .setSelfReferencingDataPaths(pluginExecutor.getSelfReferencingDataPaths()); + return actionDTO; + }); } private boolean isPluginTypeOrPluginIdMissing(NewAction action) { @@ -1154,38 +1180,36 @@ private Mono<NewAction> providePluginTypeAndIdToNewActionObjectUsingJSTypeOrData } private Mono<NewAction> setPluginTypeFromId(NewAction action, String pluginId) { - return pluginService.findById(pluginId) - .flatMap(plugin -> { - action.setPluginType(plugin.getType()); - return Mono.just(action); - }); + return pluginService.findById(pluginId).flatMap(plugin -> { + action.setPluginType(plugin.getType()); + return Mono.just(action); + }); } private Mono<NewAction> setPluginIdAndTypeForJSAction(NewAction action) { action.setPluginType(JS_PLUGIN_TYPE); - return pluginService.findByPackageName(JS_PLUGIN_PACKAGE_NAME) - .flatMap(plugin -> { - action.setPluginId(plugin.getId()); - return Mono.just(action); - }); + return pluginService.findByPackageName(JS_PLUGIN_PACKAGE_NAME).flatMap(plugin -> { + action.setPluginId(plugin.getId()); + return Mono.just(action); + }); } // We can afford to make this call all the time since we already have all the info we need in context private Mono<DatasourceContext> getRemoteDatasourceContext(Plugin plugin, Datasource datasource) { final DatasourceContext datasourceContext = new DatasourceContext(); - return configService.getInstanceId() - .map(instanceId -> { - ExecutePluginDTO executePluginDTO = new ExecutePluginDTO(); - executePluginDTO.setInstallationKey(instanceId); - executePluginDTO.setPluginName(plugin.getPluginName()); - executePluginDTO.setPluginVersion(plugin.getVersion()); - executePluginDTO.setDatasource(new RemoteDatasourceDTO(datasource.getId(), datasource.getDatasourceConfiguration())); - datasourceContext.setConnection(executePluginDTO); + return configService.getInstanceId().map(instanceId -> { + ExecutePluginDTO executePluginDTO = new ExecutePluginDTO(); + executePluginDTO.setInstallationKey(instanceId); + executePluginDTO.setPluginName(plugin.getPluginName()); + executePluginDTO.setPluginVersion(plugin.getVersion()); + executePluginDTO.setDatasource( + new RemoteDatasourceDTO(datasource.getId(), datasource.getDatasourceConfiguration())); + datasourceContext.setConnection(executePluginDTO); - return datasourceContext; - }); + return datasourceContext; + }); } @Override @@ -1195,15 +1219,15 @@ public Mono<NewAction> save(NewAction action) { action.setGitSyncId(action.getApplicationId() + "_" + Instant.now().toString()); } - return sanitizeAction(action) - .flatMap(sanitizedAction -> repository.save(sanitizedAction)); + return sanitizeAction(action).flatMap(sanitizedAction -> repository.save(sanitizedAction)); } @Override public Flux<NewAction> saveAll(List<NewAction> actions) { actions.stream() .filter(action -> action.getGitSyncId() == null) - .forEach(action -> action.setGitSyncId(action.getApplicationId() + "_" + Instant.now().toString())); + .forEach(action -> action.setGitSyncId( + action.getApplicationId() + "_" + Instant.now().toString())); return Flux.fromIterable(actions) .flatMap(this::sanitizeAction) @@ -1213,8 +1237,7 @@ public Flux<NewAction> saveAll(List<NewAction> actions) { @Override public Flux<NewAction> findByPageId(String pageId) { - return repository.findByPageId(pageId) - .flatMap(this::sanitizeAction); + return repository.findByPageId(pageId).flatMap(this::sanitizeAction); } /** @@ -1230,14 +1253,16 @@ public Flux<NewAction> findByPageId(String pageId) { * @return */ @Override - public Mono<Boolean> updateActionsExecuteOnLoad(List<ActionDTO> onLoadActions, - String pageId, - List<LayoutActionUpdateDTO> actionUpdates, - List<String> messages) { + public Mono<Boolean> updateActionsExecuteOnLoad( + List<ActionDTO> onLoadActions, + String pageId, + List<LayoutActionUpdateDTO> actionUpdates, + List<String> messages) { List<ActionDTO> toUpdateActions = new ArrayList<>(); - MultiValueMap<String, String> params = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); + MultiValueMap<String, String> params = + CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); params.add(FieldName.PAGE_ID, pageId); // Fetch all the actions which exist in this page. @@ -1271,16 +1296,12 @@ public Mono<Boolean> updateActionsExecuteOnLoad(List<ActionDTO> onLoadActions, } // Extract names of existing page load actions and new page load actions for quick lookup. - Set<String> existingOnPageLoadActionNames = existingOnPageLoadActions - .stream() - .map(ActionDTO::getValidName) - .collect(Collectors.toSet()); - - Set<String> newOnLoadActionNames = onLoadActions - .stream() + Set<String> existingOnPageLoadActionNames = existingOnPageLoadActions.stream() .map(ActionDTO::getValidName) .collect(Collectors.toSet()); + Set<String> newOnLoadActionNames = + onLoadActions.stream().map(ActionDTO::getValidName).collect(Collectors.toSet()); // Calculate the actions which would need to be updated from execute on load TRUE to FALSE. Set<String> turnedOffActionNames = new HashSet<>(); @@ -1295,8 +1316,10 @@ public Mono<Boolean> updateActionsExecuteOnLoad(List<ActionDTO> onLoadActions, for (ActionDTO action : pageActions) { String actionName = action.getValidName(); - // If a user has ever set execute on load, this field can not be changed automatically. It has to be - // explicitly changed by the user again. Add the action to update only if this condition is false. + // If a user has ever set execute on load, this field can not be changed automatically. It has + // to be + // explicitly changed by the user again. Add the action to update only if this condition is + // false. if (FALSE.equals(action.getUserSetOnLoad())) { // If this action is no longer an onload action, turn the execute on load to false @@ -1319,14 +1342,10 @@ public Mono<Boolean> updateActionsExecuteOnLoad(List<ActionDTO> onLoadActions, } // Add newly turned on page actions to report back to the caller - actionUpdates.addAll( - addActionUpdatesForActionNames(pageActions, turnedOnActionNames) - ); + actionUpdates.addAll(addActionUpdatesForActionNames(pageActions, turnedOnActionNames)); // Add newly turned off page actions to report back to the caller - actionUpdates.addAll( - addActionUpdatesForActionNames(pageActions, turnedOffActionNames) - ); + actionUpdates.addAll(addActionUpdatesForActionNames(pageActions, turnedOffActionNames)); // Now add messages that would eventually be displayed to the developer user informing them // about the action setting change. @@ -1345,11 +1364,10 @@ public Mono<Boolean> updateActionsExecuteOnLoad(List<ActionDTO> onLoadActions, }); } - private List<LayoutActionUpdateDTO> addActionUpdatesForActionNames(List<ActionDTO> pageActions, - Set<String> actionNames) { + private List<LayoutActionUpdateDTO> addActionUpdatesForActionNames( + List<ActionDTO> pageActions, Set<String> actionNames) { - return pageActions - .stream() + return pageActions.stream() .filter(pageAction -> actionNames.contains(pageAction.getValidName())) .map(pageAction -> { LayoutActionUpdateDTO layoutActionUpdateDTO = new LayoutActionUpdateDTO(); @@ -1357,7 +1375,8 @@ private List<LayoutActionUpdateDTO> addActionUpdatesForActionNames(List<ActionDT layoutActionUpdateDTO.setName(pageAction.getValidName()); layoutActionUpdateDTO.setCollectionId(pageAction.getCollectionId()); layoutActionUpdateDTO.setExecuteOnLoad(pageAction.getExecuteOnLoad()); - layoutActionUpdateDTO.setDefaultActionId(pageAction.getDefaultResources().getActionId()); + layoutActionUpdateDTO.setDefaultActionId( + pageAction.getDefaultResources().getActionId()); return layoutActionUpdateDTO; }) .collect(Collectors.toList()); @@ -1365,41 +1384,37 @@ private List<LayoutActionUpdateDTO> addActionUpdatesForActionNames(List<ActionDT @Override public Mono<NewAction> archiveById(String id) { - Mono<NewAction> actionMono = repository.findById(id) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))); - return actionMono - .flatMap(toDelete -> repository - .archive(toDelete) - .zipWith(Mono.defer(() -> { - final ActionDTO action = toDelete.getUnpublishedAction(); - if (action.getDatasource() != null && - action.getDatasource().getId() != null) { - return datasourceService.findById(action.getDatasource().getId()); - } else { - return Mono.justOrEmpty(action.getDatasource()); - } - })) - .flatMap(zippedActions -> { - final Datasource datasource = zippedActions.getT2(); - final NewAction newAction1 = zippedActions.getT1(); - final Map<String, Object> data = this.getAnalyticsProperties(newAction1, datasource); - final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), - FieldName.ACTION, newAction1 - ); - data.put(FieldName.EVENT_DATA, eventData); - - return analyticsService - .sendDeleteEvent(newAction1, data) - .thenReturn(zippedActions.getT1()); + Mono<NewAction> actionMono = repository + .findById(id) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))); + return actionMono.flatMap(toDelete -> repository + .archive(toDelete) + .zipWith(Mono.defer(() -> { + final ActionDTO action = toDelete.getUnpublishedAction(); + if (action.getDatasource() != null && action.getDatasource().getId() != null) { + return datasourceService.findById(action.getDatasource().getId()); + } else { + return Mono.justOrEmpty(action.getDatasource()); + } + })) + .flatMap(zippedActions -> { + final Datasource datasource = zippedActions.getT2(); + final NewAction newAction1 = zippedActions.getT1(); + final Map<String, Object> data = this.getAnalyticsProperties(newAction1, datasource); + final Map<String, Object> eventData = + Map.of(FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.ACTION, newAction1); + data.put(FieldName.EVENT_DATA, eventData); - }) - .thenReturn(toDelete)); + return analyticsService.sendDeleteEvent(newAction1, data).thenReturn(zippedActions.getT1()); + }) + .thenReturn(toDelete)); } @Override public Mono<NewAction> archiveByIdAndBranchName(String id, String branchName) { - Mono<NewAction> branchedActionMono = this.findByBranchNameAndDefaultActionId(branchName, id, actionPermission.getDeletePermission()); + Mono<NewAction> branchedActionMono = + this.findByBranchNameAndDefaultActionId(branchName, id, actionPermission.getDeletePermission()); return branchedActionMono .flatMap(branchedAction -> this.archiveById(branchedAction.getId())) @@ -1413,7 +1428,8 @@ public Mono<NewAction> archive(NewAction newAction) { @Override public Mono<List<NewAction>> archiveActionsByApplicationId(String applicationId, AclPermission permission) { - return repository.findByApplicationId(applicationId, permission) + return repository + .findByApplicationId(applicationId, permission) .flatMap(repository::archive) .onErrorResume(throwable -> { log.error(throwable.getMessage()); @@ -1431,11 +1447,11 @@ public String replaceMustacheWithQuestionMark(String query, List<String> mustach ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody(query); - Map<String, String> replaceParamsMap = mustacheBindings - .stream() - .collect(Collectors.toMap(Function.identity(), v -> "?")); + Map<String, String> replaceParamsMap = + mustacheBindings.stream().collect(Collectors.toMap(Function.identity(), v -> "?")); - ActionConfiguration updatedActionConfiguration = MustacheHelper.renderFieldValues(actionConfiguration, replaceParamsMap); + ActionConfiguration updatedActionConfiguration = + MustacheHelper.renderFieldValues(actionConfiguration, replaceParamsMap); return updatedActionConfiguration.getBody(); } @@ -1447,67 +1463,67 @@ private Mono<Datasource> updateDatasourcePolicyForPublicAction(NewAction action, String applicationId = action.getApplicationId(); - return permissionGroupService.getPublicPermissionGroup() - .flatMap(publicPermissionGroup -> { - String publicPermissionGroupId = publicPermissionGroup.getId(); - // If action has EXECUTE permission for anonymous, check and assign the same to the datasource. - boolean isPublicAction = permissionGroupService.isEntityAccessible(action, actionPermission.getExecutePermission().getValue(), publicPermissionGroupId); + return permissionGroupService.getPublicPermissionGroup().flatMap(publicPermissionGroup -> { + String publicPermissionGroupId = publicPermissionGroup.getId(); + // If action has EXECUTE permission for anonymous, check and assign the same to the datasource. + boolean isPublicAction = permissionGroupService.isEntityAccessible( + action, actionPermission.getExecutePermission().getValue(), publicPermissionGroupId); - if (!isPublicAction) { - return Mono.just(datasource); - } - // Check if datasource has execute permission - boolean isPublicDatasource = permissionGroupService.isEntityAccessible(datasource, datasourcePermission.getExecutePermission().getValue(), publicPermissionGroupId); - if (isPublicDatasource) { - // Datasource has correct permission. Return as is - return Mono.just(datasource); - } + if (!isPublicAction) { + return Mono.just(datasource); + } + // Check if datasource has execute permission + boolean isPublicDatasource = permissionGroupService.isEntityAccessible( + datasource, datasourcePermission.getExecutePermission().getValue(), publicPermissionGroupId); + if (isPublicDatasource) { + // Datasource has correct permission. Return as is + return Mono.just(datasource); + } - // Add the permission to datasource - return applicationService.findById(applicationId) - .flatMap(application -> { - if (!application.getIsPublic()) { - return Mono.error(new AppsmithException(AppsmithError.PUBLIC_APP_NO_PERMISSION_GROUP)); - } - - Policy executePolicy = Policy.builder() - .permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(publicPermissionGroupId)) - .build(); - Map<String, Policy> datasourcePolicyMap = Map.of( - EXECUTE_DATASOURCES.getValue(), executePolicy - ); - - Datasource updatedDatasource = - policySolution.addPoliciesToExistingObject(datasourcePolicyMap, datasource); - - return datasourceService.save(updatedDatasource); - }); - }); + // Add the permission to datasource + return applicationService.findById(applicationId).flatMap(application -> { + if (!application.getIsPublic()) { + return Mono.error(new AppsmithException(AppsmithError.PUBLIC_APP_NO_PERMISSION_GROUP)); + } + + Policy executePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of(publicPermissionGroupId)) + .build(); + Map<String, Policy> datasourcePolicyMap = Map.of(EXECUTE_DATASOURCES.getValue(), executePolicy); + + Datasource updatedDatasource = + policySolution.addPoliciesToExistingObject(datasourcePolicyMap, datasource); + + return datasourceService.save(updatedDatasource); + }); + }); } - public Mono<NewAction> findByBranchNameAndDefaultActionId(String branchName, String defaultActionId, AclPermission permission) { + public Mono<NewAction> findByBranchNameAndDefaultActionId( + String branchName, String defaultActionId, AclPermission permission) { if (!StringUtils.hasLength(branchName)) { - return repository.findById(defaultActionId, permission) + return repository + .findById(defaultActionId, permission) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, defaultActionId)) - ); + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, defaultActionId))); } - return repository.findByBranchNameAndDefaultActionId(branchName, defaultActionId, permission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, defaultActionId + "," + branchName)) - ) + return repository + .findByBranchNameAndDefaultActionId(branchName, defaultActionId, permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, defaultActionId + "," + branchName))) .flatMap(this::sanitizeAction); } - public Mono<String> findBranchedIdByBranchNameAndDefaultActionId(String branchName, String defaultActionId, AclPermission permission) { + public Mono<String> findBranchedIdByBranchNameAndDefaultActionId( + String branchName, String defaultActionId, AclPermission permission) { if (!StringUtils.hasLength(branchName)) { return Mono.just(defaultActionId); } - return repository.findByBranchNameAndDefaultActionId(branchName, defaultActionId, permission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION, defaultActionId + "," + branchName)) - ) + return repository + .findByBranchNameAndDefaultActionId(branchName, defaultActionId, permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION, defaultActionId + "," + branchName))) .map(NewAction::getId); } @@ -1536,10 +1552,18 @@ public Map<String, Object> getAnalyticsProperties(NewAction savedAction) { analyticsProperties.put("pluginType", ObjectUtils.defaultIfNull(savedAction.getPluginType(), "")); analyticsProperties.put("pluginName", ObjectUtils.defaultIfNull(unpublishedAction.getPluginName(), "")); if (unpublishedAction.getDatasource() != null) { - analyticsProperties.put("dsId", ObjectUtils.defaultIfNull(unpublishedAction.getDatasource().getId(), "")); - analyticsProperties.put("dsName", ObjectUtils.defaultIfNull(unpublishedAction.getDatasource().getName(), "")); - analyticsProperties.put("dsIsTemplate", ObjectUtils.defaultIfNull(unpublishedAction.getDatasource().getIsTemplate(), "")); - analyticsProperties.put("dsIsMock", ObjectUtils.defaultIfNull(unpublishedAction.getDatasource().getIsMock(), "")); + analyticsProperties.put( + "dsId", + ObjectUtils.defaultIfNull(unpublishedAction.getDatasource().getId(), "")); + analyticsProperties.put( + "dsName", + ObjectUtils.defaultIfNull(unpublishedAction.getDatasource().getName(), "")); + analyticsProperties.put( + "dsIsTemplate", + ObjectUtils.defaultIfNull(unpublishedAction.getDatasource().getIsTemplate(), "")); + analyticsProperties.put( + "dsIsMock", + ObjectUtils.defaultIfNull(unpublishedAction.getDatasource().getIsMock(), "")); } return analyticsProperties; } @@ -1563,16 +1587,17 @@ public void populateDefaultResources(NewAction newAction, NewAction branchedActi newAction.getPublishedAction().setDefaultResources(defaultsDTO); } - newAction.getUnpublishedAction().setDeletedAt(branchedAction.getUnpublishedAction().getDeletedAt()); + newAction + .getUnpublishedAction() + .setDeletedAt(branchedAction.getUnpublishedAction().getDeletedAt()); newAction.setDeletedAt(branchedAction.getDeletedAt()); newAction.setDeleted(branchedAction.getDeleted()); // Set policies from existing branch object newAction.setPolicies(branchedAction.getPolicies()); } - private NewPage updatePageInAction(ActionDTO action, - Map<String, NewPage> pageNameMap, - Map<String, String> actionIdMap) { + private NewPage updatePageInAction( + ActionDTO action, Map<String, NewPage> pageNameMap, Map<String, String> actionIdMap) { NewPage parentPage = pageNameMap.get(action.getPageId()); if (parentPage == null) { return null; @@ -1588,8 +1613,12 @@ private NewPage updatePageInAction(ActionDTO action, return parentPage; } - private void updateExistingAction(NewAction existingAction, NewAction actionToImport, String branchName, ImportApplicationPermissionProvider permissionProvider) { - //Since the resource is already present in DB, just update resource + private void updateExistingAction( + NewAction existingAction, + NewAction actionToImport, + String branchName, + ImportApplicationPermissionProvider permissionProvider) { + // Since the resource is already present in DB, just update resource if (!permissionProvider.hasEditPermission(existingAction)) { log.error("User does not have permission to edit action with id: {}", existingAction.getId()); throw new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.ACTION, existingAction.getId()); @@ -1599,7 +1628,9 @@ private void updateExistingAction(NewAction existingAction, NewAction actionToIm // Update branchName existingAction.getDefaultResources().setBranchName(branchName); // Recover the deleted state present in DB from imported action - existingAction.getUnpublishedAction().setDeletedAt(actionToImport.getUnpublishedAction().getDeletedAt()); + existingAction + .getUnpublishedAction() + .setDeletedAt(actionToImport.getUnpublishedAction().getDeletedAt()); existingAction.setDeletedAt(actionToImport.getDeletedAt()); existingAction.setDeleted(actionToImport.getDeleted()); existingAction.setPolicies(existingPolicy); @@ -1609,27 +1640,41 @@ private void putActionIdInMap(NewAction newAction, ImportActionResultDTO importA // Populate actionIdsMap to associate the appropriate actions to run on page load if (newAction.getUnpublishedAction() != null) { ActionDTO unpublishedAction = newAction.getUnpublishedAction(); - importActionResultDTO.getActionIdMap().put( - importActionResultDTO.getActionIdMap().get(unpublishedAction.getValidName() + unpublishedAction.getPageId()), - newAction.getId() - ); + importActionResultDTO + .getActionIdMap() + .put( + importActionResultDTO + .getActionIdMap() + .get(unpublishedAction.getValidName() + unpublishedAction.getPageId()), + newAction.getId()); if (unpublishedAction.getCollectionId() != null) { - importActionResultDTO.getUnpublishedCollectionIdToActionIdsMap().putIfAbsent(unpublishedAction.getCollectionId(), new HashMap<>()); - final Map<String, String> actionIds = importActionResultDTO.getUnpublishedCollectionIdToActionIdsMap().get(unpublishedAction.getCollectionId()); + importActionResultDTO + .getUnpublishedCollectionIdToActionIdsMap() + .putIfAbsent(unpublishedAction.getCollectionId(), new HashMap<>()); + final Map<String, String> actionIds = importActionResultDTO + .getUnpublishedCollectionIdToActionIdsMap() + .get(unpublishedAction.getCollectionId()); actionIds.put(newAction.getDefaultResources().getActionId(), newAction.getId()); } } if (newAction.getPublishedAction() != null) { ActionDTO publishedAction = newAction.getPublishedAction(); - importActionResultDTO.getActionIdMap().put( - importActionResultDTO.getActionIdMap().get(publishedAction.getValidName() + publishedAction.getPageId()), - newAction.getId() - ); + importActionResultDTO + .getActionIdMap() + .put( + importActionResultDTO + .getActionIdMap() + .get(publishedAction.getValidName() + publishedAction.getPageId()), + newAction.getId()); if (publishedAction.getCollectionId() != null) { - importActionResultDTO.getPublishedCollectionIdToActionIdsMap().putIfAbsent(publishedAction.getCollectionId(), new HashMap<>()); - final Map<String, String> actionIds = importActionResultDTO.getPublishedCollectionIdToActionIdsMap().get(publishedAction.getCollectionId()); + importActionResultDTO + .getPublishedCollectionIdToActionIdsMap() + .putIfAbsent(publishedAction.getCollectionId(), new HashMap<>()); + final Map<String, String> actionIds = importActionResultDTO + .getPublishedCollectionIdToActionIdsMap() + .get(publishedAction.getCollectionId()); actionIds.put(newAction.getDefaultResources().getActionId(), newAction.getId()); } } @@ -1650,20 +1695,30 @@ private void putActionIdInMap(NewAction newAction, ImportActionResultDTO importA * @return A DTO class with several information */ @Override - public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActionList, Application application, String branchName, Map<String, NewPage> pageNameMap, Map<String, String> pluginMap, Map<String, String> datasourceMap, ImportApplicationPermissionProvider permissionProvider) { + public Mono<ImportActionResultDTO> importActions( + List<NewAction> importedNewActionList, + Application application, + String branchName, + Map<String, NewPage> pageNameMap, + Map<String, String> pluginMap, + Map<String, String> datasourceMap, + ImportApplicationPermissionProvider permissionProvider) { /* Mono.just(application) is created to avoid the eagerly fetching of existing actions * during the pipeline construction. It should be fetched only when the pipeline is subscribed/executed. */ return Mono.just(application).flatMap(importedApplication -> { - Mono<Map<String, NewAction>> actionsInCurrentAppMono = repository.findByApplicationId(importedApplication.getId()) + Mono<Map<String, NewAction>> actionsInCurrentAppMono = repository + .findByApplicationId(importedApplication.getId()) .filter(newAction -> newAction.getGitSyncId() != null) .collectMap(NewAction::getGitSyncId); // find existing actions in all the branches of this application and put them in a map Mono<Map<String, NewAction>> actionsInOtherBranchesMono; if (importedApplication.getGitApplicationMetadata() != null) { - final String defaultApplicationId = importedApplication.getGitApplicationMetadata().getDefaultApplicationId(); - actionsInOtherBranchesMono = repository.findByDefaultApplicationId(defaultApplicationId, Optional.empty()) + final String defaultApplicationId = + importedApplication.getGitApplicationMetadata().getDefaultApplicationId(); + actionsInOtherBranchesMono = repository + .findByDefaultApplicationId(defaultApplicationId, Optional.empty()) .filter(newAction -> newAction.getGitSyncId() != null) .collectMap(NewAction::getGitSyncId); } else { @@ -1685,7 +1740,9 @@ public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActi importActionResultDTO.setExistingActions(actionsInCurrentApp.values()); for (NewAction newAction : importedNewActionList) { - if (newAction.getUnpublishedAction() == null || !StringUtils.hasLength(newAction.getUnpublishedAction().getPageId())) { + if (newAction.getUnpublishedAction() == null + || !StringUtils.hasLength( + newAction.getUnpublishedAction().getPageId())) { continue; } @@ -1698,7 +1755,8 @@ public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActi if (unpublishedAction.getValidName() != null) { unpublishedAction.setId(newAction.getId()); - parentPage = updatePageInAction(unpublishedAction, pageNameMap, importActionResultDTO.getActionIdMap()); + parentPage = updatePageInAction( + unpublishedAction, pageNameMap, importActionResultDTO.getActionIdMap()); sanitizeDatasourceInActionDTO(unpublishedAction, datasourceMap, pluginMap, workspaceId, false); } @@ -1707,7 +1765,8 @@ public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActi if (!StringUtils.hasLength(publishedAction.getPageId())) { publishedAction.setPageId(fallbackParentPageId); } - NewPage publishedActionPage = updatePageInAction(publishedAction, pageNameMap, importActionResultDTO.getActionIdMap()); + NewPage publishedActionPage = updatePageInAction( + publishedAction, pageNameMap, importActionResultDTO.getActionIdMap()); parentPage = parentPage == null ? publishedActionPage : parentPage; sanitizeDatasourceInActionDTO(publishedAction, datasourceMap, pluginMap, workspaceId, false); } @@ -1719,8 +1778,7 @@ public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActi this.generateAndSetActionPolicies(parentPage, newAction); // Check if the action has gitSyncId and if it's already in DB - if (newAction.getGitSyncId() != null - && actionsInCurrentApp.containsKey(newAction.getGitSyncId())) { + if (newAction.getGitSyncId() != null && actionsInCurrentApp.containsKey(newAction.getGitSyncId())) { // Since the resource is already present in DB, just update resource NewAction existingAction = actionsInCurrentApp.get(newAction.getGitSyncId()); @@ -1733,8 +1791,11 @@ public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActi } else { // check whether user has permission to add new action if (!permissionProvider.canCreateAction(parentPage)) { - log.error("User does not have permission to create action in page with id: {}", parentPage.getId()); - throw new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, parentPage.getId()); + log.error( + "User does not have permission to create action in page with id: {}", + parentPage.getId()); + throw new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, parentPage.getId()); } // this will generate the id and other auto generated fields e.g. createdAt @@ -1742,7 +1803,8 @@ public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActi // set gitSyncId if doesn't exist if (newAction.getGitSyncId() == null) { - newAction.setGitSyncId(newAction.getApplicationId() + "_" + Instant.now().toString()); + newAction.setGitSyncId(newAction.getApplicationId() + "_" + + Instant.now().toString()); } if (importedApplication.getGitApplicationMetadata() != null) { @@ -1754,7 +1816,9 @@ public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActi } else { // This is the first action we are saving with given gitSyncId in this instance DefaultResources defaultResources = new DefaultResources(); - defaultResources.setApplicationId(importedApplication.getGitApplicationMetadata().getDefaultApplicationId()); + defaultResources.setApplicationId(importedApplication + .getGitApplicationMetadata() + .getDefaultApplicationId()); defaultResources.setActionId(newAction.getId()); defaultResources.setBranchName(branchName); newAction.setDefaultResources(defaultResources); @@ -1773,10 +1837,14 @@ public Mono<ImportActionResultDTO> importActions(List<NewAction> importedNewActi } } - log.info("Saving actions in bulk. New: {}, Updated: {}", newNewActionList.size(), existingNewActionList.size()); + log.info( + "Saving actions in bulk. New: {}, Updated: {}", + newNewActionList.size(), + existingNewActionList.size()); // Save all the new actions in bulk - return repository.bulkInsert(newNewActionList) + return repository + .bulkInsert(newNewActionList) .then(repository.bulkUpdate(existingNewActionList)) .thenReturn(importActionResultDTO); }); @@ -1791,20 +1859,24 @@ public Mono<ImportedActionAndCollectionMapsDTO> updateActionsWithImportedCollect ImportedActionAndCollectionMapsDTO mapsDTO = new ImportedActionAndCollectionMapsDTO(); final HashSet<String> actionIds = new HashSet<>(); - for (Map.Entry<String, ActionCollection> entry : importActionCollectionResultDTO.getSavedActionCollectionMap().entrySet()) { + for (Map.Entry<String, ActionCollection> entry : + importActionCollectionResultDTO.getSavedActionCollectionMap().entrySet()) { String importedActionCollectionId = entry.getKey(); ActionCollection savedActionCollection = entry.getValue(); final String savedActionCollectionId = savedActionCollection.getId(); - final String defaultCollectionId = savedActionCollection.getDefaultResources().getCollectionId(); + final String defaultCollectionId = + savedActionCollection.getDefaultResources().getCollectionId(); List<String> collectionIds = List.of(savedActionCollectionId, defaultCollectionId); - importActionResultDTO.getUnpublishedCollectionIdToActionIdsMap() + importActionResultDTO + .getUnpublishedCollectionIdToActionIdsMap() .getOrDefault(importedActionCollectionId, Map.of()) .forEach((defaultActionId, actionId) -> { mapsDTO.getUnpublishedActionIdToCollectionIdMap().putIfAbsent(actionId, collectionIds); }); - importActionResultDTO.getPublishedCollectionIdToActionIdsMap() + importActionResultDTO + .getPublishedCollectionIdToActionIdsMap() .getOrDefault(importedActionCollectionId, Map.of()) .forEach((defaultActionId, actionId) -> { mapsDTO.getPublishedActionIdToCollectionIdMap().putIfAbsent(actionId, collectionIds); @@ -1814,7 +1886,8 @@ public Mono<ImportedActionAndCollectionMapsDTO> updateActionsWithImportedCollect actionIds.addAll(mapsDTO.getPublishedActionIdToCollectionIdMap().keySet()); } - return repository.findAllById(actionIds) + return repository + .findAllById(actionIds) .map(newAction -> { // Update collectionId and defaultCollectionIds in actionDTOs ActionDTO unpublishedAction = newAction.getUnpublishedAction(); @@ -1823,30 +1896,36 @@ public Mono<ImportedActionAndCollectionMapsDTO> updateActionsWithImportedCollect if (!CollectionUtils.isEmpty(mapsDTO.getUnpublishedActionIdToCollectionIdMap()) && mapsDTO.getUnpublishedActionIdToCollectionIdMap().containsKey(newAction.getId())) { - unpublishedAction.setCollectionId( - mapsDTO.getUnpublishedActionIdToCollectionIdMap().get(newAction.getId()).get(0) - ); + unpublishedAction.setCollectionId(mapsDTO.getUnpublishedActionIdToCollectionIdMap() + .get(newAction.getId()) + .get(0)); if (unpublishedAction.getDefaultResources() != null - && !StringUtils.hasLength(unpublishedAction.getDefaultResources().getCollectionId())) { - - unpublishedAction.getDefaultResources().setCollectionId( - mapsDTO.getUnpublishedActionIdToCollectionIdMap().get(newAction.getId()).get(1) - ); + && !StringUtils.hasLength( + unpublishedAction.getDefaultResources().getCollectionId())) { + + unpublishedAction + .getDefaultResources() + .setCollectionId(mapsDTO.getUnpublishedActionIdToCollectionIdMap() + .get(newAction.getId()) + .get(1)); } } if (!CollectionUtils.isEmpty(mapsDTO.getPublishedActionIdToCollectionIdMap()) && mapsDTO.getPublishedActionIdToCollectionIdMap().containsKey(newAction.getId())) { - publishedAction.setCollectionId( - mapsDTO.getPublishedActionIdToCollectionIdMap().get(newAction.getId()).get(0) - ); + publishedAction.setCollectionId(mapsDTO.getPublishedActionIdToCollectionIdMap() + .get(newAction.getId()) + .get(0)); if (publishedAction.getDefaultResources() != null - && !StringUtils.hasLength(publishedAction.getDefaultResources().getCollectionId())) { - - publishedAction.getDefaultResources().setCollectionId( - mapsDTO.getPublishedActionIdToCollectionIdMap().get(newAction.getId()).get(1) - ); + && !StringUtils.hasLength( + publishedAction.getDefaultResources().getCollectionId())) { + + publishedAction + .getDefaultResources() + .setCollectionId(mapsDTO.getPublishedActionIdToCollectionIdMap() + .get(newAction.getId()) + .get(1)); } } return newAction; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java index 9bc7a8db56bc..286382758b84 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java @@ -39,22 +39,21 @@ public interface NewPageServiceCE extends CrudService<NewPage, String> { Mono<Void> deleteAll(); - Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewModeAndBranch(String applicationId, - String branchName, - Boolean view, - boolean markApplicationAsRecentlyAccessed); + Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewModeAndBranch( + String applicationId, String branchName, Boolean view, boolean markApplicationAsRecentlyAccessed); - Mono<ApplicationPagesDTO> findApplicationPages(String applicationId, String pageId, String branchName, ApplicationMode mode); + Mono<ApplicationPagesDTO> findApplicationPages( + String applicationId, String pageId, String branchName, ApplicationMode mode); Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode( - String applicationId, Boolean view, boolean markApplicationAsRecentlyAccessed - ); + String applicationId, Boolean view, boolean markApplicationAsRecentlyAccessed); Layout createDefaultLayout(); Mono<ApplicationPagesDTO> findNamesByApplicationNameAndViewMode(String applicationName, Boolean view); - Mono<PageDTO> findByNameAndApplicationIdAndViewMode(String name, String applicationId, AclPermission permission, Boolean view); + Mono<PageDTO> findByNameAndApplicationIdAndViewMode( + String name, String applicationId, AclPermission permission, Boolean view); Mono<List<NewPage>> archivePagesByApplicationId(String applicationId, AclPermission permission); @@ -82,9 +81,11 @@ Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode( Mono<String> findRootApplicationIdFromNewPage(String branchName, String defaultPageId); - Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission); + Mono<NewPage> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, AclPermission permission); - Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission); + Mono<NewPage> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission); Flux<NewPage> findPageSlugsByApplicationIds(List<String> applicationIds, AclPermission aclPermission); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java index 8a98fff4c2f7..1dc187f317ad 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java @@ -51,7 +51,6 @@ import static com.appsmith.external.helpers.AppsmithBeanUtils.copyNewFieldValuesIntoOldObject; import static com.appsmith.server.exceptions.AppsmithError.INVALID_PARAMETER; - @Slf4j public class NewPageServiceCEImpl extends BaseService<NewPageRepository, NewPage, String> implements NewPageServiceCE { @@ -62,20 +61,20 @@ public class NewPageServiceCEImpl extends BaseService<NewPageRepository, NewPage private final PagePermission pagePermission; private final ApplicationSnapshotRepository applicationSnapshotRepository; - @Autowired - public NewPageServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - NewPageRepository repository, - AnalyticsService analyticsService, - ApplicationService applicationService, - UserDataService userDataService, - ResponseUtils responseUtils, - ApplicationPermission applicationPermission, - PagePermission pagePermission, - ApplicationSnapshotRepository applicationSnapshotRepository) { + public NewPageServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + NewPageRepository repository, + AnalyticsService analyticsService, + ApplicationService applicationService, + UserDataService userDataService, + ResponseUtils responseUtils, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ApplicationSnapshotRepository applicationSnapshotRepository) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.applicationService = applicationService; this.userDataService = userDataService; @@ -95,7 +94,8 @@ public Mono<PageDTO> getPageByViewMode(NewPage newPage, Boolean viewMode) { page.setName(newPage.getPublishedPage().getName()); } else { // We are trying to fetch published page but it doesnt exist because the page hasn't been published yet - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, newPage.getId())); + return Mono.error( + new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, newPage.getId())); } } else { if (newPage.getUnpublishedPage() != null) { @@ -117,7 +117,6 @@ public Mono<PageDTO> getPageByViewMode(NewPage newPage, Boolean viewMode) { // We shouldn't reach here. return Mono.error(new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR)); - } @Override @@ -127,8 +126,7 @@ public Mono<NewPage> findById(String pageId, AclPermission aclPermission) { @Override public Mono<PageDTO> findPageById(String pageId, AclPermission aclPermission, Boolean view) { - return this.findById(pageId, aclPermission) - .flatMap(page -> getPageByViewMode(page, view)); + return this.findById(pageId, aclPermission).flatMap(page -> getPageByViewMode(page, view)); } @Override @@ -138,8 +136,7 @@ public Mono<NewPage> findById(String pageId, Optional<AclPermission> aclPermissi @Override public Flux<PageDTO> findByApplicationId(String applicationId, AclPermission permission, Boolean view) { - return findNewPagesByApplicationId(applicationId, permission) - .flatMap(page -> getPageByViewMode(page, view)); + return findNewPagesByApplicationId(applicationId, permission).flatMap(page -> getPageByViewMode(page, view)); } @Override @@ -180,7 +177,8 @@ public Mono<PageDTO> createDefault(PageDTO object) { return super.create(newPage) .flatMap(savedPage -> { if (defaultResources == null) { - return Mono.error(new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "page", savedPage.getId())); + return Mono.error(new AppsmithException( + AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "page", savedPage.getId())); } if (StringUtils.isEmpty(defaultResources.getPageId())) { NewPage updatePage = new NewPage(); @@ -195,15 +193,16 @@ public Mono<PageDTO> createDefault(PageDTO object) { } @Override - public Mono<PageDTO> findByIdAndLayoutsId(String pageId, String layoutId, AclPermission aclPermission, Boolean view) { - return repository.findByIdAndLayoutsIdAndViewMode(pageId, layoutId, aclPermission, view) + public Mono<PageDTO> findByIdAndLayoutsId( + String pageId, String layoutId, AclPermission aclPermission, Boolean view) { + return repository + .findByIdAndLayoutsIdAndViewMode(pageId, layoutId, aclPermission, view) .flatMap(page -> getPageByViewMode(page, view)); } @Override public Mono<PageDTO> findByNameAndViewMode(String name, AclPermission permission, Boolean view) { - return repository.findByNameAndViewMode(name, permission, view) - .flatMap(page -> getPageByViewMode(page, view)); + return repository.findByNameAndViewMode(name, permission, view).flatMap(page -> getPageByViewMode(page, view)); } @Override @@ -226,7 +225,8 @@ public Mono<Void> deleteAll() { } @Override - public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(String applicationId, Boolean view, boolean markApplicationAsRecentlyAccessed) { + public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode( + String applicationId, Boolean view, boolean markApplicationAsRecentlyAccessed) { AclPermission permission; if (view) { @@ -235,16 +235,21 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str permission = applicationPermission.getEditPermission(); } - Mono<Application> applicationMono = applicationService.findById(applicationId, permission) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) + Mono<Application> applicationMono = applicationService + .findById(applicationId, permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) // Throw a 404 error if the application has never been published .flatMap(application -> { if (Boolean.TRUE.equals(view)) { - if (application.getPublishedPages() == null || application.getPublishedPages().isEmpty()) { + if (application.getPublishedPages() == null + || application.getPublishedPages().isEmpty()) { // We are trying to fetch published pages but they don't exist because the application // hasn't been published yet - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, - FieldName.PUBLISHED_APPLICATION, application.getId())); + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.PUBLISHED_APPLICATION, + application.getId())); } } return Mono.just(application); @@ -253,7 +258,8 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str log.debug("Fetched application data for id: {}", applicationId); if (markApplicationAsRecentlyAccessed) { // add this application and workspace id to the recently used list in UserData - return userDataService.updateLastUsedAppAndWorkspaceList(application) + return userDataService + .updateLastUsedAppAndWorkspaceList(application) .thenReturn(application); } else { return Mono.just(application); @@ -261,27 +267,26 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str }) .cache(); - Mono<String> defaultPageIdMono = applicationMono - .map(application -> { - String defaultPageId = null; - List<ApplicationPage> applicationPages; - if (Boolean.TRUE.equals(view)) { - applicationPages = application.getPublishedPages(); - } else { - applicationPages = application.getPages(); - } + Mono<String> defaultPageIdMono = applicationMono.map(application -> { + String defaultPageId = null; + List<ApplicationPage> applicationPages; + if (Boolean.TRUE.equals(view)) { + applicationPages = application.getPublishedPages(); + } else { + applicationPages = application.getPages(); + } - for (ApplicationPage applicationPage : applicationPages) { - if (Boolean.TRUE.equals(applicationPage.getIsDefault())) { - defaultPageId = applicationPage.getId(); - } - } - if (!StringUtils.hasLength(defaultPageId) && !CollectionUtils.isEmpty(applicationPages)) { - log.error("application {} has no default page, returning first page as default", application.getId()); - defaultPageId = applicationPages.get(0).getId(); - } - return defaultPageId; - }); + for (ApplicationPage applicationPage : applicationPages) { + if (Boolean.TRUE.equals(applicationPage.getIsDefault())) { + defaultPageId = applicationPage.getId(); + } + } + if (!StringUtils.hasLength(defaultPageId) && !CollectionUtils.isEmpty(applicationPages)) { + log.error("application {} has no default page, returning first page as default", application.getId()); + defaultPageId = applicationPages.get(0).getId(); + } + return defaultPageId; + }); Mono<List<PageNameIdDTO>> pagesListMono = applicationMono .map(application -> { @@ -295,11 +300,7 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str }) .flatMapMany(pageIds -> repository.findAllPageDTOsByIds(pageIds, pagePermission.getReadPermission())) .collectList() - .flatMap(pagesFromDb -> Mono.zip( - Mono.just(pagesFromDb), - defaultPageIdMono, - applicationMono - )) + .flatMap(pagesFromDb -> Mono.zip(Mono.just(pagesFromDb), defaultPageIdMono, applicationMono)) .flatMap(tuple -> { log.debug("Retrieved Page DTOs from DB ..."); List<NewPage> pagesFromDb = tuple.getT1(); @@ -328,15 +329,18 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str pageNameIdDTO.setId(pageFromDb.getId()); if (pageFromDb.getDefaultResources() == null) { - return Mono.error(new AppsmithException(AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "page", pageFromDb.getId())); + return Mono.error(new AppsmithException( + AppsmithError.DEFAULT_RESOURCES_UNAVAILABLE, "page", pageFromDb.getId())); } - pageNameIdDTO.setDefaultPageId(pageFromDb.getDefaultResources().getPageId()); + pageNameIdDTO.setDefaultPageId( + pageFromDb.getDefaultResources().getPageId()); PageDTO pageDTO; if (Boolean.TRUE.equals(view)) { if (pageFromDb.getPublishedPage() == null) { - // We are trying to fetch published page but it doesnt exist because the page hasn't been published yet - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, - FieldName.PAGE, pageFromDb.getId())); + // We are trying to fetch published page but it doesnt exist because the page hasn't + // been published yet + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, pageFromDb.getId())); } pageDTO = pageFromDb.getPublishedPage(); } else { @@ -357,35 +361,31 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(Str pageNameIdDTOList.add(pageNameIdDTO); } if (Boolean.TRUE.equals(view)) { - Collections.sort(pageNameIdDTOList, - Comparator.comparing(item -> publishedPagesOrder.get(item.getId()))); + Collections.sort( + pageNameIdDTOList, Comparator.comparing(item -> publishedPagesOrder.get(item.getId()))); } else { - Collections.sort(pageNameIdDTOList, - Comparator.comparing(item -> pagesOrder.get(item.getId()))); + Collections.sort(pageNameIdDTOList, Comparator.comparing(item -> pagesOrder.get(item.getId()))); } return Mono.just(pageNameIdDTOList); }); - return Mono.zip(applicationMono, pagesListMono) - .map(tuple -> { - log.debug("Populating applicationPagesDTO ..."); - Application application = tuple.getT1(); - application.setPages(null); - application.setPublishedPages(null); - application.setViewMode(view); - List<PageNameIdDTO> nameIdDTOList = tuple.getT2(); - ApplicationPagesDTO applicationPagesDTO = new ApplicationPagesDTO(); - applicationPagesDTO.setWorkspaceId(application.getWorkspaceId()); - applicationPagesDTO.setPages(nameIdDTOList); - applicationPagesDTO.setApplication(application); - return applicationPagesDTO; - }); - } - - public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewModeAndBranch(String defaultApplicationId, - String branchName, - Boolean view, - boolean markApplicationAsRecentlyAccessed) { + return Mono.zip(applicationMono, pagesListMono).map(tuple -> { + log.debug("Populating applicationPagesDTO ..."); + Application application = tuple.getT1(); + application.setPages(null); + application.setPublishedPages(null); + application.setViewMode(view); + List<PageNameIdDTO> nameIdDTOList = tuple.getT2(); + ApplicationPagesDTO applicationPagesDTO = new ApplicationPagesDTO(); + applicationPagesDTO.setWorkspaceId(application.getWorkspaceId()); + applicationPagesDTO.setPages(nameIdDTOList); + applicationPagesDTO.setApplication(application); + return applicationPagesDTO; + }); + } + + public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewModeAndBranch( + String defaultApplicationId, String branchName, Boolean view, boolean markApplicationAsRecentlyAccessed) { AclPermission permission; if (view) { permission = applicationPermission.getReadPermission(); @@ -393,14 +393,14 @@ public Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewModeAndB permission = applicationPermission.getEditPermission(); } - return applicationService.findBranchedApplicationId(branchName, defaultApplicationId, permission) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, - FieldName.APPLICATION, defaultApplicationId))) - .flatMap(childApplicationId -> - findApplicationPagesByApplicationIdViewMode(childApplicationId, view, markApplicationAsRecentlyAccessed) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, - FieldName.APPLICATION, childApplicationId))) - ) + return applicationService + .findBranchedApplicationId(branchName, defaultApplicationId, permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, defaultApplicationId))) + .flatMap(childApplicationId -> findApplicationPagesByApplicationIdViewMode( + childApplicationId, view, markApplicationAsRecentlyAccessed) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, childApplicationId)))) .map(responseUtils::updateApplicationPagesDTOWithDefaultResources); } @@ -414,23 +414,24 @@ public Mono<ApplicationPagesDTO> findNamesByApplicationNameAndViewMode(String ap permission = applicationPermission.getEditPermission(); } - Mono<Application> applicationMono = applicationService.findByName(applicationName, permission) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.NAME, applicationName))) + Mono<Application> applicationMono = applicationService + .findByName(applicationName, permission) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.NAME, applicationName))) .cache(); Mono<List<PageNameIdDTO>> pagesListMono = applicationMono .flatMapMany(application -> findNamesByApplication(application, view)) .collectList(); - return Mono.zip(applicationMono, pagesListMono) - .map(tuple -> { - Application application = tuple.getT1(); - List<PageNameIdDTO> nameIdDTOList = tuple.getT2(); - ApplicationPagesDTO applicationPagesDTO = new ApplicationPagesDTO(); - applicationPagesDTO.setWorkspaceId(application.getWorkspaceId()); - applicationPagesDTO.setPages(nameIdDTOList); - return applicationPagesDTO; - }); + return Mono.zip(applicationMono, pagesListMono).map(tuple -> { + Application application = tuple.getT1(); + List<PageNameIdDTO> nameIdDTOList = tuple.getT2(); + ApplicationPagesDTO applicationPagesDTO = new ApplicationPagesDTO(); + applicationPagesDTO.setWorkspaceId(application.getWorkspaceId()); + applicationPagesDTO.setPages(nameIdDTOList); + return applicationPagesDTO; + }); } private Flux<PageNameIdDTO> findNamesByApplication(Application application, Boolean viewMode) { @@ -443,7 +444,10 @@ private Flux<PageNameIdDTO> findNamesByApplication(Application application, Bool } return findByApplicationId(application.getId(), pagePermission.getReadPermission(), viewMode) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE + " by application id", application.getId()))) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.PAGE + " by application id", + application.getId()))) .map(page -> { PageNameIdDTO pageNameIdDTO = new PageNameIdDTO(); pageNameIdDTO.setId(page.getId()); @@ -458,8 +462,10 @@ private Flux<PageNameIdDTO> findNamesByApplication(Application application, Bool } @Override - public Mono<PageDTO> findByNameAndApplicationIdAndViewMode(String name, String applicationId, AclPermission permission, Boolean view) { - return repository.findByNameAndApplicationIdAndViewMode(name, applicationId, permission, view) + public Mono<PageDTO> findByNameAndApplicationIdAndViewMode( + String name, String applicationId, AclPermission permission, Boolean view) { + return repository + .findByNameAndApplicationIdAndViewMode(name, applicationId, permission, view) .flatMap(page -> getPageByViewMode(page, view)); } @@ -481,7 +487,8 @@ public Mono<List<NewPage>> archivePagesByApplicationId(String applicationId, Acl } @Override - public Mono<List<String>> findAllPageIdsInApplication(String applicationId, AclPermission aclPermission, Boolean view) { + public Mono<List<String>> findAllPageIdsInApplication( + String applicationId, AclPermission aclPermission, Boolean view) { return findNewPagesByApplicationId(applicationId, aclPermission) .flatMap(newPage -> { if (Boolean.TRUE.equals(view)) { @@ -501,8 +508,10 @@ public Mono<List<String>> findAllPageIdsInApplication(String applicationId, AclP @Override public Mono<PageDTO> updatePage(String pageId, PageDTO page) { - return repository.findById(pageId, pagePermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, pageId))) + return repository + .findById(pageId, pagePermission.getEditPermission()) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, pageId))) .flatMap(dbPage -> { copyNewFieldValuesIntoOldObject(page, dbPage.getUnpublishedPage()); if (!StringUtils.isEmpty(page.getName())) { @@ -510,13 +519,15 @@ public Mono<PageDTO> updatePage(String pageId, PageDTO page) { } return this.update(pageId, dbPage); }) - .flatMap(savedPage -> applicationService.saveLastEditInformation(savedPage.getApplicationId()) + .flatMap(savedPage -> applicationService + .saveLastEditInformation(savedPage.getApplicationId()) .then(getPageByViewMode(savedPage, false))); } @Override public Mono<PageDTO> updatePageByDefaultPageIdAndBranch(String defaultPageId, PageDTO page, String branchName) { - return repository.findPageByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) + return repository + .findPageByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) .flatMap(newPage -> updatePage(newPage.getId(), page)) .map(responseUtils::updatePageDTOWithDefaultResources); } @@ -547,12 +558,11 @@ public Mono<NewPage> archiveById(String id) { public Mono<NewPage> archiveByIdEx(String id, Optional<AclPermission> permission) { Mono<NewPage> pageMono = this.findById(id, permission) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE_ID, id))) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE_ID, id))) .cache(); - return pageMono - .flatMap(newPage -> repository.archiveById(id)) - .then(pageMono); + return pageMono.flatMap(newPage -> repository.archiveById(id)).then(pageMono); } @Override @@ -569,34 +579,35 @@ public Mono<String> getNameByPageId(String pageId, boolean isPublishedName) { } @Override - public Mono<NewPage> findByBranchNameAndDefaultPageId(String branchName, String defaultPageId, AclPermission permission) { + public Mono<NewPage> findByBranchNameAndDefaultPageId( + String branchName, String defaultPageId, AclPermission permission) { if (!StringUtils.hasText(defaultPageId)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.PAGE_ID)); } else if (!StringUtils.hasText(branchName)) { return this.findById(defaultPageId, permission) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, defaultPageId)) - ); + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, defaultPageId))); } - return repository.findPageByBranchNameAndDefaultPageId(branchName, defaultPageId, permission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, defaultPageId + ", " + branchName)) - ); + return repository + .findPageByBranchNameAndDefaultPageId(branchName, defaultPageId, permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, defaultPageId + ", " + branchName))); } @Override public Mono<String> findBranchedPageId(String branchName, String defaultPageId, AclPermission permission) { if (!StringUtils.hasText(branchName)) { if (!StringUtils.hasText(defaultPageId)) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.PAGE_ID, defaultPageId)); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.PAGE_ID, defaultPageId)); } return Mono.just(defaultPageId); } - return repository.findPageByBranchNameAndDefaultPageId(branchName, defaultPageId, permission) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE_ID, defaultPageId + ", " + branchName)) - ) + return repository + .findPageByBranchNameAndDefaultPageId(branchName, defaultPageId, permission) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE_ID, defaultPageId + ", " + branchName))) .map(NewPage::getId); } @@ -612,12 +623,12 @@ public Mono<String> findRootApplicationIdFromNewPage(String branchName, String d List.of(FieldName.APPLICATION_ID, FieldName.DEFAULT_RESOURCES), pagePermission.getReadPermission()); } else { - getPageMono = repository.findPageByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getReadPermission()); + getPageMono = repository.findPageByBranchNameAndDefaultPageId( + branchName, defaultPageId, pagePermission.getReadPermission()); } return getPageMono - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE_ID, defaultPageId + ", " + branchName)) - ) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE_ID, defaultPageId + ", " + branchName))) .map(newPage -> { log.debug("Retrieved possible application ids for page, picking the appropriate one now"); if (newPage.getDefaultResources() != null) { @@ -629,12 +640,14 @@ public Mono<String> findRootApplicationIdFromNewPage(String branchName, String d } @Override - public Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission) { + public Mono<NewPage> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, AclPermission permission) { return repository.findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, gitSyncId, permission); } @Override - public Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission) { + public Mono<NewPage> findByGitSyncIdAndDefaultApplicationId( + String defaultApplicationId, String gitSyncId, Optional<AclPermission> permission) { return repository.findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, gitSyncId, permission); } @@ -656,15 +669,18 @@ public Flux<NewPage> findPageSlugsByApplicationIds(List<String> applicationIds, * @return List of ApplicationPagesDTO */ @Override - public Mono<ApplicationPagesDTO> findApplicationPages(String applicationId, String pageId, String branchName, ApplicationMode mode) { + public Mono<ApplicationPagesDTO> findApplicationPages( + String applicationId, String pageId, String branchName, ApplicationMode mode) { boolean isViewMode = (mode == ApplicationMode.PUBLISHED); if (StringUtils.hasLength(applicationId)) { return findApplicationPagesByApplicationIdViewModeAndBranch(applicationId, branchName, isViewMode, true); } else if (StringUtils.hasLength(pageId)) { return findRootApplicationIdFromNewPage(branchName, pageId) - .flatMap(rootApplicationId -> findApplicationPagesByApplicationIdViewModeAndBranch(rootApplicationId, branchName, isViewMode, true)); + .flatMap(rootApplicationId -> findApplicationPagesByApplicationIdViewModeAndBranch( + rootApplicationId, branchName, isViewMode, true)); } else { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID + " or " + FieldName.PAGE_ID)); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID + " or " + FieldName.PAGE_ID)); } } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NotificationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NotificationServiceCEImpl.java index 0097bab2ee91..ecd49610e791 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NotificationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NotificationServiceCEImpl.java @@ -29,8 +29,7 @@ import java.time.format.DateTimeParseException; @Slf4j -public class NotificationServiceCEImpl - extends BaseService<NotificationRepository, Notification, String> +public class NotificationServiceCEImpl extends BaseService<NotificationRepository, Notification, String> implements NotificationServiceCE { private final SessionUserService sessionUserService; @@ -55,23 +54,23 @@ public NotificationServiceCEImpl( public Mono<Notification> create(Notification notification) { Mono<Notification> notificationWithUsernameMono; if (StringUtils.isEmpty(notification.getForUsername())) { - notificationWithUsernameMono = sessionUserService.getCurrentUser() - .map(user -> { - notification.setForUsername(user.getUsername()); - return notification; - }); + notificationWithUsernameMono = sessionUserService.getCurrentUser().map(user -> { + notification.setForUsername(user.getUsername()); + return notification; + }); } else { notificationWithUsernameMono = Mono.just(notification); } - return notificationWithUsernameMono - .flatMap(super::create); + return notificationWithUsernameMono.flatMap(super::create); } @Override public Flux<Notification> get(MultiValueMap<String, String> params) { // results will be sorted in descending order of createdAt - Sort sort = Sort.by(Sort.Direction.DESC, QNotification.notification.createdAt.getMetadata().getName()); + Sort sort = Sort.by( + Sort.Direction.DESC, + QNotification.notification.createdAt.getMetadata().getName()); // Remove branch name as notifications are not shared across branches params.remove(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME); // get page size from query params, default is 10 if param not present @@ -96,12 +95,10 @@ public Flux<Notification> get(MultiValueMap<String, String> params) { instant = Instant.now(); // param not present, use current time } - return sessionUserService.getCurrentUser() - .flatMapMany( - user -> repository.findByForUsernameAndCreatedAtBefore( - user.getUsername(), instant, pageRequest - ) - ) + return sessionUserService + .getCurrentUser() + .flatMapMany(user -> + repository.findByForUsernameAndCreatedAtBefore(user.getUsername(), instant, pageRequest)) .map(notification -> { return notification; }); @@ -110,34 +107,29 @@ public Flux<Notification> get(MultiValueMap<String, String> params) { @Override public Mono<Notification> findByIdAndBranchName(String id, String branchName) { // Ignore branch name as notifications are independent of branchNames - return repository.findById(id) - .map(notification -> { - return notification; - }); + return repository.findById(id).map(notification -> { + return notification; + }); } @Override public Mono<UpdateIsReadNotificationByIdDTO> updateIsRead(UpdateIsReadNotificationByIdDTO dto) { - return sessionUserService.getCurrentUser() - .flatMap(user -> - repository.updateIsReadByForUsernameAndIdList( - user.getUsername(), dto.getIdList(), dto.getIsRead() - ).thenReturn(dto) - ); + return sessionUserService.getCurrentUser().flatMap(user -> repository + .updateIsReadByForUsernameAndIdList(user.getUsername(), dto.getIdList(), dto.getIsRead()) + .thenReturn(dto)); } @Override public Mono<UpdateIsReadNotificationDTO> updateIsRead(UpdateIsReadNotificationDTO dto) { - return sessionUserService.getCurrentUser() - .flatMap(user -> repository.updateIsReadByForUsername(user.getUsername(), dto.getIsRead()) - .thenReturn(dto) - ); + return sessionUserService.getCurrentUser().flatMap(user -> repository + .updateIsReadByForUsername(user.getUsername(), dto.getIsRead()) + .thenReturn(dto)); } @Override public Mono<Long> getUnreadCount() { - return sessionUserService.getCurrentUser().flatMap(user -> - repository.countByForUsernameAndIsReadIsFalse(user.getUsername()) - ); + return sessionUserService + .getCurrentUser() + .flatMap(user -> repository.countByForUsernameAndIsReadIsFalse(user.getUsername())); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PermissionGroupServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PermissionGroupServiceCE.java index 7354c8500126..289054cc6ba3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PermissionGroupServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PermissionGroupServiceCE.java @@ -18,7 +18,8 @@ public interface PermissionGroupServiceCE extends CrudService<PermissionGroup, S Mono<PermissionGroup> bulkUnassignFromUsers(String permissionGroupId, List<User> users); - Mono<Boolean> bulkUnassignUsersFromPermissionGroupsWithoutPermission(Set<String> userIds, Set<String> permissionGroupIds); + Mono<Boolean> bulkUnassignUsersFromPermissionGroupsWithoutPermission( + Set<String> userIds, Set<String> permissionGroupIds); Flux<PermissionGroup> getByDefaultWorkspace(Workspace workspace, AclPermission permission); @@ -34,7 +35,8 @@ public interface PermissionGroupServiceCE extends CrudService<PermissionGroup, S Mono<PermissionGroup> unassignFromUser(PermissionGroup permissionGroup, User user); - Flux<PermissionGroup> getAllByAssignedToUserAndDefaultWorkspace(User user, Workspace defaultWorkspace, AclPermission aclPermission); + Flux<PermissionGroup> getAllByAssignedToUserAndDefaultWorkspace( + User user, Workspace defaultWorkspace, AclPermission aclPermission); Mono<Void> delete(String id); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PermissionGroupServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PermissionGroupServiceCEImpl.java index 396cc16ae0e8..c261582bc497 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PermissionGroupServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PermissionGroupServiceCEImpl.java @@ -12,7 +12,6 @@ import com.appsmith.server.dtos.Permission; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.repositories.ConfigRepository; import com.appsmith.server.repositories.PermissionGroupRepository; import com.appsmith.server.repositories.UserRepository; @@ -21,6 +20,7 @@ import com.appsmith.server.services.SessionUserService; import com.appsmith.server.services.TenantService; import com.appsmith.server.solutions.PermissionGroupPermission; +import com.appsmith.server.solutions.PolicySolution; import jakarta.validation.Validator; import org.apache.commons.collections.CollectionUtils; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; @@ -43,7 +43,6 @@ import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.fieldName; import static java.lang.Boolean.TRUE; - public class PermissionGroupServiceCEImpl extends BaseService<PermissionGroupRepository, PermissionGroup, String> implements PermissionGroupServiceCE { @@ -57,18 +56,19 @@ public class PermissionGroupServiceCEImpl extends BaseService<PermissionGroupRep private PermissionGroup publicPermissionGroup = null; - public PermissionGroupServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - PermissionGroupRepository repository, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - TenantService tenantService, - UserRepository userRepository, - PolicySolution policySolution, - ConfigRepository configRepository, - PermissionGroupPermission permissionGroupPermission) { + public PermissionGroupServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + PermissionGroupRepository repository, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + TenantService tenantService, + UserRepository userRepository, + PolicySolution policySolution, + ConfigRepository configRepository, + PermissionGroupPermission permissionGroupPermission) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.sessionUserService = sessionUserService; @@ -81,14 +81,17 @@ public PermissionGroupServiceCEImpl(Scheduler scheduler, @Override public Mono<PermissionGroup> create(PermissionGroup permissionGroup) { - return repository.save(permissionGroup) + return repository + .save(permissionGroup) .map(pg -> { - Set<Permission> permissions = new HashSet<>(Optional.ofNullable(pg.getPermissions()).orElse(Set.of())); + Set<Permission> permissions = new HashSet<>( + Optional.ofNullable(pg.getPermissions()).orElse(Set.of())); // Permission to unassign self is always given // so user can unassign himself from permission group permissions.add(new Permission(pg.getId(), UNASSIGN_PERMISSION_GROUPS)); pg.setPermissions(permissions); - Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject(pg, pg.getId()); + Map<String, Policy> policyMap = + policySolution.generatePolicyFromPermissionGroupForObject(pg, pg.getId()); policySolution.addPoliciesToExistingObject(policyMap, pg); return pg; }) @@ -113,43 +116,39 @@ public Mono<PermissionGroup> getById(String id, AclPermission permission) { @Override public Mono<Void> delete(String id) { - return repository.findById(id) - .flatMap(permissionGroup -> { + return repository.findById(id).flatMap(permissionGroup -> { + Mono<Void> returnMono = null; - Mono<Void> returnMono = null; + Set<String> assignedToUserIds = permissionGroup.getAssignedToUserIds(); - Set<String> assignedToUserIds = permissionGroup.getAssignedToUserIds(); + if (assignedToUserIds == null || assignedToUserIds.isEmpty()) { + returnMono = repository.deleteById(id); + } else { + returnMono = bulkUnassignFromUserIds(permissionGroup, List.copyOf(assignedToUserIds)) + .then(repository.deleteById(id)); + } - if (assignedToUserIds == null || assignedToUserIds.isEmpty()) { - returnMono = repository.deleteById(id); - } else { - returnMono = bulkUnassignFromUserIds(permissionGroup, List.copyOf(assignedToUserIds)) - .then(repository.deleteById(id)); - } - - return returnMono; - }); + return returnMono; + }); } @Override public Mono<Void> deleteWithoutPermission(String id) { - return repository.findById(id) - .flatMap(permissionGroup -> { - - Mono<Void> returnMono = null; + return repository.findById(id).flatMap(permissionGroup -> { + Mono<Void> returnMono = null; - Set<String> assignedToUserIds = permissionGroup.getAssignedToUserIds(); + Set<String> assignedToUserIds = permissionGroup.getAssignedToUserIds(); - if (assignedToUserIds == null || assignedToUserIds.isEmpty()) { - returnMono = repository.deleteById(id); - } else { - returnMono = bulkUnassignUsersFromPermissionGroupsWithoutPermission(assignedToUserIds, Set.of(id)) - .then(repository.deleteById(id)); - } + if (assignedToUserIds == null || assignedToUserIds.isEmpty()) { + returnMono = repository.deleteById(id); + } else { + returnMono = bulkUnassignUsersFromPermissionGroupsWithoutPermission(assignedToUserIds, Set.of(id)) + .then(repository.deleteById(id)); + } - return returnMono; - }); + return returnMono; + }); } @Override @@ -178,20 +177,22 @@ public Mono<PermissionGroup> bulkAssignToUsers(PermissionGroup pg, List<User> us return Mono.zip( permissionGroupUpdateMono, - cleanPermissionGroupCacheForUsers(userIds).thenReturn(TRUE) - ) + cleanPermissionGroupCacheForUsers(userIds).thenReturn(TRUE)) .map(tuple -> tuple.getT1()); } @Override public Mono<PermissionGroup> bulkAssignToUsers(String permissionGroupId, List<User> users) { - return repository.findById(permissionGroupId, permissionGroupPermission.getAssignPermission()) + return repository + .findById(permissionGroupId, permissionGroupPermission.getAssignPermission()) .flatMap(permissionGroup -> bulkAssignToUsers(permissionGroup, users)); } @Override - public Flux<PermissionGroup> getAllByAssignedToUserAndDefaultWorkspace(User user, Workspace defaultWorkspace, AclPermission permission) { - return repository.findAllByAssignedToUserIdAndDefaultWorkspaceId(user.getId(), defaultWorkspace.getId(), permission); + public Flux<PermissionGroup> getAllByAssignedToUserAndDefaultWorkspace( + User user, Workspace defaultWorkspace, AclPermission permission) { + return repository.findAllByAssignedToUserIdAndDefaultWorkspaceId( + user.getId(), defaultWorkspace.getId(), permission); } @Override @@ -207,14 +208,14 @@ public Mono<PermissionGroup> bulkUnassignFromUsers(PermissionGroup pg, List<User pg.getAssignedToUserIds().removeAll(userIds); return Mono.zip( repository.updateById(pg.getId(), pg, permissionGroupPermission.getUnAssignPermission()), - cleanPermissionGroupCacheForUsers(userIds).thenReturn(TRUE) - ) + cleanPermissionGroupCacheForUsers(userIds).thenReturn(TRUE)) .map(tuple -> tuple.getT1()); } @Override public Mono<PermissionGroup> bulkUnassignFromUsers(String permissionGroupId, List<User> users) { - return repository.findById(permissionGroupId, permissionGroupPermission.getUnAssignPermission()) + return repository + .findById(permissionGroupId, permissionGroupPermission.getUnAssignPermission()) .flatMap(permissionGroup -> bulkUnassignFromUsers(permissionGroup, users)); } @@ -223,14 +224,15 @@ Mono<PermissionGroup> bulkUnassignFromUserIds(PermissionGroup pg, List<String> u pg.getAssignedToUserIds().removeAll(userIds); return Mono.zip( repository.updateById(pg.getId(), pg, permissionGroupPermission.getUnAssignPermission()), - cleanPermissionGroupCacheForUsers(userIds).thenReturn(TRUE) - ) + cleanPermissionGroupCacheForUsers(userIds).thenReturn(TRUE)) .map(tuple -> tuple.getT1()); } @Override - public Mono<Boolean> bulkUnassignUsersFromPermissionGroupsWithoutPermission(Set<String> userIds, Set<String> permissionGroupIds) { - return repository.findAllById(permissionGroupIds) + public Mono<Boolean> bulkUnassignUsersFromPermissionGroupsWithoutPermission( + Set<String> userIds, Set<String> permissionGroupIds) { + return repository + .findAllById(permissionGroupIds) .flatMap(pg -> { Set<String> assignedToUserIds = pg.getAssignedToUserIds(); assignedToUserIds.removeAll(userIds); @@ -242,8 +244,7 @@ public Mono<Boolean> bulkUnassignUsersFromPermissionGroupsWithoutPermission(Set< return Mono.zip( repository.updateById(pg.getId(), updateObj), - cleanPermissionGroupCacheForUsers(List.copyOf(userIds)) - ) + cleanPermissionGroupCacheForUsers(List.copyOf(userIds))) .map(tuple -> tuple.getT1()); }) .then(Mono.just(TRUE)); @@ -262,20 +263,21 @@ public Flux<PermissionGroup> getByDefaultWorkspaces(Set<String> workspaceIds, Ac @Override public Mono<Void> cleanPermissionGroupCacheForUsers(List<String> userIds) { - Mono<Map<String, String>> userMapMono = userRepository.findAllById(userIds) - .collectMap(user -> user.getId(), user -> user.getEmail()); + Mono<Map<String, String>> userMapMono = + userRepository.findAllById(userIds).collectMap(user -> user.getId(), user -> user.getEmail()); - return tenantService.getDefaultTenantId() + return tenantService + .getDefaultTenantId() .zipWith(userMapMono) .flatMapMany(tuple -> { String defaultTenantId = tuple.getT1(); Map<String, String> userMap = tuple.getT2(); - return Flux.fromIterable(userIds) - .flatMap(userId -> { - String email = userMap.get(userId); - return repository.evictAllPermissionGroupCachesForUser(email, defaultTenantId) - .thenReturn(TRUE); - }); + return Flux.fromIterable(userIds).flatMap(userId -> { + String email = userMap.get(userId); + return repository + .evictAllPermissionGroupCachesForUser(email, defaultTenantId) + .thenReturn(TRUE); + }); }) .then(); } @@ -287,7 +289,8 @@ public Mono<PermissionGroup> getPublicPermissionGroup() { return Mono.just(publicPermissionGroup); } - return configRepository.findByName(PUBLIC_PERMISSION_GROUP) + return configRepository + .findByName(PUBLIC_PERMISSION_GROUP) .map(configObj -> configObj.getConfig().getAsString(PERMISSION_GROUP_ID)) .flatMap(permissionGroupId -> repository.findById(permissionGroupId)) .doOnNext(permissionGroup -> publicPermissionGroup = permissionGroup); @@ -295,44 +298,52 @@ public Mono<PermissionGroup> getPublicPermissionGroup() { @Override public Mono<String> getPublicPermissionGroupId() { - return getPublicPermissionGroup() - .map(PermissionGroup::getId); + return getPublicPermissionGroup().map(PermissionGroup::getId); } @Override public boolean isEntityAccessible(BaseDomain object, String permission, String permissionGroupId) { - return object.getPolicies() - .stream() - .filter(policy -> policy.getPermission().equals(permission) && - policy.getPermissionGroups().contains(permissionGroupId)) + return object.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(permission) + && policy.getPermissionGroups().contains(permissionGroupId)) .findFirst() .isPresent(); } - protected Mono<PermissionGroup> sendEventUsersAssociatedToRole(PermissionGroup permissionGroup, - List<String> usernames) { + protected Mono<PermissionGroup> sendEventUsersAssociatedToRole( + PermissionGroup permissionGroup, List<String> usernames) { Mono<PermissionGroup> sendAssignedUsersToPermissionGroupEvent = Mono.just(permissionGroup); if (CollectionUtils.isNotEmpty(usernames)) { Map<String, Object> eventData = Map.of(FieldName.ASSIGNED_USERS_TO_PERMISSION_GROUPS, usernames); - Map<String, Object> extraPropsForCloudHostedInstance = Map.of(FieldName.ASSIGNED_USERS_TO_PERMISSION_GROUPS, usernames); - Map<String, Object> analyticsProperties = Map.of(FieldName.NUMBER_OF_ASSIGNED_USERS, usernames.size(), - FieldName.EVENT_DATA, eventData, - FieldName.CLOUD_HOSTED_EXTRA_PROPS, extraPropsForCloudHostedInstance); + Map<String, Object> extraPropsForCloudHostedInstance = + Map.of(FieldName.ASSIGNED_USERS_TO_PERMISSION_GROUPS, usernames); + Map<String, Object> analyticsProperties = Map.of( + FieldName.NUMBER_OF_ASSIGNED_USERS, + usernames.size(), + FieldName.EVENT_DATA, + eventData, + FieldName.CLOUD_HOSTED_EXTRA_PROPS, + extraPropsForCloudHostedInstance); sendAssignedUsersToPermissionGroupEvent = analyticsService.sendObjectEvent( AnalyticsEvents.ASSIGNED_USERS_TO_PERMISSION_GROUP, permissionGroup, analyticsProperties); } return sendAssignedUsersToPermissionGroupEvent; } - protected Mono<PermissionGroup> sendEventUserRemovedFromRole(PermissionGroup permissionGroup, - List<String> usernames) { + protected Mono<PermissionGroup> sendEventUserRemovedFromRole( + PermissionGroup permissionGroup, List<String> usernames) { Mono<PermissionGroup> sendUnAssignedUsersToPermissionGroupEvent = Mono.just(permissionGroup); if (CollectionUtils.isNotEmpty(usernames)) { Map<String, Object> eventData = Map.of(FieldName.UNASSIGNED_USERS_FROM_PERMISSION_GROUPS, usernames); - Map<String, Object> extraPropsForCloudHostedInstance = Map.of(FieldName.UNASSIGNED_USERS_FROM_PERMISSION_GROUPS, usernames); - Map<String, Object> analyticsProperties = Map.of(FieldName.NUMBER_OF_UNASSIGNED_USERS, usernames.size(), - FieldName.EVENT_DATA, eventData, - FieldName.CLOUD_HOSTED_EXTRA_PROPS, extraPropsForCloudHostedInstance); + Map<String, Object> extraPropsForCloudHostedInstance = + Map.of(FieldName.UNASSIGNED_USERS_FROM_PERMISSION_GROUPS, usernames); + Map<String, Object> analyticsProperties = Map.of( + FieldName.NUMBER_OF_UNASSIGNED_USERS, + usernames.size(), + FieldName.EVENT_DATA, + eventData, + FieldName.CLOUD_HOSTED_EXTRA_PROPS, + extraPropsForCloudHostedInstance); sendUnAssignedUsersToPermissionGroupEvent = analyticsService.sendObjectEvent( AnalyticsEvents.UNASSIGNED_USERS_FROM_PERMISSION_GROUP, permissionGroup, analyticsProperties); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PluginServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PluginServiceCEImpl.java index df79519ccdd8..ff3390e385b1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PluginServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PluginServiceCEImpl.java @@ -78,7 +78,8 @@ public class PluginServiceCEImpl extends BaseService<PluginRepository, Plugin, S private static final String UQI_QUERY_EDITOR_BASE_FOLDER = "editor"; private static final String UQI_QUERY_EDITOR_ROOT_FILE = "root.json"; - private static final String BASE_UQI_URL = "https://raw.githubusercontent.com/appsmithorg/uqi-configurations/master/"; + private static final String BASE_UQI_URL = + "https://raw.githubusercontent.com/appsmithorg/uqi-configurations/master/"; private static final String KEY_EDITOR = "editor"; private static final String KEY_CONFIG_PROPERTY = "configProperty"; @@ -91,17 +92,18 @@ public class PluginServiceCEImpl extends BaseService<PluginRepository, Plugin, S public static final String KEY_FILES = "files"; @Autowired - public PluginServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - PluginRepository repository, - AnalyticsService analyticsService, - WorkspaceService workspaceService, - PluginManager pluginManager, - ReactiveRedisTemplate<String, String> reactiveTemplate, - ChannelTopic topic, - ObjectMapper objectMapper) { + public PluginServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + PluginRepository repository, + AnalyticsService analyticsService, + WorkspaceService workspaceService, + PluginManager pluginManager, + ReactiveRedisTemplate<String, String> reactiveTemplate, + ChannelTopic topic, + ObjectMapper objectMapper) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.workspaceService = workspaceService; this.pluginManager = pluginManager; @@ -131,8 +133,7 @@ public Flux<Plugin> get(MultiValueMap<String, String> params) { return Flux.empty(); } - List<String> pluginIds = org.getPlugins() - .stream() + List<String> pluginIds = org.getPlugins().stream() .filter(plugin -> plugin.getDeleted() == false) .map(WorkspacePlugin::getPluginId) .collect(Collectors.toList()); @@ -152,10 +153,7 @@ public Flux<Plugin> get(MultiValueMap<String, String> params) { return mongoTemplate.find(query, Plugin.class); }) .flatMap(plugin -> - getTemplates(plugin) - .doOnSuccess(plugin::setTemplates) - .thenReturn(plugin) - ); + getTemplates(plugin).doOnSuccess(plugin::setTemplates).thenReturn(plugin)); } @Override @@ -187,29 +185,26 @@ public Mono<Workspace> installPlugin(PluginWorkspaceDTO pluginOrgDTO) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); } - return storeWorkspacePlugin(pluginOrgDTO, pluginOrgDTO.getStatus()) - .switchIfEmpty(Mono.empty()); + return storeWorkspacePlugin(pluginOrgDTO, pluginOrgDTO.getStatus()).switchIfEmpty(Mono.empty()); } @Override public Flux<Workspace> installDefaultPlugins(List<Plugin> plugins) { - final List<WorkspacePlugin> newWorkspacePlugins = plugins - .stream() + final List<WorkspacePlugin> newWorkspacePlugins = plugins.stream() .filter(plugin -> Boolean.TRUE.equals(plugin.getDefaultInstall())) .map(plugin -> { return new WorkspacePlugin(plugin.getId(), WorkspacePluginStatus.ACTIVATED); }) .collect(Collectors.toList()); - return workspaceService.getAll() - .flatMap(workspace -> { - // Only perform a DB op if plugins associated to this org have changed - if (workspace.getPlugins().containsAll(newWorkspacePlugins)) { - return Mono.just(workspace); - } else { - workspace.getPlugins().addAll(newWorkspacePlugins); - return workspaceService.save(workspace); - } - }); + return workspaceService.getAll().flatMap(workspace -> { + // Only perform a DB op if plugins associated to this org have changed + if (workspace.getPlugins().containsAll(newWorkspacePlugins)) { + return Mono.just(workspace); + } else { + workspace.getPlugins().addAll(newWorkspacePlugins); + return workspaceService.save(workspace); + } + }); } @Override @@ -221,18 +216,22 @@ public Mono<Workspace> uninstallPlugin(PluginWorkspaceDTO pluginDTO) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); } - //Find the workspace using id and plugin id -> This is to find if the workspace has the plugin installed - Mono<Workspace> workspaceMono = workspaceService.findByIdAndPluginsPluginId(pluginDTO.getWorkspaceId(), - pluginDTO.getPluginId()); + // Find the workspace using id and plugin id -> This is to find if the workspace has the plugin installed + Mono<Workspace> workspaceMono = + workspaceService.findByIdAndPluginsPluginId(pluginDTO.getWorkspaceId(), pluginDTO.getPluginId()); return workspaceMono - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.PLUGIN_NOT_INSTALLED, pluginDTO.getPluginId()))) - //In case the plugin is not found for the workspace, the workspaceMono would not emit and the rest of the flow would stop - //i.e. the rest of the code flow would only happen when there is a plugin found for the workspace that can - //be uninstalled. + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.PLUGIN_NOT_INSTALLED, pluginDTO.getPluginId()))) + // In case the plugin is not found for the workspace, the workspaceMono would not emit and the rest of + // the flow would stop + // i.e. the rest of the code flow would only happen when there is a plugin found for the workspace that + // can + // be uninstalled. .flatMap(workspace -> { Set<WorkspacePlugin> workspacePluginList = workspace.getPlugins(); - workspacePluginList.removeIf(listPlugin -> listPlugin.getPluginId().equals(pluginDTO.getPluginId())); + workspacePluginList.removeIf( + listPlugin -> listPlugin.getPluginId().equals(pluginDTO.getPluginId())); workspace.setPlugins(workspacePluginList); return workspaceService.save(workspace); }); @@ -240,55 +239,53 @@ public Mono<Workspace> uninstallPlugin(PluginWorkspaceDTO pluginDTO) { private Mono<Workspace> storeWorkspacePlugin(PluginWorkspaceDTO pluginDTO, WorkspacePluginStatus status) { - Mono<Workspace> pluginInWorkspaceMono = workspaceService - .findByIdAndPluginsPluginId(pluginDTO.getWorkspaceId(), pluginDTO.getPluginId()); + Mono<Workspace> pluginInWorkspaceMono = + workspaceService.findByIdAndPluginsPluginId(pluginDTO.getWorkspaceId(), pluginDTO.getPluginId()); + + // If plugin is already present for the workspace, just return the workspace, else install and return workspace + return pluginInWorkspaceMono.switchIfEmpty(Mono.defer(() -> { + log.debug("Plugin {} not already installed. Installing now", pluginDTO.getPluginId()); + // If the plugin is not found in the workspace, its not installed already. Install now. + return repository + .findById(pluginDTO.getPluginId()) + .map(plugin -> { + log.debug("Before publishing to the redis queue"); + // Publish the event to the pub/sub queue + InstallPluginRedisDTO installPluginRedisDTO = new InstallPluginRedisDTO(); + installPluginRedisDTO.setWorkspaceId(pluginDTO.getWorkspaceId()); + installPluginRedisDTO.setPluginWorkspaceDTO(pluginDTO); + String jsonString; + try { + jsonString = objectMapper.writeValueAsString(installPluginRedisDTO); + } catch (JsonProcessingException e) { + log.error("", e); + return Mono.error(e); + } + return reactiveTemplate + .convertAndSend(topic.getTopic(), jsonString) + .subscribe(); + }) + // Now that the plugin jar has been successfully downloaded, go on and add the plugin to the + // workspace + .then(workspaceService.getById(pluginDTO.getWorkspaceId())) + .flatMap(workspace -> { + Set<WorkspacePlugin> workspacePluginList = workspace.getPlugins(); + if (workspacePluginList == null) { + workspacePluginList = new HashSet<>(); + } + WorkspacePlugin workspacePlugin = new WorkspacePlugin(); + workspacePlugin.setPluginId(pluginDTO.getPluginId()); + workspacePlugin.setStatus(status); + workspacePluginList.add(workspacePlugin); + workspace.setPlugins(workspacePluginList); - //If plugin is already present for the workspace, just return the workspace, else install and return workspace - return pluginInWorkspaceMono - .switchIfEmpty(Mono.defer(() -> { - log.debug("Plugin {} not already installed. Installing now", pluginDTO.getPluginId()); - //If the plugin is not found in the workspace, its not installed already. Install now. - return repository - .findById(pluginDTO.getPluginId()) - .map(plugin -> { - - log.debug("Before publishing to the redis queue"); - //Publish the event to the pub/sub queue - InstallPluginRedisDTO installPluginRedisDTO = new InstallPluginRedisDTO(); - installPluginRedisDTO.setWorkspaceId(pluginDTO.getWorkspaceId()); - installPluginRedisDTO.setPluginWorkspaceDTO(pluginDTO); - String jsonString; - try { - jsonString = objectMapper.writeValueAsString(installPluginRedisDTO); - } catch (JsonProcessingException e) { - log.error("", e); - return Mono.error(e); - } - return reactiveTemplate - .convertAndSend(topic.getTopic(), jsonString) - .subscribe(); - }) - //Now that the plugin jar has been successfully downloaded, go on and add the plugin to the workspace - .then(workspaceService.getById(pluginDTO.getWorkspaceId())) - .flatMap(workspace -> { - - Set<WorkspacePlugin> workspacePluginList = workspace.getPlugins(); - if (workspacePluginList == null) { - workspacePluginList = new HashSet<>(); - } - - WorkspacePlugin workspacePlugin = new WorkspacePlugin(); - workspacePlugin.setPluginId(pluginDTO.getPluginId()); - workspacePlugin.setStatus(status); - workspacePluginList.add(workspacePlugin); - workspace.setPlugins(workspacePluginList); - - log.debug("Going to save the workspace with install plugin. This means that installation has been successful"); - - return workspaceService.save(workspace); - }); - })); + log.debug( + "Going to save the workspace with install plugin. This means that installation has been successful"); + + return workspaceService.save(workspace); + }); + })); } public Mono<Plugin> findByName(String name) { @@ -306,21 +303,23 @@ public Mono<Plugin> findById(String id) { @Override public Mono<String> getPluginName(Mono<Datasource> datasourceMono) { - return - datasourceMono - .flatMap(datasource -> this.findById(datasource.getPluginId()) - .map(plugin -> plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName())); + return datasourceMono.flatMap(datasource -> this.findById(datasource.getPluginId()) + .map(plugin -> plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName())); } @Override public Plugin redisInstallPlugin(InstallPluginRedisDTO installPluginRedisDTO) { - Mono<Plugin> pluginMono = repository.findById(installPluginRedisDTO.getPluginWorkspaceDTO().getPluginId()); + Mono<Plugin> pluginMono = repository.findById( + installPluginRedisDTO.getPluginWorkspaceDTO().getPluginId()); return pluginMono .flatMap(plugin -> downloadAndStartPlugin(installPluginRedisDTO.getWorkspaceId(), plugin)) .switchIfEmpty(Mono.defer(() -> { - log.debug("During redisInstallPlugin, no plugin with plugin id {} found. Returning without download and install", installPluginRedisDTO.getPluginWorkspaceDTO().getPluginId()); + log.debug( + "During redisInstallPlugin, no plugin with plugin id {} found. Returning without download and install", + installPluginRedisDTO.getPluginWorkspaceDTO().getPluginId()); return Mono.just(new Plugin()); - })).block(); + })) + .block(); } private Mono<Plugin> downloadAndStartPlugin(String workspaceId, Plugin plugin) { @@ -339,18 +338,15 @@ private Mono<Plugin> downloadAndStartPlugin(String workspaceId, Plugin plugin) { try { FileUtils.copyURLToFile( - new URL(plugin.getJarLocation()), - new File(baseUrl, pluginJar), - CONNECTION_TIMEOUT, - READ_TIMEOUT); + new URL(plugin.getJarLocation()), new File(baseUrl, pluginJar), CONNECTION_TIMEOUT, READ_TIMEOUT); } catch (Exception e) { log.error("", e); return Mono.error(new AppsmithException(AppsmithError.PLUGIN_INSTALLATION_FAILED_DOWNLOAD_ERROR)); } - //Now that the plugin has been downloaded, load and restart the plugin + // Now that the plugin has been downloaded, load and restart the plugin pluginManager.loadPlugin(Path.of(baseUrl + pluginJar)); - //The following only starts plugins which have been loaded but hasn't been started yet. + // The following only starts plugins which have been loaded but hasn't been started yet. pluginManager.startPlugins(); return Mono.just(plugin); @@ -362,29 +358,25 @@ public Mono<Map> getFormConfig(String pluginId) { final Mono<Map> formMono = loadPluginResource(pluginId, "form.json") .doOnError(throwable -> // Remove this pluginId from the cache so it is tried again next time. - formCache.remove(pluginId) - ) + formCache.remove(pluginId)) .onErrorMap(Exceptions::unwrap) .cache(); final Mono<Map> editorMono = loadPluginResource(pluginId, "editor.json") .doOnError(throwable -> // Remove this pluginId from the cache so it is tried again next time. - formCache.remove(pluginId) - ) + formCache.remove(pluginId)) .onErrorReturn(new HashMap()) .cache(); final Mono<Map> settingMono = loadPluginResource(pluginId, "setting.json") .doOnError(throwable -> // Remove this pluginId from the cache so it is tried again next time. - formCache.remove(pluginId) - ) + formCache.remove(pluginId)) .onErrorReturn(new HashMap()) .cache(); final Mono<Map> dependencyMono = loadPluginResource(pluginId, "dependency.json") .doOnError(throwable -> // Remove this pluginId from the cache so it is tried again next time. - formCache.remove(pluginId) - ) + formCache.remove(pluginId)) .onErrorReturn(new HashMap()) .cache(); @@ -420,44 +412,38 @@ public Mono<Map> getEditorConfigLabelMap(String pluginId) { return Mono.just(new HashMap()); } - Mono<Map> labelMapMono = formConfig - .flatMap(formMap -> { - Map<String, String> labelMap = new LinkedHashMap(); // need to keep the key value pairs in order - List editorMap = (List) formMap.get(KEY_EDITOR); - if (editorMap == null) { - return Mono.just(new HashMap()); - } + Mono<Map> labelMapMono = formConfig.flatMap(formMap -> { + Map<String, String> labelMap = new LinkedHashMap(); // need to keep the key value pairs in order + List editorMap = (List) formMap.get(KEY_EDITOR); + if (editorMap == null) { + return Mono.just(new HashMap()); + } - editorMap.stream() - .filter(item -> { - if (((Map) item).get(KEY_CHILDREN) == null) { - return false; - } - return true; - }) - .map(item -> ((Map) item).get(KEY_CHILDREN)) - .forEach(item -> - ((List<Map>) item).stream() - .forEach(queryField -> { - /* - * - First check for "label" key. - * - If "label" key has empty value, then get the value against - * "internalLabel" key. - */ - String label = StringUtils.isEmpty(queryField.get(KEY_LABEL)) ? - (StringUtils.isEmpty(queryField.get(KEY_INTERNAL_LABEL)) ? - DEFAULT_LABEL : (String) queryField.get(KEY_INTERNAL_LABEL)) : - (String) queryField.get(KEY_LABEL); - String configProperty = (String) queryField.get(KEY_CONFIG_PROPERTY); - labelMap.put( - configProperty, - label - ); - }) - ); - - return Mono.just(labelMap); - }); + editorMap.stream() + .filter(item -> { + if (((Map) item).get(KEY_CHILDREN) == null) { + return false; + } + return true; + }) + .map(item -> ((Map) item).get(KEY_CHILDREN)) + .forEach(item -> ((List<Map>) item).stream().forEach(queryField -> { + /* + * - First check for "label" key. + * - If "label" key has empty value, then get the value against + * "internalLabel" key. + */ + String label = StringUtils.isEmpty(queryField.get(KEY_LABEL)) + ? (StringUtils.isEmpty(queryField.get(KEY_INTERNAL_LABEL)) + ? DEFAULT_LABEL + : (String) queryField.get(KEY_INTERNAL_LABEL)) + : (String) queryField.get(KEY_LABEL); + String configProperty = (String) queryField.get(KEY_CONFIG_PROPERTY); + labelMap.put(configProperty, label); + })); + + return Mono.just(labelMap); + }); labelCache.put(pluginId, labelMapMono); @@ -469,18 +455,18 @@ private Mono<Map<String, String>> getTemplates(Plugin plugin) { if (!templateCache.containsKey(pluginId)) { final Mono<Map<String, String>> mono = Mono.fromSupplier(() -> loadTemplatesFromPlugin(plugin)) - .onErrorResume(throwable -> throwable.getCause() instanceof FileNotFoundException, throwable -> Mono.just(Collections.emptyMap())) + .onErrorResume( + throwable -> throwable.getCause() instanceof FileNotFoundException, + throwable -> Mono.just(Collections.emptyMap())) .doOnError(throwable -> // Remove this pluginId from the cache so it is tried again next time. - templateCache.remove(pluginId) - ) + templateCache.remove(pluginId)) // It's okay if the templates folder is not present, we just return empty templates collection. .onErrorMap(throwable -> { log.error("Error loading templates for plugin {}.", plugin.getPackageName(), throwable); return new AppsmithException( AppsmithError.PLUGIN_LOAD_TEMPLATES_FAIL, - Exceptions.unwrap(throwable).getMessage() - ); + Exceptions.unwrap(throwable).getMessage()); }) .cache(); @@ -492,22 +478,16 @@ private Mono<Map<String, String>> getTemplates(Plugin plugin) { private Map<String, String> loadTemplatesFromPlugin(Plugin plugin) { final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( - pluginManager - .getPlugin(plugin.getPackageName()) - .getPluginClassLoader() - ); + pluginManager.getPlugin(plugin.getPackageName()).getPluginClassLoader()); final PluginTemplatesMeta pluginTemplatesMeta; try { pluginTemplatesMeta = objectMapper.readValue( - resolver.getResource("templates/meta.json").getInputStream(), - PluginTemplatesMeta.class - ); + resolver.getResource("templates/meta.json").getInputStream(), PluginTemplatesMeta.class); } catch (IOException e) { log.error("Error loading templates metadata in plugin {}", plugin.getPackageName()); throw Exceptions.propagate(e); - } if (pluginTemplatesMeta.getTemplates() == null) { @@ -531,15 +511,11 @@ private Map<String, String> loadTemplatesFromPlugin(Plugin plugin) { : template.getTitle(); try { - templates.put( - title, - StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset()) - ); + templates.put(title, StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset())); } catch (IOException e) { log.error("Error loading template {} for plugin {}", filename, plugin.getId()); throw Exceptions.propagate(e); - } } @@ -548,14 +524,14 @@ private Map<String, String> loadTemplatesFromPlugin(Plugin plugin) { InputStream getConfigInputStream(Plugin plugin, String fileName) throws IOException { String resourcePath = UQI_QUERY_EDITOR_BASE_FOLDER + "/" + fileName; -// if (Set.of( -// "google-sheets-plugin", -// "mongo-plugin", -// "amazons3-plugin", -// "firestore-plugin" -// ).contains(plugin.getPackageName())) { -// return new URL(BASE_UQI_URL + plugin.getPackageName() + "/editor/" + fileName).openStream(); -// } + // if (Set.of( + // "google-sheets-plugin", + // "mongo-plugin", + // "amazons3-plugin", + // "firestore-plugin" + // ).contains(plugin.getPackageName())) { + // return new URL(BASE_UQI_URL + plugin.getPackageName() + "/editor/" + fileName).openStream(); + // } return pluginManager .getPlugin(plugin.getPackageName()) .getPluginClassLoader() @@ -578,14 +554,22 @@ public Map loadEditorPluginResourceUqi(Plugin plugin) { try (InputStream resourceAsStream = getConfigInputStream(plugin, UQI_QUERY_EDITOR_ROOT_FILE)) { if (resourceAsStream == null) { - throw new AppsmithException(AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), "form resource " + resourcePath + " not found"); + throw new AppsmithException( + AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, + plugin.getPackageName(), + "form resource " + resourcePath + " not found"); } // Read the root.json content. rootTree = objectMapper.readValue(resourceAsStream, ObjectNode.class); } catch (IOException e) { - log.error("Error loading resource JSON for plugin {} and resourcePath {}", plugin.getPackageName(), resourcePath, e); - throw new AppsmithException(AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), e.getMessage()); + log.error( + "Error loading resource JSON for plugin {} and resourcePath {}", + plugin.getPackageName(), + resourcePath, + e); + throw new AppsmithException( + AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), e.getMessage()); } /* @@ -619,17 +603,19 @@ public Map loadEditorPluginResourceUqi(Plugin plugin) { templateChildrenNode.add(templateConfig); } catch (AppsmithException e) { // Either the file doesn't exist or malformed JSON was found. Ignore the command template - log.error("Error loading resource JSON for plugin {} and resourcePath {} : ", plugin.getPackageName(), resourcePath, e); + log.error( + "Error loading resource JSON for plugin {} and resourcePath {} : ", + plugin.getPackageName(), + resourcePath, + e); } - } } ObjectNode topLevel = objectMapper.createObjectNode(); topLevel.set("editor", editorArray); - return objectMapper.convertValue(topLevel, new TypeReference<Map<String, Object>>() { - }); + return objectMapper.convertValue(topLevel, new TypeReference<Map<String, Object>>() {}); } @Override @@ -649,14 +635,19 @@ private Map loadPluginResourceGivenPluginAsMap(Plugin plugin, String resourcePat .getResourceAsStream(resourcePath)) { if (resourceAsStream == null) { - throw new AppsmithException(AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), "form resource " + resourcePath + " not found"); + throw new AppsmithException( + AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, + plugin.getPackageName(), + "form resource " + resourcePath + " not found"); } Map resourceMap = objectMapper.readValue(resourceAsStream, Map.class); return resourceMap; } catch (IOException e) { - log.error("[{}] : Error loading resource JSON for resourcePath {}", plugin.getPackageName(), resourcePath, e); - throw new AppsmithException(AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), e.getMessage()); + log.error( + "[{}] : Error loading resource JSON for resourcePath {}", plugin.getPackageName(), resourcePath, e); + throw new AppsmithException( + AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), e.getMessage()); } } @@ -664,38 +655,42 @@ private JsonNode loadPluginResourceGivenPluginAsJsonNode(Plugin plugin, String r try (InputStream resourceAsStream = getConfigInputStream(plugin, resourcePath)) { if (resourceAsStream == null) { - throw new AppsmithException(AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), "form resource " + resourcePath + " not found"); + throw new AppsmithException( + AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, + plugin.getPackageName(), + "form resource " + resourcePath + " not found"); } return objectMapper.readTree(resourceAsStream); } catch (IOException e) { - log.error("[{}] : Error loading resource JSON for resourcePath {}", plugin.getPackageName(), resourcePath, e); - throw new AppsmithException(AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), e.getMessage()); + log.error( + "[{}] : Error loading resource JSON for resourcePath {}", plugin.getPackageName(), resourcePath, e); + throw new AppsmithException( + AppsmithError.PLUGIN_LOAD_FORM_JSON_FAIL, plugin.getPackageName(), e.getMessage()); } } @Override public Mono<Map> loadPluginResource(String pluginId, String resourcePath) { - return findById(pluginId) - .map(plugin -> { - if ("editor.json".equals(resourcePath)) { - // UI config will be available if this plugin is sourced from the cloud - if (plugin.getActionUiConfig() != null) { - return plugin.getActionUiConfig(); - } - // For UQI, use another format of loading the config - if (UQI_DB_EDITOR_FORM.equals(plugin.getUiComponent())) { - return loadEditorPluginResourceUqi(plugin); - } - } - if ("form.json".equals(resourcePath)) { - // UI config will be available if this plugin is sourced from the cloud - if (plugin.getDatasourceUiConfig() != null) { - return plugin.getDatasourceUiConfig(); - } - } - return loadPluginResourceGivenPluginAsMap(plugin, resourcePath); - }); + return findById(pluginId).map(plugin -> { + if ("editor.json".equals(resourcePath)) { + // UI config will be available if this plugin is sourced from the cloud + if (plugin.getActionUiConfig() != null) { + return plugin.getActionUiConfig(); + } + // For UQI, use another format of loading the config + if (UQI_DB_EDITOR_FORM.equals(plugin.getUiComponent())) { + return loadEditorPluginResourceUqi(plugin); + } + } + if ("form.json".equals(resourcePath)) { + // UI config will be available if this plugin is sourced from the cloud + if (plugin.getDatasourceUiConfig() != null) { + return plugin.getDatasourceUiConfig(); + } + } + return loadPluginResourceGivenPluginAsMap(plugin, resourcePath); + }); } @Data diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PostmanImporterServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PostmanImporterServiceCEImpl.java index ad88450b76ad..2375c9c6fdbe 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PostmanImporterServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/PostmanImporterServiceCEImpl.java @@ -25,16 +25,16 @@ public class PostmanImporterServiceCEImpl extends BaseApiImporter implements Pos private final ResponseUtils responseUtils; private final PagePermission pagePermission; - public PostmanImporterServiceCEImpl(NewPageService newPageService, - ResponseUtils responseUtils, - PagePermission pagePermission) { + public PostmanImporterServiceCEImpl( + NewPageService newPageService, ResponseUtils responseUtils, PagePermission pagePermission) { this.newPageService = newPageService; this.responseUtils = responseUtils; this.pagePermission = pagePermission; } @Override - public Mono<ActionDTO> importAction(Object input, String pageId, String name, String workspaceId, String branchName) { + public Mono<ActionDTO> importAction( + Object input, String pageId, String name, String workspaceId, String branchName) { ActionDTO action = new ActionDTO(); ActionConfiguration actionConfiguration = new ActionConfiguration(); Datasource datasource = new Datasource(); @@ -44,7 +44,8 @@ public Mono<ActionDTO> importAction(Object input, String pageId, String name, St action.setActionConfiguration(actionConfiguration); action.setPageId(pageId); action.setName(name); - return newPageService.findByBranchNameAndDefaultPageId(branchName, pageId, pagePermission.getActionCreatePermission()) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, pageId, pagePermission.getActionCreatePermission()) .map(branchedPage -> { action.setDefaultResources(branchedPage.getDefaultResources()); return action; @@ -114,5 +115,4 @@ private TemplateCollection createTemplateCollection(String id) { return templateCollection; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ProviderServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ProviderServiceCE.java index 8d0967360898..52c19668f015 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ProviderServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ProviderServiceCE.java @@ -9,5 +9,4 @@ public interface ProviderServiceCE extends CrudService<Provider, String> { public Mono<List<String>> getAllCategories(); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ProviderServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ProviderServiceCEImpl.java index 90851c4aee24..2466c6026205 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ProviderServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ProviderServiceCEImpl.java @@ -21,22 +21,60 @@ import java.util.List; @Slf4j -public class ProviderServiceCEImpl extends BaseService<ProviderRepository, Provider, String> implements ProviderServiceCE { +public class ProviderServiceCEImpl extends BaseService<ProviderRepository, Provider, String> + implements ProviderServiceCE { - private static final List<String> CATEGORIES = Arrays.asList("Business", "Visual Recognition", "Location", "Science", - "Food", "Travel, Transportation", "Music", "Tools", "Text Analysis", "Weather", "Gaming", "SMS", "Events", "Health, Fitness", - "Payments", "Financial", "Translation", "Storage", "Logistics", "Database", "Search", "Reward", "Mapping", "Machine Learning", - "Email", "News, Media", "Video, Images", "eCommerce", "Medical", "Devices", "Business Software", "Advertising", "Education", - "Media", "Social", "Commerce", "Communication", "Other", "Monitoring", "Energy"); + private static final List<String> CATEGORIES = Arrays.asList( + "Business", + "Visual Recognition", + "Location", + "Science", + "Food", + "Travel, Transportation", + "Music", + "Tools", + "Text Analysis", + "Weather", + "Gaming", + "SMS", + "Events", + "Health, Fitness", + "Payments", + "Financial", + "Translation", + "Storage", + "Logistics", + "Database", + "Search", + "Reward", + "Mapping", + "Machine Learning", + "Email", + "News, Media", + "Video, Images", + "eCommerce", + "Medical", + "Devices", + "Business Software", + "Advertising", + "Education", + "Media", + "Social", + "Commerce", + "Communication", + "Other", + "Monitoring", + "Energy"); private static final String DEFAULT_CATEGORY = "Business Software"; - public ProviderServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ProviderRepository repository, - AnalyticsService analyticsService) { + public ProviderServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ProviderRepository repository, + AnalyticsService analyticsService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SequenceServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SequenceServiceCE.java index 92c40f2aaf1a..97e5c93756ce 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SequenceServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SequenceServiceCE.java @@ -10,5 +10,4 @@ public interface SequenceServiceCE { Mono<Long> getNext(Class<? extends BaseDomain> domainClass, String suffix); Mono<String> getNextAsSuffix(Class<? extends BaseDomain> domainClass, String suffix); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SequenceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SequenceServiceCEImpl.java index 6bbe6cf52951..4808bc3c63e6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SequenceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SequenceServiceCEImpl.java @@ -11,7 +11,6 @@ import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; - public class SequenceServiceCEImpl implements SequenceServiceCE { private final ReactiveMongoTemplate mongoTemplate; @@ -28,8 +27,7 @@ public Mono<Long> getNext(String name) { query(where("name").is(name)), new Update().inc("nextNumber", 1), options().returnNew(true).upsert(true), - Sequence.class - ) + Sequence.class) .map(Sequence::getNextNumber); } @@ -43,5 +41,4 @@ public Mono<String> getNextAsSuffix(Class<? extends BaseDomain> domainClass, Str return getNext(mongoTemplate.getCollectionName(domainClass) + suffix) .map(number -> number > 1 ? " " + number : ""); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SessionUserServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SessionUserServiceCEImpl.java index ed67c80450a0..97c44f98b75f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SessionUserServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/SessionUserServiceCEImpl.java @@ -30,8 +30,8 @@ public class SessionUserServiceCEImpl implements SessionUserServiceCE { private final UserRepository userRepository; private final ReactiveRedisOperations<String, Object> redisOperations; - public final static String SPRING_SESSION_PATTERN = "spring:session:sessions:*"; - private final static String SESSION_ATTRIBUTE = "sessionAttr:"; + public static final String SPRING_SESSION_PATTERN = "spring:session:sessions:*"; + private static final String SESSION_ATTRIBUTE = "sessionAttr:"; @Override public Mono<User> getCurrentUser() { @@ -43,31 +43,32 @@ public Mono<User> getCurrentUser() { @Override public Mono<User> refreshCurrentUser(ServerWebExchange exchange) { return Mono.zip( - getCurrentUser().map(User::getEmail).flatMap(userRepository::findByEmail), - ReactiveSecurityContextHolder.getContext(), - exchange.getSession() - ).flatMap(tuple -> { - final User user = tuple.getT1(); - final SecurityContext context = tuple.getT2(); - final WebSession session = tuple.getT3(); - final Authentication currentToken = context.getAuthentication(); - final Authentication newToken; - if (currentToken instanceof UsernamePasswordAuthenticationToken) { - newToken = new UsernamePasswordAuthenticationToken(user, null, currentToken.getAuthorities()); - } else if (currentToken instanceof OAuth2AuthenticationToken) { - newToken = new OAuth2AuthenticationToken( - user, - currentToken.getAuthorities(), - ((OAuth2AuthenticationToken) currentToken).getAuthorizedClientRegistrationId() - ); - } else { - log.error("Unrecognized session token type when updating user in session: {}.", currentToken.getClass()); - return Mono.error(new AppsmithException(AppsmithError.FAIL_UPDATE_USER_IN_SESSION)); - } - context.setAuthentication(newToken); - session.getAttributes().put(DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME, context); - return Mono.just(user); - }); + getCurrentUser().map(User::getEmail).flatMap(userRepository::findByEmail), + ReactiveSecurityContextHolder.getContext(), + exchange.getSession()) + .flatMap(tuple -> { + final User user = tuple.getT1(); + final SecurityContext context = tuple.getT2(); + final WebSession session = tuple.getT3(); + final Authentication currentToken = context.getAuthentication(); + final Authentication newToken; + if (currentToken instanceof UsernamePasswordAuthenticationToken) { + newToken = new UsernamePasswordAuthenticationToken(user, null, currentToken.getAuthorities()); + } else if (currentToken instanceof OAuth2AuthenticationToken) { + newToken = new OAuth2AuthenticationToken( + user, + currentToken.getAuthorities(), + ((OAuth2AuthenticationToken) currentToken).getAuthorizedClientRegistrationId()); + } else { + log.error( + "Unrecognized session token type when updating user in session: {}.", + currentToken.getClass()); + return Mono.error(new AppsmithException(AppsmithError.FAIL_UPDATE_USER_IN_SESSION)); + } + context.setAuthentication(newToken); + session.getAttributes().put(DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME, context); + return Mono.just(user); + }); } @Override @@ -80,33 +81,36 @@ public Mono<Void> logoutAllSessions(String email) { @Override public Mono<List<String>> getSessionKeysByUserEmail(String email) { // This pattern string comes from calling `ReactiveRedisSessionRepository.getSessionKey("*")` private method. - return redisOperations.keys(SPRING_SESSION_PATTERN) + return redisOperations + .keys(SPRING_SESSION_PATTERN) .flatMap(key -> Mono.zip( Mono.just(key), // The values are maps, containing various pieces of session related information. // One of them, holds the serialized User object. We want just that. - redisOperations.opsForHash().entries(key) - .filter(e -> e.getValue() != null && - (SESSION_ATTRIBUTE + DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME).equals(e.getKey()) - ) - .map(e -> (User) ((SecurityContext) e.getValue()).getAuthentication().getPrincipal()) - .next() - )) + redisOperations + .opsForHash() + .entries(key) + .filter(e -> e.getValue() != null + && (SESSION_ATTRIBUTE + DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME) + .equals(e.getKey())) + .map(e -> (User) ((SecurityContext) e.getValue()) + .getAuthentication() + .getPrincipal()) + .next())) // Now we have tuples of session keys, and the corresponding user objects. // Filter the ones we need to clear out. - .filter(tuple -> StringUtils.equalsIgnoreCase(email, tuple.getT2().getEmail())) + .filter(tuple -> + StringUtils.equalsIgnoreCase(email, tuple.getT2().getEmail())) .map(Tuple2::getT1) .collectList(); - } @Override public Mono<Long> deleteSessionsByKeys(List<String> keys) { return CollectionUtils.isNullOrEmpty(keys) ? Mono.just(0L) - : redisOperations.delete(keys.toArray(String[]::new) - ) - .doOnError(error -> log.error("Error clearing user sessions", error)); + : redisOperations + .delete(keys.toArray(String[]::new)) + .doOnError(error -> log.error("Error clearing user sessions", error)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/TenantServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/TenantServiceCEImpl.java index caadd756e7a3..b69619cb04a1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/TenantServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/TenantServiceCEImpl.java @@ -26,13 +26,14 @@ public class TenantServiceCEImpl extends BaseService<TenantRepository, Tenant, S private final ConfigService configService; - public TenantServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - TenantRepository repository, - AnalyticsService analyticsService, - ConfigService configService) { + public TenantServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + TenantRepository repository, + AnalyticsService analyticsService, + ConfigService configService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.configService = configService; } @@ -45,33 +46,32 @@ public Mono<String> getDefaultTenantId() { return Mono.just(tenantId); } - return repository.findBySlug(FieldName.DEFAULT) - .map(Tenant::getId) - .map(tenantId -> { - // Set the cache value before returning. - this.tenantId = tenantId; - return tenantId; - }); + return repository.findBySlug(FieldName.DEFAULT).map(Tenant::getId).map(tenantId -> { + // Set the cache value before returning. + this.tenantId = tenantId; + return tenantId; + }); } @Override public Mono<Tenant> updateTenantConfiguration(String tenantId, TenantConfiguration tenantConfiguration) { - return repository.findById(tenantId, MANAGE_TENANT) - .flatMap(tenant -> { - TenantConfiguration oldtenantConfiguration = tenant.getTenantConfiguration(); - if (oldtenantConfiguration == null) { - oldtenantConfiguration = new TenantConfiguration(); - } - AppsmithBeanUtils.copyNestedNonNullProperties(tenantConfiguration, oldtenantConfiguration); - tenant.setTenantConfiguration(oldtenantConfiguration); - return repository.updateById(tenantId, tenant, MANAGE_TENANT); - }); + return repository.findById(tenantId, MANAGE_TENANT).flatMap(tenant -> { + TenantConfiguration oldtenantConfiguration = tenant.getTenantConfiguration(); + if (oldtenantConfiguration == null) { + oldtenantConfiguration = new TenantConfiguration(); + } + AppsmithBeanUtils.copyNestedNonNullProperties(tenantConfiguration, oldtenantConfiguration); + tenant.setTenantConfiguration(oldtenantConfiguration); + return repository.updateById(tenantId, tenant, MANAGE_TENANT); + }); } @Override public Mono<Tenant> findById(String tenantId, AclPermission permission) { - return repository.findById(tenantId, permission) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "tenantId", tenantId))); + return repository + .findById(tenantId, permission) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "tenantId", tenantId))); } /* @@ -81,50 +81,47 @@ public Mono<Tenant> findById(String tenantId, AclPermission permission) { @Override public Mono<Tenant> getTenantConfiguration() { Mono<Tenant> dbTenantMono = getDefaultTenant(); - Mono<Tenant> clientTenantMono = configService.getInstanceId() - .map(instanceId -> { - final Tenant tenant = new Tenant(); - tenant.setInstanceId(instanceId); + Mono<Tenant> clientTenantMono = configService.getInstanceId().map(instanceId -> { + final Tenant tenant = new Tenant(); + tenant.setInstanceId(instanceId); - final TenantConfiguration config = new TenantConfiguration(); - tenant.setTenantConfiguration(config); + final TenantConfiguration config = new TenantConfiguration(); + tenant.setTenantConfiguration(config); - config.setGoogleMapsKey(System.getenv("APPSMITH_GOOGLE_MAPS_API_KEY")); + config.setGoogleMapsKey(System.getenv("APPSMITH_GOOGLE_MAPS_API_KEY")); - if (StringUtils.hasText(System.getenv("APPSMITH_OAUTH2_GOOGLE_CLIENT_ID"))) { - config.addThirdPartyAuth("google"); - } + if (StringUtils.hasText(System.getenv("APPSMITH_OAUTH2_GOOGLE_CLIENT_ID"))) { + config.addThirdPartyAuth("google"); + } - if (StringUtils.hasText(System.getenv("APPSMITH_OAUTH2_GITHUB_CLIENT_ID"))) { - config.addThirdPartyAuth("github"); - } + if (StringUtils.hasText(System.getenv("APPSMITH_OAUTH2_GITHUB_CLIENT_ID"))) { + config.addThirdPartyAuth("github"); + } - config.setIsFormLoginEnabled(!"true".equals(System.getenv("APPSMITH_FORM_LOGIN_DISABLED"))); + config.setIsFormLoginEnabled(!"true".equals(System.getenv("APPSMITH_FORM_LOGIN_DISABLED"))); - return tenant; - }); + return tenant; + }); - return Mono.zip(dbTenantMono, clientTenantMono) - .map(tuple -> { - Tenant dbTenant = tuple.getT1(); - Tenant clientTenant = tuple.getT2(); - return getClientPertinentTenant(dbTenant, clientTenant); - }); + return Mono.zip(dbTenantMono, clientTenantMono).map(tuple -> { + Tenant dbTenant = tuple.getT1(); + Tenant clientTenant = tuple.getT2(); + return getClientPertinentTenant(dbTenant, clientTenant); + }); } @Override public Mono<Tenant> getDefaultTenant() { // Get the default tenant object from the DB and then populate the relevant user permissions in that // We are doing this differently because `findBySlug` is a Mongo JPA query and not a custom Appsmith query - return repository.findBySlug(FieldName.DEFAULT) - .flatMap(tenant -> repository.setUserPermissionsInObject(tenant) - .switchIfEmpty(Mono.just(tenant))); + return repository + .findBySlug(FieldName.DEFAULT) + .flatMap(tenant -> repository.setUserPermissionsInObject(tenant).switchIfEmpty(Mono.just(tenant))); } @Override public Mono<Tenant> updateDefaultTenantConfiguration(TenantConfiguration tenantConfiguration) { - return getDefaultTenantId() - .flatMap(tenantId -> updateTenantConfiguration(tenantId, tenantConfiguration)); + return getDefaultTenantId().flatMap(tenantId -> updateTenantConfiguration(tenantId, tenantConfiguration)); } /** @@ -149,5 +146,4 @@ protected Tenant getClientPertinentTenant(Tenant dbTenant, Tenant clientTenant) return clientTenant; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java index 0bfd25f35f72..91016a05867e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java @@ -38,18 +38,19 @@ public class ThemeServiceCEImpl extends BaseService<ThemeRepositoryCE, Theme, St private final ApplicationService applicationService; private final PolicyGenerator policyGenerator; private final ApplicationPermission applicationPermission; - private String defaultThemeId; // acts as a simple cache so that we don't need to fetch from DB always - - public ThemeServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - ThemeRepository repository, - AnalyticsService analyticsService, - ApplicationRepository applicationRepository, - ApplicationService applicationService, - PolicyGenerator policyGenerator, - ApplicationPermission applicationPermission) { + private String defaultThemeId; // acts as a simple cache so that we don't need to fetch from DB always + + public ThemeServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + ThemeRepository repository, + AnalyticsService analyticsService, + ApplicationRepository applicationRepository, + ApplicationService applicationService, + PolicyGenerator policyGenerator, + ApplicationPermission applicationPermission) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.applicationRepository = applicationRepository; this.applicationService = applicationService; @@ -59,8 +60,7 @@ public ThemeServiceCEImpl(Scheduler scheduler, @Override public Mono<Theme> create(Theme resource) { - return repository.save(resource) - .flatMap(analyticsService::sendCreateEvent); + return repository.save(resource).flatMap(analyticsService::sendCreateEvent); } @Override @@ -83,17 +83,19 @@ public Flux<Theme> get(MultiValueMap<String, String> params) { @Override public Mono<Theme> getApplicationTheme(String applicationId, ApplicationMode applicationMode, String branchName) { - return applicationService.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getReadPermission()) + return applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getReadPermission()) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId)) - ) + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) .flatMap(application -> { String themeId = application.getEditModeThemeId(); if (applicationMode == ApplicationMode.PUBLISHED) { themeId = application.getPublishedModeThemeId(); } if (StringUtils.hasLength(themeId)) { - return repository.findById(themeId, READ_THEMES) + return repository + .findById(themeId, READ_THEMES) .switchIfEmpty(repository.getSystemThemeByName(Theme.DEFAULT_THEME_NAME)); } else { // theme id is not present, return default theme return repository.getSystemThemeByName(Theme.DEFAULT_THEME_NAME); @@ -103,7 +105,9 @@ public Mono<Theme> getApplicationTheme(String applicationId, ApplicationMode app @Override public Flux<Theme> getApplicationThemes(String applicationId, String branchName) { - return applicationService.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getReadPermission()) + return applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getReadPermission()) .flatMapMany(application -> repository.getApplicationThemes(application.getId(), READ_THEMES)); } @@ -114,21 +118,27 @@ public Flux<Theme> getSystemThemes() { @Override public Mono<Theme> updateTheme(String applicationId, String branchName, Theme resource) { - return applicationService.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getEditPermission()) .flatMap(application -> { - // makes sure user has permission to edit application and an application exists by this applicationId + // makes sure user has permission to edit application and an application exists by this + // applicationId // check if this application has already a customized them - return saveThemeForApplication(application.getEditModeThemeId(), resource, application, ApplicationMode.EDIT); + return saveThemeForApplication( + application.getEditModeThemeId(), resource, application, ApplicationMode.EDIT); }); } @Override public Mono<Theme> changeCurrentTheme(String newThemeId, String applicationId, String branchName) { - return applicationService.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getEditPermission()) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId)) - ) - .flatMap(application -> repository.findById(application.getEditModeThemeId(), READ_THEMES) + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) + .flatMap(application -> repository + .findById(application.getEditModeThemeId(), READ_THEMES) .defaultIfEmpty(new Theme()) .zipWith(repository.findById(newThemeId, READ_THEMES)) .flatMap(themeTuple2 -> { @@ -141,33 +151,40 @@ public Mono<Theme> changeCurrentTheme(String newThemeId, String applicationId, S newTheme.setApplicationId(null); newTheme.setWorkspaceId(null); newTheme.setPolicies(policyGenerator.getAllChildPolicies( - application.getPolicies(), Application.class, Theme.class - )); + application.getPolicies(), Application.class, Theme.class)); saveThemeMono = repository.save(newTheme); } else { saveThemeMono = Mono.just(newTheme); } - return saveThemeMono.flatMap(savedTheme -> { - if (StringUtils.hasLength(currentTheme.getId()) && !currentTheme.isSystemTheme() - && !StringUtils.hasLength(currentTheme.getApplicationId())) { - // current theme is neither a system theme nor app theme, delete the user customizations - return repository.delete(currentTheme) - .then(applicationRepository.setAppTheme( - application.getId(), savedTheme.getId(), null, applicationPermission.getEditPermission() - )) - .thenReturn(savedTheme); - } else { - return applicationRepository.setAppTheme( - application.getId(), savedTheme.getId(), null, applicationPermission.getEditPermission() - ) - .thenReturn(savedTheme); - } - }).flatMap(savedTheme -> - analyticsService.sendObjectEvent(AnalyticsEvents.APPLY, savedTheme) - ); - }) - ); + return saveThemeMono + .flatMap(savedTheme -> { + if (StringUtils.hasLength(currentTheme.getId()) + && !currentTheme.isSystemTheme() + && !StringUtils.hasLength(currentTheme.getApplicationId())) { + // current theme is neither a system theme nor app theme, delete the user + // customizations + return repository + .delete(currentTheme) + .then(applicationRepository.setAppTheme( + application.getId(), + savedTheme.getId(), + null, + applicationPermission.getEditPermission())) + .thenReturn(savedTheme); + } else { + return applicationRepository + .setAppTheme( + application.getId(), + savedTheme.getId(), + null, + applicationPermission.getEditPermission()) + .thenReturn(savedTheme); + } + }) + .flatMap(savedTheme -> + analyticsService.sendObjectEvent(AnalyticsEvents.APPLY, savedTheme)); + })); } @Override @@ -183,20 +200,18 @@ public Mono<String> getDefaultThemeId() { @Override public Mono<Theme> cloneThemeToApplication(String srcThemeId, Application destApplication) { - return repository.findById(srcThemeId, READ_THEMES) - .flatMap(theme -> { - if (theme.isSystemTheme()) { // it's a system theme, no need to copy - return Mono.just(theme); - } else { // it's a customized theme, create a copy and return the copy - theme.setId(null); // setting id to null so that save method will create a new instance - theme.setApplicationId(null); - theme.setWorkspaceId(null); - theme.setPolicies(policyGenerator.getAllChildPolicies( - destApplication.getPolicies(), Application.class, Theme.class - )); - return repository.save(theme); - } - }); + return repository.findById(srcThemeId, READ_THEMES).flatMap(theme -> { + if (theme.isSystemTheme()) { // it's a system theme, no need to copy + return Mono.just(theme); + } else { // it's a customized theme, create a copy and return the copy + theme.setId(null); // setting id to null so that save method will create a new instance + theme.setApplicationId(null); + theme.setWorkspaceId(null); + theme.setPolicies(policyGenerator.getAllChildPolicies( + destApplication.getPolicies(), Application.class, Theme.class)); + return repository.save(theme); + } + }); } /** @@ -208,30 +223,39 @@ public Mono<Theme> cloneThemeToApplication(String srcThemeId, Application destAp @Override public Mono<Theme> publishTheme(String applicationId) { // fetch application to make sure user has permission to manage this application - return applicationRepository.findById(applicationId, applicationPermission.getEditPermission()).flatMap(application -> { - Mono<Theme> editModeThemeMono; - if (!StringUtils.hasLength(application.getEditModeThemeId())) { // theme id is empty, use the default theme - editModeThemeMono = repository.getSystemThemeByName(Theme.LEGACY_THEME_NAME); - } else { // theme id is not empty, fetch it by id - editModeThemeMono = repository.findById(application.getEditModeThemeId(), READ_THEMES); - } + return applicationRepository + .findById(applicationId, applicationPermission.getEditPermission()) + .flatMap(application -> { + Mono<Theme> editModeThemeMono; + if (!StringUtils.hasLength( + application.getEditModeThemeId())) { // theme id is empty, use the default theme + editModeThemeMono = repository.getSystemThemeByName(Theme.LEGACY_THEME_NAME); + } else { // theme id is not empty, fetch it by id + editModeThemeMono = repository.findById(application.getEditModeThemeId(), READ_THEMES); + } - return editModeThemeMono.flatMap(editModeTheme -> { - if (editModeTheme.isSystemTheme()) { // system theme is set as edit mode theme - // Delete published mode theme if it was a copy of custom theme - return deletePublishedCustomizedThemeCopy(application.getPublishedModeThemeId()).then( - // Set the system theme id as edit and published mode theme id to application object - applicationRepository.setAppTheme( - applicationId, editModeTheme.getId(), editModeTheme.getId(), applicationPermission.getEditPermission() - ) - ).thenReturn(editModeTheme); - } else { // a customized theme is set as edit mode theme, copy that theme for published mode - return saveThemeForApplication( - application.getPublishedModeThemeId(), editModeTheme, application, ApplicationMode.PUBLISHED - ); - } - }); - }); + return editModeThemeMono.flatMap(editModeTheme -> { + if (editModeTheme.isSystemTheme()) { // system theme is set as edit mode theme + // Delete published mode theme if it was a copy of custom theme + return deletePublishedCustomizedThemeCopy(application.getPublishedModeThemeId()) + .then( + // Set the system theme id as edit and published mode theme id to + // application object + applicationRepository.setAppTheme( + applicationId, + editModeTheme.getId(), + editModeTheme.getId(), + applicationPermission.getEditPermission())) + .thenReturn(editModeTheme); + } else { // a customized theme is set as edit mode theme, copy that theme for published mode + return saveThemeForApplication( + application.getPublishedModeThemeId(), + editModeTheme, + application, + ApplicationMode.PUBLISHED); + } + }); + }); } /** @@ -245,8 +269,13 @@ public Mono<Theme> publishTheme(String applicationId) { * @param applicationMode In which mode this theme will be set * @return Updated or newly created theme Publisher */ - private Mono<Theme> saveThemeForApplication(String currentThemeId, Theme targetThemeResource, Application application, ApplicationMode applicationMode) { - return repository.findById(currentThemeId, READ_THEMES) + private Mono<Theme> saveThemeForApplication( + String currentThemeId, + Theme targetThemeResource, + Application application, + ApplicationMode applicationMode) { + return repository + .findById(currentThemeId, READ_THEMES) .flatMap(currentTheme -> { // update the attributes of entity as per the request DTO currentTheme.setConfig(targetThemeResource.getConfig()); @@ -267,25 +296,34 @@ private Mono<Theme> saveThemeForApplication(String currentThemeId, Theme targetT currentTheme.setId(null); // setting id to null will create a new theme currentTheme.setSystemTheme(false); currentTheme.setPolicies(policyGenerator.getAllChildPolicies( - application.getPolicies(), Application.class, Theme.class - )); - // Not setting the application id in the theme because only the named themes have an application id + application.getPolicies(), Application.class, Theme.class)); + // Not setting the application id in the theme because only the named themes have an application + // id newThemeCreated = true; } return repository.save(currentTheme).zipWith(Mono.just(newThemeCreated)); - }).flatMap(savedThemeTuple -> { + }) + .flatMap(savedThemeTuple -> { Theme theme = savedThemeTuple.getT1(); if (savedThemeTuple.getT2()) { // new theme created, update the application if (applicationMode == ApplicationMode.EDIT) { - return applicationRepository.setAppTheme( - application.getId(), theme.getId(), null, applicationPermission.getEditPermission() - ).then(analyticsService.sendUpdateEvent(theme)) + return applicationRepository + .setAppTheme( + application.getId(), + theme.getId(), + null, + applicationPermission.getEditPermission()) + .then(analyticsService.sendUpdateEvent(theme)) .then(analyticsService.sendUpdateEvent(application)) .thenReturn(theme); } else { - return applicationRepository.setAppTheme( - application.getId(), null, theme.getId(), applicationPermission.getEditPermission() - ).thenReturn(theme); + return applicationRepository + .setAppTheme( + application.getId(), + null, + theme.getId(), + applicationPermission.getEditPermission()) + .thenReturn(theme); } } else { return Mono.just(theme); // old theme overwritten, no need to update application @@ -296,17 +334,17 @@ private Mono<Theme> saveThemeForApplication(String currentThemeId, Theme targetT @Override public Mono<Theme> persistCurrentTheme(String applicationId, String branchName, Theme resource) { - return applicationService.findByBranchNameAndDefaultApplicationId(branchName, applicationId, applicationPermission.getEditPermission()) + return applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, applicationId, applicationPermission.getEditPermission()) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId)) - ) + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId))) .flatMap(application -> { String themeId = application.getEditModeThemeId(); if (!StringUtils.hasLength(themeId)) { // theme id is not present, raise error return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION)); } else { - return repository.findById(themeId, READ_THEMES) - .map(theme -> Tuples.of(theme, application)); + return repository.findById(themeId, READ_THEMES).map(theme -> Tuples.of(theme, application)); } }) .flatMap(themeAndApplicationTuple -> { @@ -318,8 +356,7 @@ public Mono<Theme> persistCurrentTheme(String applicationId, String branchName, theme.setApplicationId(application.getId()); theme.setWorkspaceId(application.getWorkspaceId()); theme.setPolicies(policyGenerator.getAllChildPolicies( - application.getPolicies(), Application.class, Theme.class - )); + application.getPolicies(), Application.class, Theme.class)); // need to remove it when FE adapts displayName everywhere if (StringUtils.hasLength(resource.getName())) { @@ -334,7 +371,8 @@ public Mono<Theme> persistCurrentTheme(String applicationId, String branchName, theme.setDisplayName(theme.getName()); } return repository.save(theme); - }).flatMap(theme -> analyticsService.sendObjectEvent(AnalyticsEvents.FORK, theme)); + }) + .flatMap(theme -> analyticsService.sendObjectEvent(AnalyticsEvents.FORK, theme)); } /** @@ -361,16 +399,19 @@ private Mono<Theme> deletePublishedCustomizedThemeCopy(String themeId) { @Override public Mono<Theme> archiveById(String themeId) { - return repository.findById(themeId, MANAGE_THEMES) + return repository + .findById(themeId, MANAGE_THEMES) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, FieldName.THEME)) - ).flatMap(theme -> { - if (StringUtils.hasLength(theme.getApplicationId())) { // only persisted themes are allowed to be deleted + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, FieldName.THEME))) + .flatMap(theme -> { + if (StringUtils.hasLength( + theme.getApplicationId())) { // only persisted themes are allowed to be deleted return repository.archive(theme); } else { return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION)); } - }).flatMap(analyticsService::sendDeleteEvent); + }) + .flatMap(analyticsService::sendDeleteEvent); } @Override @@ -378,7 +419,6 @@ public Mono<Theme> getSystemTheme(String themeName) { return repository.getSystemThemeByName(themeName); } - @Override public Mono<Theme> getThemeById(String themeId, AclPermission permission) { return repository.findById(themeId, permission); @@ -391,10 +431,10 @@ public Mono<Theme> save(Theme theme) { @Override public Mono<Theme> updateName(String id, Theme themeDto) { - return repository.findById(id, MANAGE_THEMES) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.THEME, id)) - ).flatMap(theme -> { + return repository + .findById(id, MANAGE_THEMES) + .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.THEME, id))) + .flatMap(theme -> { if (StringUtils.hasLength(themeDto.getName())) { theme.setName(themeDto.getName()); } @@ -411,14 +451,14 @@ public Mono<Theme> getOrSaveTheme(Theme theme, Application destApplication) { if (theme == null) { // this application was exported without theme, assign the legacy theme to it return repository.getSystemThemeByName(Theme.LEGACY_THEME_NAME); // return the default theme } else if (theme.isSystemTheme()) { - return repository.getSystemThemeByName(theme.getName()) + return repository + .getSystemThemeByName(theme.getName()) .switchIfEmpty(repository.getSystemThemeByName(Theme.DEFAULT_THEME_NAME)); } else { // create a new theme Theme newTheme = new Theme(); - newTheme.setPolicies(policyGenerator.getAllChildPolicies( - destApplication.getPolicies(), Application.class, Theme.class - )); + newTheme.setPolicies( + policyGenerator.getAllChildPolicies(destApplication.getPolicies(), Application.class, Theme.class)); newTheme.setStylesheet(theme.getStylesheet()); newTheme.setProperties(theme.getProperties()); newTheme.setConfig(theme.getConfig()); @@ -438,8 +478,10 @@ public Mono<Theme> getOrSaveTheme(Theme theme, Application destApplication) { */ @Override public Mono<Application> archiveApplicationThemes(Application application) { - return repository.archiveByApplicationId(application.getId()) - .then(repository.archiveDraftThemesById(application.getEditModeThemeId(), application.getPublishedModeThemeId())) + return repository + .archiveByApplicationId(application.getId()) + .then(repository.archiveDraftThemesById( + application.getEditModeThemeId(), application.getPublishedModeThemeId())) .thenReturn(application); } @@ -457,16 +499,13 @@ public Mono<Application> archiveApplicationThemes(Application application) { * @param sourceJson ApplicationJSON from file or Git * @return Updated application that has editModeThemeId and publishedModeThemeId set */ - @Override public Mono<Application> importThemesToApplication(Application destinationApp, ApplicationJson sourceJson) { Mono<Theme> editModeTheme = updateExistingAppThemeFromJSON( - destinationApp, destinationApp.getEditModeThemeId(), sourceJson.getEditModeTheme() - ); + destinationApp, destinationApp.getEditModeThemeId(), sourceJson.getEditModeTheme()); Mono<Theme> publishedModeTheme = updateExistingAppThemeFromJSON( - destinationApp, destinationApp.getPublishedModeThemeId(), sourceJson.getPublishedTheme() - ); + destinationApp, destinationApp.getPublishedModeThemeId(), sourceJson.getPublishedTheme()); return Mono.zip(editModeTheme, publishedModeTheme).flatMap(importedThemesTuple -> { String editModeThemeId = importedThemesTuple.getT1().getId(); @@ -476,13 +515,18 @@ public Mono<Application> importThemesToApplication(Application destinationApp, A destinationApp.setPublishedModeThemeId(publishedModeThemeId); // this will update the theme id in DB // also returning the updated application object so that theme id are available to the next pipeline - return applicationService.setAppTheme( - destinationApp.getId(), editModeThemeId, publishedModeThemeId, applicationPermission.getEditPermission() - ).thenReturn(destinationApp); + return applicationService + .setAppTheme( + destinationApp.getId(), + editModeThemeId, + publishedModeThemeId, + applicationPermission.getEditPermission()) + .thenReturn(destinationApp); }); } - private Mono<Theme> updateExistingAppThemeFromJSON(Application destinationApp, String existingThemeId, Theme themeFromJson) { + private Mono<Theme> updateExistingAppThemeFromJSON( + Application destinationApp, String existingThemeId, Theme themeFromJson) { if (!StringUtils.hasLength(existingThemeId)) { return getOrSaveTheme(themeFromJson, destinationApp); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UsagePulseServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UsagePulseServiceCEImpl.java index 77f8e50bf93e..bdd9ae0f218b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UsagePulseServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UsagePulseServiceCEImpl.java @@ -59,41 +59,42 @@ public Mono<UsagePulse> createPulse(UsagePulseDTO usagePulseDTO) { Mono<String> tenantIdMono = tenantService.getDefaultTenantId(); Mono<String> instanceIdMono = configService.getInstanceId(); - return Mono.zip(currentUserMono, tenantIdMono, instanceIdMono) - .flatMap(tuple -> { - User user = tuple.getT1(); - String tenantId = tuple.getT2(); - String instanceId = tuple.getT3(); - usagePulse.setTenantId(tenantId); - usagePulse.setInstanceId(instanceId); - - if (user.isAnonymous()) { - if (null == usagePulseDTO.getAnonymousUserId()) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ANONYMOUS_USER_ID)); - } - usagePulse.setIsAnonymousUser(true); - usagePulse.setUser(usagePulseDTO.getAnonymousUserId()); - } else { - usagePulse.setIsAnonymousUser(false); - if (user.getHashedEmail() == null || StringUtils.isEmpty(user.getHashedEmail())) { - String hashedEmail = DigestUtils.sha256Hex(user.getEmail()); - usagePulse.setUser(hashedEmail); - // Hashed user email is stored to user for future mapping of user and pulses - User updateUser = new User(); - updateUser.setHashedEmail(hashedEmail); - - // Avoid updating the ACL fields - updateUser.setGroupIds(null); - updateUser.setPolicies(null); - updateUser.setPermissions(null); - - return userService.updateWithoutPermission(user.getId(), updateUser) - .then(save(usagePulse)); - } - usagePulse.setUser(user.getHashedEmail()); - } - return save(usagePulse); - }); + return Mono.zip(currentUserMono, tenantIdMono, instanceIdMono).flatMap(tuple -> { + User user = tuple.getT1(); + String tenantId = tuple.getT2(); + String instanceId = tuple.getT3(); + usagePulse.setTenantId(tenantId); + usagePulse.setInstanceId(instanceId); + + if (user.isAnonymous()) { + if (null == usagePulseDTO.getAnonymousUserId()) { + return Mono.error( + new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ANONYMOUS_USER_ID)); + } + usagePulse.setIsAnonymousUser(true); + usagePulse.setUser(usagePulseDTO.getAnonymousUserId()); + } else { + usagePulse.setIsAnonymousUser(false); + if (user.getHashedEmail() == null || StringUtils.isEmpty(user.getHashedEmail())) { + String hashedEmail = DigestUtils.sha256Hex(user.getEmail()); + usagePulse.setUser(hashedEmail); + // Hashed user email is stored to user for future mapping of user and pulses + User updateUser = new User(); + updateUser.setHashedEmail(hashedEmail); + + // Avoid updating the ACL fields + updateUser.setGroupIds(null); + updateUser.setPolicies(null); + updateUser.setPermissions(null); + + return userService + .updateWithoutPermission(user.getId(), updateUser) + .then(save(usagePulse)); + } + usagePulse.setUser(user.getHashedEmail()); + } + return save(usagePulse); + }); } /** @@ -105,5 +106,4 @@ public Mono<UsagePulse> createPulse(UsagePulseDTO usagePulseDTO) { public Mono<UsagePulse> save(UsagePulse usagePulse) { return repository.save(usagePulse); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserDataServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserDataServiceCEImpl.java index e45c68490fd3..fcc8a81501c9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserDataServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserDataServiceCEImpl.java @@ -42,8 +42,8 @@ import static com.appsmith.server.repositories.BaseAppsmithRepositoryImpl.fieldName; - -public class UserDataServiceCEImpl extends BaseService<UserDataRepository, UserData, String> implements UserDataServiceCE { +public class UserDataServiceCEImpl extends BaseService<UserDataRepository, UserData, String> + implements UserDataServiceCE { private final UserRepository userRepository; @@ -63,22 +63,22 @@ public class UserDataServiceCEImpl extends BaseService<UserDataRepository, UserD private static final int MAX_PROFILE_PHOTO_SIZE_KB = 1024; - @Autowired - public UserDataServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - UserDataRepository repository, - AnalyticsService analyticsService, - UserRepository userRepository, - SessionUserService sessionUserService, - AssetService assetService, - ReleaseNotesService releaseNotesService, - FeatureFlagService featureFlagService, - UserChangedHandler userChangedHandler, - ApplicationRepository applicationRepository, - TenantService tenantService) { + public UserDataServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + UserDataRepository repository, + AnalyticsService analyticsService, + UserRepository userRepository, + SessionUserService sessionUserService, + AssetService assetService, + ReleaseNotesService releaseNotesService, + FeatureFlagService featureFlagService, + UserChangedHandler userChangedHandler, + ApplicationRepository applicationRepository, + TenantService tenantService) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.userRepository = userRepository; this.releaseNotesService = releaseNotesService; @@ -106,25 +106,24 @@ public Mono<UserData> getForUser(String userId) { @Override public Mono<UserData> getForCurrentUser() { - return sessionUserService.getCurrentUser() - .map(User::getEmail) - .flatMap(this::getForUserEmail); + return sessionUserService.getCurrentUser().map(User::getEmail).flatMap(this::getForUserEmail); } @Override public Mono<UserData> getForUserEmail(String email) { - return tenantService.getDefaultTenantId() + return tenantService + .getDefaultTenantId() .flatMap(tenantId -> userRepository.findByEmailAndTenantId(email, tenantId)) .flatMap(this::getForUser); } @Override public Mono<UserData> updateForCurrentUser(UserData updates) { - return sessionUserService.getCurrentUser() - .flatMap(user -> - tenantService.getDefaultTenantId() - .flatMap(tenantId -> userRepository.findByEmailAndTenantId(user.getEmail(), tenantId)) - ) + return sessionUserService + .getCurrentUser() + .flatMap(user -> tenantService + .getDefaultTenantId() + .flatMap(tenantId -> userRepository.findByEmailAndTenantId(user.getEmail(), tenantId))) .flatMap(user -> updateForUser(user, updates)); } @@ -140,10 +139,12 @@ public Mono<UserData> updateForUser(User user, UserData updates) { @Override public Mono<UserData> update(String userId, UserData resource) { if (userId == null) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, fieldName(QUserData.userData.userId))); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_PARAMETER, fieldName(QUserData.userData.userId))); } - Query query = new Query(Criteria.where(fieldName(QUserData.userData.userId)).is(userId)); + Query query = + new Query(Criteria.where(fieldName(QUserData.userData.userId)).is(userId)); // In case the update is not used to update the policies, then set the policies to null to ensure that the // existing policies are not overwritten. @@ -157,8 +158,10 @@ public Mono<UserData> update(String userId, UserData resource) { Map<String, Object> updateMap = update.toMap(); updateMap.entrySet().stream().forEach(entry -> updateObj.set(entry.getKey(), entry.getValue())); - return mongoTemplate.updateFirst(query, updateObj, resource.getClass()) - .flatMap(updateResult -> updateResult.getMatchedCount() == 0 ? Mono.empty() : repository.findByUserId(userId)) + return mongoTemplate + .updateFirst(query, updateObj, resource.getClass()) + .flatMap(updateResult -> + updateResult.getMatchedCount() == 0 ? Mono.empty() : repository.findByUserId(userId)) .flatMap(analyticsService::sendUpdateEvent); } @@ -179,46 +182,43 @@ public Mono<User> setViewedCurrentVersionReleaseNotes(User user, String version) } return Mono.justOrEmpty(user.getId()) - .switchIfEmpty( - tenantService.getDefaultTenantId() - .flatMap(tenantId -> userRepository.findByEmailAndTenantId(user.getEmail(), tenantId)) - .flatMap(user1 -> Mono.justOrEmpty(user1.getId())) - ) + .switchIfEmpty(tenantService + .getDefaultTenantId() + .flatMap(tenantId -> userRepository.findByEmailAndTenantId(user.getEmail(), tenantId)) + .flatMap(user1 -> Mono.justOrEmpty(user1.getId()))) .flatMap(userId -> repository.saveReleaseNotesViewedVersion(userId, version)) .thenReturn(user); } @Override public Mono<User> ensureViewedCurrentVersionReleaseNotes(User user) { - return getForUser(user) - .flatMap(userData -> { - if (userData != null && userData.getReleaseNotesViewedVersion() == null) { - return setViewedCurrentVersionReleaseNotes(user); - } - return Mono.just(user); - }); + return getForUser(user).flatMap(userData -> { + if (userData != null && userData.getReleaseNotesViewedVersion() == null) { + return setViewedCurrentVersionReleaseNotes(user); + } + return Mono.just(user); + }); } @Override public Mono<UserData> saveProfilePhoto(Part filePart) { - final Mono<String> prevAssetIdMono = getForCurrentUser() - .map(userData -> ObjectUtils.defaultIfNull(userData.getProfilePhotoAssetId(), "")); + final Mono<String> prevAssetIdMono = + getForCurrentUser().map(userData -> ObjectUtils.defaultIfNull(userData.getProfilePhotoAssetId(), "")); final Mono<Asset> uploaderMono = assetService.upload(List.of(filePart), MAX_PROFILE_PHOTO_SIZE_KB, true); - return Mono.zip(prevAssetIdMono, uploaderMono) - .flatMap(tuple -> { - final String oldAssetId = tuple.getT1(); - final Asset uploadedAsset = tuple.getT2(); - final UserData updates = new UserData(); - updates.setProfilePhotoAssetId(uploadedAsset.getId()); - final Mono<UserData> updateMono = updateForCurrentUser(updates); - if (!StringUtils.hasLength(oldAssetId)) { - return updateMono; - } else { - return assetService.remove(oldAssetId).then(updateMono); - } - }); + return Mono.zip(prevAssetIdMono, uploaderMono).flatMap(tuple -> { + final String oldAssetId = tuple.getT1(); + final Asset uploadedAsset = tuple.getT2(); + final UserData updates = new UserData(); + updates.setProfilePhotoAssetId(uploadedAsset.getId()); + final Mono<UserData> updateMono = updateForCurrentUser(updates); + if (!StringUtils.hasLength(oldAssetId)) { + return updateMono; + } else { + return assetService.remove(oldAssetId).then(updateMono); + } + }); } @Override @@ -234,14 +234,12 @@ public Mono<Void> deleteProfilePhoto() { @Override public Mono<Void> makeProfilePhotoResponse(ServerWebExchange exchange, String email) { - return getForUserEmail(email) - .flatMap(userData -> makeProfilePhotoResponse(exchange, userData)); + return getForUserEmail(email).flatMap(userData -> makeProfilePhotoResponse(exchange, userData)); } @Override public Mono<Void> makeProfilePhotoResponse(ServerWebExchange exchange) { - return getForCurrentUser() - .flatMap(userData -> makeProfilePhotoResponse(exchange, userData)); + return getForCurrentUser().flatMap(userData -> makeProfilePhotoResponse(exchange, userData)); } private Mono<Void> makeProfilePhotoResponse(ServerWebExchange exchange, UserData userData) { @@ -257,23 +255,21 @@ private Mono<Void> makeProfilePhotoResponse(ServerWebExchange exchange, UserData */ @Override public Mono<UserData> updateLastUsedAppAndWorkspaceList(Application application) { - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .zipWhen(this::getForUser) .flatMap(tuple -> { final User user = tuple.getT1(); final UserData userData = tuple.getT2(); // set recently used workspace ids - userData.setRecentlyUsedWorkspaceIds( - addIdToRecentList(userData.getRecentlyUsedWorkspaceIds(), application.getWorkspaceId(), 10) - ); + userData.setRecentlyUsedWorkspaceIds(addIdToRecentList( + userData.getRecentlyUsedWorkspaceIds(), application.getWorkspaceId(), 10)); // set recently used application ids userData.setRecentlyUsedAppIds( - addIdToRecentList(userData.getRecentlyUsedAppIds(), application.getId(), 20) - ); + addIdToRecentList(userData.getRecentlyUsedAppIds(), application.getId(), 20)); return Mono.zip( analyticsService.identifyUser(user, userData, application.getWorkspaceId()), - repository.save(userData) - ); + repository.save(userData)); }) .map(Tuple2::getT2); } @@ -283,8 +279,7 @@ public Mono<UserData> addTemplateIdToLastUsedList(String templateId) { return this.getForCurrentUser().flatMap(userData -> { // set recently used template ids userData.setRecentlyUsedTemplateIds( - addIdToRecentList(userData.getRecentlyUsedTemplateIds(), templateId, 5) - ); + addIdToRecentList(userData.getRecentlyUsedTemplateIds(), templateId, 5)); return repository.save(userData); }); } @@ -319,9 +314,8 @@ public Mono<Map<String, Boolean>> getFeatureFlagsForCurrentUser() { */ @Override public Mono<UpdateResult> removeRecentWorkspaceAndApps(String userId, String workspaceId) { - return applicationRepository.getAllApplicationId(workspaceId).flatMap(appIdsList -> - repository.removeIdFromRecentlyUsedList(userId, workspaceId, appIdsList) - ); + return applicationRepository + .getAllApplicationId(workspaceId) + .flatMap(appIdsList -> repository.removeIdFromRecentlyUsedList(userId, workspaceId, appIdsList)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserIdentifierServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserIdentifierServiceCE.java index c93f35a86fe7..f5e58d6ccf10 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserIdentifierServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserIdentifierServiceCE.java @@ -7,5 +7,4 @@ public interface UserIdentifierServiceCE { String getUserIdentifier(User user); String hash(String value); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserIdentifierServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserIdentifierServiceCEImpl.java index d6cf2d712d06..fa20b2d1eada 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserIdentifierServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserIdentifierServiceCEImpl.java @@ -5,12 +5,12 @@ import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Autowired; -public class UserIdentifierServiceCEImpl implements UserIdentifierServiceCE{ +public class UserIdentifierServiceCEImpl implements UserIdentifierServiceCE { private final CommonConfig commonConfig; @Autowired - public UserIdentifierServiceCEImpl(CommonConfig commonConfig){ + public UserIdentifierServiceCEImpl(CommonConfig commonConfig) { this.commonConfig = commonConfig; } @@ -22,7 +22,7 @@ public UserIdentifierServiceCEImpl(CommonConfig commonConfig){ * @return */ @Override - public String getUserIdentifier(User user){ + public String getUserIdentifier(User user) { String userIdentifier = user.getUsername(); if (!commonConfig.isCloudHosting()) { userIdentifier = hash(user.getUsername()); @@ -34,6 +34,4 @@ public String getUserIdentifier(User user){ public String hash(String value) { return value == null ? "" : DigestUtils.sha256Hex(value); } - } - diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCE.java index 68fc61c84cf8..7082ced55a28 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCE.java @@ -33,8 +33,8 @@ public interface UserServiceCE extends CrudService<User, String> { Mono<User> userCreate(User user, boolean isAdminUser); - Mono<? extends User> createNewUserAndSendInviteEmail(String email, String originHeader, - Workspace workspace, User inviter, String role); + Mono<? extends User> createNewUserAndSendInviteEmail( + String email, String originHeader, Workspace workspace, User inviter, String role); Mono<User> updateCurrentUser(UserUpdateDTO updates, ServerWebExchange exchange); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java index e6dbd543aa99..ccbe591f23bb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java @@ -24,7 +24,6 @@ import com.appsmith.server.dtos.UserUpdateDTO; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.helpers.UserUtils; import com.appsmith.server.helpers.ValidationUtils; import com.appsmith.server.notifications.EmailSender; @@ -38,6 +37,7 @@ import com.appsmith.server.services.TenantService; import com.appsmith.server.services.UserDataService; import com.appsmith.server.services.WorkspaceService; +import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.solutions.UserChangedHandler; import jakarta.validation.Validator; import lombok.extern.slf4j.Slf4j; @@ -104,27 +104,28 @@ public class UserServiceCEImpl extends BaseService<UserRepository, User, String> private static final Pattern ALLOWED_ACCENTED_CHARACTERS_PATTERN = Pattern.compile("^[\\p{L} 0-9 .\'\\-]+$"); @Autowired - public UserServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - UserRepository repository, - WorkspaceService workspaceService, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - PasswordResetTokenRepository passwordResetTokenRepository, - PasswordEncoder passwordEncoder, - EmailSender emailSender, - ApplicationRepository applicationRepository, - PolicySolution policySolution, - CommonConfig commonConfig, - EmailConfig emailConfig, - UserChangedHandler userChangedHandler, - EncryptionService encryptionService, - UserDataService userDataService, - TenantService tenantService, - PermissionGroupService permissionGroupService, - UserUtils userUtils) { + public UserServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + UserRepository repository, + WorkspaceService workspaceService, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + PasswordResetTokenRepository passwordResetTokenRepository, + PasswordEncoder passwordEncoder, + EmailSender emailSender, + ApplicationRepository applicationRepository, + PolicySolution policySolution, + CommonConfig commonConfig, + EmailConfig emailConfig, + UserChangedHandler userChangedHandler, + EncryptionService encryptionService, + UserDataService userDataService, + TenantService tenantService, + PermissionGroupService permissionGroupService, + UserUtils userUtils) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.workspaceService = workspaceService; this.sessionUserService = sessionUserService; @@ -145,8 +146,7 @@ public UserServiceCEImpl(Scheduler scheduler, @Override public Mono<User> findByEmail(String email) { - return tenantService.getDefaultTenantId() - .flatMap(tenantId -> findByEmailAndTenantId(email, tenantId)); + return tenantService.getDefaultTenantId().flatMap(tenantId -> findByEmailAndTenantId(email, tenantId)); } @Override @@ -166,7 +166,8 @@ public Mono<User> switchCurrentWorkspace(String workspaceId) { if (workspaceId == null || workspaceId.isEmpty()) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "workspaceId")); } - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .flatMap(user -> repository.findByEmail(user.getUsername())) .flatMap(user -> { log.debug("Going to set workspaceId: {} for user: {}", workspaceId, user.getId()); @@ -177,7 +178,8 @@ public Mono<User> switchCurrentWorkspace(String workspaceId) { Set<String> workspaceIds = user.getWorkspaceIds(); if (workspaceIds == null || workspaceIds.isEmpty()) { - return Mono.error(new AppsmithException(AppsmithError.USER_DOESNT_BELONG_ANY_WORKSPACE, user.getId())); + return Mono.error( + new AppsmithException(AppsmithError.USER_DOESNT_BELONG_ANY_WORKSPACE, user.getId())); } Optional<String> maybeWorkspaceId = workspaceIds.stream() @@ -190,11 +192,11 @@ public Mono<User> switchCurrentWorkspace(String workspaceId) { } // Throw an exception if the workspaceId is not part of the user's workspaces - return Mono.error(new AppsmithException(AppsmithError.USER_DOESNT_BELONG_TO_WORKSPACE, user.getId(), workspaceId)); + return Mono.error(new AppsmithException( + AppsmithError.USER_DOESNT_BELONG_TO_WORKSPACE, user.getId(), workspaceId)); }); } - /** * This function creates a one-time token for resetting the user's password. This token is stored in the `passwordResetToken` * collection with an expiry time of 48 hours. The user must provide this one-time token when updating with the new password. @@ -209,7 +211,8 @@ public Mono<Boolean> forgotPasswordTokenGenerate(ResetUserPasswordDTO resetUserP return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.EMAIL)); } - if (resetUserPasswordDTO.getBaseUrl() == null || resetUserPasswordDTO.getBaseUrl().isBlank()) { + if (resetUserPasswordDTO.getBaseUrl() == null + || resetUserPasswordDTO.getBaseUrl().isBlank()) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ORIGIN)); } @@ -219,13 +222,16 @@ public Mono<Boolean> forgotPasswordTokenGenerate(ResetUserPasswordDTO resetUserP final String token = UUID.randomUUID().toString(); // Check if the user exists in our DB. If not, we will not send a password reset link to the user - return repository.findByEmail(email) + return repository + .findByEmail(email) .switchIfEmpty(repository.findByCaseInsensitiveEmail(email)) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.USER, email))) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.USER, email))) .flatMap(user -> { // an user found with the provided email address // Generate the password reset link for the user - return passwordResetTokenRepository.findByEmail(user.getEmail()) + return passwordResetTokenRepository + .findByEmail(user.getEmail()) .switchIfEmpty(Mono.defer(() -> { PasswordResetToken passwordResetToken = new PasswordResetToken(); passwordResetToken.setEmail(user.getEmail()); @@ -251,8 +257,7 @@ public Mono<Boolean> forgotPasswordTokenGenerate(ResetUserPasswordDTO resetUserP String resetUrl = String.format( FORGOT_PASSWORD_CLIENT_URL_FORMAT, resetUserPasswordDTO.getBaseUrl(), - encryptionService.encryptString(urlParams) - ); + encryptionService.encryptString(urlParams)); log.debug("Password reset url for email: {}: {}", passwordResetToken.getEmail(), resetUrl); @@ -260,9 +265,8 @@ public Mono<Boolean> forgotPasswordTokenGenerate(ResetUserPasswordDTO resetUserP params.put("resetUrl", resetUrl); return updateTenantLogoInParams(params, resetUserPasswordDTO.getBaseUrl()) - .flatMap(updatedParams -> - emailSender.sendMail(email, "Appsmith Password Reset", FORGOT_PASSWORD_EMAIL_TEMPLATE, updatedParams) - ); + .flatMap(updatedParams -> emailSender.sendMail( + email, "Appsmith Password Reset", FORGOT_PASSWORD_EMAIL_TEMPLATE, updatedParams)); }) .thenReturn(true); } @@ -336,7 +340,8 @@ public Mono<Boolean> resetPasswordAfterForgotPassword(String encryptedToken, Use .findByEmail(emailTokenDTO.getEmail()) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INVALID_PASSWORD_RESET))) .map(passwordResetToken -> { - boolean matches = this.passwordEncoder.matches(emailTokenDTO.getToken(), passwordResetToken.getTokenHash()); + boolean matches = + this.passwordEncoder.matches(emailTokenDTO.getToken(), passwordResetToken.getTokenHash()); if (!matches) { throw new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, FieldName.TOKEN); } else { @@ -345,35 +350,40 @@ public Mono<Boolean> resetPasswordAfterForgotPassword(String encryptedToken, Use }) .flatMap(emailAddress -> repository .findByEmail(emailAddress) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.USER, emailAddress))) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.USER, emailAddress))) .flatMap(userFromDb -> { if (!ValidationUtils.validateLoginPassword(user.getPassword())) { return Mono.error(new AppsmithException( - AppsmithError.INVALID_PASSWORD_LENGTH, LOGIN_PASSWORD_MIN_LENGTH, LOGIN_PASSWORD_MAX_LENGTH) - ); + AppsmithError.INVALID_PASSWORD_LENGTH, + LOGIN_PASSWORD_MIN_LENGTH, + LOGIN_PASSWORD_MAX_LENGTH)); } - //User has verified via the forgot password token verfication route. Allow the user to set new password. + // User has verified via the forgot password token verfication route. Allow the user to set + // new password. userFromDb.setPasswordResetInitiated(false); userFromDb.setPassword(passwordEncoder.encode(user.getPassword())); - // If the user has been invited but has not signed up yet, and is following the route of reset + // If the user has been invited but has not signed up yet, and is following the route of + // reset // password flow to set up their password, enable the user's account as well userFromDb.setIsEnabled(true); return passwordResetTokenRepository .findByEmail(userFromDb.getEmail()) .switchIfEmpty(Mono.error(new AppsmithException( - AppsmithError.NO_RESOURCE_FOUND, FieldName.TOKEN, emailTokenDTO.getToken() - ))) + AppsmithError.NO_RESOURCE_FOUND, + FieldName.TOKEN, + emailTokenDTO.getToken()))) .flatMap(passwordResetTokenRepository::delete) .then(repository.save(userFromDb)) .doOnSuccess(result -> // In a separate thread, we delete all other sessions of this user. - sessionUserService.logoutAllSessions(userFromDb.getEmail()) + sessionUserService + .logoutAllSessions(userFromDb.getEmail()) .subscribeOn(Schedulers.boundedElastic()) - .subscribe() - ) + .subscribe()) .thenReturn(true); })); } @@ -384,7 +394,6 @@ public Mono<User> create(User user) { return createUserAndSendEmail(user, null).map(UserSignupDTO::getUser); } - @Override public Mono<User> userCreate(User user, boolean isAdminUser) { // It is assumed here that the user's password has already been encoded. @@ -392,18 +401,16 @@ public Mono<User> userCreate(User user, boolean isAdminUser) { // convert the user email to lowercase user.setEmail(user.getEmail().toLowerCase()); - Mono<User> userWithTenantMono = Mono.just(user) - .flatMap(userBeforeSave -> { - if (userBeforeSave.getTenantId() == null) { - return tenantService.getDefaultTenantId() - .map(tenantId -> { - userBeforeSave.setTenantId(tenantId); - return userBeforeSave; - }); - } - // The tenant has been set already. No need to set the default tenant id. - return Mono.just(userBeforeSave); + Mono<User> userWithTenantMono = Mono.just(user).flatMap(userBeforeSave -> { + if (userBeforeSave.getTenantId() == null) { + return tenantService.getDefaultTenantId().map(tenantId -> { + userBeforeSave.setTenantId(tenantId); + return userBeforeSave; }); + } + // The tenant has been set already. No need to set the default tenant id. + return Mono.just(userBeforeSave); + }); // Save the new user return userWithTenantMono @@ -412,15 +419,13 @@ public Mono<User> userCreate(User user, boolean isAdminUser) { .flatMap(this::addUserPoliciesAndSaveToRepo) .flatMap(crudUser -> { if (isAdminUser) { - return userUtils.makeSuperUser(List.of(crudUser)) - .then(Mono.just(crudUser)); + return userUtils.makeSuperUser(List.of(crudUser)).then(Mono.just(crudUser)); } return Mono.just(crudUser); }) .then(Mono.zip( repository.findByEmail(user.getUsername()), - userDataService.getForUserEmail(user.getUsername()) - )) + userDataService.getForUserEmail(user.getUsername()))) .flatMap(tuple -> analyticsService.identifyUser(tuple.getT1(), tuple.getT2())); } @@ -430,30 +435,23 @@ protected Mono<User> addUserPolicies(User savedUser) { PermissionGroup userManagementPermissionGroup = new PermissionGroup(); userManagementPermissionGroup.setName(savedUser.getUsername() + FieldName.SUFFIX_USER_MANAGEMENT_ROLE); // Add CRUD permissions for user to the group - userManagementPermissionGroup.setPermissions( - Set.of( - new Permission(savedUser.getId(), MANAGE_USERS) - ) - ); + userManagementPermissionGroup.setPermissions(Set.of(new Permission(savedUser.getId(), MANAGE_USERS))); // Assign the permission group to the user userManagementPermissionGroup.setAssignedToUserIds(Set.of(savedUser.getId())); - return permissionGroupService.save(userManagementPermissionGroup) - .map(savedPermissionGroup -> { + return permissionGroupService.save(userManagementPermissionGroup).map(savedPermissionGroup -> { + Map<String, Policy> crudUserPolicies = + policySolution.generatePolicyFromPermissionGroupForObject(savedPermissionGroup, savedUser.getId()); - Map<String, Policy> crudUserPolicies = policySolution.generatePolicyFromPermissionGroupForObject(savedPermissionGroup, - savedUser.getId()); + User updatedWithPolicies = policySolution.addPoliciesToExistingObject(crudUserPolicies, savedUser); - User updatedWithPolicies = policySolution.addPoliciesToExistingObject(crudUserPolicies, savedUser); - - return updatedWithPolicies; - }); + return updatedWithPolicies; + }); } private Mono<User> addUserPoliciesAndSaveToRepo(User user) { - return addUserPolicies(user) - .flatMap(repository::save); + return addUserPolicies(user).flatMap(repository::save); } /** @@ -485,7 +483,8 @@ public Mono<UserSignupDTO> createUserAndSendEmail(User user, String originHeader } // If the user doesn't exist, create the user. If the user exists, return a duplicate key exception - return repository.findByCaseInsensitiveEmail(user.getUsername()) + return repository + .findByCaseInsensitiveEmail(user.getUsername()) .flatMap(savedUser -> { if (!savedUser.isEnabled()) { // First enable the user @@ -499,7 +498,8 @@ public Mono<UserSignupDTO> createUserAndSendEmail(User user, String originHeader return userSignupDTO; }); } - return Mono.error(new AppsmithException(AppsmithError.USER_ALREADY_EXISTS_SIGNUP, savedUser.getUsername())); + return Mono.error( + new AppsmithException(AppsmithError.USER_ALREADY_EXISTS_SIGNUP, savedUser.getUsername())); }) .switchIfEmpty(Mono.defer(() -> { return signupIfAllowed(user) @@ -507,26 +507,36 @@ public Mono<UserSignupDTO> createUserAndSendEmail(User user, String originHeader final UserSignupDTO userSignupDTO = new UserSignupDTO(); userSignupDTO.setUser(savedUser); - return workspaceService.createDefault(new Workspace(), savedUser) + return workspaceService + .createDefault(new Workspace(), savedUser) .elapsed() .map(pair -> { - log.debug("UserServiceCEImpl::Time taken to create default workspace: {} ms", pair.getT1()); + log.debug( + "UserServiceCEImpl::Time taken to create default workspace: {} ms", + pair.getT1()); return pair.getT2(); }) .map(workspace -> { - log.debug("Created blank default workspace for user '{}'.", savedUser.getEmail()); + log.debug( + "Created blank default workspace for user '{}'.", + savedUser.getEmail()); userSignupDTO.setDefaultWorkspaceId(workspace.getId()); return userSignupDTO; }) .onErrorResume(e -> { - log.debug("Error creating default workspace for user '{}'.", savedUser.getEmail(), e); + log.debug( + "Error creating default workspace for user '{}'.", + savedUser.getEmail(), + e); return Mono.just(userSignupDTO); }); }) - .flatMap(userSignupDTO -> findByEmail(userSignupDTO.getUser().getEmail()).map(user1 -> { - userSignupDTO.setUser(user1); - return userSignupDTO; - })) + .flatMap(userSignupDTO -> findByEmail( + userSignupDTO.getUser().getEmail()) + .map(user1 -> { + userSignupDTO.setUser(user1); + return userSignupDTO; + })) .elapsed() .map(pair -> { log.debug("UserServiceCEImpl::Time taken to find created user: {} ms", pair.getT1()); @@ -534,14 +544,12 @@ public Mono<UserSignupDTO> createUserAndSendEmail(User user, String originHeader }); })) .flatMap(userSignupDTO -> { - User savedUser = userSignupDTO.getUser(); - Mono<User> userMono = emailConfig.isWelcomeEmailEnabled() - ? sendWelcomeEmail(savedUser, finalOriginHeader) - : Mono.just(savedUser); - return userMono.thenReturn(userSignupDTO); - } - - ); + User savedUser = userSignupDTO.getUser(); + Mono<User> userMono = emailConfig.isWelcomeEmailEnabled() + ? sendWelcomeEmail(savedUser, finalOriginHeader) + : Mono.just(savedUser); + return userMono.thenReturn(userSignupDTO); + }); } private Mono<User> signupIfAllowed(User user) { @@ -572,12 +580,10 @@ private Mono<User> signupIfAllowed(User user) { } // No special configurations found, allow signup for the new user. - return userCreate(user, isAdminUser) - .elapsed() - .map(pair -> { - log.debug("UserServiceCEImpl::Time taken for create user: {} ms", pair.getT1()); - return pair.getT2(); - }); + return userCreate(user, isAdminUser).elapsed().map(pair -> { + log.debug("UserServiceCEImpl::Time taken for create user: {} ms", pair.getT1()); + return pair.getT2(); + }); } public Mono<User> sendWelcomeEmail(User user, String originHeader) { @@ -586,10 +592,7 @@ public Mono<User> sendWelcomeEmail(User user, String originHeader) { return updateTenantLogoInParams(params, originHeader) .flatMap(updatedParams -> emailSender.sendMail( - user.getEmail(), - "Welcome to Appsmith", - WELCOME_USER_EMAIL_TEMPLATE, - updatedParams)) + user.getEmail(), "Welcome to Appsmith", WELCOME_USER_EMAIL_TEMPLATE, updatedParams)) .elapsed() .map(pair -> { log.debug("UserServiceCEImpl::Time taken to send email: {} ms", pair.getT1()); @@ -600,8 +603,7 @@ public Mono<User> sendWelcomeEmail(User user, String originHeader) { log.error( "Ignoring error: Unable to send welcome email to the user {}. Cause: ", user.getEmail(), - Exceptions.unwrap(error) - ); + Exceptions.unwrap(error)); return Mono.just(TRUE); }) .thenReturn(user); @@ -609,11 +611,11 @@ public Mono<User> sendWelcomeEmail(User user, String originHeader) { @Override public Mono<User> update(String id, User userUpdate) { - Mono<User> userFromRepository = repository.findById(id, MANAGE_USERS) + Mono<User> userFromRepository = repository + .findById(id, MANAGE_USERS) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.USER, id))); - return userFromRepository - .flatMap(existingUser -> this.update(existingUser, userUpdate)); + return userFromRepository.flatMap(existingUser -> this.update(existingUser, userUpdate)); } /** @@ -625,11 +627,11 @@ public Mono<User> update(String id, User userUpdate) { */ @Override public Mono<User> updateWithoutPermission(String id, User update) { - Mono<User> userFromRepository = repository.findById(id) + Mono<User> userFromRepository = repository + .findById(id) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.USER, id))); - return userFromRepository - .flatMap(existingUser -> this.update(existingUser, update)); + return userFromRepository.flatMap(existingUser -> this.update(existingUser, update)); } private Mono<User> update(User existingUser, User userUpdate) { @@ -640,13 +642,12 @@ private Mono<User> update(User existingUser, User userUpdate) { } AppsmithBeanUtils.copyNewFieldValuesIntoOldObject(userUpdate, existingUser); - return repository.save(existingUser) - .map(userChangedHandler::publish); + return repository.save(existingUser).map(userChangedHandler::publish); } @Override - public Mono<? extends User> createNewUserAndSendInviteEmail(String email, String originHeader, - Workspace workspace, User inviter, String role) { + public Mono<? extends User> createNewUserAndSendInviteEmail( + String email, String originHeader, Workspace workspace, User inviter, String role) { User newUser = new User(); newUser.setEmail(email.toLowerCase()); @@ -659,26 +660,24 @@ public Mono<? extends User> createNewUserAndSendInviteEmail(String email, String boolean isAdminUser = commonConfig.getAdminEmails().contains(email.toLowerCase()); - // Call user service's userCreate function so that the default workspace, etc are also created along with assigning basic permissions. - return userCreate(newUser, isAdminUser) - .flatMap(createdUser -> { - log.debug("Going to send email for invite user to {}", createdUser.getEmail()); - String inviteUrl = String.format( - INVITE_USER_CLIENT_URL_FORMAT, - originHeader, - URLEncoder.encode(createdUser.getEmail(), StandardCharsets.UTF_8) - ); - - // Email template parameters initialization below. - Map<String, String> params = getEmailParams(workspace, inviter, inviteUrl, true); - - // We have sent out the emails. Just send back the saved user. - return updateTenantLogoInParams(params, originHeader) - .flatMap(updatedParams -> - emailSender.sendMail(createdUser.getEmail(), "Invite for Appsmith", INVITE_USER_EMAIL_TEMPLATE, updatedParams) - ) - .thenReturn(createdUser); - }); + // Call user service's userCreate function so that the default workspace, etc are also created along with + // assigning basic permissions. + return userCreate(newUser, isAdminUser).flatMap(createdUser -> { + log.debug("Going to send email for invite user to {}", createdUser.getEmail()); + String inviteUrl = String.format( + INVITE_USER_CLIENT_URL_FORMAT, + originHeader, + URLEncoder.encode(createdUser.getEmail(), StandardCharsets.UTF_8)); + + // Email template parameters initialization below. + Map<String, String> params = getEmailParams(workspace, inviter, inviteUrl, true); + + // We have sent out the emails. Just send back the saved user. + return updateTenantLogoInParams(params, originHeader) + .flatMap(updatedParams -> emailSender.sendMail( + createdUser.getEmail(), "Invite for Appsmith", INVITE_USER_EMAIL_TEMPLATE, updatedParams)) + .thenReturn(createdUser); + }); } @Override @@ -689,9 +688,9 @@ public Flux<User> get(MultiValueMap<String, String> params) { private boolean validateName(String name) { /* - Regex allows for Accented characters and alphanumeric with some special characters dot (.), apostrophe ('), - hyphen (-) and spaces - */ + Regex allows for Accented characters and alphanumeric with some special characters dot (.), apostrophe ('), + hyphen (-) and spaces + */ return ALLOWED_ACCENTED_CHARACTERS_PATTERN.matcher(name).matches(); } @@ -710,19 +709,18 @@ public Mono<User> updateCurrentUser(final UserUpdateDTO allUpdates, ServerWebExc return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.NAME)); } updates.setName(inputName); - updatedUserMono = sessionUserService.getCurrentUser() - .flatMap(user -> - update(user.getEmail(), updates, fieldName(QUser.user.email)) - .then(exchange == null + updatedUserMono = sessionUserService + .getCurrentUser() + .flatMap(user -> update(user.getEmail(), updates, fieldName(QUser.user.email)) + .then( + exchange == null ? repository.findByEmail(user.getEmail()) - : sessionUserService.refreshCurrentUser(exchange)) - ) + : sessionUserService.refreshCurrentUser(exchange))) .map(userChangedHandler::publish) .cache(); monos.add(updatedUserMono.then()); } else { - updatedUserMono = sessionUserService.getCurrentUser() - .flatMap(user -> findByEmail(user.getEmail())); + updatedUserMono = sessionUserService.getCurrentUser().flatMap(user -> findByEmail(user.getEmail())); } if (allUpdates.hasUserDataUpdates()) { @@ -756,7 +754,9 @@ public Map<String, String> getEmailParams(Workspace workspace, User inviter, Str Map<String, String> params = new HashMap<>(); if (inviter != null) { - params.put("inviterFirstName", org.apache.commons.lang3.StringUtils.defaultIfEmpty(inviter.getName(), inviter.getEmail())); + params.put( + "inviterFirstName", + org.apache.commons.lang3.StringUtils.defaultIfEmpty(inviter.getName(), inviter.getEmail())); } if (workspace != null) { params.put("inviterWorkspaceName", workspace.getName()); @@ -781,18 +781,15 @@ public Mono<Boolean> isUsersEmpty() { @Override public Mono<UserProfileDTO> buildUserProfileDTO(User user) { - Mono<User> userFromDbMono = findByEmail(user.getEmail()) - .cache(); + Mono<User> userFromDbMono = findByEmail(user.getEmail()).cache(); - Mono<Boolean> isSuperUserMono = userFromDbMono - .flatMap(userUtils::isSuperUser); + Mono<Boolean> isSuperUserMono = userFromDbMono.flatMap(userUtils::isSuperUser); return Mono.zip( isUsersEmpty(), userFromDbMono, userDataService.getForCurrentUser().defaultIfEmpty(new UserData()), - isSuperUserMono - ) + isSuperUserMono) .map(tuple -> { final boolean isUsersEmpty = Boolean.TRUE.equals(tuple.getT1()); final User userFromDb = tuple.getT2(); @@ -813,7 +810,8 @@ public Mono<UserProfileDTO> buildUserProfileDTO(User user) { profile.setPhotoId(userData.getProfilePhotoAssetId()); profile.setEnableTelemetry(!commonConfig.isTelemetryDisabled()); // Intercom consent is defaulted to true on cloud hosting - profile.setIntercomConsentGiven(commonConfig.isCloudHosting() ? true : userData.isIntercomConsentGiven()); + profile.setIntercomConsentGiven( + commonConfig.isCloudHosting() ? true : userData.isIntercomConsentGiven()); profile.setSuperUser(isSuperUser); profile.setConfigurable(!StringUtils.isEmpty(commonConfig.getEnvFilePath())); @@ -841,4 +839,4 @@ public Flux<User> getAllByEmails(Set<String> emails, AclPermission permission) { public Mono<Map<String, String>> updateTenantLogoInParams(Map<String, String> params, String origin) { return Mono.just(params); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserWorkspaceServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserWorkspaceServiceCE.java index 71f315a31c24..a0c14fcedd8e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserWorkspaceServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserWorkspaceServiceCE.java @@ -14,7 +14,8 @@ public interface UserWorkspaceServiceCE { Mono<User> leaveWorkspace(String workspaceId); - Mono<MemberInfoDTO> updatePermissionGroupForMember(String workspaceId, UpdatePermissionGroupDTO changeUserGroupDTO, String originHeader); + Mono<MemberInfoDTO> updatePermissionGroupForMember( + String workspaceId, UpdatePermissionGroupDTO changeUserGroupDTO, String originHeader); Mono<List<MemberInfoDTO>> getWorkspaceMembers(String workspaceId); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserWorkspaceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserWorkspaceServiceCEImpl.java index c0b7e80d0691..fe358e0bdb86 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserWorkspaceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserWorkspaceServiceCEImpl.java @@ -11,7 +11,6 @@ import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.server.helpers.AppsmithComparators; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.notifications.EmailSender; import com.appsmith.server.repositories.UserDataRepository; import com.appsmith.server.repositories.UserRepository; @@ -21,6 +20,7 @@ import com.appsmith.server.services.TenantService; import com.appsmith.server.services.UserDataService; import com.appsmith.server.solutions.PermissionGroupPermission; +import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.solutions.WorkspacePermission; import com.mongodb.client.result.UpdateResult; import lombok.extern.slf4j.Slf4j; @@ -42,7 +42,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; - @Slf4j public class UserWorkspaceServiceCEImpl implements UserWorkspaceServiceCE { private final SessionUserService sessionUserService; @@ -58,17 +57,18 @@ public class UserWorkspaceServiceCEImpl implements UserWorkspaceServiceCE { private final PermissionGroupPermission permissionGroupPermission; @Autowired - public UserWorkspaceServiceCEImpl(SessionUserService sessionUserService, - WorkspaceRepository workspaceRepository, - UserRepository userRepository, - UserDataRepository userDataRepository, - PolicySolution policySolution, - EmailSender emailSender, - UserDataService userDataService, - PermissionGroupService permissionGroupService, - TenantService tenantService, - WorkspacePermission workspacePermission, - PermissionGroupPermission permissionGroupPermission) { + public UserWorkspaceServiceCEImpl( + SessionUserService sessionUserService, + WorkspaceRepository workspaceRepository, + UserRepository userRepository, + UserDataRepository userDataRepository, + PolicySolution policySolution, + EmailSender emailSender, + UserDataService userDataService, + PermissionGroupService permissionGroupService, + TenantService tenantService, + WorkspacePermission workspacePermission, + PermissionGroupPermission permissionGroupPermission) { this.sessionUserService = sessionUserService; this.workspaceRepository = workspaceRepository; this.userRepository = userRepository; @@ -85,8 +85,10 @@ public UserWorkspaceServiceCEImpl(SessionUserService sessionUserService, @Override public Mono<User> leaveWorkspace(String workspaceId) { // Read the workspace - Mono<Workspace> workspaceMono = workspaceRepository.findById(workspaceId, workspacePermission.getReadPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); + Mono<Workspace> workspaceMono = workspaceRepository + .findById(workspaceId, workspacePermission.getReadPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); Mono<User> userMono = sessionUserService.getCurrentUser().cache(); @@ -94,36 +96,38 @@ public Mono<User> leaveWorkspace(String workspaceId) { .flatMapMany(tuple -> { Workspace workspace = tuple.getT1(); User user = tuple.getT2(); - return permissionGroupService.getAllByAssignedToUserAndDefaultWorkspace(user, workspace, permissionGroupPermission.getUnAssignPermission()); + return permissionGroupService.getAllByAssignedToUserAndDefaultWorkspace( + user, workspace, permissionGroupPermission.getUnAssignPermission()); }) /* * The below switchIfEmpty will be invoked in 2 cases. * 1. Explicit Backend Invocation: The user actually didn't have access to the Workspace. * 2. User Interaction: User who is part of a UserGroup. */ - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Workspace is not assigned to the user."))) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Workspace is not assigned to the user."))) .single() .flatMap(permissionGroup -> { - if (permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR) && permissionGroup.getAssignedToUserIds().size() == 1) { + if (permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR) + && permissionGroup.getAssignedToUserIds().size() == 1) { return Mono.error(new AppsmithException(AppsmithError.REMOVE_LAST_WORKSPACE_ADMIN_ERROR)); } return Mono.just(permissionGroup); }) - // If we cannot find the groups, that means either user is not part of any default group or current user has no access to the group - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Change role of a member"))); + // If we cannot find the groups, that means either user is not part of any default group or current user + // has no access to the group + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Change role of a member"))); // the user is being removed from the workspace. Remove the workspace from recent workspace list of UserData - Mono<UpdateResult> updateUserDataMono = userMono - .flatMap(user -> userDataService - .removeRecentWorkspaceAndApps(user.getId(), workspaceId)); + Mono<UpdateResult> updateUserDataMono = + userMono.flatMap(user -> userDataService.removeRecentWorkspaceAndApps(user.getId(), workspaceId)); Mono<PermissionGroup> removeUserFromOldPermissionGroupMono = oldDefaultPermissionGroupsMono .zipWith(userMono) .flatMap(tuple -> permissionGroupService.unassignFromUser(tuple.getT1(), tuple.getT2())); - return removeUserFromOldPermissionGroupMono - .then(updateUserDataMono) - .then(userMono); + return removeUserFromOldPermissionGroupMono.then(updateUserDataMono).then(userMono); } /** @@ -137,29 +141,36 @@ public Mono<User> leaveWorkspace(String workspaceId) { */ @Transactional @Override - public Mono<MemberInfoDTO> updatePermissionGroupForMember(String workspaceId, UpdatePermissionGroupDTO changeUserGroupDTO, String originHeader) { + public Mono<MemberInfoDTO> updatePermissionGroupForMember( + String workspaceId, UpdatePermissionGroupDTO changeUserGroupDTO, String originHeader) { if (changeUserGroupDTO.getUsername() == null) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.USERNAME)); } // Read the workspace - Mono<Workspace> workspaceMono = workspaceRepository.findById(workspaceId, workspacePermission.getReadPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))) + Mono<Workspace> workspaceMono = workspaceRepository + .findById(workspaceId, workspacePermission.getReadPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))) .cache(); // Get the user - Mono<User> userMono = tenantService.getDefaultTenantId() + Mono<User> userMono = tenantService + .getDefaultTenantId() .flatMap(tenantId -> userRepository.findByEmailAndTenantId(changeUserGroupDTO.getUsername(), tenantId)) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.USER, changeUserGroupDTO.getUsername()))) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.USER, changeUserGroupDTO.getUsername()))) .cache(); Mono<PermissionGroup> oldDefaultPermissionGroupMono = Mono.zip(workspaceMono, userMono) .flatMapMany(tuple -> { Workspace workspace = tuple.getT1(); User user = tuple.getT2(); - return permissionGroupService.getAllByAssignedToUserAndDefaultWorkspace(user, workspace, permissionGroupPermission.getUnAssignPermission()); + return permissionGroupService.getAllByAssignedToUserAndDefaultWorkspace( + user, workspace, permissionGroupPermission.getUnAssignPermission()); }) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Change permissionGroup of a member"))) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Change permissionGroup of a member"))) .single() .flatMap(permissionGroup -> { if (this.isLastAdminRoleEntity(permissionGroup)) { @@ -176,46 +187,49 @@ public Mono<MemberInfoDTO> updatePermissionGroupForMember(String workspaceId, Up * The below operation is responsible for the first DB operation, if a user is removed from the workspace. */ // Unassigned old permission group from user - Mono<PermissionGroup> permissionGroupUnassignedMono = userMono - .zipWhen(user -> oldDefaultPermissionGroupMono) + Mono<PermissionGroup> permissionGroupUnassignedMono = userMono.zipWhen(user -> oldDefaultPermissionGroupMono) .flatMap(pair -> permissionGroupService.unAssignFromUserAndSendEvent(pair.getT2(), pair.getT1())); - // If new permission group id is not present, just unassign old permission group and return PermissionAndGroupDTO + // If new permission group id is not present, just unassign old permission group and return + // PermissionAndGroupDTO if (!StringUtils.hasText(changeUserGroupDTO.getNewPermissionGroupId())) { - return permissionGroupUnassignedMono.then(userMono) - .map(user -> MemberInfoDTO.builder().username(user.getUsername()).name(user.getName()).build()); + return permissionGroupUnassignedMono.then(userMono).map(user -> MemberInfoDTO.builder() + .username(user.getUsername()) + .name(user.getName()) + .build()); } // Get the new permission group - Mono<PermissionGroup> newDefaultPermissionGroupMono = permissionGroupService.getById(changeUserGroupDTO.getNewPermissionGroupId(), permissionGroupPermission.getAssignPermission()) - // If we cannot find the group, that means either newGroupId is not a default group or current user has no access to the group - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Change permissionGroup of a member"))); + Mono<PermissionGroup> newDefaultPermissionGroupMono = permissionGroupService + .getById(changeUserGroupDTO.getNewPermissionGroupId(), permissionGroupPermission.getAssignPermission()) + // If we cannot find the group, that means either newGroupId is not a default group or current user has + // no access to the group + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Change permissionGroup of a member"))); // Unassign old permission group, assign new permission group - Mono<PermissionGroup> changePermissionGroupsMono = newDefaultPermissionGroupMono - .flatMap(newPermissionGroup -> { - return permissionGroupUnassignedMono - .then(userMono) - .flatMap(user -> permissionGroupService.assignToUserAndSendEvent(newPermissionGroup, user)); - }); + Mono<PermissionGroup> changePermissionGroupsMono = newDefaultPermissionGroupMono.flatMap(newPermissionGroup -> { + return permissionGroupUnassignedMono + .then(userMono) + .flatMap(user -> permissionGroupService.assignToUserAndSendEvent(newPermissionGroup, user)); + }); /* * The below operation is responsible for the first DB operation, if workspace role is changed ƒor the user, * hence we need to make this operation sequential as well. */ - return userMono - .zipWhen(user -> changePermissionGroupsMono) - .map(pair -> { - User user = pair.getT1(); - PermissionGroup role = pair.getT2(); - PermissionGroupInfoDTO roleInfoDTO = new PermissionGroupInfoDTO(role.getId(), role.getName(), role.getDescription()); - roleInfoDTO.setEntityType(Workspace.class.getSimpleName()); - return MemberInfoDTO.builder() - .username(user.getUsername()) - .name(user.getName()) - .roles(List.of(roleInfoDTO)) - .build(); - }); + return userMono.zipWhen(user -> changePermissionGroupsMono).map(pair -> { + User user = pair.getT1(); + PermissionGroup role = pair.getT2(); + PermissionGroupInfoDTO roleInfoDTO = + new PermissionGroupInfoDTO(role.getId(), role.getName(), role.getDescription()); + roleInfoDTO.setEntityType(Workspace.class.getSimpleName()); + return MemberInfoDTO.builder() + .username(user.getUsername()) + .name(user.getName()) + .roles(List.of(roleInfoDTO)) + .build(); + }); } @Override @@ -238,41 +252,42 @@ public Mono<List<MemberInfoDTO>> getWorkspaceMembers(String workspaceId) { .cache(); // Create a map of User.id to User - Mono<Map<String, User>> userMapMono = userIdsMono - .flatMapMany(userRepository::findAllById) - .collectMap(User::getId); + Mono<Map<String, User>> userMapMono = + userIdsMono.flatMapMany(userRepository::findAllById).collectMap(User::getId); // Create a map of UserData.userUd to UserData Mono<Map<String, UserData>> userDataMapMono = userIdsMono // get the profile photos of the list of users - .flatMapMany(userIdsSet -> userDataRepository.findPhotoAssetsByUserIds(userIdsSet.stream().toList())) + .flatMapMany(userIdsSet -> userDataRepository.findPhotoAssetsByUserIds( + userIdsSet.stream().toList())) .collectMap(UserData::getUserId); // Update name and username in the list of UserAndGroupDTO - userAndPermissionGroupDTOsMono = Mono.zip(userAndPermissionGroupDTOsMono, userMapMono, userDataMapMono).map(tuple -> { - List<MemberInfoDTO> workspaceMemberInfoDTOList = tuple.getT1(); - Map<String, User> userMap = tuple.getT2(); - Map<String, UserData> userDataMap = tuple.getT3(); - workspaceMemberInfoDTOList.forEach(userAndPermissionGroupDTO -> { - User user = userMap.get(userAndPermissionGroupDTO.getUserId()); - UserData userData = userDataMap.get(userAndPermissionGroupDTO.getUserId()); - userAndPermissionGroupDTO.setName(Optional.ofNullable(user.getName()).orElse(user.computeFirstName())); - userAndPermissionGroupDTO.setUsername(user.getUsername()); - if (userData != null) { - userAndPermissionGroupDTO.setPhotoId(userData.getProfilePhotoAssetId()); - } - }); - return workspaceMemberInfoDTOList; - }); + userAndPermissionGroupDTOsMono = Mono.zip(userAndPermissionGroupDTOsMono, userMapMono, userDataMapMono) + .map(tuple -> { + List<MemberInfoDTO> workspaceMemberInfoDTOList = tuple.getT1(); + Map<String, User> userMap = tuple.getT2(); + Map<String, UserData> userDataMap = tuple.getT3(); + workspaceMemberInfoDTOList.forEach(userAndPermissionGroupDTO -> { + User user = userMap.get(userAndPermissionGroupDTO.getUserId()); + UserData userData = userDataMap.get(userAndPermissionGroupDTO.getUserId()); + userAndPermissionGroupDTO.setName( + Optional.ofNullable(user.getName()).orElse(user.computeFirstName())); + userAndPermissionGroupDTO.setUsername(user.getUsername()); + if (userData != null) { + userAndPermissionGroupDTO.setPhotoId(userData.getProfilePhotoAssetId()); + } + }); + return workspaceMemberInfoDTOList; + }); // Sort the members by permission group - //TODO get users sorted from DB and fill in three buckets - admin, developer and viewer - Mono<List<MemberInfoDTO>> sortedListMono = userAndPermissionGroupDTOsMono - .map(userAndPermissionGroupDTOS -> { - Collections.sort(userAndPermissionGroupDTOS, AppsmithComparators.workspaceMembersComparator()); + // TODO get users sorted from DB and fill in three buckets - admin, developer and viewer + Mono<List<MemberInfoDTO>> sortedListMono = userAndPermissionGroupDTOsMono.map(userAndPermissionGroupDTOS -> { + Collections.sort(userAndPermissionGroupDTOS, AppsmithComparators.workspaceMembersComparator()); - return userAndPermissionGroupDTOS; - }); + return userAndPermissionGroupDTOS; + }); return sortedListMono; } @@ -281,7 +296,8 @@ public Mono<List<MemberInfoDTO>> getWorkspaceMembers(String workspaceId) { public Mono<Map<String, List<MemberInfoDTO>>> getWorkspaceMembers(Set<String> workspaceIds) { // Get default permission groups - Flux<PermissionGroup> permissionGroupFlux = permissionGroupService.getByDefaultWorkspaces(workspaceIds, permissionGroupPermission.getMembersReadPermission()) + Flux<PermissionGroup> permissionGroupFlux = permissionGroupService + .getByDefaultWorkspaces(workspaceIds, permissionGroupPermission.getMembersReadPermission()) .cache(); Mono<Map<String, Collection<PermissionGroup>>> permissionGroupsByWorkspacesMono = permissionGroupFlux @@ -299,17 +315,16 @@ public Mono<Map<String, List<MemberInfoDTO>>> getWorkspaceMembers(Set<String> wo .collect(Collectors.toSet()) .cache(); - Mono<Map<String, User>> userMapMono = userIdsMono - .flatMapMany(userRepository::findAllById) - .collectMap(User::getId); + Mono<Map<String, User>> userMapMono = + userIdsMono.flatMapMany(userRepository::findAllById).collectMap(User::getId); // Create a map of UserData.userUd to UserData Mono<Map<String, UserData>> userDataMapMono = userIdsMono .flatMapMany(userDataRepository::findPhotoAssetsByUserIds) .collectMap(UserData::getUserId); - Flux<Map<String, Collection<PermissionGroup>>> permissionGroupsByWorkspaceFlux = permissionGroupsByWorkspacesMono - .repeat(); + Flux<Map<String, Collection<PermissionGroup>>> permissionGroupsByWorkspaceFlux = + permissionGroupsByWorkspacesMono.repeat(); Mono<Map<String, List<MemberInfoDTO>>> workspaceMembersMono = permissionGroupsByWorkspacesMono .flatMapMany(permissionGroupsByWorkspaces -> Flux.fromIterable(permissionGroupsByWorkspaces.keySet())) @@ -317,13 +332,13 @@ public Mono<Map<String, List<MemberInfoDTO>>> getWorkspaceMembers(Set<String> wo .flatMap(tuple -> { String workspaceId = tuple.getT1(); Map<String, Collection<PermissionGroup>> collectionMap = tuple.getT2(); - List<PermissionGroup> permissionGroups = collectionMap.get(workspaceId).stream().collect(Collectors.toList()); + List<PermissionGroup> permissionGroups = + collectionMap.get(workspaceId).stream().collect(Collectors.toList()); Mono<List<MemberInfoDTO>> userAndPermissionGroupDTOsMono = Mono.zip( Mono.just(mapPermissionGroupListToUserAndPermissionGroupDTOList(permissionGroups)), userMapMono, - userDataMapMono - ) + userDataMapMono) .map(tuple1 -> { List<MemberInfoDTO> workspaceMemberInfoDTOList = tuple1.getT1(); Map<String, User> userMap = tuple1.getT2(); @@ -331,7 +346,8 @@ public Mono<Map<String, List<MemberInfoDTO>>> getWorkspaceMembers(Set<String> wo workspaceMemberInfoDTOList.forEach(userAndPermissionGroupDTO -> { User user = userMap.get(userAndPermissionGroupDTO.getUserId()); UserData userData = userDataMap.get(userAndPermissionGroupDTO.getUserId()); - userAndPermissionGroupDTO.setName(Optional.ofNullable(user.getName()).orElse(user.computeFirstName())); + userAndPermissionGroupDTO.setName( + Optional.ofNullable(user.getName()).orElse(user.computeFirstName())); userAndPermissionGroupDTO.setUsername(user.getUsername()); if (userData != null) { userAndPermissionGroupDTO.setPhotoId(userData.getProfilePhotoAssetId()); @@ -347,30 +363,37 @@ public Mono<Map<String, List<MemberInfoDTO>>> getWorkspaceMembers(Set<String> wo return workspaceMembersMono; } - private List<MemberInfoDTO> mapPermissionGroupListToUserAndPermissionGroupDTOList(List<PermissionGroup> permissionGroupList) { + private List<MemberInfoDTO> mapPermissionGroupListToUserAndPermissionGroupDTOList( + List<PermissionGroup> permissionGroupList) { Set<String> userIds = new HashSet<>(); // Set of already collected users List<MemberInfoDTO> userAndGroupDTOList = new ArrayList<>(); permissionGroupList.forEach(permissionGroup -> { - PermissionGroupInfoDTO roleInfoDTO = new PermissionGroupInfoDTO(permissionGroup.getId(), permissionGroup.getName(), permissionGroup.getDescription()); + PermissionGroupInfoDTO roleInfoDTO = new PermissionGroupInfoDTO( + permissionGroup.getId(), permissionGroup.getName(), permissionGroup.getDescription()); roleInfoDTO.setEntityType(Workspace.class.getSimpleName()); - Stream.ofNullable(permissionGroup.getAssignedToUserIds()).flatMap(Collection::stream).filter(userId -> !userIds.contains(userId)).forEach(userId -> { - userAndGroupDTOList.add(MemberInfoDTO.builder() - .userId(userId) - .roles(List.of(roleInfoDTO)) - .build()); // collect user - userIds.add(userId); // update set of already collected users - }); + Stream.ofNullable(permissionGroup.getAssignedToUserIds()) + .flatMap(Collection::stream) + .filter(userId -> !userIds.contains(userId)) + .forEach(userId -> { + userAndGroupDTOList.add(MemberInfoDTO.builder() + .userId(userId) + .roles(List.of(roleInfoDTO)) + .build()); // collect user + userIds.add(userId); // update set of already collected users + }); }); return userAndGroupDTOList; } protected Flux<PermissionGroup> getPermissionGroupsForWorkspace(String workspaceId) { - Mono<Workspace> workspaceMono = workspaceRepository.findById(workspaceId, workspacePermission.getReadPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); + Mono<Workspace> workspaceMono = workspaceRepository + .findById(workspaceId, workspacePermission.getReadPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); // Get default permission groups - return workspaceMono - .flatMapMany(workspace -> permissionGroupService.getByDefaultWorkspace(workspace, permissionGroupPermission.getMembersReadPermission())); + return workspaceMono.flatMapMany(workspace -> permissionGroupService.getByDefaultWorkspace( + workspace, permissionGroupPermission.getMembersReadPermission())); } @Override @@ -378,4 +401,4 @@ public Boolean isLastAdminRoleEntity(PermissionGroup permissionGroup) { return permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR) && permissionGroup.getAssignedToUserIds().size() == 1; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/WorkspaceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/WorkspaceServiceCEImpl.java index a8309904ae24..1706ac4403c0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/WorkspaceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/WorkspaceServiceCEImpl.java @@ -17,7 +17,6 @@ import com.appsmith.server.dtos.WorkspacePluginStatus; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.helpers.TextUtils; import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.AssetRepository; @@ -29,6 +28,7 @@ import com.appsmith.server.services.PermissionGroupService; import com.appsmith.server.services.SessionUserService; import com.appsmith.server.solutions.PermissionGroupPermission; +import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.solutions.WorkspacePermission; import com.mongodb.DBObject; import jakarta.validation.Validator; @@ -88,24 +88,24 @@ public class WorkspaceServiceCEImpl extends BaseService<WorkspaceRepository, Wor private final WorkspacePermission workspacePermission; private final PermissionGroupPermission permissionGroupPermission; - @Autowired - public WorkspaceServiceCEImpl(Scheduler scheduler, - Validator validator, - MongoConverter mongoConverter, - ReactiveMongoTemplate reactiveMongoTemplate, - WorkspaceRepository repository, - AnalyticsService analyticsService, - PluginRepository pluginRepository, - SessionUserService sessionUserService, - AssetRepository assetRepository, - AssetService assetService, - ApplicationRepository applicationRepository, - PermissionGroupService permissionGroupService, - PolicySolution policySolution, - ModelMapper modelMapper, - WorkspacePermission workspacePermission, - PermissionGroupPermission permissionGroupPermission) { + public WorkspaceServiceCEImpl( + Scheduler scheduler, + Validator validator, + MongoConverter mongoConverter, + ReactiveMongoTemplate reactiveMongoTemplate, + WorkspaceRepository repository, + AnalyticsService analyticsService, + PluginRepository pluginRepository, + SessionUserService sessionUserService, + AssetRepository assetRepository, + AssetService assetService, + ApplicationRepository applicationRepository, + PermissionGroupService permissionGroupService, + PolicySolution policySolution, + ModelMapper modelMapper, + WorkspacePermission workspacePermission, + PermissionGroupPermission permissionGroupPermission) { super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService); this.pluginRepository = pluginRepository; @@ -122,15 +122,14 @@ public WorkspaceServiceCEImpl(Scheduler scheduler, @Override public Flux<Workspace> get(MultiValueMap<String, String> params) { - return sessionUserService.getCurrentUser() - .flatMapMany(user -> { - Set<String> workspaceIds = user.getWorkspaceIds(); - if (workspaceIds == null || workspaceIds.isEmpty()) { - log.error("No workspace set for user: {}. Returning empty list of workspaces", user.getEmail()); - return Flux.empty(); - } - return repository.findAllById(workspaceIds); - }); + return sessionUserService.getCurrentUser().flatMapMany(user -> { + Set<String> workspaceIds = user.getWorkspaceIds(); + if (workspaceIds == null || workspaceIds.isEmpty()) { + log.error("No workspace set for user: {}. Returning empty list of workspaces", user.getEmail()); + return Flux.empty(); + } + return repository.findAllById(workspaceIds); + }); } /** @@ -177,16 +176,18 @@ public Mono<Workspace> create(Workspace workspace, User user, Boolean isDefault) return createWorkspaceAllowedMono .flatMap(isCreateWorkspaceAllowed -> { if (!isCreateWorkspaceAllowed) { - return Mono.error(new AppsmithException(AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Create workspace")); + return Mono.error( + new AppsmithException(AppsmithError.ACTION_IS_NOT_AUTHORIZED, "Create workspace")); } return validateObject(workspace); }) // Install all the default plugins when the org is created /* TODO: This is a hack. We should ideally use the pluginService.installPlugin() function. - Not using it right now because of circular dependency b/w workspaceService and pluginService - Also, since all our deployments are single node, this logic will still work - */ - .flatMap(org -> pluginRepository.findByDefaultInstall(true) + Not using it right now because of circular dependency b/w workspaceService and pluginService + Also, since all our deployments are single node, this logic will still work + */ + .flatMap(org -> pluginRepository + .findByDefaultInstall(true) .map(obj -> new WorkspacePlugin(obj.getId(), WorkspacePluginStatus.FREE)) .collect(Collectors.toSet()) .map(pluginList -> { @@ -219,14 +220,14 @@ protected Mono<Workspace> createWorkspaceDependents(Workspace createdWorkspace) return Mono.just(createdWorkspace); } - protected Mono<Workspace> addPoliciesAndSaveWorkspace(Set<PermissionGroup> permissionGroups, Workspace createdWorkspace) { + protected Mono<Workspace> addPoliciesAndSaveWorkspace( + Set<PermissionGroup> permissionGroups, Workspace createdWorkspace) { createdWorkspace.setDefaultPermissionGroups( - permissionGroups.stream() - .map(PermissionGroup::getId) - .collect(Collectors.toSet())); + permissionGroups.stream().map(PermissionGroup::getId).collect(Collectors.toSet())); // Apply the permissions to the workspace for (PermissionGroup permissionGroup : permissionGroups) { - Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject(permissionGroup, createdWorkspace.getId()); + Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject( + permissionGroup, createdWorkspace.getId()); createdWorkspace = policySolution.addPoliciesToExistingObject(policyMap, createdWorkspace); } return repository.save(createdWorkspace); @@ -255,7 +256,6 @@ private String generateNewDefaultName(String oldName, String workspaceName) { return oldName; } - private Mono<Set<PermissionGroup>> generateDefaultPermissionGroupsWithoutPermissions(Workspace workspace) { String workspaceName = workspace.getName(); String workspaceId = workspace.getId(); @@ -291,22 +291,23 @@ private Mono<Set<PermissionGroup>> generateDefaultPermissionGroupsWithoutPermiss .collect(Collectors.toSet()); } - Mono<Set<PermissionGroup>> generatePermissionsForDefaultPermissionGroups(Set<PermissionGroup> permissionGroups, - Workspace workspace, User user) { + Mono<Set<PermissionGroup>> generatePermissionsForDefaultPermissionGroups( + Set<PermissionGroup> permissionGroups, Workspace workspace, User user) { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); // Administrator permissions - Set<Permission> workspacePermissions = AppsmithRole.ORGANIZATION_ADMIN - .getPermissions() - .stream() + Set<Permission> workspacePermissions = AppsmithRole.ORGANIZATION_ADMIN.getPermissions().stream() .filter(aclPermission -> aclPermission.getEntity().equals(Workspace.class)) .map(aclPermission -> new Permission(workspace.getId(), aclPermission)) .collect(Collectors.toSet()); @@ -316,13 +317,14 @@ Mono<Set<PermissionGroup>> generatePermissionsForDefaultPermissionGroups(Set<Per .collect(Collectors.toSet()); // All the default permission groups should be readable by all the members of the workspace Set<Permission> readPermissionGroupPermissions = permissionGroups.stream() - .map(permissionGroup -> new Permission(permissionGroup.getId(), AclPermission.READ_PERMISSION_GROUP_MEMBERS)) + .map(permissionGroup -> + new Permission(permissionGroup.getId(), AclPermission.READ_PERMISSION_GROUP_MEMBERS)) .collect(Collectors.toSet()); Set<Permission> unassignPermissionGroupPermissions = permissionGroups.stream() - .map(permissionGroup -> new Permission(permissionGroup.getId(), AclPermission.UNASSIGN_PERMISSION_GROUPS)) + .map(permissionGroup -> + new Permission(permissionGroup.getId(), AclPermission.UNASSIGN_PERMISSION_GROUPS)) .collect(Collectors.toSet()); - Set<Permission> permissions = collateAllPermissions( workspacePermissions, assignPermissionGroupPermissions, @@ -334,9 +336,7 @@ Mono<Set<PermissionGroup>> generatePermissionsForDefaultPermissionGroups(Set<Per adminPermissionGroup.setAssignedToUserIds(Set.of(user.getId())); // Developer Permissions - workspacePermissions = AppsmithRole.ORGANIZATION_DEVELOPER - .getPermissions() - .stream() + workspacePermissions = AppsmithRole.ORGANIZATION_DEVELOPER.getPermissions().stream() .filter(aclPermission -> aclPermission.getEntity().equals(Workspace.class)) .map(aclPermission -> new Permission(workspace.getId(), aclPermission)) .collect(Collectors.toSet()); @@ -344,15 +344,12 @@ Mono<Set<PermissionGroup>> generatePermissionsForDefaultPermissionGroups(Set<Per assignPermissionGroupPermissions = Set.of(developerPermissionGroup, viewerPermissionGroup).stream() .map(permissionGroup -> new Permission(permissionGroup.getId(), ASSIGN_PERMISSION_GROUPS)) .collect(Collectors.toSet()); - permissions = collateAllPermissions(workspacePermissions, - assignPermissionGroupPermissions, - readPermissionGroupPermissions); + permissions = collateAllPermissions( + workspacePermissions, assignPermissionGroupPermissions, readPermissionGroupPermissions); developerPermissionGroup.setPermissions(permissions); // App Viewer Permissions - workspacePermissions = AppsmithRole.ORGANIZATION_VIEWER - .getPermissions() - .stream() + workspacePermissions = AppsmithRole.ORGANIZATION_VIEWER.getPermissions().stream() .filter(aclPermission -> aclPermission.getEntity().equals(Workspace.class)) .map(aclPermission -> new Permission(workspace.getId(), aclPermission)) .collect(Collectors.toSet()); @@ -361,9 +358,8 @@ Mono<Set<PermissionGroup>> generatePermissionsForDefaultPermissionGroups(Set<Per .map(permissionGroup -> new Permission(permissionGroup.getId(), ASSIGN_PERMISSION_GROUPS)) .collect(Collectors.toSet()); - permissions = collateAllPermissions(workspacePermissions, - assignPermissionGroupPermissions, - readPermissionGroupPermissions); + permissions = collateAllPermissions( + workspacePermissions, assignPermissionGroupPermissions, readPermissionGroupPermissions); viewerPermissionGroup.setPermissions(permissions); Mono<Set<PermissionGroup>> savedPermissionGroupsMono = Flux.fromIterable(permissionGroups) @@ -373,7 +369,8 @@ Mono<Set<PermissionGroup>> generatePermissionsForDefaultPermissionGroups(Set<Per // Apply the permissions to the permission groups for (PermissionGroup permissionGroup : savedPermissionGroups) { for (PermissionGroup nestedPermissionGroup : savedPermissionGroups) { - Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject(permissionGroup, nestedPermissionGroup.getId()); + Map<String, Policy> policyMap = policySolution.generatePolicyFromPermissionGroupForObject( + permissionGroup, nestedPermissionGroup.getId()); policySolution.addPoliciesToExistingObject(policyMap, nestedPermissionGroup); } } @@ -383,15 +380,13 @@ Mono<Set<PermissionGroup>> generatePermissionsForDefaultPermissionGroups(Set<Per .flatMap(permissionGroup -> permissionGroupService.save(permissionGroup)) .collect(Collectors.toSet()); - // Also evict the cache entry for the user creating the workspace to ensure that the user cache has the latest permissions - Mono<Boolean> cleanPermissionGroupCacheForCurrentUser = - permissionGroupService.cleanPermissionGroupCacheForUsers(List.of(user.getId())) - .thenReturn(TRUE); + // Also evict the cache entry for the user creating the workspace to ensure that the user cache has the latest + // permissions + Mono<Boolean> cleanPermissionGroupCacheForCurrentUser = permissionGroupService + .cleanPermissionGroupCacheForUsers(List.of(user.getId())) + .thenReturn(TRUE); - return Mono.zip( - savedPermissionGroupsMono, - cleanPermissionGroupCacheForCurrentUser - ) + return Mono.zip(savedPermissionGroupsMono, cleanPermissionGroupCacheForCurrentUser) .map(tuple -> tuple.getT1()); } @@ -399,7 +394,8 @@ protected Mono<Set<PermissionGroup>> generateDefaultPermissionGroups(Workspace w return generateDefaultPermissionGroupsWithoutPermissions(workspace) // Generate the permissions per permission group - .flatMap(permissionGroups -> generatePermissionsForDefaultPermissionGroups(permissionGroups, workspace, user)); + .flatMap(permissionGroups -> + generatePermissionsForDefaultPermissionGroups(permissionGroups, workspace, user)); } /** @@ -410,8 +406,7 @@ protected Mono<Set<PermissionGroup>> generateDefaultPermissionGroups(Workspace w */ @Override public Mono<Workspace> create(Workspace workspace) { - return sessionUserService.getCurrentUser() - .flatMap(user -> create(workspace, user, Boolean.FALSE)); + return sessionUserService.getCurrentUser().flatMap(user -> create(workspace, user, Boolean.FALSE)); } @Override @@ -421,8 +416,10 @@ public Mono<Workspace> update(String id, Workspace resource) { // Ensure the resource has the same ID as from the parameter. resource.setId(id); - Mono<Workspace> findWorkspaceMono = repository.findById(id, workspacePermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, id))) + Mono<Workspace> findWorkspaceMono = repository + .findById(id, workspacePermission.getEditPermission()) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, id))) .cache(); // In case the update is not used to update the policies, then set the policies to null to ensure that the @@ -437,21 +434,21 @@ public Mono<Workspace> update(String id, Workspace resource) { if (StringUtils.hasLength(newWorkspaceName)) { // There's a change in the workspace name. resource.setSlug(TextUtils.makeSlug(newWorkspaceName)); - updateDefaultGroups_thenReturnWorkspaceMono = findWorkspaceMono - .flatMap(workspace -> { - Set<String> defaultPermissionGroupsIds = workspace.getDefaultPermissionGroups(); + updateDefaultGroups_thenReturnWorkspaceMono = findWorkspaceMono.flatMap(workspace -> { + Set<String> defaultPermissionGroupsIds = workspace.getDefaultPermissionGroups(); - Flux<PermissionGroup> defaultPermissionGroupsFlux = permissionGroupService.findAllByIds(defaultPermissionGroupsIds); + Flux<PermissionGroup> defaultPermissionGroupsFlux = + permissionGroupService.findAllByIds(defaultPermissionGroupsIds); - Flux<PermissionGroup> updatedPermissionGroupFlux = defaultPermissionGroupsFlux - .flatMap(permissionGroup -> { - permissionGroup.setName(generateNewDefaultName(permissionGroup.getName(), newWorkspaceName)); - return permissionGroupService.save(permissionGroup); - }); + Flux<PermissionGroup> updatedPermissionGroupFlux = + defaultPermissionGroupsFlux.flatMap(permissionGroup -> { + permissionGroup.setName( + generateNewDefaultName(permissionGroup.getName(), newWorkspaceName)); + return permissionGroupService.save(permissionGroup); + }); - return updatedPermissionGroupFlux - .then(Mono.just(workspace)); - }); + return updatedPermissionGroupFlux.then(Mono.just(workspace)); + }); } return updateDefaultGroups_thenReturnWorkspaceMono @@ -461,18 +458,20 @@ public Mono<Workspace> update(String id, Workspace resource) { }) .flatMap(this::validateObject) .then(Mono.defer(() -> { - Query query = new Query(Criteria.where(fieldName(QWorkspace.workspace.id)).is(id)); + Query query = new Query( + Criteria.where(fieldName(QWorkspace.workspace.id)).is(id)); DBObject update = getDbObject(resource); Update updateObj = new Update(); Map<String, Object> updateMap = update.toMap(); updateMap.forEach(updateObj::set); - return mongoTemplate.updateFirst(query, updateObj, resource.getClass()) + return mongoTemplate + .updateFirst(query, updateObj, resource.getClass()) .flatMap(updateResult -> { if (updateResult.getMatchedCount() == 0) { - return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, id)); + return Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, id)); } - return repository.findById(id) - .flatMap(analyticsService::sendUpdateEvent); + return repository.findById(id).flatMap(analyticsService::sendUpdateEvent); }); })); } @@ -522,14 +521,16 @@ public Mono<List<PermissionGroupInfoDTO>> getPermissionGroupsForWorkspace(String Mono<Workspace> workspaceMono = repository.findById(workspaceId, workspacePermission.getReadPermission()); // Get default permission groups - Flux<PermissionGroup> permissionGroupFlux = workspaceMono - .flatMapMany(workspace -> permissionGroupService.getByDefaultWorkspace(workspace, permissionGroupPermission.getAssignPermission())); + Flux<PermissionGroup> permissionGroupFlux = + workspaceMono.flatMapMany(workspace -> permissionGroupService.getByDefaultWorkspace( + workspace, permissionGroupPermission.getAssignPermission())); // Map to PermissionGroupInfoDTO - Flux<PermissionGroupInfoDTO> permissionGroupInfoFlux = permissionGroupFlux - .map(permissionGroup -> modelMapper.map(permissionGroup, PermissionGroupInfoDTO.class)); + Flux<PermissionGroupInfoDTO> permissionGroupInfoFlux = permissionGroupFlux.map( + permissionGroup -> modelMapper.map(permissionGroup, PermissionGroupInfoDTO.class)); - Mono<List<PermissionGroupInfoDTO>> permissionGroupInfoDTOListMono = permissionGroupInfoFlux.collectList() + Mono<List<PermissionGroupInfoDTO>> permissionGroupInfoDTOListMono = permissionGroupInfoFlux + .collectList() .map(list -> { PermissionGroupInfoDTO[] permissionGroupInfoDTOArray = new PermissionGroupInfoDTO[3]; @@ -559,11 +560,14 @@ public Mono<Workspace> uploadLogo(String workspaceId, Part filePart) { return Mono.error(new AppsmithException(AppsmithError.VALIDATION_FAILURE, "Please upload a valid image.")); } - final Mono<Workspace> findWorkspaceMono = repository.findById(workspaceId, workspacePermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); + final Mono<Workspace> findWorkspaceMono = repository + .findById(workspaceId, workspacePermission.getEditPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))); // We don't execute the upload Mono if we don't find the workspace. - final Mono<Asset> uploadAssetMono = assetService.upload(List.of(filePart), Constraint.WORKSPACE_LOGO_SIZE_KB, false); + final Mono<Asset> uploadAssetMono = + assetService.upload(List.of(filePart), Constraint.WORKSPACE_LOGO_SIZE_KB, false); return findWorkspaceMono .flatMap(workspace -> Mono.zip(Mono.just(workspace), uploadAssetMono)) @@ -573,14 +577,13 @@ public Mono<Workspace> uploadLogo(String workspaceId, Part filePart) { final String prevAssetId = workspace.getLogoAssetId(); workspace.setLogoAssetId(uploadedAsset.getId()); - return repository.save(workspace) - .flatMap(savedWorkspace -> { - if (StringUtils.isEmpty(prevAssetId)) { - return Mono.just(savedWorkspace); - } else { - return assetService.remove(prevAssetId).thenReturn(savedWorkspace); - } - }); + return repository.save(workspace).flatMap(savedWorkspace -> { + if (StringUtils.isEmpty(prevAssetId)) { + return Mono.just(savedWorkspace); + } else { + return assetService.remove(prevAssetId).thenReturn(savedWorkspace); + } + }); }); } @@ -588,15 +591,19 @@ public Mono<Workspace> uploadLogo(String workspaceId, Part filePart) { public Mono<Workspace> deleteLogo(String workspaceId) { return repository .findById(workspaceId, workspacePermission.getEditPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))) .flatMap(workspace -> { final String prevAssetId = workspace.getLogoAssetId(); if (prevAssetId == null) { - return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ASSET, prevAssetId)); + return Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ASSET, prevAssetId)); } workspace.setLogoAssetId(null); - return assetRepository.findById(prevAssetId) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ASSET, prevAssetId))) + return assetRepository + .findById(prevAssetId) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.ASSET, prevAssetId))) .flatMap(asset -> assetRepository.delete(asset).thenReturn(asset)) .flatMap(analyticsService::sendDeleteEvent) .then(repository.save(workspace)); @@ -613,16 +620,18 @@ public Mono<Workspace> archiveById(String workspaceId) { return applicationRepository.countByWorkspaceId(workspaceId).flatMap(appCount -> { if (appCount == 0) { // no application found under this workspace // fetching the workspace first to make sure user has permission to archive - return repository.findById(workspaceId, workspacePermission.getDeletePermission()) + return repository + .findById(workspaceId, workspacePermission.getDeletePermission()) .switchIfEmpty(Mono.error(new AppsmithException( - AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId - ))) + AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId))) .flatMap(workspace -> { // Delete permission groups associated with this workspace before deleting the workspace // Since we have already asserted that the user has the delete permission on the workspace, - // lets go ahead with the cleanup without permissions for the default permission groups (roles) - // since we can't leave the permission groups in a state where they are not associated with any workspace + // lets go ahead with the cleanup without permissions for the default permission groups + // (roles) + // since we can't leave the permission groups in a state where they are not associated with + // any workspace Set<String> defaultPermissionGroups = workspace.getDefaultPermissionGroups(); return Flux.fromIterable(defaultPermissionGroups) @@ -647,7 +656,8 @@ private void validateIncomingWorkspace(Workspace workspace) { if (StringUtils.hasLength(workspace.getEmail()) && !Pattern.matches(EMAIL_PATTERN, workspace.getEmail())) { throw new AppsmithException(AppsmithError.INVALID_PARAMETER, EMAIL); } - if (StringUtils.hasLength(workspace.getWebsite()) && !Pattern.matches(WEBSITE_PATTERN, workspace.getWebsite())) { + if (StringUtils.hasLength(workspace.getWebsite()) + && !Pattern.matches(WEBSITE_PATTERN, workspace.getWebsite())) { throw new AppsmithException(AppsmithError.INVALID_PARAMETER, WEBSITE); } } @@ -656,5 +666,4 @@ private void validateIncomingWorkspace(Workspace workspace) { public Flux<Workspace> getAll(AclPermission permission) { return repository.findAll(permission); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionExecutionSolution.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionExecutionSolution.java index 5dc0d4bf1a0a..785bd4c24522 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionExecutionSolution.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionExecutionSolution.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.ActionExecutionSolutionCE; -public interface ActionExecutionSolution extends ActionExecutionSolutionCE { -} +public interface ActionExecutionSolution extends ActionExecutionSolutionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionExecutionSolutionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionExecutionSolutionImpl.java index 98cebb46ab1c..4a8d6600f88c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionExecutionSolutionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionExecutionSolutionImpl.java @@ -19,26 +19,41 @@ @Service public class ActionExecutionSolutionImpl extends ActionExecutionSolutionCEImpl implements ActionExecutionSolution { - public ActionExecutionSolutionImpl(NewActionService newActionService, - ActionPermission actionPermission, - ObservationRegistry observationRegistry, - ObjectMapper objectMapper, - NewActionRepository repository, - DatasourceService datasourceService, - PluginService pluginService, - DatasourceContextService datasourceContextService, - PluginExecutorHelper pluginExecutorHelper, - NewPageService newPageService, - ApplicationService applicationService, - SessionUserService sessionUserService, - AuthenticationValidator authenticationValidator, - DatasourcePermission datasourcePermission, - AnalyticsService analyticsService, - DatasourceStorageService datasourceStorageService, - DatasourceStorageTransferSolution datasourceStorageTransferSolution) { - super(newActionService, actionPermission, observationRegistry, objectMapper, repository, datasourceService, - pluginService, datasourceContextService, pluginExecutorHelper, newPageService, applicationService, - sessionUserService, authenticationValidator, datasourcePermission, analyticsService, - datasourceStorageService, datasourceStorageTransferSolution); + public ActionExecutionSolutionImpl( + NewActionService newActionService, + ActionPermission actionPermission, + ObservationRegistry observationRegistry, + ObjectMapper objectMapper, + NewActionRepository repository, + DatasourceService datasourceService, + PluginService pluginService, + DatasourceContextService datasourceContextService, + PluginExecutorHelper pluginExecutorHelper, + NewPageService newPageService, + ApplicationService applicationService, + SessionUserService sessionUserService, + AuthenticationValidator authenticationValidator, + DatasourcePermission datasourcePermission, + AnalyticsService analyticsService, + DatasourceStorageService datasourceStorageService, + DatasourceStorageTransferSolution datasourceStorageTransferSolution) { + super( + newActionService, + actionPermission, + observationRegistry, + objectMapper, + repository, + datasourceService, + pluginService, + datasourceContextService, + pluginExecutorHelper, + newPageService, + applicationService, + sessionUserService, + authenticationValidator, + datasourcePermission, + analyticsService, + datasourceStorageService, + datasourceStorageTransferSolution); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionPermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionPermission.java index eda9b3ce9240..0f76c42d76a9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionPermission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionPermission.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.ActionPermissionCE; -public interface ActionPermission extends ActionPermissionCE, DomainPermission { -} +public interface ActionPermission extends ActionPermissionCE, DomainPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionPermissionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionPermissionImpl.java index aac01da72ef2..ef610602e929 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionPermissionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ActionPermissionImpl.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class ActionPermissionImpl extends ActionPermissionCEImpl implements ActionPermission { -} +public class ActionPermissionImpl extends ActionPermissionCEImpl implements ActionPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationFetcher.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationFetcher.java index be94946da081..d367cd25fc3f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationFetcher.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationFetcher.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.ApplicationFetcherCE; -public interface ApplicationFetcher extends ApplicationFetcherCE { - -} +public interface ApplicationFetcher extends ApplicationFetcherCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationFetcherImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationFetcherImpl.java index f3ca62d3d186..bc795e32a172 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationFetcherImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationFetcherImpl.java @@ -11,25 +11,35 @@ import com.appsmith.server.solutions.ce.ApplicationFetcherCEImpl; import org.springframework.stereotype.Component; - @Component public class ApplicationFetcherImpl extends ApplicationFetcherCEImpl implements ApplicationFetcher { - public ApplicationFetcherImpl(SessionUserService sessionUserService, - UserService userService, - UserDataService userDataService, - WorkspaceService workspaceService, - ApplicationRepository applicationRepository, - ReleaseNotesService releaseNotesService, - ResponseUtils responseUtils, - NewPageService newPageService, - UserWorkspaceService userWorkspaceService, - WorkspacePermission workspacePermission, - ApplicationPermission applicationPermission, - PagePermission pagePermission) { + public ApplicationFetcherImpl( + SessionUserService sessionUserService, + UserService userService, + UserDataService userDataService, + WorkspaceService workspaceService, + ApplicationRepository applicationRepository, + ReleaseNotesService releaseNotesService, + ResponseUtils responseUtils, + NewPageService newPageService, + UserWorkspaceService userWorkspaceService, + WorkspacePermission workspacePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission) { - super(sessionUserService, userService, userDataService, workspaceService, applicationRepository, - releaseNotesService, responseUtils, newPageService, userWorkspaceService, workspacePermission, - applicationPermission, pagePermission); + super( + sessionUserService, + userService, + userDataService, + workspaceService, + applicationRepository, + releaseNotesService, + responseUtils, + newPageService, + userWorkspaceService, + workspacePermission, + applicationPermission, + pagePermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationForkingService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationForkingService.java index ecf31737cf73..72523a73df7d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationForkingService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationForkingService.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.ApplicationForkingServiceCE; -public interface ApplicationForkingService extends ApplicationForkingServiceCE { - -} +public interface ApplicationForkingService extends ApplicationForkingServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationForkingServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationForkingServiceImpl.java index c90579f9ef29..a3ea0aa40e4b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationForkingServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationForkingServiceImpl.java @@ -11,17 +11,27 @@ @Service @Slf4j -public class ApplicationForkingServiceImpl extends ApplicationForkingServiceCEImpl implements ApplicationForkingService { - public ApplicationForkingServiceImpl(ApplicationService applicationService, - WorkspaceService workspaceService, - ForkExamplesWorkspace examplesWorkspaceCloner, - SessionUserService sessionUserService, - AnalyticsService analyticsService, - ResponseUtils responseUtils, - WorkspacePermission workspacePermission, - ApplicationPermission applicationPermission, - ImportExportApplicationService importExportApplicationService) { - super(applicationService, workspaceService, examplesWorkspaceCloner, sessionUserService, analyticsService, - responseUtils, workspacePermission, applicationPermission, importExportApplicationService); +public class ApplicationForkingServiceImpl extends ApplicationForkingServiceCEImpl + implements ApplicationForkingService { + public ApplicationForkingServiceImpl( + ApplicationService applicationService, + WorkspaceService workspaceService, + ForkExamplesWorkspace examplesWorkspaceCloner, + SessionUserService sessionUserService, + AnalyticsService analyticsService, + ResponseUtils responseUtils, + WorkspacePermission workspacePermission, + ApplicationPermission applicationPermission, + ImportExportApplicationService importExportApplicationService) { + super( + applicationService, + workspaceService, + examplesWorkspaceCloner, + sessionUserService, + analyticsService, + responseUtils, + workspacePermission, + applicationPermission, + importExportApplicationService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationPermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationPermission.java index 6f38f7ccadb6..a84f6f4d4ed5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationPermission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationPermission.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.ApplicationPermissionCE; -public interface ApplicationPermission extends ApplicationPermissionCE, DomainPermission { -} +public interface ApplicationPermission extends ApplicationPermissionCE, DomainPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationPermissionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationPermissionImpl.java index 62dbc6439aa1..3e06d8f78209 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationPermissionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ApplicationPermissionImpl.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class ApplicationPermissionImpl extends ApplicationPermissionCEImpl implements ApplicationPermission { -} +public class ApplicationPermissionImpl extends ApplicationPermissionCEImpl implements ApplicationPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/AuthenticationService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/AuthenticationService.java index 8e1d106104cd..bbb7e649e81e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/AuthenticationService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/AuthenticationService.java @@ -2,7 +2,4 @@ import com.appsmith.server.solutions.ce.AuthenticationServiceCE; - -public interface AuthenticationService extends AuthenticationServiceCE { - -} +public interface AuthenticationService extends AuthenticationServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/AuthenticationServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/AuthenticationServiceImpl.java index bf6fa0526e24..cad3dde70907 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/AuthenticationServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/AuthenticationServiceImpl.java @@ -6,7 +6,6 @@ import com.appsmith.server.services.ConfigService; import com.appsmith.server.services.DatasourceService; import com.appsmith.server.services.DatasourceStorageService; -import com.appsmith.server.services.FeatureFlagService; import com.appsmith.server.services.NewPageService; import com.appsmith.server.services.PluginService; import com.appsmith.server.solutions.ce.AuthenticationServiceCEImpl; @@ -16,18 +15,27 @@ @Service @Slf4j public class AuthenticationServiceImpl extends AuthenticationServiceCEImpl implements AuthenticationService { - public AuthenticationServiceImpl(DatasourceService datasourceService, - PluginService pluginService, - RedirectHelper redirectHelper, - NewPageService newPageService, - CloudServicesConfig cloudServicesConfig, - ConfigService configService, - DatasourcePermission datasourcePermission, - PagePermission pagePermission, - PluginExecutorHelper pluginExecutorHelper, - DatasourceStorageService datasourceStorageService) { - super(datasourceService, pluginService, redirectHelper, newPageService, cloudServicesConfig, - configService, datasourcePermission, pagePermission, pluginExecutorHelper, + public AuthenticationServiceImpl( + DatasourceService datasourceService, + PluginService pluginService, + RedirectHelper redirectHelper, + NewPageService newPageService, + CloudServicesConfig cloudServicesConfig, + ConfigService configService, + DatasourcePermission datasourcePermission, + PagePermission pagePermission, + PluginExecutorHelper pluginExecutorHelper, + DatasourceStorageService datasourceStorageService) { + super( + datasourceService, + pluginService, + redirectHelper, + newPageService, + cloudServicesConfig, + configService, + datasourcePermission, + pagePermission, + pluginExecutorHelper, datasourceStorageService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/CreateDBTablePageSolution.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/CreateDBTablePageSolution.java index e1e65a535c24..a4ffc04535cb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/CreateDBTablePageSolution.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/CreateDBTablePageSolution.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.CreateDBTablePageSolutionCE; -public interface CreateDBTablePageSolution extends CreateDBTablePageSolutionCE { - -} \ No newline at end of file +public interface CreateDBTablePageSolution extends CreateDBTablePageSolutionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/CreateDBTablePageSolutionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/CreateDBTablePageSolutionImpl.java index f5591c1ecf25..4441971142c6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/CreateDBTablePageSolutionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/CreateDBTablePageSolutionImpl.java @@ -17,26 +17,40 @@ @Service @Slf4j -public class CreateDBTablePageSolutionImpl extends CreateDBTablePageSolutionCEImpl implements CreateDBTablePageSolution { +public class CreateDBTablePageSolutionImpl extends CreateDBTablePageSolutionCEImpl + implements CreateDBTablePageSolution { - public CreateDBTablePageSolutionImpl(DatasourceService datasourceService, - DatasourceStorageService datasourceStorageService, - NewPageService newPageService, - LayoutActionService layoutActionService, - ApplicationPageService applicationPageService, - ApplicationService applicationService, - PluginService pluginService, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - ResponseUtils responseUtils, - PluginExecutorHelper pluginExecutorHelper, - DatasourcePermission datasourcePermission, - ApplicationPermission applicationPermission, - PagePermission pagePermission, - DatasourceStructureSolution datasourceStructureSolution) { - super(datasourceService, datasourceStorageService, newPageService, layoutActionService, - applicationPageService, applicationService, pluginService, analyticsService, - sessionUserService, responseUtils, pluginExecutorHelper, datasourcePermission, - applicationPermission, pagePermission, datasourceStructureSolution); + public CreateDBTablePageSolutionImpl( + DatasourceService datasourceService, + DatasourceStorageService datasourceStorageService, + NewPageService newPageService, + LayoutActionService layoutActionService, + ApplicationPageService applicationPageService, + ApplicationService applicationService, + PluginService pluginService, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + ResponseUtils responseUtils, + PluginExecutorHelper pluginExecutorHelper, + DatasourcePermission datasourcePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + DatasourceStructureSolution datasourceStructureSolution) { + super( + datasourceService, + datasourceStorageService, + newPageService, + layoutActionService, + applicationPageService, + applicationService, + pluginService, + analyticsService, + sessionUserService, + responseUtils, + pluginExecutorHelper, + datasourcePermission, + applicationPermission, + pagePermission, + datasourceStructureSolution); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourcePermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourcePermission.java index 7cb4baa4d621..e3184242680d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourcePermission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourcePermission.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.DatasourcePermissionCE; -public interface DatasourcePermission extends DatasourcePermissionCE, DomainPermission { -} +public interface DatasourcePermission extends DatasourcePermissionCE, DomainPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourcePermissionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourcePermissionImpl.java index 105c3791a068..68369d9a7fcb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourcePermissionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourcePermissionImpl.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class DatasourcePermissionImpl extends DatasourcePermissionCEImpl implements DatasourcePermission { -} +public class DatasourcePermissionImpl extends DatasourcePermissionCEImpl implements DatasourcePermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStorageTransferSolution.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStorageTransferSolution.java index c1787f003ce3..d5aefba83e2a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStorageTransferSolution.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStorageTransferSolution.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.DatasourceStorageTransferSolutionCE; -public interface DatasourceStorageTransferSolution extends DatasourceStorageTransferSolutionCE { -} +public interface DatasourceStorageTransferSolution extends DatasourceStorageTransferSolutionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStorageTransferSolutionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStorageTransferSolutionImpl.java index db1e7d8c905e..79e2e9ab863a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStorageTransferSolutionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStorageTransferSolutionImpl.java @@ -7,14 +7,14 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; - @Service @Slf4j public class DatasourceStorageTransferSolutionImpl extends DatasourceStorageTransferSolutionCEImpl implements DatasourceStorageTransferSolution { - public DatasourceStorageTransferSolutionImpl(DatasourceRepository datasourceRepository, - DatasourceStorageRepository datasourceStorageRepository, - WorkspaceService workspaceService) { + public DatasourceStorageTransferSolutionImpl( + DatasourceRepository datasourceRepository, + DatasourceStorageRepository datasourceStorageRepository, + WorkspaceService workspaceService) { super(datasourceRepository, datasourceStorageRepository, workspaceService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStructureSolution.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStructureSolution.java index fb5acaf14699..4b10ec42268c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStructureSolution.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStructureSolution.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.DatasourceStructureSolutionCE; -public interface DatasourceStructureSolution extends DatasourceStructureSolutionCE { - -} +public interface DatasourceStructureSolution extends DatasourceStructureSolutionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStructureSolutionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStructureSolutionImpl.java index 7bea3d9b8dba..5c2f063998c3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStructureSolutionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceStructureSolutionImpl.java @@ -13,17 +13,25 @@ @Component @Slf4j -public class DatasourceStructureSolutionImpl extends DatasourceStructureSolutionCEImpl implements DatasourceStructureSolution { - public DatasourceStructureSolutionImpl(DatasourceService datasourceService, - DatasourceStorageService datasourceStorageService, - PluginExecutorHelper pluginExecutorHelper, - PluginService pluginService, - DatasourceContextService datasourceContextService, - DatasourcePermission datasourcePermission, - DatasourceStructureService datasourceStructureService, - AnalyticsService analyticsService) { - super(datasourceService, datasourceStorageService, pluginExecutorHelper, pluginService, - datasourceContextService, datasourcePermission, - datasourceStructureService, analyticsService); +public class DatasourceStructureSolutionImpl extends DatasourceStructureSolutionCEImpl + implements DatasourceStructureSolution { + public DatasourceStructureSolutionImpl( + DatasourceService datasourceService, + DatasourceStorageService datasourceStorageService, + PluginExecutorHelper pluginExecutorHelper, + PluginService pluginService, + DatasourceContextService datasourceContextService, + DatasourcePermission datasourcePermission, + DatasourceStructureService datasourceStructureService, + AnalyticsService analyticsService) { + super( + datasourceService, + datasourceStorageService, + pluginExecutorHelper, + pluginService, + datasourceContextService, + datasourcePermission, + datasourceStructureService, + analyticsService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceTriggerSolution.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceTriggerSolution.java index 2cabaa28c989..8f6641fe3a3e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceTriggerSolution.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceTriggerSolution.java @@ -2,7 +2,4 @@ import com.appsmith.server.solutions.ce.DatasourceTriggerSolutionCE; - -public interface DatasourceTriggerSolution extends DatasourceTriggerSolutionCE { - -} +public interface DatasourceTriggerSolution extends DatasourceTriggerSolutionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceTriggerSolutionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceTriggerSolutionImpl.java index 703a70cd8f85..6220d9d9e974 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceTriggerSolutionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DatasourceTriggerSolutionImpl.java @@ -12,17 +12,26 @@ @Component @Slf4j -public class DatasourceTriggerSolutionImpl extends DatasourceTriggerSolutionCEImpl implements DatasourceTriggerSolution { +public class DatasourceTriggerSolutionImpl extends DatasourceTriggerSolutionCEImpl + implements DatasourceTriggerSolution { - public DatasourceTriggerSolutionImpl(DatasourceService datasourceService, - DatasourceStorageService datasourceStorageService, - PluginExecutorHelper pluginExecutorHelper, - PluginService pluginService, - DatasourceStructureSolution datasourceStructureSolution, - AuthenticationValidator authenticationValidator, - DatasourceContextService datasourceContextService, - DatasourcePermission datasourcePermission) { - super(datasourceService, datasourceStorageService, pluginExecutorHelper, pluginService, - datasourceStructureSolution, authenticationValidator, datasourceContextService, datasourcePermission); + public DatasourceTriggerSolutionImpl( + DatasourceService datasourceService, + DatasourceStorageService datasourceStorageService, + PluginExecutorHelper pluginExecutorHelper, + PluginService pluginService, + DatasourceStructureSolution datasourceStructureSolution, + AuthenticationValidator authenticationValidator, + DatasourceContextService datasourceContextService, + DatasourcePermission datasourcePermission) { + super( + datasourceService, + datasourceStorageService, + pluginExecutorHelper, + pluginService, + datasourceStructureSolution, + authenticationValidator, + datasourceContextService, + datasourcePermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DomainPermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DomainPermission.java index dcf3aa667416..98018c5c67ba 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DomainPermission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/DomainPermission.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.DomainPermissionCE; -public interface DomainPermission extends DomainPermissionCE { - -} +public interface DomainPermission extends DomainPermissionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EmailEventHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EmailEventHandler.java index 9bb2520f8122..d3be98868296 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EmailEventHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EmailEventHandler.java @@ -1,5 +1,3 @@ package com.appsmith.server.solutions; -public interface EmailEventHandler { - -} +public interface EmailEventHandler {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManager.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManager.java index a068499d91c3..b610650fb862 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManager.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManager.java @@ -2,7 +2,4 @@ import com.appsmith.server.solutions.ce.EnvManagerCE; - -public interface EnvManager extends EnvManagerCE { - -} +public interface EnvManager extends EnvManagerCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManagerImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManagerImpl.java index 1687b0df932b..d90b3f874be9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManagerImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManagerImpl.java @@ -23,24 +23,38 @@ @Slf4j public class EnvManagerImpl extends EnvManagerCEImpl implements EnvManager { - public EnvManagerImpl(SessionUserService sessionUserService, - UserService userService, - AnalyticsService analyticsService, - UserRepository userRepository, - EmailSender emailSender, - CommonConfig commonConfig, - EmailConfig emailConfig, - JavaMailSender javaMailSender, - GoogleRecaptchaConfig googleRecaptchaConfig, - FileUtils fileUtils, - PermissionGroupService permissionGroupService, - ConfigService configService, - UserUtils userUtils, - TenantService tenantService, - ObjectMapper objectMapper) { + public EnvManagerImpl( + SessionUserService sessionUserService, + UserService userService, + AnalyticsService analyticsService, + UserRepository userRepository, + EmailSender emailSender, + CommonConfig commonConfig, + EmailConfig emailConfig, + JavaMailSender javaMailSender, + GoogleRecaptchaConfig googleRecaptchaConfig, + FileUtils fileUtils, + PermissionGroupService permissionGroupService, + ConfigService configService, + UserUtils userUtils, + TenantService tenantService, + ObjectMapper objectMapper) { - super(sessionUserService, userService, analyticsService, userRepository, emailSender, commonConfig, emailConfig, - javaMailSender, googleRecaptchaConfig, fileUtils, permissionGroupService, configService, userUtils, - tenantService, objectMapper); + super( + sessionUserService, + userService, + analyticsService, + userRepository, + emailSender, + commonConfig, + emailConfig, + javaMailSender, + googleRecaptchaConfig, + fileUtils, + permissionGroupService, + configService, + userUtils, + tenantService, + objectMapper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ForkExamplesWorkspace.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ForkExamplesWorkspace.java index 06f50e5bb232..ee7d999f3e50 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ForkExamplesWorkspace.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ForkExamplesWorkspace.java @@ -2,7 +2,4 @@ import com.appsmith.server.solutions.ce.ForkExamplesWorkspaceCE; - -public interface ForkExamplesWorkspace extends ForkExamplesWorkspaceCE { - -} +public interface ForkExamplesWorkspace extends ForkExamplesWorkspaceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ForkExamplesWorkspaceServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ForkExamplesWorkspaceServiceImpl.java index a9daa174d9a4..d6abf2d303e8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ForkExamplesWorkspaceServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ForkExamplesWorkspaceServiceImpl.java @@ -21,28 +21,44 @@ @Slf4j @Component -public class ForkExamplesWorkspaceServiceImpl extends ForkExamplesWorkspaceServiceCEImpl implements ForkExamplesWorkspace { +public class ForkExamplesWorkspaceServiceImpl extends ForkExamplesWorkspaceServiceCEImpl + implements ForkExamplesWorkspace { - public ForkExamplesWorkspaceServiceImpl(WorkspaceService workspaceService, - WorkspaceRepository workspaceRepository, - DatasourceService datasourceService, - DatasourceStorageService datasourceStorageService, - DatasourceRepository datasourceRepository, - ConfigService configService, - SessionUserService sessionUserService, - UserService userService, - ApplicationService applicationService, - ApplicationPageService applicationPageService, - NewPageRepository newPageRepository, - NewActionService newActionService, - LayoutActionService layoutActionService, - ActionCollectionService actionCollectionService, - ThemeService themeService, - ApplicationPermission applicationPermission, - PagePermission pagePermission) { - super(workspaceService, workspaceRepository, datasourceService, datasourceStorageService, datasourceRepository, - configService, sessionUserService, userService, applicationService, applicationPageService, - newPageRepository, newActionService, layoutActionService, actionCollectionService, themeService, - applicationPermission, pagePermission); + public ForkExamplesWorkspaceServiceImpl( + WorkspaceService workspaceService, + WorkspaceRepository workspaceRepository, + DatasourceService datasourceService, + DatasourceStorageService datasourceStorageService, + DatasourceRepository datasourceRepository, + ConfigService configService, + SessionUserService sessionUserService, + UserService userService, + ApplicationService applicationService, + ApplicationPageService applicationPageService, + NewPageRepository newPageRepository, + NewActionService newActionService, + LayoutActionService layoutActionService, + ActionCollectionService actionCollectionService, + ThemeService themeService, + ApplicationPermission applicationPermission, + PagePermission pagePermission) { + super( + workspaceService, + workspaceRepository, + datasourceService, + datasourceStorageService, + datasourceRepository, + configService, + sessionUserService, + userService, + applicationService, + applicationPageService, + newPageRepository, + newActionService, + layoutActionService, + actionCollectionService, + themeService, + applicationPermission, + pagePermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationService.java index ef74c29030df..a245cb349323 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationService.java @@ -2,7 +2,4 @@ import com.appsmith.server.solutions.ce.ImportExportApplicationServiceCE; - -public interface ImportExportApplicationService extends ImportExportApplicationServiceCE { - -} +public interface ImportExportApplicationService extends ImportExportApplicationServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java index bf4d93fdb8d9..d6876bc044c4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java @@ -29,40 +29,63 @@ @Slf4j @Component @Primary -public class ImportExportApplicationServiceImpl extends ImportExportApplicationServiceCEImpl implements ImportExportApplicationService { +public class ImportExportApplicationServiceImpl extends ImportExportApplicationServiceCEImpl + implements ImportExportApplicationService { - public ImportExportApplicationServiceImpl(DatasourceService datasourceService, - SessionUserService sessionUserService, - NewActionRepository newActionRepository, - DatasourceRepository datasourceRepository, - PluginRepository pluginRepository, - WorkspaceService workspaceService, - ApplicationService applicationService, - NewPageService newPageService, - ApplicationPageService applicationPageService, - NewPageRepository newPageRepository, - NewActionService newActionService, - SequenceService sequenceService, - ActionCollectionRepository actionCollectionRepository, - ActionCollectionService actionCollectionService, - ThemeService themeService, - AnalyticsService analyticsService, - CustomJSLibService customJSLibService, - DatasourcePermission datasourcePermission, - WorkspacePermission workspacePermission, - ApplicationPermission applicationPermission, - PagePermission pagePermission, - ActionPermission actionPermission, - Gson gson, - TransactionalOperator transactionalOperator, - DatasourceStorageService datasourceStorageService, - PermissionGroupRepository permissionGroupRepository) { + public ImportExportApplicationServiceImpl( + DatasourceService datasourceService, + SessionUserService sessionUserService, + NewActionRepository newActionRepository, + DatasourceRepository datasourceRepository, + PluginRepository pluginRepository, + WorkspaceService workspaceService, + ApplicationService applicationService, + NewPageService newPageService, + ApplicationPageService applicationPageService, + NewPageRepository newPageRepository, + NewActionService newActionService, + SequenceService sequenceService, + ActionCollectionRepository actionCollectionRepository, + ActionCollectionService actionCollectionService, + ThemeService themeService, + AnalyticsService analyticsService, + CustomJSLibService customJSLibService, + DatasourcePermission datasourcePermission, + WorkspacePermission workspacePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission, + Gson gson, + TransactionalOperator transactionalOperator, + DatasourceStorageService datasourceStorageService, + PermissionGroupRepository permissionGroupRepository) { - super(datasourceService, sessionUserService, newActionRepository, datasourceRepository, pluginRepository, - workspaceService, applicationService, newPageService, applicationPageService, newPageRepository, - newActionService, sequenceService, actionCollectionRepository, actionCollectionService, themeService, - analyticsService, customJSLibService, datasourcePermission, workspacePermission, applicationPermission, - pagePermission, actionPermission, gson, transactionalOperator, datasourceStorageService, + super( + datasourceService, + sessionUserService, + newActionRepository, + datasourceRepository, + pluginRepository, + workspaceService, + applicationService, + newPageService, + applicationPageService, + newPageRepository, + newActionService, + sequenceService, + actionCollectionRepository, + actionCollectionService, + themeService, + analyticsService, + customJSLibService, + datasourcePermission, + workspacePermission, + applicationPermission, + pagePermission, + actionPermission, + gson, + transactionalOperator, + datasourceStorageService, permissionGroupRepository); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PageLoadActionsUtil.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PageLoadActionsUtil.java index e76951338107..ae552dafc74e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PageLoadActionsUtil.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PageLoadActionsUtil.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.PageLoadActionsUtilCE; -public interface PageLoadActionsUtil extends PageLoadActionsUtilCE { - -} +public interface PageLoadActionsUtil extends PageLoadActionsUtilCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PageLoadActionsUtilImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PageLoadActionsUtilImpl.java index 2257692c71b5..668a1f24aa21 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PageLoadActionsUtilImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PageLoadActionsUtilImpl.java @@ -11,10 +11,11 @@ @Component public class PageLoadActionsUtilImpl extends PageLoadActionsUtilCEImpl implements PageLoadActionsUtil { - public PageLoadActionsUtilImpl(NewActionService newActionService, - AstService astService, - ActionPermission actionPermission, - ObjectMapper objectMapper) { + public PageLoadActionsUtilImpl( + NewActionService newActionService, + AstService astService, + ActionPermission actionPermission, + ObjectMapper objectMapper) { super(newActionService, astService, actionPermission, objectMapper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PagePermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PagePermission.java index 0ddd2fbf23e1..f3f5793bc614 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PagePermission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PagePermission.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.PagePermissionCE; -public interface PagePermission extends PagePermissionCE, DomainPermission { -} +public interface PagePermission extends PagePermissionCE, DomainPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PagePermissionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PagePermissionImpl.java index 701cbd53491e..dd9245f93fe8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PagePermissionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PagePermissionImpl.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class PagePermissionImpl extends PagePermissionCEImpl implements PagePermission { -} +public class PagePermissionImpl extends PagePermissionCEImpl implements PagePermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PermissionGroupPermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PermissionGroupPermission.java index 7fc6be371e7d..2c0991b01017 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PermissionGroupPermission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PermissionGroupPermission.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.PermissionGroupPermissionCE; -public interface PermissionGroupPermission extends PermissionGroupPermissionCE, DomainPermission { -} +public interface PermissionGroupPermission extends PermissionGroupPermissionCE, DomainPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PermissionGroupPermissionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PermissionGroupPermissionImpl.java index dd4eb31b8c1c..f6b4f53fb001 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PermissionGroupPermissionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PermissionGroupPermissionImpl.java @@ -4,5 +4,5 @@ import org.springframework.stereotype.Component; @Component -public class PermissionGroupPermissionImpl extends PermissionGroupPermissionCEImpl implements PermissionGroupPermission { -} +public class PermissionGroupPermissionImpl extends PermissionGroupPermissionCEImpl + implements PermissionGroupPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PingScheduledTask.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PingScheduledTask.java index cb5edd0a435b..3d43f742fa56 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PingScheduledTask.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PingScheduledTask.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.PingScheduledTaskCE; -public interface PingScheduledTask extends PingScheduledTaskCE { - -} +public interface PingScheduledTask extends PingScheduledTaskCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PingScheduledTaskImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PingScheduledTaskImpl.java index 2a56314e75f0..1c8b5f4c4643 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PingScheduledTaskImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PingScheduledTaskImpl.java @@ -37,8 +37,7 @@ public PingScheduledTaskImpl( DatasourceRepository datasourceRepository, UserRepository userRepository, ProjectProperties projectProperties, - NetworkUtils networkUtils - ) { + NetworkUtils networkUtils) { super( configService, @@ -51,7 +50,6 @@ public PingScheduledTaskImpl( datasourceRepository, userRepository, projectProperties, - networkUtils - ); + networkUtils); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PluginScheduledTask.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PluginScheduledTask.java index 6833332ed602..249a6ea7fb8b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PluginScheduledTask.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PluginScheduledTask.java @@ -5,6 +5,4 @@ /** * This class represents a scheduled task that pings cloud services for any updates in available plugins. */ -public interface PluginScheduledTask extends PluginScheduledTaskCE { - -} +public interface PluginScheduledTask extends PluginScheduledTaskCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PluginScheduledTaskImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PluginScheduledTaskImpl.java index 825868b14df5..73a555b2a260 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PluginScheduledTaskImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PluginScheduledTaskImpl.java @@ -5,7 +5,6 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; - @Slf4j @Component public class PluginScheduledTaskImpl extends PluginScheduledTaskCEImpl implements PluginScheduledTask { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PolicySolution.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PolicySolution.java index 5c612dcf06e3..434e1706eebd 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PolicySolution.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PolicySolution.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.PolicySolutionCE; -public interface PolicySolution extends PolicySolutionCE { -} +public interface PolicySolution extends PolicySolutionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PolicySolutionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PolicySolutionImpl.java index 1c79bcaeb923..1e5994e8199b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PolicySolutionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/PolicySolutionImpl.java @@ -12,7 +12,27 @@ @Service public class PolicySolutionImpl extends PolicySolutionCEImpl implements PolicySolution { - public PolicySolutionImpl(PolicyGenerator policyGenerator, ApplicationRepository applicationRepository, DatasourceRepository datasourceRepository, NewPageRepository newPageRepository, NewActionRepository newActionRepository, ActionCollectionRepository actionCollectionRepository, ThemeRepository themeRepository, DatasourcePermission datasourcePermission, ApplicationPermission applicationPermission, PagePermission pagePermission) { - super(policyGenerator, applicationRepository, datasourceRepository, newPageRepository, newActionRepository, actionCollectionRepository, themeRepository, datasourcePermission, applicationPermission, pagePermission); + public PolicySolutionImpl( + PolicyGenerator policyGenerator, + ApplicationRepository applicationRepository, + DatasourceRepository datasourceRepository, + NewPageRepository newPageRepository, + NewActionRepository newActionRepository, + ActionCollectionRepository actionCollectionRepository, + ThemeRepository themeRepository, + DatasourcePermission datasourcePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission) { + super( + policyGenerator, + applicationRepository, + datasourceRepository, + newPageRepository, + newActionRepository, + actionCollectionRepository, + themeRepository, + datasourcePermission, + applicationPermission, + pagePermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/RefactoringSolution.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/RefactoringSolution.java index 7d5c4a102a5b..4bf8ea68c5b4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/RefactoringSolution.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/RefactoringSolution.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.RefactoringSolutionCE; -public interface RefactoringSolution extends RefactoringSolutionCE { -} +public interface RefactoringSolution extends RefactoringSolutionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/RefactoringSolutionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/RefactoringSolutionImpl.java index b5cfe0120a89..9a56f75db41d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/RefactoringSolutionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/RefactoringSolutionImpl.java @@ -19,20 +19,22 @@ @Slf4j public class RefactoringSolutionImpl extends RefactoringSolutionCEImpl implements RefactoringSolution { - public RefactoringSolutionImpl(ObjectMapper objectMapper, - NewPageService newPageService, - NewActionService newActionService, - ActionCollectionService actionCollectionService, - ResponseUtils responseUtils, - LayoutActionService layoutActionService, - ApplicationService applicationService, - AstService astService, - InstanceConfig instanceConfig, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - PagePermission pagePermission, - ActionPermission actionPermission) { - super(objectMapper, + public RefactoringSolutionImpl( + ObjectMapper objectMapper, + NewPageService newPageService, + NewActionService newActionService, + ActionCollectionService actionCollectionService, + ResponseUtils responseUtils, + LayoutActionService layoutActionService, + ApplicationService applicationService, + AstService astService, + InstanceConfig instanceConfig, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + PagePermission pagePermission, + ActionPermission actionPermission) { + super( + objectMapper, newPageService, newActionService, actionCollectionService, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ReleaseNotesService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ReleaseNotesService.java index b0b45f9eed34..13bd8017515d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ReleaseNotesService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ReleaseNotesService.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.ReleaseNotesServiceCE; -public interface ReleaseNotesService extends ReleaseNotesServiceCE { - -} +public interface ReleaseNotesService extends ReleaseNotesServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ReleaseNotesServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ReleaseNotesServiceImpl.java index bc390f1fabba..f4753e74ce22 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ReleaseNotesServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ReleaseNotesServiceImpl.java @@ -6,7 +6,6 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; - @Service @Slf4j public class ReleaseNotesServiceImpl extends ReleaseNotesServiceCEImpl implements ReleaseNotesService { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserAndAccessManagementService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserAndAccessManagementService.java index a5865b35fc96..a47c5af25d8d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserAndAccessManagementService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserAndAccessManagementService.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.UserAndAccessManagementServiceCE; -public interface UserAndAccessManagementService extends UserAndAccessManagementServiceCE { - -} +public interface UserAndAccessManagementService extends UserAndAccessManagementServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserAndAccessManagementServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserAndAccessManagementServiceImpl.java index acee43962ac6..b5ec088edf86 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserAndAccessManagementServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserAndAccessManagementServiceImpl.java @@ -13,18 +13,27 @@ @Component @Slf4j -public class UserAndAccessManagementServiceImpl extends UserAndAccessManagementServiceCEImpl implements UserAndAccessManagementService { +public class UserAndAccessManagementServiceImpl extends UserAndAccessManagementServiceCEImpl + implements UserAndAccessManagementService { - public UserAndAccessManagementServiceImpl(SessionUserService sessionUserService, - PermissionGroupService permissionGroupService, - WorkspaceService workspaceService, - UserRepository userRepository, - AnalyticsService analyticsService, - UserService userService, - EmailSender emailSender, - PermissionGroupPermission permissionGroupPermission) { + public UserAndAccessManagementServiceImpl( + SessionUserService sessionUserService, + PermissionGroupService permissionGroupService, + WorkspaceService workspaceService, + UserRepository userRepository, + AnalyticsService analyticsService, + UserService userService, + EmailSender emailSender, + PermissionGroupPermission permissionGroupPermission) { - super(sessionUserService, permissionGroupService, workspaceService, userRepository, analyticsService, userService, emailSender, + super( + sessionUserService, + permissionGroupService, + workspaceService, + userRepository, + analyticsService, + userService, + emailSender, permissionGroupPermission); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserChangedHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserChangedHandler.java index 7fe7aae5f87d..d434fd697d28 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserChangedHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserChangedHandler.java @@ -2,7 +2,4 @@ import com.appsmith.server.solutions.ce.UserChangedHandlerCE; - -public interface UserChangedHandler extends UserChangedHandlerCE { - -} +public interface UserChangedHandler extends UserChangedHandlerCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserChangedHandlerImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserChangedHandlerImpl.java index 33c524ebc163..fa85635e66ed 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserChangedHandlerImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserChangedHandlerImpl.java @@ -11,9 +11,10 @@ @Slf4j public class UserChangedHandlerImpl extends UserChangedHandlerCEImpl implements UserChangedHandler { - public UserChangedHandlerImpl(ApplicationEventPublisher applicationEventPublisher, - NotificationRepository notificationRepository, - WorkspaceRepository workspaceRepository) { + public UserChangedHandlerImpl( + ApplicationEventPublisher applicationEventPublisher, + NotificationRepository notificationRepository, + WorkspaceRepository workspaceRepository) { super(applicationEventPublisher, notificationRepository, workspaceRepository); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserSignup.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserSignup.java index 577788093fb8..2621fca3493e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserSignup.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserSignup.java @@ -2,6 +2,4 @@ import com.appsmith.server.solutions.ce.UserSignupCE; -public interface UserSignup extends UserSignupCE { - -} +public interface UserSignup extends UserSignupCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserSignupImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserSignupImpl.java index 7c7b0d126ada..cd3007004be5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserSignupImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/UserSignupImpl.java @@ -17,18 +17,28 @@ @Slf4j public class UserSignupImpl extends UserSignupCEImpl implements UserSignup { - public UserSignupImpl(UserService userService, - UserDataService userDataService, - CaptchaService captchaService, - AuthenticationSuccessHandler authenticationSuccessHandler, - ConfigService configService, - AnalyticsService analyticsService, - EnvManager envManager, - CommonConfig commonConfig, - UserUtils userUtils, - NetworkUtils networkUtils) { + public UserSignupImpl( + UserService userService, + UserDataService userDataService, + CaptchaService captchaService, + AuthenticationSuccessHandler authenticationSuccessHandler, + ConfigService configService, + AnalyticsService analyticsService, + EnvManager envManager, + CommonConfig commonConfig, + UserUtils userUtils, + NetworkUtils networkUtils) { - super(userService, userDataService, captchaService, authenticationSuccessHandler, configService, - analyticsService, envManager, commonConfig, userUtils, networkUtils); + super( + userService, + userDataService, + captchaService, + authenticationSuccessHandler, + configService, + analyticsService, + envManager, + commonConfig, + userUtils, + networkUtils); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/WorkspacePermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/WorkspacePermission.java index 2038b9aae9ea..0a2a8a5b6643 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/WorkspacePermission.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/WorkspacePermission.java @@ -2,5 +2,4 @@ import com.appsmith.server.solutions.ce.WorkspacePermissionCE; -public interface WorkspacePermission extends WorkspacePermissionCE, DomainPermission { -} +public interface WorkspacePermission extends WorkspacePermissionCE, DomainPermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/WorkspacePermissionImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/WorkspacePermissionImpl.java index 86a15146fa64..f6d69dca08b5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/WorkspacePermissionImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/WorkspacePermissionImpl.java @@ -4,5 +4,4 @@ import org.springframework.stereotype.Component; @Component -public class WorkspacePermissionImpl extends WorkspacePermissionCEImpl implements WorkspacePermission { -} +public class WorkspacePermissionImpl extends WorkspacePermissionCEImpl implements WorkspacePermission {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCE.java index fa285558128d..79fba0a69352 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCE.java @@ -3,7 +3,6 @@ import com.appsmith.external.dtos.ExecuteActionDTO; import com.appsmith.external.models.ActionDTO; import com.appsmith.external.models.ActionExecutionResult; -import com.appsmith.server.domains.NewAction; import org.springframework.http.codec.multipart.Part; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -18,5 +17,4 @@ public interface ActionExecutionSolutionCE { Mono<ActionDTO> getValidActionForExecution(ExecuteActionDTO executeActionDTO); <T> T variableSubstitution(T configuration, Map<String, String> replaceParamsMap); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImpl.java index 1d322caef777..a84fbf30c1ee 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImpl.java @@ -117,29 +117,31 @@ public class ActionExecutionSolutionCEImpl implements ActionExecutionSolutionCE private final DatasourceStorageService datasourceStorageService; static final String PARAM_KEY_REGEX = "^k\\d+$"; - static final String BLOB_KEY_REGEX = "^blob:[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$"; + static final String BLOB_KEY_REGEX = + "^blob:[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$"; static final String EXECUTE_ACTION_DTO = "executeActionDTO"; static final String PARAMETER_MAP = "parameterMap"; List<Pattern> patternList = new ArrayList<>(); private DatasourceStorageTransferSolution datasourceStorageTransferSolution; - public ActionExecutionSolutionCEImpl(NewActionService newActionService, - ActionPermission actionPermission, - ObservationRegistry observationRegistry, - ObjectMapper objectMapper, - NewActionRepository repository, - DatasourceService datasourceService, - PluginService pluginService, - DatasourceContextService datasourceContextService, - PluginExecutorHelper pluginExecutorHelper, - NewPageService newPageService, - ApplicationService applicationService, - SessionUserService sessionUserService, - AuthenticationValidator authenticationValidator, - DatasourcePermission datasourcePermission, - AnalyticsService analyticsService, - DatasourceStorageService datasourceStorageService, - DatasourceStorageTransferSolution datasourceStorageTransferSolution) { + public ActionExecutionSolutionCEImpl( + NewActionService newActionService, + ActionPermission actionPermission, + ObservationRegistry observationRegistry, + ObjectMapper objectMapper, + NewActionRepository repository, + DatasourceService datasourceService, + PluginService pluginService, + DatasourceContextService datasourceContextService, + PluginExecutorHelper pluginExecutorHelper, + NewPageService newPageService, + ApplicationService applicationService, + SessionUserService sessionUserService, + AuthenticationValidator authenticationValidator, + DatasourcePermission datasourcePermission, + AnalyticsService analyticsService, + DatasourceStorageService datasourceStorageService, + DatasourceStorageTransferSolution datasourceStorageTransferSolution) { this.newActionService = newActionService; this.actionPermission = actionPermission; this.observationRegistry = observationRegistry; @@ -158,7 +160,6 @@ public ActionExecutionSolutionCEImpl(NewActionService newActionService, this.datasourceStorageService = datasourceStorageService; this.datasourceStorageTransferSolution = datasourceStorageTransferSolution; - this.patternList.add(Pattern.compile(PARAM_KEY_REGEX)); this.patternList.add(Pattern.compile(BLOB_KEY_REGEX)); this.patternList.add(Pattern.compile(EXECUTE_ACTION_DTO)); @@ -176,16 +177,14 @@ public ActionExecutionSolutionCEImpl(NewActionService newActionService, @Override public Mono<ActionExecutionResult> executeAction(Flux<Part> partFlux, String branchName, String environmentId) { return createExecuteActionDTO(partFlux) - .flatMap(executeActionDTO -> newActionService.findByBranchNameAndDefaultActionId( - branchName, - executeActionDTO.getActionId(), - actionPermission.getExecutePermission()) + .flatMap(executeActionDTO -> newActionService + .findByBranchNameAndDefaultActionId( + branchName, executeActionDTO.getActionId(), actionPermission.getExecutePermission()) .flatMap(branchedAction -> { executeActionDTO.setActionId(branchedAction.getId()); return Mono.just(executeActionDTO) .zipWith(datasourceService.getTrueEnvironmentId( - branchedAction.getWorkspaceId(), - environmentId)); + branchedAction.getWorkspaceId(), environmentId)); })) .flatMap(tuple2 -> this.executeAction(tuple2.getT1(), tuple2.getT2())) // getTrue is temporary call .name(ACTION_EXECUTION_SERVER_EXECUTION) @@ -209,7 +208,8 @@ public Mono<ActionExecutionResult> executeAction(ExecuteActionDTO executeActionD actionName.set(""); // 2. Fetch the action from the DB and check if it can be executed - Mono<ActionDTO> actionDTOMono = getValidActionForExecution(executeActionDTO).cache(); + Mono<ActionDTO> actionDTOMono = + getValidActionForExecution(executeActionDTO).cache(); // 3. Instantiate the implementation class based on the query type Mono<DatasourceStorage> datasourceStorageMono = getCachedDatasourceStorage(actionDTOMono, environmentId); @@ -217,11 +217,8 @@ public Mono<ActionExecutionResult> executeAction(ExecuteActionDTO executeActionD Mono<PluginExecutor> pluginExecutorMono = pluginExecutorHelper.getPluginExecutor(pluginMono); // 4. Execute the query - Mono<ActionExecutionResult> actionExecutionResultMono = getActionExecutionResult(executeActionDTO, - actionDTOMono, - datasourceStorageMono, - pluginMono, - pluginExecutorMono); + Mono<ActionExecutionResult> actionExecutionResultMono = getActionExecutionResult( + executeActionDTO, actionDTOMono, datasourceStorageMono, pluginMono, pluginExecutorMono); Mono<Map> editorConfigLabelMapMono = getEditorConfigLabelMap(datasourceStorageMono); @@ -229,7 +226,8 @@ public Mono<ActionExecutionResult> executeAction(ExecuteActionDTO executeActionD .zipWith(editorConfigLabelMapMono, (result, labelMap) -> { if (TRUE.equals(executeActionDTO.getViewMode())) { result.setRequest(null); - } else if (result.getRequest() != null && result.getRequest().getRequestParams() != null) { + } else if (result.getRequest() != null + && result.getRequest().getRequestParams() != null) { transformRequestParams(result, labelMap); } return result; @@ -269,9 +267,9 @@ protected Mono<ExecuteActionDTO> createExecuteActionDTO(Flux<Part> partFlux) { * @param dto The ExecuteActionDTO object to store all results in * @return */ - protected Flux<Param> parsePartsAndGetParamsFlux(Flux<Part> partFlux, AtomicLong totalReadableByteCount, ExecuteActionDTO dto) { - return partFlux - .groupBy(part -> { + protected Flux<Param> parsePartsAndGetParamsFlux( + Flux<Part> partFlux, AtomicLong totalReadableByteCount, ExecuteActionDTO dto) { + return partFlux.groupBy(part -> { // We're grouping parts by the type of processing required // Expected types: meta, value, blob @@ -286,24 +284,26 @@ protected Flux<Param> parsePartsAndGetParamsFlux(Flux<Part> partFlux, AtomicLong .flatMap(groupedPartsFlux -> { String key = groupedPartsFlux.key(); return switch (key) { - case PARAM_KEY_REGEX -> - groupedPartsFlux.flatMap(part -> this.parseExecuteParameter(part, totalReadableByteCount)); - case BLOB_KEY_REGEX -> - this.parseExecuteBlobs(groupedPartsFlux, dto, totalReadableByteCount).then(Mono.empty()); - case EXECUTE_ACTION_DTO -> - groupedPartsFlux.next().flatMap(part -> this.parseExecuteActionPart(part, dto)).then(Mono.empty()); - case PARAMETER_MAP -> - groupedPartsFlux.next().flatMap(part -> this.parseExecuteParameterMapPart(part, dto)).then(Mono.empty()); - default -> - Mono.error(new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, "Unexpected part found: " + key)); + case PARAM_KEY_REGEX -> groupedPartsFlux.flatMap( + part -> this.parseExecuteParameter(part, totalReadableByteCount)); + case BLOB_KEY_REGEX -> this.parseExecuteBlobs(groupedPartsFlux, dto, totalReadableByteCount) + .then(Mono.empty()); + case EXECUTE_ACTION_DTO -> groupedPartsFlux + .next() + .flatMap(part -> this.parseExecuteActionPart(part, dto)) + .then(Mono.empty()); + case PARAMETER_MAP -> groupedPartsFlux + .next() + .flatMap(part -> this.parseExecuteParameterMapPart(part, dto)) + .then(Mono.empty()); + default -> Mono.error(new AppsmithException( + AppsmithError.GENERIC_BAD_REQUEST, "Unexpected part found: " + key)); }; }); } - protected Mono<Void> parseExecuteActionPart(Part part, ExecuteActionDTO dto) { - return DataBufferUtils - .join(part.content()) + return DataBufferUtils.join(part.content()) .flatMap(executeActionDTOBuffer -> { byte[] byteData = new byte[executeActionDTOBuffer.readableByteCount()]; executeActionDTOBuffer.read(byteData); @@ -325,15 +325,13 @@ protected Mono<Void> parseExecuteActionPart(Part part, ExecuteActionDTO dto) { } protected Mono<Void> parseExecuteParameterMapPart(Part part, ExecuteActionDTO dto) { - return DataBufferUtils - .join(part.content()) + return DataBufferUtils.join(part.content()) .flatMap(parameterMapBuffer -> { byte[] byteData = new byte[parameterMapBuffer.readableByteCount()]; parameterMapBuffer.read(byteData); DataBufferUtils.release(parameterMapBuffer); try { - return Mono.just(objectMapper.readValue(byteData, new TypeReference<Map<String, String>>() { - })); + return Mono.just(objectMapper.readValue(byteData, new TypeReference<Map<String, String>>() {})); } catch (IOException e) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, PARAMETER_MAP)); } @@ -347,40 +345,37 @@ protected Mono<Void> parseExecuteParameterMapPart(Part part, ExecuteActionDTO dt protected Mono<Param> parseExecuteParameter(Part part, AtomicLong totalReadableByteCount) { final Param param = new Param(); param.setPseudoBindingName(part.name()); - return DataBufferUtils - .join(part.content()) - .map(dataBuffer -> { - byte[] bytes = new byte[dataBuffer.readableByteCount()]; - totalReadableByteCount.addAndGet(dataBuffer.readableByteCount()); - dataBuffer.read(bytes); - DataBufferUtils.release(dataBuffer); - param.setValue(new String(bytes, StandardCharsets.UTF_8)); - return param; - }); + return DataBufferUtils.join(part.content()).map(dataBuffer -> { + byte[] bytes = new byte[dataBuffer.readableByteCount()]; + totalReadableByteCount.addAndGet(dataBuffer.readableByteCount()); + dataBuffer.read(bytes); + DataBufferUtils.release(dataBuffer); + param.setValue(new String(bytes, StandardCharsets.UTF_8)); + return param; + }); } - protected Mono<Void> parseExecuteBlobs(Flux<Part> partsFlux, ExecuteActionDTO dto, AtomicLong totalReadableByteCount) { + protected Mono<Void> parseExecuteBlobs( + Flux<Part> partsFlux, ExecuteActionDTO dto, AtomicLong totalReadableByteCount) { Map<String, String> blobMap = new HashMap<>(); dto.setBlobValuesMap(blobMap); return partsFlux .flatMap(part -> { - return DataBufferUtils - .join(part.content()) - .map(dataBuffer -> { - byte[] bytes = new byte[dataBuffer.readableByteCount()]; - totalReadableByteCount.addAndGet(dataBuffer.readableByteCount()); - dataBuffer.read(bytes); - DataBufferUtils.release(dataBuffer); - blobMap.put(part.name(), new String(bytes, StandardCharsets.ISO_8859_1)); - return Mono.empty(); - }); + return DataBufferUtils.join(part.content()).map(dataBuffer -> { + byte[] bytes = new byte[dataBuffer.readableByteCount()]; + totalReadableByteCount.addAndGet(dataBuffer.readableByteCount()); + dataBuffer.read(bytes); + DataBufferUtils.release(dataBuffer); + blobMap.put(part.name(), new String(bytes, StandardCharsets.ISO_8859_1)); + return Mono.empty(); + }); }) .then(); } - - protected Mono<ExecuteActionDTO> enrichExecutionParam(AtomicLong totalReadableByteCount, ExecuteActionDTO dto, List<Param> params) { + protected Mono<ExecuteActionDTO> enrichExecutionParam( + AtomicLong totalReadableByteCount, ExecuteActionDTO dto, List<Param> params) { if (dto.getActionId() == null) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ACTION_ID)); } @@ -389,39 +384,33 @@ protected Mono<ExecuteActionDTO> enrichExecutionParam(AtomicLong totalReadableBy final Set<String> visitedBindings = new HashSet<>(); /* - Parts in multipart request can appear in any order. In order to avoid NPE original name of the parameters - along with the client-side data type are set here as it's guaranteed at this point that the part having the parameterMap is already collected. - Ref: https://github.com/appsmithorg/appsmith/issues/16722 - */ - params.forEach( - param -> { - String pseudoBindingName = param.getPseudoBindingName(); - String bindingValue = dto.getInvertParameterMap().get(pseudoBindingName); - param.setKey(bindingValue); - visitedBindings.add(bindingValue); - // if the type is not an array e.g. "k1": "string" or "k1": "boolean" - ParamProperty paramProperty = dto.getParamProperties().get(pseudoBindingName); - if (paramProperty != null) { - this.identifyExecutionParamDatatype(param, paramProperty); - - this.substituteBlobValuesInParam(dto, param, paramProperty); - } - - } - ); + Parts in multipart request can appear in any order. In order to avoid NPE original name of the parameters + along with the client-side data type are set here as it's guaranteed at this point that the part having the parameterMap is already collected. + Ref: https://github.com/appsmithorg/appsmith/issues/16722 + */ + params.forEach(param -> { + String pseudoBindingName = param.getPseudoBindingName(); + String bindingValue = dto.getInvertParameterMap().get(pseudoBindingName); + param.setKey(bindingValue); + visitedBindings.add(bindingValue); + // if the type is not an array e.g. "k1": "string" or "k1": "boolean" + ParamProperty paramProperty = dto.getParamProperties().get(pseudoBindingName); + if (paramProperty != null) { + this.identifyExecutionParamDatatype(param, paramProperty); + + this.substituteBlobValuesInParam(dto, param, paramProperty); + } + }); // In case there are parameters that did not receive a value in the multipart request, // initialize these bindings with empty strings if (dto.getParameterMap() != null) { - dto.getParameterMap() - .keySet() - .stream() - .forEach(parameter -> { - if (!visitedBindings.contains(parameter)) { - Param newParam = new Param(parameter, ""); - params.add(newParam); - } - }); + dto.getParameterMap().keySet().stream().forEach(parameter -> { + if (!visitedBindings.contains(parameter)) { + Param newParam = new Param(parameter, ""); + params.add(newParam); + } + }); } dto.setParams(params); return Mono.just(dto); @@ -429,12 +418,11 @@ protected Mono<ExecuteActionDTO> enrichExecutionParam(AtomicLong totalReadableBy private void substituteBlobValuesInParam(ExecuteActionDTO dto, Param param, ParamProperty paramProperty) { // Check if this param has blobUrlPaths - if (paramProperty.getBlobIdentifiers() != null && !paramProperty.getBlobIdentifiers().isEmpty()) { + if (paramProperty.getBlobIdentifiers() != null + && !paramProperty.getBlobIdentifiers().isEmpty()) { // If it does, trigger the replacement logic for each of these urlPaths String replacedValue = this.replaceBlobValuesInParam( - param.getValue(), - paramProperty.getBlobIdentifiers(), - dto.getBlobValuesMap()); + param.getValue(), paramProperty.getBlobIdentifiers(), dto.getBlobValuesMap()); // And then update the value for this param param.setValue(replacedValue); } @@ -443,29 +431,27 @@ private void substituteBlobValuesInParam(ExecuteActionDTO dto, Param param, Para private void identifyExecutionParamDatatype(Param param, ParamProperty paramProperty) { Object datatype = paramProperty.getDatatype(); if (datatype instanceof String) { - param.setClientDataType(ClientDataType.valueOf(String.valueOf(datatype).toUpperCase())); + param.setClientDataType( + ClientDataType.valueOf(String.valueOf(datatype).toUpperCase())); } else if (datatype instanceof LinkedHashMap) { // if the type is an array e.g. "k1": { "array": [ "string", "number", "string", "boolean"] - LinkedHashMap<String, ArrayList> stringArrayListLinkedHashMap = - (LinkedHashMap<String, ArrayList>) datatype; - Optional<String> firstKeyOpt = stringArrayListLinkedHashMap.keySet() - .stream() - .findFirst(); + LinkedHashMap<String, ArrayList> stringArrayListLinkedHashMap = (LinkedHashMap<String, ArrayList>) datatype; + Optional<String> firstKeyOpt = + stringArrayListLinkedHashMap.keySet().stream().findFirst(); if (firstKeyOpt.isPresent()) { String firstKey = firstKeyOpt.get(); param.setClientDataType(ClientDataType.valueOf(firstKey.toUpperCase())); List<String> individualTypes = stringArrayListLinkedHashMap.get(firstKey); - List<ClientDataType> dataTypesOfArrayElements = - individualTypes.stream() - .map(it -> ClientDataType.valueOf(String.valueOf(it) - .toUpperCase())) - .collect(Collectors.toList()); + List<ClientDataType> dataTypesOfArrayElements = individualTypes.stream() + .map(it -> ClientDataType.valueOf(String.valueOf(it).toUpperCase())) + .collect(Collectors.toList()); param.setDataTypesOfArrayElements(dataTypesOfArrayElements); } } } - protected String replaceBlobValuesInParam(String value, List<String> blobIdentifiers, Map<String, String> blobValuesMap) { + protected String replaceBlobValuesInParam( + String value, List<String> blobIdentifiers, Map<String, String> blobValuesMap) { // If there is no blobId reference against this param, return as is if (blobIdentifiers == null || blobIdentifiers.isEmpty()) { return value; @@ -512,14 +498,17 @@ protected Mono<DatasourceStorage> getCachedDatasourceStorage(Mono<ActionDTO> act if (datasource != null && datasource.getId() != null) { // This is an action with a global datasource, // we need to find the entry from db and populate storage - datasourceStorageMono = datasourceService.findById(datasource.getId(), datasourcePermission.getExecutePermission()) - .flatMap(datasource1 -> datasourceStorageService - .findByDatasourceAndEnvironmentIdForExecution(datasource1, environmentId)); + datasourceStorageMono = datasourceService + .findById(datasource.getId(), datasourcePermission.getExecutePermission()) + .flatMap(datasource1 -> + datasourceStorageService.findByDatasourceAndEnvironmentIdForExecution( + datasource1, environmentId)); } else if (datasource == null) { datasourceStorageMono = Mono.empty(); } else { // For embedded datasources, we are simply relying on datasource configuration property - datasourceStorageMono = Mono.just(datasourceStorageTransferSolution.initializeDatasourceStorage(datasource, environmentId)); + datasourceStorageMono = Mono.just(datasourceStorageTransferSolution.initializeDatasourceStorage( + datasource, environmentId)); } return datasourceStorageMono @@ -529,15 +518,19 @@ protected Mono<DatasourceStorage> getCachedDatasourceStorage(Mono<ActionDTO> act return datasourceStorageService.validateDatasourceStorage(datasourceStorage, true); } - // The external datasourceStorage have already been validated. No need to validate again. + // The external datasourceStorage have already been validated. No need to validate + // again. return Mono.just(datasourceStorage); }) .flatMap(datasourceStorage -> { Set<String> invalids = datasourceStorage.getInvalids(); if (!CollectionUtils.isEmpty(invalids)) { - log.error("Unable to execute actionId: {} because it's datasource is not valid. Cause: {}", - actionDTO.getId(), ArrayUtils.toString(invalids)); - return Mono.error(new AppsmithException(AppsmithError.INVALID_DATASOURCE, + log.error( + "Unable to execute actionId: {} because it's datasource is not valid. Cause: {}", + actionDTO.getId(), + ArrayUtils.toString(invalids)); + return Mono.error(new AppsmithException( + AppsmithError.INVALID_DATASOURCE, datasourceStorage.getName(), ArrayUtils.toString(invalids))); } @@ -557,9 +550,9 @@ protected Mono<DatasourceStorage> getCachedDatasourceStorage(Mono<ActionDTO> act */ protected Mono<Plugin> getCachedPluginForActionExecution(Mono<DatasourceStorage> datasourceStorageMono) { - return datasourceStorageMono.flatMap(datasourceStorage -> pluginService.findById(datasourceStorage.getPluginId())) + return datasourceStorageMono + .flatMap(datasourceStorage -> pluginService.findById(datasourceStorage.getPluginId())) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN))); - } /** @@ -597,58 +590,61 @@ protected Mono<Map> getEditorConfigLabelMap(Mono<DatasourceStorage> datasourceSt * @param pluginExecutor * @return actionExecutionResultMono */ - protected Mono<ActionExecutionResult> verifyDatasourceAndMakeRequest(ExecuteActionDTO executeActionDTO, - ActionDTO actionDTO, - DatasourceStorage datasourceStorage, - Plugin plugin, - PluginExecutor pluginExecutor) { - - Mono<ActionExecutionResult> executionMono = - authenticationValidator.validateAuthentication(datasourceStorage) - .zipWhen(validatedDatasource -> datasourceContextService.getDatasourceContext(validatedDatasource, plugin) - .tag("plugin", plugin.getPackageName()) - .name(ACTION_EXECUTION_DATASOURCE_CONTEXT) - .tap(Micrometer.observation(observationRegistry))) - .flatMap(tuple2 -> { - DatasourceStorage datasourceStorage1 = tuple2.getT1(); - DatasourceContext<?> resourceContext = tuple2.getT2(); - // Now that we have the context (connection details), execute the action. - - Instant requestedAt = Instant.now(); - return ((PluginExecutor<Object>) pluginExecutor) - .executeParameterizedWithMetrics(resourceContext.getConnection(), - executeActionDTO, - datasourceStorage1.getDatasourceConfiguration(), - actionDTO.getActionConfiguration(), - observationRegistry) - .map(actionExecutionResult -> { - ActionExecutionRequest actionExecutionRequest = actionExecutionResult.getRequest(); - if (actionExecutionRequest == null) { - actionExecutionRequest = new ActionExecutionRequest(); - } - - actionExecutionRequest.setActionId(executeActionDTO.getActionId()); - actionExecutionRequest.setRequestedAt(requestedAt); - - actionExecutionResult.setRequest(actionExecutionRequest); - return actionExecutionResult; - }); - }); - - return executionMono - .onErrorResume(StaleConnectionException.class, error -> { - log.info("Looks like the connection is stale. Retrying with a fresh context."); - return datasourceContextService.deleteDatasourceContext(datasourceStorage) - .then(executionMono); + protected Mono<ActionExecutionResult> verifyDatasourceAndMakeRequest( + ExecuteActionDTO executeActionDTO, + ActionDTO actionDTO, + DatasourceStorage datasourceStorage, + Plugin plugin, + PluginExecutor pluginExecutor) { + + Mono<ActionExecutionResult> executionMono = authenticationValidator + .validateAuthentication(datasourceStorage) + .zipWhen(validatedDatasource -> datasourceContextService + .getDatasourceContext(validatedDatasource, plugin) + .tag("plugin", plugin.getPackageName()) + .name(ACTION_EXECUTION_DATASOURCE_CONTEXT) + .tap(Micrometer.observation(observationRegistry))) + .flatMap(tuple2 -> { + DatasourceStorage datasourceStorage1 = tuple2.getT1(); + DatasourceContext<?> resourceContext = tuple2.getT2(); + // Now that we have the context (connection details), execute the action. + + Instant requestedAt = Instant.now(); + return ((PluginExecutor<Object>) pluginExecutor) + .executeParameterizedWithMetrics( + resourceContext.getConnection(), + executeActionDTO, + datasourceStorage1.getDatasourceConfiguration(), + actionDTO.getActionConfiguration(), + observationRegistry) + .map(actionExecutionResult -> { + ActionExecutionRequest actionExecutionRequest = actionExecutionResult.getRequest(); + if (actionExecutionRequest == null) { + actionExecutionRequest = new ActionExecutionRequest(); + } + + actionExecutionRequest.setActionId(executeActionDTO.getActionId()); + actionExecutionRequest.setRequestedAt(requestedAt); + + actionExecutionResult.setRequest(actionExecutionRequest); + return actionExecutionResult; + }); }); + + return executionMono.onErrorResume(StaleConnectionException.class, error -> { + log.info("Looks like the connection is stale. Retrying with a fresh context."); + return datasourceContextService + .deleteDatasourceContext(datasourceStorage) + .then(executionMono); + }); } - protected Function<? super Throwable, ? extends Throwable> executionExceptionMapper(ActionDTO actionDTO, - Integer timeoutDuration) { + protected Function<? super Throwable, ? extends Throwable> executionExceptionMapper( + ActionDTO actionDTO, Integer timeoutDuration) { return error -> { if (error instanceof TimeoutException e) { - return new AppsmithPluginException(AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR, - actionDTO.getName(), timeoutDuration); + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR, actionDTO.getName(), timeoutDuration); } else if (error instanceof StaleConnectionException e) { return new AppsmithPluginException(AppsmithPluginError.STALE_CONNECTION_ERROR, e.getMessage()); } else { @@ -659,8 +655,10 @@ protected Mono<ActionExecutionResult> verifyDatasourceAndMakeRequest(ExecuteActi protected Function<? super Throwable, Mono<ActionExecutionResult>> executionExceptionHandler(ActionDTO actionDTO) { return error -> { - log.debug("{}: In the action execution error mode.", - Thread.currentThread().getName(), error); + log.debug( + "{}: In the action execution error mode.", + Thread.currentThread().getName(), + error); ActionExecutionResult result = new ActionExecutionResult(); result.setErrorInfo(error); result.setIsExecutionSuccess(false); @@ -682,11 +680,12 @@ protected Function<? super Throwable, Mono<ActionExecutionResult>> executionExce * @param pluginExecutorMono * @return actionExecutionResultMono */ - protected Mono<ActionExecutionResult> getActionExecutionResult(ExecuteActionDTO executeActionDTO, - Mono<ActionDTO> actionDTOMono, - Mono<DatasourceStorage> datasourceStorageMono, - Mono<Plugin> pluginMono, - Mono<PluginExecutor> pluginExecutorMono) { + protected Mono<ActionExecutionResult> getActionExecutionResult( + ExecuteActionDTO executeActionDTO, + Mono<ActionDTO> actionDTOMono, + Mono<DatasourceStorage> datasourceStorageMono, + Mono<Plugin> pluginMono, + Mono<PluginExecutor> pluginExecutorMono) { return Mono.zip(actionDTOMono, datasourceStorageMono, pluginExecutorMono, pluginMono) .flatMap(tuple -> { @@ -695,16 +694,18 @@ protected Mono<ActionExecutionResult> getActionExecutionResult(ExecuteActionDTO final PluginExecutor pluginExecutor = tuple.getT3(); final Plugin plugin = tuple.getT4(); - log.debug("[{}]Execute Action called in Page {}, for action id : {} action name : {}", + log.debug( + "[{}]Execute Action called in Page {}, for action id : {} action name : {}", Thread.currentThread().getName(), - actionDTO.getPageId(), actionDTO.getId(), actionDTO.getName()); + actionDTO.getPageId(), + actionDTO.getId(), + actionDTO.getName()); Integer timeoutDuration = actionDTO.getActionConfiguration().getTimeoutInMillisecond(); - Mono<ActionExecutionResult> actionExecutionResultMono = - verifyDatasourceAndMakeRequest(executeActionDTO, actionDTO, datasourceStorage, - plugin, pluginExecutor) - .timeout(Duration.ofMillis(timeoutDuration)); + Mono<ActionExecutionResult> actionExecutionResultMono = verifyDatasourceAndMakeRequest( + executeActionDTO, actionDTO, datasourceStorage, plugin, pluginExecutor) + .timeout(Duration.ofMillis(timeoutDuration)); return actionExecutionResultMono .onErrorMap(executionExceptionMapper(actionDTO, timeoutDuration)) @@ -715,14 +716,15 @@ protected Mono<ActionExecutionResult> getActionExecutionResult(ExecuteActionDTO Long timeElapsed = tuple1.getT1(); ActionExecutionResult result = tuple1.getT2(); - log.debug("{}: Action {} with id {} execution time : {} ms", + log.debug( + "{}: Action {} with id {} execution time : {} ms", Thread.currentThread().getName(), actionDTO.getName(), actionDTO.getId(), - timeElapsed - ); + timeElapsed); - return sendExecuteAnalyticsEvent(actionDTO, datasourceStorage, executeActionDTO, result, timeElapsed) + return sendExecuteAnalyticsEvent( + actionDTO, datasourceStorage, executeActionDTO, result, timeElapsed) .thenReturn(result); }); }); @@ -730,12 +732,13 @@ protected Mono<ActionExecutionResult> getActionExecutionResult(ExecuteActionDTO @Override public Mono<ActionDTO> getValidActionForExecution(ExecuteActionDTO executeActionDTO) { - return newActionService.findActionDTObyIdAndViewMode( + return newActionService + .findActionDTObyIdAndViewMode( executeActionDTO.getActionId(), executeActionDTO.getViewMode(), actionPermission.getExecutePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, - FieldName.ACTION, executeActionDTO.getActionId()))) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, executeActionDTO.getActionId()))) .flatMap(action -> { // Now check for erroneous situations which would deter the execution of the action @@ -744,8 +747,7 @@ public Mono<ActionDTO> getValidActionForExecution(ExecuteActionDTO executeAction return Mono.error(new AppsmithException( AppsmithError.INVALID_ACTION, action.getName(), - ArrayUtils.toString(action.getInvalids().toArray()) - )); + ArrayUtils.toString(action.getInvalids().toArray()))); } // Error out in case of JS Plugin (this is currently client side execution only) @@ -772,18 +774,18 @@ public <T> T variableSubstitution(T configuration, Map<String, String> replacePa private void transformRequestParams(ActionExecutionResult result, Map<String, String> labelMap) { Map<String, Object> transformedParams = new LinkedHashMap<>(); Map<String, RequestParamDTO> requestParamsConfigMap = new HashMap(); - ((List) result.getRequest().getRequestParams()).stream() - .forEach(param -> requestParamsConfigMap.put(((RequestParamDTO) param).getConfigProperty(), - (RequestParamDTO) param)); - - labelMap.entrySet().stream() - .forEach(e -> { - String configProperty = e.getKey(); - if (requestParamsConfigMap.containsKey(configProperty)) { - RequestParamDTO param = requestParamsConfigMap.get(configProperty); - transformedParams.put(e.getValue(), param); - } - }); + ((List) result.getRequest().getRequestParams()) + .stream() + .forEach(param -> requestParamsConfigMap.put( + ((RequestParamDTO) param).getConfigProperty(), (RequestParamDTO) param)); + + labelMap.entrySet().stream().forEach(e -> { + String configProperty = e.getKey(); + if (requestParamsConfigMap.containsKey(configProperty)) { + RequestParamDTO param = requestParamsConfigMap.get(configProperty); + transformedParams.put(e.getValue(), param); + } + }); result.getRequest().setRequestParams(transformedParams); } @@ -823,8 +825,7 @@ private Mono<ActionExecutionRequest> sendExecuteAnalyticsEvent( DatasourceStorage datasourceStorage, ExecuteActionDTO executeActionDto, ActionExecutionResult actionExecutionResult, - Long timeElapsed - ) { + Long timeElapsed) { if (!isSendExecuteAnalyticsEvent()) { return Mono.empty(); @@ -843,8 +844,7 @@ private Mono<ActionExecutionRequest> sendExecuteAnalyticsEvent( actionExecutionRequest.getUrl(), actionExecutionRequest.getProperties(), actionExecutionRequest.getExecutionParameters(), - null - ); + null); } else { request = new ActionExecutionRequest(); } @@ -890,8 +890,7 @@ private Mono<ActionExecutionRequest> sendExecuteAnalyticsEvent( Mono.just(application), sessionUserService.getCurrentUser(), newPageService.getNameByPageId(actionDTO.getPageId(), executeActionDto.getViewMode()), - pluginService.getById(actionDTO.getPluginId()) - )) + pluginService.getById(actionDTO.getPluginId()))) .flatMap(tuple -> { final Application application = tuple.getT1(); final User user = tuple.getT2(); @@ -899,22 +898,31 @@ private Mono<ActionExecutionRequest> sendExecuteAnalyticsEvent( final Plugin plugin = tuple.getT4(); final PluginType pluginType = actionDTO.getPluginType(); - final String appMode = TRUE.equals(executeActionDto.getViewMode()) ? ApplicationMode.PUBLISHED.toString() : ApplicationMode.EDIT.toString(); + final String appMode = TRUE.equals(executeActionDto.getViewMode()) + ? ApplicationMode.PUBLISHED.toString() + : ApplicationMode.EDIT.toString(); final Map<String, Object> data = new HashMap<>(Map.of( - "username", user.getUsername(), - "type", pluginType, - "pluginName", plugin.getName(), - "name", actionDTO.getName(), - "datasource", Map.of( - "name", datasourceStorage.getName() - ), - "orgId", application.getWorkspaceId(), - "appId", actionDTO.getApplicationId(), - FieldName.APP_MODE, appMode, - "appName", application.getName(), - "isExampleApp", application.isAppIsExample() - )); + "username", + user.getUsername(), + "type", + pluginType, + "pluginName", + plugin.getName(), + "name", + actionDTO.getName(), + "datasource", + Map.of("name", datasourceStorage.getName()), + "orgId", + application.getWorkspaceId(), + "appId", + actionDTO.getApplicationId(), + FieldName.APP_MODE, + appMode, + "appName", + application.getName(), + "isExampleApp", + application.isAppIsExample())); String dsCreatedAt = ""; if (datasourceStorage.getCreatedAt() != null) { @@ -924,47 +932,45 @@ private Mono<ActionExecutionRequest> sendExecuteAnalyticsEvent( if (paramsList == null) { paramsList = new ArrayList<>(); } - List<String> executionParams = paramsList.stream().map(param -> param.getValue()).collect(Collectors.toList()); + List<String> executionParams = + paramsList.stream().map(param -> param.getValue()).collect(Collectors.toList()); data.putAll(Map.of( "request", request, "pageId", ObjectUtils.defaultIfNull(actionDTO.getPageId(), ""), "pageName", pageName, - "isSuccessfulExecution", ObjectUtils.defaultIfNull(actionExecutionResult.getIsExecutionSuccess(), false), + "isSuccessfulExecution", + ObjectUtils.defaultIfNull(actionExecutionResult.getIsExecutionSuccess(), false), "statusCode", ObjectUtils.defaultIfNull(actionExecutionResult.getStatusCode(), ""), "timeElapsed", timeElapsed, "actionCreated", DateUtils.ISO_FORMATTER.format(actionDTO.getCreatedAt()), - "actionId", ObjectUtils.defaultIfNull(actionDTO.getId(), "") - )); + "actionId", ObjectUtils.defaultIfNull(actionDTO.getId(), ""))); data.putAll(Map.of( - FieldName.ACTION_EXECUTION_REQUEST_PARAMS_SIZE, executeActionDto.getTotalReadableByteCount(), - FieldName.ACTION_EXECUTION_REQUEST_PARAMS_COUNT, executionParams.size() - )); + FieldName.ACTION_EXECUTION_REQUEST_PARAMS_SIZE, + executeActionDto.getTotalReadableByteCount(), + FieldName.ACTION_EXECUTION_REQUEST_PARAMS_COUNT, executionParams.size())); - ActionExecutionResult.PluginErrorDetails pluginErrorDetails = actionExecutionResult.getPluginErrorDetails(); + ActionExecutionResult.PluginErrorDetails pluginErrorDetails = + actionExecutionResult.getPluginErrorDetails(); - data.putAll( - Map.of( - "pluginErrorDetails", ObjectUtils.defaultIfNull(pluginErrorDetails, "") - ) - ); + data.putAll(Map.of("pluginErrorDetails", ObjectUtils.defaultIfNull(pluginErrorDetails, ""))); if (pluginErrorDetails != null) { data.putAll(Map.of( "appsmithErrorCode", pluginErrorDetails.getAppsmithErrorCode(), "appsmithErrorMessage", pluginErrorDetails.getAppsmithErrorMessage(), - "errorType", pluginErrorDetails.getErrorType() - )); + "errorType", pluginErrorDetails.getErrorType())); } data.putAll(Map.of( DATASOURCE_ID_SHORTNAME, ObjectUtils.defaultIfNull(datasourceStorage.getDatasourceId(), ""), - ENVIRONMENT_ID_SHORTNAME, ObjectUtils.defaultIfNull(datasourceStorage.getEnvironmentId(), ""), + ENVIRONMENT_ID_SHORTNAME, + ObjectUtils.defaultIfNull(datasourceStorage.getEnvironmentId(), ""), DATASOURCE_NAME_SHORTNAME, datasourceStorage.getName(), - DATASOURCE_IS_TEMPLATE_SHORTNAME, ObjectUtils.defaultIfNull(datasourceStorage.getIsTemplate(), ""), + DATASOURCE_IS_TEMPLATE_SHORTNAME, + ObjectUtils.defaultIfNull(datasourceStorage.getIsTemplate(), ""), DATASOURCE_IS_MOCK_SHORTNAME, ObjectUtils.defaultIfNull(datasourceStorage.getIsMock(), ""), - DATASOURCE_CREATED_AT_SHORTNAME, dsCreatedAt - )); + DATASOURCE_CREATED_AT_SHORTNAME, dsCreatedAt)); // Add the error message in case of erroneous execution if (FALSE.equals(actionExecutionResult.getIsExecutionSuccess())) { @@ -983,8 +989,10 @@ private Mono<ActionExecutionRequest> sendExecuteAnalyticsEvent( } String executionRequestQuery = ""; - if (actionExecutionResult.getRequest() != null && actionExecutionResult.getRequest().getQuery() != null) { - executionRequestQuery = actionExecutionResult.getRequest().getQuery(); + if (actionExecutionResult.getRequest() != null + && actionExecutionResult.getRequest().getQuery() != null) { + executionRequestQuery = + actionExecutionResult.getRequest().getQuery(); } final Map<String, Object> eventData = new HashMap<>(Map.of( @@ -995,8 +1003,7 @@ private Mono<ActionExecutionRequest> sendExecuteAnalyticsEvent( FieldName.ACTION_EXECUTION_TIME, timeElapsed, FieldName.ACTION_EXECUTION_QUERY, executionRequestQuery, FieldName.APPLICATION, application, - FieldName.PLUGIN, plugin - )); + FieldName.PLUGIN, plugin)); if (executeActionDto.getTotalReadableByteCount() <= Constraint.MAX_ANALYTICS_SIZE_BYTES) { // Only send params info if total size is less than 5 MB @@ -1006,7 +1013,8 @@ private Mono<ActionExecutionRequest> sendExecuteAnalyticsEvent( } data.put(FieldName.EVENT_DATA, eventData); - return analyticsService.sendObjectEvent(AnalyticsEvents.EXECUTE_ACTION, actionDTO, data) + return analyticsService + .sendObjectEvent(AnalyticsEvents.EXECUTE_ACTION, actionDTO, data) .thenReturn(request); }) .onErrorResume(error -> { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionPermissionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionPermissionCE.java index caa8bd434ef6..216e1b4c3923 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionPermissionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ActionPermissionCE.java @@ -4,5 +4,6 @@ public interface ActionPermissionCE { AclPermission getDeletePermission(); + AclPermission getExecutePermission(); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationFetcherCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationFetcherCEImpl.java index a6fdb64f0926..5fb05a50922f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationFetcherCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationFetcherCEImpl.java @@ -7,12 +7,12 @@ import com.appsmith.server.domains.User; import com.appsmith.server.domains.UserData; import com.appsmith.server.domains.Workspace; +import com.appsmith.server.dtos.MemberInfoDTO; import com.appsmith.server.dtos.PageDTO; +import com.appsmith.server.dtos.ReleaseItemsDTO; import com.appsmith.server.dtos.ReleaseNode; -import com.appsmith.server.dtos.MemberInfoDTO; import com.appsmith.server.dtos.UserHomepageDTO; import com.appsmith.server.dtos.WorkspaceApplicationsDTO; -import com.appsmith.server.dtos.ReleaseItemsDTO; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.server.helpers.ResponseUtils; @@ -44,7 +44,6 @@ import java.util.function.Function; import java.util.stream.Collectors; - @Slf4j @RequiredArgsConstructor public class ApplicationFetcherCEImpl implements ApplicationFetcherCE { @@ -53,8 +52,8 @@ public class ApplicationFetcherCEImpl implements ApplicationFetcherCE { * A component responsible for generating a list of applications accessible by the currently logged-in user. * TODO: Return applications shared with the user as part of this. */ - private final SessionUserService sessionUserService; + private final UserService userService; private final UserDataService userDataService; private final WorkspaceService workspaceService; @@ -71,7 +70,8 @@ private <Domain extends BaseDomain> Flux<Domain> sortDomain(Flux<Domain> domainF if (CollectionUtils.isEmpty(sortOrder)) { return domainFlux; } - return domainFlux.collect(Collectors.toMap(Domain::getId, Function.identity(), (key1, key2) -> key1, LinkedHashMap::new)) + return domainFlux + .collect(Collectors.toMap(Domain::getId, Function.identity(), (key1, key2) -> key1, LinkedHashMap::new)) .map(domainMap -> { List<Domain> sortedDomains = new ArrayList<>(); for (String id : sortOrder) { @@ -105,10 +105,12 @@ public Mono<UserHomepageDTO> getAllApplications() { .flatMap(userService::findByEmail) .cache(); - Mono<UserData> userDataMono = userDataService.getForCurrentUser().defaultIfEmpty(new UserData()).cache(); + Mono<UserData> userDataMono = userDataService + .getForCurrentUser() + .defaultIfEmpty(new UserData()) + .cache(); - return userMono - .zipWith(userDataMono) + return userMono.zipWith(userDataMono) .flatMap(userAndUserDataTuple -> { User user = userAndUserDataTuple.getT1(); UserData userData = userAndUserDataTuple.getT2(); @@ -119,31 +121,41 @@ public Mono<UserHomepageDTO> getAllApplications() { // Collect all the applications as a map with workspace id as a key Flux<Application> applicationFlux = applicationRepository .findAllUserApps(applicationPermission.getReadPermission()) - //sort transformation + // sort transformation .transform(domainFlux -> sortDomain(domainFlux, userData.getRecentlyUsedAppIds())) // Git connected apps will have gitApplicationMetadat .filter(application -> application.getGitApplicationMetadata() == null - // 1. When the ssh key is generated by user and then the connect app fails - || (StringUtils.isEmpty(application.getGitApplicationMetadata().getDefaultBranchName()) - && StringUtils.isEmpty(application.getGitApplicationMetadata().getBranchName())) - // 2. When the DefaultBranchName is missing due to branch creation flow failures or corrupted scenarios - || (!StringUtils.isEmpty(application.getGitApplicationMetadata().getBranchName()) - && application.getGitApplicationMetadata().getBranchName().equals(application.getGitApplicationMetadata().getDefaultBranchName()) - ) - ) + // 1. When the ssh key is generated by user and then the connect app fails + || (StringUtils.isEmpty(application + .getGitApplicationMetadata() + .getDefaultBranchName()) + && StringUtils.isEmpty(application + .getGitApplicationMetadata() + .getBranchName())) + // 2. When the DefaultBranchName is missing due to branch creation flow failures or + // corrupted scenarios + || (!StringUtils.isEmpty(application + .getGitApplicationMetadata() + .getBranchName()) + && application + .getGitApplicationMetadata() + .getBranchName() + .equals(application + .getGitApplicationMetadata() + .getDefaultBranchName()))) .map(responseUtils::updateApplicationWithDefaultResources); - Mono<Map<String, Collection<Application>>> applicationsMapMono = applicationFlux.collectMultimap( - Application::getWorkspaceId, Function.identity() - ); + Mono<Map<String, Collection<Application>>> applicationsMapMono = + applicationFlux.collectMultimap(Application::getWorkspaceId, Function.identity()); - Flux<Workspace> workspacesFromRepoFlux = workspaceService.getAll(workspacePermission.getReadPermission()) + Flux<Workspace> workspacesFromRepoFlux = workspaceService + .getAll(workspacePermission.getReadPermission()) .cache(); Mono<List<Workspace>> workspaceListMono = workspacesFromRepoFlux - //sort transformation + // sort transformation .transform(domainFlux -> sortDomain(domainFlux, userData.getRecentlyUsedWorkspaceIds())) - //collect to list to keep the order of the workspaces + // collect to list to keep the order of the workspaces .collectList() .cache(); @@ -156,14 +168,17 @@ public Mono<UserHomepageDTO> getAllApplications() { .map(tuple -> { List<Workspace> workspaces = tuple.getT1(); - Map<String, Collection<Application>> applicationsCollectionByWorkspaceId = tuple.getT2(); + Map<String, Collection<Application>> applicationsCollectionByWorkspaceId = + tuple.getT2(); - Map<String, List<MemberInfoDTO>> userAndPermissionGroupMapDTOByWorkspaceId = tuple.getT3(); + Map<String, List<MemberInfoDTO>> userAndPermissionGroupMapDTOByWorkspaceId = + tuple.getT3(); List<WorkspaceApplicationsDTO> workspaceApplicationsDTOS = new ArrayList<>(); for (Workspace workspace : workspaces) { - Collection<Application> applicationCollection = applicationsCollectionByWorkspaceId.get(workspace.getId()); + Collection<Application> applicationCollection = + applicationsCollectionByWorkspaceId.get(workspace.getId()); final List<Application> applicationList = new ArrayList<>(); if (!CollectionUtils.isEmpty(applicationCollection)) { @@ -173,7 +188,8 @@ public Mono<UserHomepageDTO> getAllApplications() { WorkspaceApplicationsDTO workspaceApplicationsDTO = new WorkspaceApplicationsDTO(); workspaceApplicationsDTO.setWorkspace(workspace); workspaceApplicationsDTO.setApplications(applicationList); - workspaceApplicationsDTO.setUsers(userAndPermissionGroupMapDTOByWorkspaceId.get(workspace.getId())); + workspaceApplicationsDTO.setUsers( + userAndPermissionGroupMapDTOByWorkspaceId.get(workspace.getId())); workspaceApplicationsDTOS.add(workspaceApplicationsDTO); } @@ -184,19 +200,30 @@ public Mono<UserHomepageDTO> getAllApplications() { }) .flatMap(userHomepageDTO -> { List<String> applicationIds = userHomepageDTO.getWorkspaceApplications().stream() - .map(workspaceApplicationsDTO -> - workspaceApplicationsDTO.getApplications().stream() - .map(BaseDomain::getId).collect(Collectors.toList()) - ).flatMap(Collection::stream).collect(Collectors.toList()); + .map(workspaceApplicationsDTO -> workspaceApplicationsDTO.getApplications().stream() + .map(BaseDomain::getId) + .collect(Collectors.toList())) + .flatMap(Collection::stream) + .collect(Collectors.toList()); // fetch the page slugs for the applications - return newPageService.findPageSlugsByApplicationIds(applicationIds, pagePermission.getReadPermission()) + return newPageService + .findPageSlugsByApplicationIds(applicationIds, pagePermission.getReadPermission()) .collectMultimap(NewPage::getApplicationId) .map(applicationPageMap -> { - for (WorkspaceApplicationsDTO workspaceApps : userHomepageDTO.getWorkspaceApplications()) { + for (WorkspaceApplicationsDTO workspaceApps : + userHomepageDTO.getWorkspaceApplications()) { for (Application application : workspaceApps.getApplications()) { - setDefaultPageSlug(application, applicationPageMap, Application::getPages, NewPage::getUnpublishedPage); - setDefaultPageSlug(application, applicationPageMap, Application::getPublishedPages, NewPage::getPublishedPage); + setDefaultPageSlug( + application, + applicationPageMap, + Application::getPages, + NewPage::getUnpublishedPage); + setDefaultPageSlug( + application, + applicationPageMap, + Application::getPublishedPages, + NewPage::getPublishedPage); } } return userHomepageDTO; @@ -216,40 +243,44 @@ public Mono<ReleaseItemsDTO> getReleaseItems() { .flatMap(userService::findByEmail) .cache(); - Mono<UserData> userDataMono = userDataService.getForCurrentUser().defaultIfEmpty(new UserData()).cache(); + Mono<UserData> userDataMono = userDataService + .getForCurrentUser() + .defaultIfEmpty(new UserData()) + .cache(); return userMono.flatMap(user -> Mono.zip( - Mono.just(user), - releaseNotesService.getReleaseNodes() - // In case of an error or empty response from CS Server, continue without this data. - .onErrorResume(error -> Mono.empty()) - .defaultIfEmpty(Collections.emptyList()), userDataMono) - ).flatMap(tuple -> { - User user = tuple.getT1(); - final List<ReleaseNode> releaseNodes = tuple.getT2(); - final UserData userData = tuple.getT3(); - ReleaseItemsDTO releaseItemsDTO = new ReleaseItemsDTO(); - releaseItemsDTO.setReleaseItems(releaseNodes); - - final String count = releaseNotesService.computeNewFrom(userData.getReleaseNotesViewedVersion()); - releaseItemsDTO.setNewReleasesCount("0".equals(count) ? "" : count); - - return userDataService.ensureViewedCurrentVersionReleaseNotes(user) - .thenReturn(releaseItemsDTO); - }); + Mono.just(user), + releaseNotesService + .getReleaseNodes() + // In case of an error or empty response from CS Server, continue without this data. + .onErrorResume(error -> Mono.empty()) + .defaultIfEmpty(Collections.emptyList()), + userDataMono)) + .flatMap(tuple -> { + User user = tuple.getT1(); + final List<ReleaseNode> releaseNodes = tuple.getT2(); + final UserData userData = tuple.getT3(); + ReleaseItemsDTO releaseItemsDTO = new ReleaseItemsDTO(); + releaseItemsDTO.setReleaseItems(releaseNodes); + + final String count = releaseNotesService.computeNewFrom(userData.getReleaseNotesViewedVersion()); + releaseItemsDTO.setNewReleasesCount("0".equals(count) ? "" : count); + + return userDataService + .ensureViewedCurrentVersionReleaseNotes(user) + .thenReturn(releaseItemsDTO); + }); } private void setDefaultPageSlug( Application application, Map<String, Collection<NewPage>> applicationPageMap, Function<Application, List<ApplicationPage>> getPages, - Function<NewPage, PageDTO> getPage - ) { + Function<NewPage, PageDTO> getPage) { List<ApplicationPage> applicationPages = getPages.apply(application); if (!CollectionUtils.isEmpty(applicationPages)) { - Optional<ApplicationPage> defaultPageOptional = applicationPages.stream() - .filter(ApplicationPage::isDefault) - .findFirst(); + Optional<ApplicationPage> defaultPageOptional = + applicationPages.stream().filter(ApplicationPage::isDefault).findFirst(); if (defaultPageOptional.isPresent()) { ApplicationPage defaultPage = defaultPageOptional.get(); @@ -266,10 +297,16 @@ private void setDefaultPageSlug( defaultPage.setSlug(pageDTO.getSlug()); defaultPage.setCustomSlug(pageDTO.getCustomSlug()); } else { - log.error("page dto missing for application {} page {}", application.getId(), defaultPage.getId()); + log.error( + "page dto missing for application {} page {}", + application.getId(), + defaultPage.getId()); } } else { - log.error("page not found for application id {}, page id {}", application.getId(), defaultPage.getId()); + log.error( + "page not found for application id {}, page id {}", + application.getId(), + defaultPage.getId()); } } else { log.error("no page found for application {}", application.getId()); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCE.java index f89eb26f7a28..dfec01e0effe 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCE.java @@ -6,12 +6,9 @@ public interface ApplicationForkingServiceCE { - Mono<Application> forkApplicationToWorkspaceWithEnvironment(String srcApplicationId, - String targetWorkspaceId, - String sourceEnvironmentId); - - Mono<ApplicationImportDTO> forkApplicationToWorkspace(String srcApplicationId, - String targetWorkspaceId, - String branchName); + Mono<Application> forkApplicationToWorkspaceWithEnvironment( + String srcApplicationId, String targetWorkspaceId, String sourceEnvironmentId); + Mono<ApplicationImportDTO> forkApplicationToWorkspace( + String srcApplicationId, String targetWorkspaceId, String branchName); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCEImpl.java index 60c1a3b6099e..8539c9bd718d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCEImpl.java @@ -42,18 +42,17 @@ public class ApplicationForkingServiceCEImpl implements ApplicationForkingServic private final ImportExportApplicationService importExportApplicationService; @Override - public Mono<Application> forkApplicationToWorkspaceWithEnvironment(String srcApplicationId, - String targetWorkspaceId, - String sourceEnvironmentId) { + public Mono<Application> forkApplicationToWorkspaceWithEnvironment( + String srcApplicationId, String targetWorkspaceId, String sourceEnvironmentId) { final Mono<Application> sourceApplicationMono = applicationService .findById(srcApplicationId, applicationPermission.getReadPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, - FieldName.APPLICATION, srcApplicationId))); + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, srcApplicationId))); final Mono<Workspace> targetWorkspaceMono = workspaceService .findById(targetWorkspaceId, workspacePermission.getApplicationCreatePermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, - FieldName.WORKSPACE, targetWorkspaceId))); + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, targetWorkspaceId))); Mono<User> userMono = sessionUserService.getCurrentUser(); @@ -68,13 +67,18 @@ public Mono<Application> forkApplicationToWorkspaceWithEnvironment(String srcApp eventData.put(FieldName.WORKSPACE, targetWorkspace); - // If the forking application is connected to git, do not copy those data to the new forked application + // If the forking application is connected to git, do not copy those data to the new forked + // application application.setGitApplicationMetadata(null); boolean allowFork = ( // Is this a non-anonymous user that has access to this application? - !user.isAnonymous() && application.getUserPermissions().contains(applicationPermission.getEditPermission().getValue()) - ) + !user.isAnonymous() + && application + .getUserPermissions() + .contains(applicationPermission + .getEditPermission() + .getValue())) || Boolean.TRUE.equals(application.getForkingEnabled()); if (!allowFork) { @@ -88,44 +92,46 @@ public Mono<Application> forkApplicationToWorkspaceWithEnvironment(String srcApp }) .flatMap(applicationIds -> { final String newApplicationId = applicationIds.get(0); - return applicationService.getById(newApplicationId) - .flatMap(application -> - sendForkApplicationAnalyticsEvent( - srcApplicationId, - targetWorkspaceId, - application, - eventData)); + return applicationService + .getById(newApplicationId) + .flatMap(application -> sendForkApplicationAnalyticsEvent( + srcApplicationId, targetWorkspaceId, application, eventData)); }); - // Fork application is currently a slow API because it needs to create application, clone all the pages, and then + // Fork application is currently a slow API because it needs to create application, clone all the pages, and + // then // copy all the actions and collections. This process may take time and the client may cancel the request. // This leads to the flow getting stopped midway producing corrupted DB objects. The following ensures that even // though the client may have cancelled the flow, the forking of the application should proceed uninterrupted // and whenever the user refreshes the page, the sane forked application is available. // To achieve this, we use a synchronous sink which does not take subscription cancellations into account. This - // means that even if the subscriber has cancelled its subscription, the create method still generates its event. - return Mono.create(sink -> forkApplicationMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + // means that even if the subscriber has cancelled its subscription, the create method still generates its + // event. + return Mono.create( + sink -> forkApplicationMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } - public Mono<ApplicationImportDTO> forkApplicationToWorkspace(String srcApplicationId, - String targetWorkspaceId, - String branchName) { + public Mono<ApplicationImportDTO> forkApplicationToWorkspace( + String srcApplicationId, String targetWorkspaceId, String branchName) { // First we try to find the correct database entry of application to fork, based on git Mono<Application> applicationMono; if (StringUtils.isEmpty(branchName)) { - applicationMono = applicationService.findById(srcApplicationId, applicationPermission.getReadPermission()) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, - FieldName.APPLICATION, srcApplicationId))) + applicationMono = applicationService + .findById(srcApplicationId, applicationPermission.getReadPermission()) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, srcApplicationId))) .flatMap(application -> { // For git connected application user can update the default branch // In such cases we should fork the application from the new default branch if (!(application.getGitApplicationMetadata() == null) - && !application.getGitApplicationMetadata().getBranchName() - .equals(application.getGitApplicationMetadata().getDefaultBranchName())) { + && !application + .getGitApplicationMetadata() + .getBranchName() + .equals(application + .getGitApplicationMetadata() + .getDefaultBranchName())) { return applicationService.findByBranchNameAndDefaultApplicationId( application.getGitApplicationMetadata().getDefaultBranchName(), srcApplicationId, @@ -134,37 +140,38 @@ public Mono<ApplicationImportDTO> forkApplicationToWorkspace(String srcApplicati return Mono.just(application); }); } else { - applicationMono = applicationService - .findByBranchNameAndDefaultApplicationId(branchName, srcApplicationId, applicationPermission.getReadPermission()); + applicationMono = applicationService.findByBranchNameAndDefaultApplicationId( + branchName, srcApplicationId, applicationPermission.getReadPermission()); } return applicationMono // We will be forking to the default environment in the new workspace - .zipWhen(application -> workspaceService.getDefaultEnvironmentId(application.getWorkspaceId())) + .zipWhen(application -> workspaceService.getDefaultEnvironmentId(application.getWorkspaceId())) .flatMap(tuple -> { String fromApplicationId = tuple.getT1().getId(); String sourceEnvironmentId = tuple.getT2(); - return forkApplicationToWorkspaceWithEnvironment(fromApplicationId, targetWorkspaceId, sourceEnvironmentId) + return forkApplicationToWorkspaceWithEnvironment( + fromApplicationId, targetWorkspaceId, sourceEnvironmentId) .map(responseUtils::updateApplicationWithDefaultResources) - .flatMap(application -> importExportApplicationService - .getApplicationImportDTO( - application.getId(), - application.getWorkspaceId(), - application - )); + .flatMap(application -> importExportApplicationService.getApplicationImportDTO( + application.getId(), application.getWorkspaceId(), application)); }); } - private Mono<Application> sendForkApplicationAnalyticsEvent(String applicationId, String workspaceId, Application application, Map<String, Object> eventData) { - return applicationService.findById(applicationId, applicationPermission.getReadPermission()) + private Mono<Application> sendForkApplicationAnalyticsEvent( + String applicationId, String workspaceId, Application application, Map<String, Object> eventData) { + return applicationService + .findById(applicationId, applicationPermission.getReadPermission()) .flatMap(sourceApplication -> { - final Map<String, Object> data = Map.of( - "forkedFromAppId", applicationId, - "forkedToOrgId", workspaceId, - "forkedFromAppName", sourceApplication.getName(), - FieldName.EVENT_DATA, eventData - ); + "forkedFromAppId", + applicationId, + "forkedToOrgId", + workspaceId, + "forkedFromAppName", + sourceApplication.getName(), + FieldName.EVENT_DATA, + eventData); return analyticsService.sendObjectEvent(AnalyticsEvents.FORK, application, data); }) @@ -173,5 +180,4 @@ private Mono<Application> sendForkApplicationAnalyticsEvent(String applicationId return Mono.just(application); }); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCE.java index 82699bf0fe80..53d5ba4c2da8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCE.java @@ -18,7 +18,8 @@ public interface AuthenticationServiceCE { * @param httpRequest Used to find the redirect domain * @return a url String to continue the authorization flow */ - Mono<String> getAuthorizationCodeURLForGenericOAuth2(String datasourceId, String environmentId, String pageId, ServerHttpRequest httpRequest); + Mono<String> getAuthorizationCodeURLForGenericOAuth2( + String datasourceId, String environmentId, String pageId, ServerHttpRequest httpRequest); /** * This is the method that handles callback for generic OAuth2. We will be retrieving and storing token information here @@ -29,23 +30,35 @@ public interface AuthenticationServiceCE { */ Mono<String> getAccessTokenForGenericOAuth2(AuthorizationCodeCallbackDTO callbackDTO); - Mono<String> getAppsmithToken(String datasourceId, String environmentId, String pageId, String branchName, ServerHttpRequest request, String importForGit); + Mono<String> getAppsmithToken( + String datasourceId, + String environmentId, + String pageId, + String branchName, + ServerHttpRequest request, + String importForGit); Mono<OAuth2ResponseDTO> getAccessTokenFromCloud(String datasourceId, String environmentId, String appsmithToken); Mono<DatasourceStorage> refreshAuthentication(DatasourceStorage datasourceStorage); // TODO: temporaray tranisition commit: will be removed when client starts to send environmentId in the headers: - Mono<String> getAuthorizationCodeURLForGenericOAuth2(String datasourceId, - String environmentId, - String pageId, - ServerHttpRequest httpRequest, - Boolean isTrueEnvironmentIdRequired); + Mono<String> getAuthorizationCodeURLForGenericOAuth2( + String datasourceId, + String environmentId, + String pageId, + ServerHttpRequest httpRequest, + Boolean isTrueEnvironmentIdRequired); - Mono<String> getAppsmithToken(String datasourceId, String environmentId, String pageId, String branchName, - ServerHttpRequest request, String importForGit, Boolean isTrueEnvironmentIdRequired); - - Mono<OAuth2ResponseDTO> getAccessTokenFromCloud(String datasourceId, String environmentId, String appsmithToken, - Boolean isTrueEnvironmentIdRequired); + Mono<String> getAppsmithToken( + String datasourceId, + String environmentId, + String pageId, + String branchName, + ServerHttpRequest request, + String importForGit, + Boolean isTrueEnvironmentIdRequired); + Mono<OAuth2ResponseDTO> getAccessTokenFromCloud( + String datasourceId, String environmentId, String appsmithToken, Boolean isTrueEnvironmentIdRequired); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCEImpl.java index cda3b334346a..824ceaa64b29 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCEImpl.java @@ -91,45 +91,55 @@ public class AuthenticationServiceCEImpl implements AuthenticationServiceCE { private static final String ACCESS_TOKEN_KEY = "access_token"; // TODO: Remove after client side changes have been merged - public Mono<String> getAuthorizationCodeURLForGenericOAuth2(String datasourceId, - String environmentId, - String pageId, - ServerHttpRequest httpRequest, - Boolean isTrueEnvironmentIdRequired) { + public Mono<String> getAuthorizationCodeURLForGenericOAuth2( + String datasourceId, + String environmentId, + String pageId, + ServerHttpRequest httpRequest, + Boolean isTrueEnvironmentIdRequired) { if (Boolean.TRUE.equals(isTrueEnvironmentIdRequired)) { - return datasourceService.findById(datasourceId, datasourcePermission.getEditPermission()) + return datasourceService + .findById(datasourceId, datasourcePermission.getEditPermission()) .map(Datasource::getWorkspaceId) .flatMap(workspaceId -> datasourceService.getTrueEnvironmentId(workspaceId, environmentId)) - .flatMap(trueEnvironmentId -> getAuthorizationCodeURLForGenericOAuth2(datasourceId, trueEnvironmentId, pageId, httpRequest)); + .flatMap(trueEnvironmentId -> getAuthorizationCodeURLForGenericOAuth2( + datasourceId, trueEnvironmentId, pageId, httpRequest)); } return getAuthorizationCodeURLForGenericOAuth2(datasourceId, environmentId, pageId, httpRequest); } - public Mono<String> getAppsmithToken(String datasourceId, String environmentId, String pageId, String branchName, - ServerHttpRequest request, String importForGit, - Boolean isTrueEnvironmentIdRequired) { + public Mono<String> getAppsmithToken( + String datasourceId, + String environmentId, + String pageId, + String branchName, + ServerHttpRequest request, + String importForGit, + Boolean isTrueEnvironmentIdRequired) { if (Boolean.TRUE.equals(isTrueEnvironmentIdRequired)) { - return datasourceService.findById(datasourceId, datasourcePermission.getEditPermission()) + return datasourceService + .findById(datasourceId, datasourcePermission.getEditPermission()) .map(Datasource::getWorkspaceId) .flatMap(workspaceId -> datasourceService.getTrueEnvironmentId(workspaceId, environmentId)) - .flatMap(trueEnvironmentId -> getAppsmithToken(datasourceId, trueEnvironmentId, pageId, branchName, request, importForGit)); + .flatMap(trueEnvironmentId -> getAppsmithToken( + datasourceId, trueEnvironmentId, pageId, branchName, request, importForGit)); } return getAppsmithToken(datasourceId, environmentId, pageId, branchName, request, importForGit); - } - public Mono<OAuth2ResponseDTO> getAccessTokenFromCloud(String datasourceId, String environmentId, - String appsmithToken, - Boolean isTrueEnvironmentIdRequired) { + public Mono<OAuth2ResponseDTO> getAccessTokenFromCloud( + String datasourceId, String environmentId, String appsmithToken, Boolean isTrueEnvironmentIdRequired) { if (Boolean.TRUE.equals(isTrueEnvironmentIdRequired)) { - return datasourceService.findById(datasourceId, datasourcePermission.getEditPermission()) + return datasourceService + .findById(datasourceId, datasourcePermission.getEditPermission()) .map(Datasource::getWorkspaceId) .flatMap(workspaceId -> datasourceService.getTrueEnvironmentId(workspaceId, environmentId)) - .flatMap(trueEnvironmentId -> getAccessTokenFromCloud(datasourceId, trueEnvironmentId, appsmithToken)); + .flatMap(trueEnvironmentId -> + getAccessTokenFromCloud(datasourceId, trueEnvironmentId, appsmithToken)); } return getAccessTokenFromCloud(datasourceId, environmentId, appsmithToken); @@ -145,34 +155,39 @@ public Mono<OAuth2ResponseDTO> getAccessTokenFromCloud(String datasourceId, Stri * @param httpRequest Used to find the redirect domain * @return a url String to continue the authorization flow */ - public Mono<String> getAuthorizationCodeURLForGenericOAuth2(String datasourceId, String environmentId, String pageId, ServerHttpRequest httpRequest) { + public Mono<String> getAuthorizationCodeURLForGenericOAuth2( + String datasourceId, String environmentId, String pageId, ServerHttpRequest httpRequest) { // This is the only database access that is controlled by ACL // The rest of the queries in this flow will not have context information - return datasourceService.findById(datasourceId, datasourcePermission.getEditPermission()) - .flatMap(datasource1 -> datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, environmentId)) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))) + return datasourceService + .findById(datasourceId, datasourcePermission.getEditPermission()) + .flatMap(datasource1 -> + datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, environmentId)) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))) .flatMap(this::validateRequiredFieldsForGenericOAuth2) .flatMap((datasourceStorage -> { - OAuth2 oAuth2 = (OAuth2) datasourceStorage.getDatasourceConfiguration().getAuthentication(); + OAuth2 oAuth2 = (OAuth2) + datasourceStorage.getDatasourceConfiguration().getAuthentication(); final String redirectUri = redirectHelper.getRedirectDomain(httpRequest.getHeaders()); // Adding basic uri components - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder - .fromUriString(oAuth2.getAuthorizationUrl()) + UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString( + oAuth2.getAuthorizationUrl()) .queryParam(CLIENT_ID, oAuth2.getClientId()) .queryParam(RESPONSE_TYPE, CODE) .queryParam(REDIRECT_URI, redirectUri + Url.DATASOURCE_URL + "/authorize") - // The state is used internally to calculate the redirect url when returning control to the client + // The state is used internally to calculate the redirect url when returning control to the + // client .queryParam(STATE, String.join(",", pageId, datasourceId, environmentId, redirectUri)); // Adding optional scope parameter if (oAuth2.getScope() != null && !oAuth2.getScope().isEmpty()) { - uriComponentsBuilder - .queryParam(SCOPE, StringUtils.collectionToDelimitedString(oAuth2.getScope(), " ")); + uriComponentsBuilder.queryParam( + SCOPE, StringUtils.collectionToDelimitedString(oAuth2.getScope(), " ")); } // Adding additional user-defined parameters, these would be authorization server specific if (oAuth2.getCustomAuthenticationParameters() != null) { - oAuth2.getCustomAuthenticationParameters().forEach(x -> - uriComponentsBuilder.queryParam(x.getKey(), x.getValue()) - ); + oAuth2.getCustomAuthenticationParameters() + .forEach(x -> uriComponentsBuilder.queryParam(x.getKey(), x.getValue())); } return Mono.just(uriComponentsBuilder.toUriString()); @@ -182,14 +197,18 @@ public Mono<String> getAuthorizationCodeURLForGenericOAuth2(String datasourceId, private Mono<DatasourceStorage> validateRequiredFieldsForGenericOAuth2(DatasourceStorage datasourceStorage) { // Since validation takes care of checking for fields that are present // We just need to make sure that the datasource has the right authentication type - if (datasourceStorage.getDatasourceConfiguration() == null || !(datasourceStorage.getDatasourceConfiguration().getAuthentication() instanceof OAuth2)) { + if (datasourceStorage.getDatasourceConfiguration() == null + || !(datasourceStorage.getDatasourceConfiguration().getAuthentication() instanceof OAuth2)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "authentication")); } - return datasourceStorageService.validateDatasourceStorage(datasourceStorage, true) + return datasourceStorageService + .validateDatasourceStorage(datasourceStorage, true) .flatMap(datasourceStorage1 -> { if (!datasourceStorage1.getIsValid()) { - return Mono.error(new AppsmithException(AppsmithError.VALIDATION_FAILURE, datasourceStorage1.getInvalids().iterator().next())); + return Mono.error(new AppsmithException( + AppsmithError.VALIDATION_FAILURE, + datasourceStorage1.getInvalids().iterator().next())); } return Mono.just(datasourceStorage1); }); @@ -222,21 +241,21 @@ public Mono<String> getAccessTokenForGenericOAuth2(AuthorizationCodeCallbackDTO } else return datasourceService .findById(splitStates[1]) - .flatMap(datasource1 -> datasourceStorageService - .findByDatasourceAndEnvironmentId( - datasource1, - splitStates[2])); + .flatMap(datasource1 -> datasourceStorageService.findByDatasourceAndEnvironmentId( + datasource1, splitStates[2])); }) .flatMap(datasourceStorage -> { - OAuth2 oAuth2 = (OAuth2) datasourceStorage.getDatasourceConfiguration().getAuthentication(); + OAuth2 oAuth2 = (OAuth2) + datasourceStorage.getDatasourceConfiguration().getAuthentication(); final HttpClient httpClient = HttpClient.create(); if (oAuth2.isUseSelfSignedCert()) { - httpClient.secure(SSLHelper.sslCheckForHttpClient(datasourceStorage.getDatasourceConfiguration())); + httpClient.secure( + SSLHelper.sslCheckForHttpClient(datasourceStorage.getDatasourceConfiguration())); } - WebClient.Builder builder = WebClientUtils.builder(httpClient) - .baseUrl(oAuth2.getAccessTokenUrl()); + WebClient.Builder builder = + WebClientUtils.builder(httpClient).baseUrl(oAuth2.getAccessTokenUrl()); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); @@ -266,23 +285,30 @@ public Mono<String> getAccessTokenForGenericOAuth2(AuthorizationCodeCallbackDTO final String authorizationHeader = "Basic " + Base64.encode(clientCredentials); builder.defaultHeader("Authorization", authorizationHeader); } else { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "isAuthorizationHeader")); + return Mono.error( + new AppsmithException(AppsmithError.INVALID_PARAMETER, "isAuthorizationHeader")); } return builder.build() .method(HttpMethod.POST) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromFormData(map)) .exchange() - .doOnError(e -> Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, e))) + .doOnError( + e -> Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, e))) .flatMap(response -> { if (response.statusCode().is2xxSuccessful()) { oAuth2.setIsAuthorized(true); return response.bodyToMono(Map.class); } else { - log.debug("Unable to retrieve access token for datasource {} with error {}", datasourceStorage.getId(), response.statusCode()); + log.debug( + "Unable to retrieve access token for datasource {} with error {}", + datasourceStorage.getId(), + response.statusCode()); return Mono.error(new AppsmithException( AppsmithError.INTERNAL_SERVER_ERROR, - "Unable to retrieve access token for datasource {} with error {}", datasourceStorage.getId(), response.statusCode())); + "Unable to retrieve access token for datasource {} with error {}", + datasourceStorage.getId(), + response.statusCode())); } }) .flatMap(response -> { @@ -302,7 +328,8 @@ public Mono<String> getAccessTokenForGenericOAuth2(AuthorizationCodeCallbackDTO Object expiresInResponse = response.get(Authentication.EXPIRES_IN); Instant expiresAt = null; if (expiresAtResponse != null) { - expiresAt = Instant.ofEpochSecond(Long.parseLong(String.valueOf(expiresAtResponse))); + expiresAt = + Instant.ofEpochSecond(Long.parseLong(String.valueOf(expiresAtResponse))); } else if (expiresInResponse != null) { expiresAt = issuedAt.plusSeconds(Long.parseLong(String.valueOf(expiresInResponse))); } @@ -318,7 +345,8 @@ public Mono<String> getAccessTokenForGenericOAuth2(AuthorizationCodeCallbackDTO return datasourceStorageService.save(datasourceStorage); }); }) - // We have no use of the datasource object during redirection, we merely send the response as a success state + // We have no use of the datasource object during redirection, we merely send the response as a success + // state .flatMap((datasource -> this.getPageRedirectUrl(state, null))) .onErrorResume( e -> !(e instanceof AppsmithException @@ -341,26 +369,30 @@ private Mono<String> getPageRedirectUrl(String state, String error) { response = error; } final String responseStatus = response; - return newPageService.getById(pageId) - .map(newPage -> redirectOrigin + Entity.SLASH + - Entity.APPLICATIONS + Entity.SLASH + - newPage.getApplicationId() + Entity.SLASH + - Entity.PAGES + Entity.SLASH + - newPage.getId() + Entity.SLASH + - "edit" + Entity.SLASH + - Entity.DATASOURCE + Entity.SLASH + - datasourceId + - "?response_status=" + responseStatus + - "&view_mode=true") - .onErrorResume(e -> Mono.just( - redirectOrigin + Entity.SLASH + - Entity.APPLICATIONS + - "?response_status=" + responseStatus + - "&view_mode=true")); + return newPageService + .getById(pageId) + .map(newPage -> redirectOrigin + Entity.SLASH + Entity.APPLICATIONS + + Entity.SLASH + newPage.getApplicationId() + + Entity.SLASH + Entity.PAGES + + Entity.SLASH + newPage.getId() + + Entity.SLASH + "edit" + + Entity.SLASH + Entity.DATASOURCE + + Entity.SLASH + datasourceId + + "?response_status=" + + responseStatus + "&view_mode=true") + .onErrorResume(e -> Mono.just(redirectOrigin + Entity.SLASH + Entity.APPLICATIONS + + "?response_status=" + + responseStatus + "&view_mode=true")); } @Override - public Mono<String> getAppsmithToken(String datasourceId, String environmentId, String pageId, String branchName, ServerHttpRequest request, String importForGit) { + public Mono<String> getAppsmithToken( + String datasourceId, + String environmentId, + String pageId, + String branchName, + ServerHttpRequest request, + String importForGit) { // Check whether user has access to manage the datasource // Validate the datasource according to plugin type as well // If successful, then request for appsmithToken @@ -368,13 +400,15 @@ public Mono<String> getAppsmithToken(String datasourceId, String environmentId, // Return the appsmithToken to client Mono<DatasourceStorage> datasourceStorageMono = datasourceService .findById(datasourceId, datasourcePermission.getEditPermission()) - .flatMap(datasource1 -> datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, environmentId)) + .flatMap(datasource1 -> + datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, environmentId)) .cache(); final String redirectUri = redirectHelper.getRedirectDomain(request.getHeaders()); return datasourceStorageMono - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))) .flatMap(this::validateRequiredFieldsForGenericOAuth2) .flatMap(datasource -> Mono.zip( newPageService.findById(pageId, pagePermission.getReadPermission()), @@ -403,12 +437,16 @@ public Mono<String> getAppsmithToken(String datasourceId, String environmentId, integrationDTO.setPluginVersion(plugin.getVersion()); // TODO add authenticationDTO integrationDTO.setDatasourceId(datasourceId); - integrationDTO.setScope(((OAuth2) datasource.getDatasourceConfiguration().getAuthentication()).getScope()); + integrationDTO.setScope(((OAuth2) datasource + .getDatasourceConfiguration() + .getAuthentication()) + .getScope()); integrationDTO.setRedirectionDomain(redirectUri); return integrationDTO; })) .flatMap(integrationDTO -> { - return WebClientUtils.create(cloudServicesConfig.getBaseUrl() + "/api/v1/integrations/oauth/appsmith") + return WebClientUtils.create( + cloudServicesConfig.getBaseUrl() + "/api/v1/integrations/oauth/appsmith") .method(HttpMethod.POST) .body(BodyInserters.fromValue(integrationDTO)) .exchange() @@ -417,7 +455,8 @@ public Mono<String> getAppsmithToken(String datasourceId, String environmentId, return response.bodyToMono(Map.class); } else { log.debug("Unable to retrieve appsmith token with error {}", response.statusCode()); - return Mono.error(new AppsmithException(AppsmithError.AUTHENTICATION_FAILURE, + return Mono.error(new AppsmithException( + AppsmithError.AUTHENTICATION_FAILURE, "Unable to retrieve appsmith token with error " + response.statusCode())); } }) @@ -430,21 +469,31 @@ public Mono<String> getAppsmithToken(String datasourceId, String environmentId, .getDatasourceConfiguration() .getAuthentication() .setAuthenticationStatus(AuthenticationDTO.AuthenticationStatus.IN_PROGRESS); - return datasourceStorageService.save(datasourceStorage).thenReturn(appsmithToken); + return datasourceStorageService + .save(datasourceStorage) + .thenReturn(appsmithToken); }) - .onErrorMap(ConnectException.class, + .onErrorMap( + ConnectException.class, error -> new AppsmithException( AppsmithError.AUTHENTICATION_FAILURE, - "Unable to connect to Appsmith authentication server." - )); + "Unable to connect to Appsmith authentication server.")); }) - .onErrorResume(BaseException.class, error -> datasourceStorageMono.flatMap(datasourceStorage -> { - datasourceStorage.getDatasourceConfiguration().getAuthentication().setAuthenticationStatus(AuthenticationDTO.AuthenticationStatus.FAILURE); - return datasourceStorageService.save(datasourceStorage).then(Mono.error(error)); - })); + .onErrorResume( + BaseException.class, + error -> datasourceStorageMono.flatMap(datasourceStorage -> { + datasourceStorage + .getDatasourceConfiguration() + .getAuthentication() + .setAuthenticationStatus(AuthenticationDTO.AuthenticationStatus.FAILURE); + return datasourceStorageService + .save(datasourceStorage) + .then(Mono.error(error)); + })); } - public Mono<OAuth2ResponseDTO> getAccessTokenFromCloud(String datasourceId, String environmentId, String appsmithToken) { + public Mono<OAuth2ResponseDTO> getAccessTokenFromCloud( + String datasourceId, String environmentId, String appsmithToken) { // Check if user has access to manage datasource // If yes, check if datasource is in intermediate state // If yes, request for token and store in datasource @@ -452,21 +501,27 @@ public Mono<OAuth2ResponseDTO> getAccessTokenFromCloud(String datasourceId, Stri // Return control to client Mono<Datasource> datasourceMonoCache = datasourceService - .findById(datasourceId, datasourcePermission.getEditPermission()).cache(); + .findById(datasourceId, datasourcePermission.getEditPermission()) + .cache(); Mono<DatasourceStorage> datasourceStorageMonoCache = datasourceMonoCache - .flatMap(datasource1 -> datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, environmentId)) + .flatMap(datasource1 -> + datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, environmentId)) .cache(); return datasourceStorageMonoCache - .filter(datasourceStorage -> AuthenticationDTO.AuthenticationStatus.IN_PROGRESS - .equals(datasourceStorage.getDatasourceConfiguration().getAuthentication().getAuthenticationStatus())) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))) + .filter(datasourceStorage -> AuthenticationDTO.AuthenticationStatus.IN_PROGRESS.equals(datasourceStorage + .getDatasourceConfiguration() + .getAuthentication() + .getAuthenticationStatus())) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))) .flatMap(this::validateRequiredFieldsForGenericOAuth2) .flatMap(datasourceStorage -> { UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance(); try { - uriBuilder.uri(new URI(cloudServicesConfig.getBaseUrl() + "/api/v1/integrations/oauth/token")) + uriBuilder + .uri(new URI(cloudServicesConfig.getBaseUrl() + "/api/v1/integrations/oauth/token")) .queryParam("appsmithToken", appsmithToken); } catch (URISyntaxException e) { log.debug("Error while parsing access token URL.", e); @@ -475,55 +530,69 @@ public Mono<OAuth2ResponseDTO> getAccessTokenFromCloud(String datasourceId, Stri .method(HttpMethod.POST) .uri(uriBuilder.build(true).toUri()) .exchange() - .doOnError(e -> Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, e))) + .doOnError( + e -> Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, e))) .flatMap(response -> { if (response.statusCode().is2xxSuccessful()) { return response.bodyToMono(AuthenticationResponse.class); } else { log.debug("Unable to retrieve appsmith token with error {}", response.statusCode()); - return Mono.error(new AppsmithException(AppsmithError.AUTHENTICATION_FAILURE, + return Mono.error(new AppsmithException( + AppsmithError.AUTHENTICATION_FAILURE, "Unable to retrieve appsmith token with error " + response.statusCode())); } }) .flatMap(authenticationResponse -> { - OAuth2 oAuth2 = (OAuth2) datasourceStorage.getDatasourceConfiguration().getAuthentication(); + OAuth2 oAuth2 = (OAuth2) datasourceStorage + .getDatasourceConfiguration() + .getAuthentication(); oAuth2.setAuthenticationResponse(authenticationResponse); final Map tokenResponse = (Map) authenticationResponse.getTokenResponse(); if (tokenResponse != null && tokenResponse.containsKey("scope")) { - if (!new HashSet<>(Arrays.asList(String.valueOf(tokenResponse.get("scope")).split(" "))).containsAll( - oAuth2.getScope())) { - return Mono.error(new AppsmithException(AppsmithError.AUTHENTICATION_FAILURE, - "Please provide access to all the requested scopes to use the integration correctly.")); + if (!new HashSet<>(Arrays.asList(String.valueOf(tokenResponse.get("scope")) + .split(" "))) + .containsAll(oAuth2.getScope())) { + return Mono.error( + new AppsmithException( + AppsmithError.AUTHENTICATION_FAILURE, + "Please provide access to all the requested scopes to use the integration correctly.")); } } datasourceStorage.getDatasourceConfiguration().setAuthentication(oAuth2); - // When authentication scope is for specific sheets, we need to send token and project id + // When authentication scope is for specific sheets, we need to send token and project + // id String accessToken = ""; String projectID = ""; - if (oAuth2.getScope() != null && oAuth2.getScope().contains(FILE_SPECIFIC_DRIVE_SCOPE)) { + if (oAuth2.getScope() != null + && oAuth2.getScope().contains(FILE_SPECIFIC_DRIVE_SCOPE)) { accessToken = (String) tokenResponse.get(ACCESS_TOKEN_KEY); if (authenticationResponse.getProjectID() != null) { projectID = authenticationResponse.getProjectID(); } } - // when authentication scope is other than specific sheets, we need to set authentication status as success + // when authentication scope is other than specific sheets, we need to set + // authentication status as success // for specific sheets, it needs to remain in as in progress until files are selected - // Once files are selected, client sets authentication status as SUCCESS, we can find this code in + // Once files are selected, client sets authentication status as SUCCESS, we can find + // this code in // /app/client/src/sagas/DatasourcesSagas.ts, line 1195 Set<String> oauth2Scopes = oAuth2.getScope(); if (oauth2Scopes != null) { if (oauth2Scopes.contains(FILE_SPECIFIC_DRIVE_SCOPE)) { datasourceStorage - .getDatasourceConfiguration() - .getAuthentication() - .setAuthenticationStatus(AuthenticationDTO.AuthenticationStatus.IN_PROGRESS_PERMISSIONS_GRANTED); + .getDatasourceConfiguration() + .getAuthentication() + .setAuthenticationStatus( + AuthenticationDTO.AuthenticationStatus + .IN_PROGRESS_PERMISSIONS_GRANTED); } else { datasourceStorage - .getDatasourceConfiguration() - .getAuthentication() - .setAuthenticationStatus(AuthenticationDTO.AuthenticationStatus.SUCCESS); + .getDatasourceConfiguration() + .getAuthentication() + .setAuthenticationStatus( + AuthenticationDTO.AuthenticationStatus.SUCCESS); } } @@ -548,28 +617,35 @@ public Mono<OAuth2ResponseDTO> getAccessTokenFromCloud(String datasourceId, Stri response.setProjectID(projectID); response.setDatasource(datasourceStorage); return datasourceStorageService.save(datasourceStorage).thenReturn(response); - }) - .onErrorMap(ConnectException.class, + .onErrorMap( + ConnectException.class, error -> new AppsmithException( AppsmithError.AUTHENTICATION_FAILURE, - "Unable to connect to Appsmith authentication server." - )) - .onErrorResume(BaseException.class, error -> datasourceStorageMonoCache.flatMap(datasourceStorage -> { - datasourceStorage.getDatasourceConfiguration().getAuthentication() - .setAuthenticationStatus(AuthenticationDTO.AuthenticationStatus.FAILURE); - return datasourceStorageService.save(datasourceStorage).then(Mono.error(error)); - })); + "Unable to connect to Appsmith authentication server.")) + .onErrorResume( + BaseException.class, + error -> datasourceStorageMonoCache.flatMap(datasourceStorage -> { + datasourceStorage + .getDatasourceConfiguration() + .getAuthentication() + .setAuthenticationStatus(AuthenticationDTO.AuthenticationStatus.FAILURE); + return datasourceStorageService + .save(datasourceStorage) + .then(Mono.error(error)); + })); } public Mono<DatasourceStorage> refreshAuthentication(DatasourceStorage datasourceStorage) { // This method will always be called from a point where these validations have been performed - assert (datasourceStorage != null && - datasourceStorage.getDatasourceConfiguration() != null && - datasourceStorage.getDatasourceConfiguration().getAuthentication() instanceof OAuth2); + assert (datasourceStorage != null + && datasourceStorage.getDatasourceConfiguration() != null + && datasourceStorage.getDatasourceConfiguration().getAuthentication() instanceof OAuth2); OAuth2 oAuth2 = (OAuth2) datasourceStorage.getDatasourceConfiguration().getAuthentication(); - return pluginService.findById(datasourceStorage.getPluginId()) - .filter(plugin -> PluginType.SAAS.equals(plugin.getType()) || PluginType.REMOTE.equals(plugin.getType())) + return pluginService + .findById(datasourceStorage.getPluginId()) + .filter(plugin -> + PluginType.SAAS.equals(plugin.getType()) || PluginType.REMOTE.equals(plugin.getType())) .zipWith(configService.getInstanceId()) .flatMap(tuple -> { Plugin plugin = tuple.getT1(); @@ -581,7 +657,8 @@ public Mono<DatasourceStorage> refreshAuthentication(DatasourceStorage datasourc integrationDTO.setPluginName(plugin.getPluginName()); integrationDTO.setPluginVersion(plugin.getVersion()); - return WebClientUtils.create(cloudServicesConfig.getBaseUrl() + "/api/v1/integrations/oauth/refresh") + return WebClientUtils.create( + cloudServicesConfig.getBaseUrl() + "/api/v1/integrations/oauth/refresh") .method(HttpMethod.POST) .body(BodyInserters.fromValue(integrationDTO)) .exchange() @@ -591,30 +668,39 @@ public Mono<DatasourceStorage> refreshAuthentication(DatasourceStorage datasourc return response.bodyToMono(AuthenticationResponse.class); } else { log.debug("Unable to retrieve appsmith token with error {}", response.statusCode()); - return Mono.error(new AppsmithException(AppsmithError.AUTHENTICATION_FAILURE, - response.statusCode())); + return Mono.error(new AppsmithException( + AppsmithError.AUTHENTICATION_FAILURE, response.statusCode())); } }) .flatMap(authenticationResponse -> { - // We need to set refresh token here, because refresh token API call made to google, does not return refresh token in the response - // hence it was resulting in refresh token being set as null, that would break the authentication. - authenticationResponse.setRefreshToken(integrationDTO.getAuthenticationResponse().getRefreshToken()); + // We need to set refresh token here, because refresh token API call made to google, + // does not return refresh token in the response + // hence it was resulting in refresh token being set as null, that would break the + // authentication. + authenticationResponse.setRefreshToken(integrationDTO + .getAuthenticationResponse() + .getRefreshToken()); oAuth2.setAuthenticationResponse(authenticationResponse); datasourceStorage.getDatasourceConfiguration().setAuthentication(oAuth2); - // We need to return datasourceStorage object from the database so as to get decrypted token values, - // if we dont then, encrypted token values would be returned and subsequently those encrypted values would be used to call google apis + // We need to return datasourceStorage object from the database so as to get decrypted + // token values, + // if we dont then, encrypted token values would be returned and subsequently those + // encrypted values would be used to call google apis return datasourceStorageService .save(datasourceStorage) - .flatMap(ignore -> datasourceService.findByIdWithStorages(datasourceStorage.getDatasourceId()) - .flatMap(datasource -> datasourceStorageService.findByDatasourceAndEnvironmentId(datasource, datasourceStorage.getEnvironmentId()))); + .flatMap(ignore -> datasourceService + .findByIdWithStorages(datasourceStorage.getDatasourceId()) + .flatMap(datasource -> + datasourceStorageService.findByDatasourceAndEnvironmentId( + datasource, datasourceStorage.getEnvironmentId()))); }); }) .switchIfEmpty(Mono.just(datasourceStorage)) - .onErrorMap(ConnectException.class, + .onErrorMap( + ConnectException.class, error -> new AppsmithException( AppsmithError.AUTHENTICATION_FAILURE, - "Unable to connect to Appsmith authentication server." - )); + "Unable to connect to Appsmith authentication server.")); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCE.java index 05c385e36194..8cf22dea9236 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCE.java @@ -15,13 +15,14 @@ public interface CreateDBTablePageSolutionCE { * @param environmentId * @return generated pageDTO from the template resource */ - Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, - CRUDPageResourceDTO pageResourceDTO, - String environmentId, String branchName); + Mono<CRUDPageResponseDTO> createPageFromDBTable( + String defaultPageId, CRUDPageResourceDTO pageResourceDTO, String environmentId, String branchName); // TODO Remove this interface, once the client handles environmentId changes - Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, - CRUDPageResourceDTO pageResourceDTO, - String environmentId, String branchName, Boolean isTrueEnvironmentRequired); - -} \ No newline at end of file + Mono<CRUDPageResponseDTO> createPageFromDBTable( + String defaultPageId, + CRUDPageResourceDTO pageResourceDTO, + String environmentId, + String branchName, + Boolean isTrueEnvironmentRequired); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCEImpl.java index 45b5e1362287..6f76249e46e8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCEImpl.java @@ -72,7 +72,6 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; - @RequiredArgsConstructor @Slf4j public class CreateDBTablePageSolutionCEImpl implements CreateDBTablePageSolutionCE { @@ -109,7 +108,8 @@ public class CreateDBTablePageSolutionCEImpl implements CreateDBTablePageSolutio private static final String INSERT_QUERY = "InsertQuery"; - // Default SelectWidget dropdown value for SQL and Postgres template pages which will be used in select query for sort operator + // Default SelectWidget dropdown value for SQL and Postgres template pages which will be used in select query for + // sort operator private static final String SQL_DEFAULT_DROPDOWN_VALUE = "asc"; // Default SelectWidget dropdown value for MongoDB template page which will be used in find query for sort operator @@ -127,16 +127,25 @@ public class CreateDBTablePageSolutionCEImpl implements CreateDBTablePageSolutio private static final String PRIMARY_KEY = "__primaryKey__"; - // Widget fields those need to be mapped between template DB table and user's DB table in for which we are generating + // Widget fields those need to be mapped between template DB table and user's DB table in for which we are + // generating // a CRUD page private static final Set<String> WIDGET_FIELDS = Set.of( - "defaultText", "placeholderText", "text", "options", "defaultOptionValue", "primaryColumns", "isVisible", - "sourceData", "title", "primaryColumnId" - ); + "defaultText", + "placeholderText", + "text", + "options", + "defaultOptionValue", + "primaryColumns", + "isVisible", + "sourceData", + "title", + "primaryColumnId"); // Currently, we only support string matching (like/ilike etc) for WHERE operator in SelectQuery so the allowed // types will refer to the equivalent datatype in different databases - private static final Set<String> ALLOWED_TYPE_FOR_WHERE_CLAUSE = Set.of("string", "text", "varchar", "char", "character"); + private static final Set<String> ALLOWED_TYPE_FOR_WHERE_CLAUSE = + Set.of("string", "text", "varchar", "char", "character"); // Pattern to match all words in the text private static final Pattern WORD_PATTERN = Pattern.compile("\\w+"); @@ -147,17 +156,22 @@ public class CreateDBTablePageSolutionCEImpl implements CreateDBTablePageSolutio .registerTypeAdapter(HttpMethod.class, new HttpMethodConverter()) .create(); - public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, - CRUDPageResourceDTO pageResourceDTO, - String environmentId, String branchName, Boolean isTrueEnvironmentIdRequired) { + public Mono<CRUDPageResponseDTO> createPageFromDBTable( + String defaultPageId, + CRUDPageResourceDTO pageResourceDTO, + String environmentId, + String branchName, + Boolean isTrueEnvironmentIdRequired) { if (Boolean.TRUE.equals(isTrueEnvironmentIdRequired)) { - return datasourceService.findById(pageResourceDTO.getDatasourceId()) + return datasourceService + .findById(pageResourceDTO.getDatasourceId()) .map(Datasource::getWorkspaceId) .flatMap(workspaceId -> datasourceService.getTrueEnvironmentId(workspaceId, environmentId)) - .flatMap(trueEnvironmentId ->createPageFromDBTable(defaultPageId, pageResourceDTO, trueEnvironmentId, branchName)); + .flatMap(trueEnvironmentId -> + createPageFromDBTable(defaultPageId, pageResourceDTO, trueEnvironmentId, branchName)); } - return createPageFromDBTable(defaultPageId, pageResourceDTO, environmentId,branchName); + return createPageFromDBTable(defaultPageId, pageResourceDTO, environmentId, branchName); } /** @@ -169,28 +183,22 @@ public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, * @param environmentId * @return generated pageDTO from the template resource */ - public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, - CRUDPageResourceDTO pageResourceDTO, - String environmentId, - String branchName) { + public Mono<CRUDPageResponseDTO> createPageFromDBTable( + String defaultPageId, CRUDPageResourceDTO pageResourceDTO, String environmentId, String branchName) { /* - 1. Fetch page from the application - 2. Fetch datasource structure - 3. Fetch template application from json file - 4. Map template datasource columns with resource datasource - 5. Clone layout from template application page and update using the column map created in step 4 - 6. Clone and update actions in page from the template application - */ + 1. Fetch page from the application + 2. Fetch datasource structure + 3. Fetch template application from json file + 4. Map template datasource columns with resource datasource + 5. Clone layout from template application page and update using the column map created in step 4 + 6. Clone and update actions in page from the template application + */ // All SQL datasources will be mapped to postgresql as actionBody will be same and the same logic is used // in template application resource file : CRUD-DB-Table-Template-Application.json - final Set<String> sqlPackageNames = Set.of( - "mysql-plugin", - "mssql-plugin", - "redshift-plugin", - "snowflake-plugin" - ); + final Set<String> sqlPackageNames = + Set.of("mysql-plugin", "mssql-plugin", "redshift-plugin", "snowflake-plugin"); StringBuffer templateAutogeneratedKey = new StringBuffer(); if (pageResourceDTO.getTableName() == null || pageResourceDTO.getDatasourceId() == null) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "tableName and datasourceId")); @@ -205,7 +213,7 @@ public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, final Set<String> columns = pageResourceDTO.getColumns(); final Map<String, String> pluginSpecificParams = pageResourceDTO.getPluginSpecificParams(); - //Mapped columns along with table name between template and concerned DB table + // Mapped columns along with table name between template and concerned DB table Map<String, String> mappedColumnsAndTableName = new HashMap<>(); // Fetch branched applicationId if connected to git @@ -214,58 +222,54 @@ public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, Mono<DatasourceStorage> datasourceStorageMono = datasourceService .findById(datasourceId, datasourcePermission.getEditPermission()) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId)) - ) - .flatMap(datasource -> datasourceStorageService.findByDatasourceAndEnvironmentId(datasource, environmentId)) + new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceId))) + .flatMap(datasource -> + datasourceStorageService.findByDatasourceAndEnvironmentId(datasource, environmentId)) .filter(DatasourceStorage::getIsValid) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.INVALID_DATASOURCE, FieldName.DATASOURCE, datasourceId)) - ); + new AppsmithException(AppsmithError.INVALID_DATASOURCE, FieldName.DATASOURCE, datasourceId))); return datasourceStorageMono .zipWhen(datasourceStorage -> Mono.zip( - pageMono, - pluginService.findById(datasourceStorage.getPluginId()), - datasourceStructureSolution.getStructure(datasourceStorage, false) - ) - ) + pageMono, + pluginService.findById(datasourceStorage.getPluginId()), + datasourceStructureSolution.getStructure(datasourceStorage, false))) .flatMap(tuple -> { DatasourceStorage datasourceStorage = tuple.getT1(); NewPage page = tuple.getT2().getT1(); Plugin plugin = tuple.getT2().getT2(); DatasourceStructure datasourceStructure = tuple.getT2().getT3(); - final String layoutId = page.getUnpublishedPage().getLayouts().get(0).getId(); + final String layoutId = + page.getUnpublishedPage().getLayouts().get(0).getId(); final String savedPageId = page.getId(); ApplicationJson applicationJson = new ApplicationJson(); try { - AppsmithBeanUtils.copyNestedNonNullProperties(fetchTemplateApplication(FILE_PATH), applicationJson); + AppsmithBeanUtils.copyNestedNonNullProperties( + fetchTemplateApplication(FILE_PATH), applicationJson); } catch (IOException e) { log.error(e.getMessage()); } List<NewPage> pageList = applicationJson.getPageList(); if (pageList.isEmpty()) { - return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, TEMPLATE_APPLICATION_FILE)); + return Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, TEMPLATE_APPLICATION_FILE)); } NewPage templatePage = pageList.stream() .filter(newPage -> StringUtils.equalsIgnoreCase( - newPage.getUnpublishedPage().getName(), - plugin.getGenerateCRUDPageComponent() - ) - ) + newPage.getUnpublishedPage().getName(), plugin.getGenerateCRUDPageComponent())) .findAny() .orElse(null); if (templatePage == null) { - return Mono.error( - new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION, plugin.getName()) - ); + return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION, plugin.getName())); } - Layout layout = templatePage.getUnpublishedPage().getLayouts().get(0); + Layout layout = + templatePage.getUnpublishedPage().getLayouts().get(0); if (layout == null) { return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE)); @@ -278,64 +282,68 @@ public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, final String templateTableRef = TEMPLATE_TABLE_NAME.split("\\.", 2)[1]; final String tableRef = tableName.contains(".") ? tableName.split("\\.", 2)[1] : tableName; - DatasourceStorage templateDatasource = applicationJson - .getDatasourceList() - .stream() + DatasourceStorage templateDatasource = applicationJson.getDatasourceList().stream() .filter(datasource1 -> { - final String pluginRef = plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName(); + final String pluginRef = plugin.getPluginName() == null + ? plugin.getPackageName() + : plugin.getPluginName(); return StringUtils.equals(datasource1.getPluginId(), pluginRef) - // In template resource we have used Postgresql as a representative of all sql datasource + // In template resource we have used Postgresql as a representative of all sql + // datasource // as the actionBodies will be same - || (StringUtils.equals(datasource1.getPluginId(), Entity.POSTGRES_PLUGIN_PACKAGE_NAME) - && sqlPackageNames.contains(pluginRef)); + || (StringUtils.equals( + datasource1.getPluginId(), Entity.POSTGRES_PLUGIN_PACKAGE_NAME) + && sqlPackageNames.contains(pluginRef)); }) .findAny() .orElse(null); if (templateDatasource == null) { - return Mono.error( - new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION, plugin.getName()) - ); + return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION, plugin.getName())); } - DatasourceStorageStructure templateDatasourceStorageStructure = applicationJson - .getDatasourceConfigurationStructureList() - .stream() - .filter(configurationStructure -> StringUtils.equals(configurationStructure.getDatasourceId(), templateDatasource.getName())) - .findAny() - .orElse(null); - + DatasourceStorageStructure templateDatasourceStorageStructure = + applicationJson.getDatasourceConfigurationStructureList().stream() + .filter(configurationStructure -> StringUtils.equals( + configurationStructure.getDatasourceId(), templateDatasource.getName())) + .findAny() + .orElse(null); DatasourceStructure templateStructure = templateDatasourceStorageStructure.getStructure(); // We are supporting datasources for both with and without datasource structure. So if datasource - // structure is present then we can assign the mapping dynamically as per the template datasource tables. + // structure is present then we can assign the mapping dynamically as per the template datasource + // tables. // Those datasources for which we don't have structure like Google sheet etc we are following a - // protocol in template application that all the column headers should be named as col1, col2,.... colx + // protocol in template application that all the column headers should be named as col1, col2,.... + // colx String tableNameUsedInAction = tableName; if (templateStructure != null && !CollectionUtils.isEmpty(templateStructure.getTables())) { - Table templateTable = templateStructure.getTables() - .stream() + Table templateTable = templateStructure.getTables().stream() .filter(table1 -> StringUtils.contains(table1.getName(), templateTableRef)) .findAny() .orElse(null); Table table = getTable(datasourceStructure, tableName); if (table == null) { - return Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE_STRUCTURE, datasourceStorage.getName()) - ); + return Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + FieldName.DATASOURCE_STRUCTURE, + datasourceStorage.getName())); } // Use template body to extract the table name usage in actions // Sample template body : SELECT * FROM public."templateTable" LIMIT 10; - if (!CollectionUtils.isEmpty(table.getTemplates()) && table.getTemplates().get(0).getBody() != null) { + if (!CollectionUtils.isEmpty(table.getTemplates()) + && table.getTemplates().get(0).getBody() != null) { final Pattern pattern = Pattern.compile("[^ ]*" + tableRef + "[^ ,]*"); - final Matcher matcher = pattern.matcher(table.getTemplates().get(0).getBody()); + final Matcher matcher = + pattern.matcher(table.getTemplates().get(0).getBody()); tableNameUsedInAction = matcher.find() ? matcher.group(0) : tableName; } - mappedColumnsAndTableName.putAll(mapTableColumnNames(templateTable, table, searchColumn, columns, templateAutogeneratedKey)); + mappedColumnsAndTableName.putAll(mapTableColumnNames( + templateTable, table, searchColumn, columns, templateAutogeneratedKey)); } else { int colCount = 1; // If the structure and tables not present in the template datasource then map the columns from @@ -360,43 +368,46 @@ public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, mappedColumnsAndTableName.put(templateTableRef, tableName); Set<String> deletedWidgets = new HashSet<>(); - layout.setDsl( - extractAndUpdateAllWidgetFromDSL(layout.getDsl(), mappedColumnsAndTableName, deletedWidgets, templateAutogeneratedKey.toString()) - ); + layout.setDsl(extractAndUpdateAllWidgetFromDSL( + layout.getDsl(), + mappedColumnsAndTableName, + deletedWidgets, + templateAutogeneratedKey.toString())); - List<NewAction> templateActionList = applicationJson.getActionList() - .stream() + List<NewAction> templateActionList = applicationJson.getActionList().stream() .filter(newAction -> StringUtils.equalsIgnoreCase( newAction.getUnpublishedAction().getPageId(), - plugin.getGenerateCRUDPageComponent()) - ) + plugin.getGenerateCRUDPageComponent())) .peek(newAction -> newAction.setDefaultResources(page.getDefaultResources())) .collect(Collectors.toList()); - // Extract S3 bucket name from template application and map to users bucket. Bucket name is stored at + // Extract S3 bucket name from template application and map to users bucket. Bucket name is stored + // at // index 1 in plugin specified templates - if (Entity.S3_PLUGIN_PACKAGE_NAME.equals(plugin.getPackageName()) && !CollectionUtils.isEmpty(templateActionList)) { - final Map<String, Object> formData = templateActionList.get(0).getUnpublishedAction().getActionConfiguration().getFormData(); + if (Entity.S3_PLUGIN_PACKAGE_NAME.equals(plugin.getPackageName()) + && !CollectionUtils.isEmpty(templateActionList)) { + final Map<String, Object> formData = templateActionList + .get(0) + .getUnpublishedAction() + .getActionConfiguration() + .getFormData(); mappedColumnsAndTableName.put( - (String) ((Map<?, ?>) formData.get("bucket")).get("data"), - tableName - ); + (String) ((Map<?, ?>) formData.get("bucket")).get("data"), tableName); } log.debug("Going to update layout for page {} and layout {}", savedPageId, layoutId); - return layoutActionService.updateLayout(savedPageId, page.getApplicationId(), layoutId, layout) + return layoutActionService + .updateLayout(savedPageId, page.getApplicationId(), layoutId, layout) .then(Mono.zip( Mono.just(datasourceStorage), Mono.just(templateActionList), Mono.just(deletedWidgets), Mono.just(plugin), Mono.just(tableNameUsedInAction), - Mono.just(savedPageId) - )); + Mono.just(savedPageId))); }) .flatMap(tuple -> { - DatasourceStorage datasourceStorage = tuple.getT1(); List<NewAction> templateActionList = tuple.getT2(); Set<String> deletedWidgets = tuple.getT3(); @@ -404,36 +415,39 @@ public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, String tableNameInAction = tuple.getT5(); String savedPageId = tuple.getT6(); log.debug("Going to clone actions from template application for page {}", savedPageId); - return cloneActionsFromTemplateApplication(datasourceStorage, - tableNameInAction, - savedPageId, - templateActionList, - mappedColumnsAndTableName, - deletedWidgets, - pluginSpecificParams, - templateAutogeneratedKey.toString()) - + return cloneActionsFromTemplateApplication( + datasourceStorage, + tableNameInAction, + savedPageId, + templateActionList, + mappedColumnsAndTableName, + deletedWidgets, + pluginSpecificParams, + templateAutogeneratedKey.toString()) .flatMap(actionDTO -> StringUtils.equals(actionDTO.getName(), SELECT_QUERY) - || StringUtils.equals(actionDTO.getName(), FIND_QUERY) - || StringUtils.equals(actionDTO.getName(), LIST_QUERY) - ? layoutActionService.setExecuteOnLoad(actionDTO.getId(), true) : Mono.just(actionDTO)) - .then(applicationPageService.getPage(savedPageId, false) + || StringUtils.equals(actionDTO.getName(), FIND_QUERY) + || StringUtils.equals(actionDTO.getName(), LIST_QUERY) + ? layoutActionService.setExecuteOnLoad(actionDTO.getId(), true) + : Mono.just(actionDTO)) + .then(applicationPageService + .getPage(savedPageId, false) .flatMap(pageDTO -> { CRUDPageResponseDTO crudPage = new CRUDPageResponseDTO(); crudPage.setPage(pageDTO); createSuccessMessageAndSetAsset(plugin, crudPage); - return sendGenerateCRUDPageAnalyticsEvent(crudPage, datasourceStorage, plugin.getName()) + return sendGenerateCRUDPageAnalyticsEvent( + crudPage, datasourceStorage, plugin.getName()) .map(res -> { - PageDTO sanitisedResponse = responseUtils.updatePageDTOWithDefaultResources(res.getPage()); + PageDTO sanitisedResponse = + responseUtils.updatePageDTOWithDefaultResources( + res.getPage()); crudPage.setPage(sanitisedResponse); return crudPage; }); - }) - ); + })); }); } - /** * @param defaultApplicationId application from which the page should be fetched * @param defaultPageId default page for which equivalent branched page is going to be fetched @@ -441,7 +455,8 @@ public Mono<CRUDPageResponseDTO> createPageFromDBTable(String defaultPageId, * @param branchName branch of which the page needs to be fetched * @return NewPage if not present already with the incremental suffix number to avoid duplicate application names */ - private Mono<NewPage> getOrCreatePage(String defaultApplicationId, String defaultPageId, String tableName, String branchName) { + private Mono<NewPage> getOrCreatePage( + String defaultApplicationId, String defaultPageId, String tableName, String branchName) { /* 1. Check if the page is already available @@ -449,23 +464,32 @@ private Mono<NewPage> getOrCreatePage(String defaultApplicationId, String defaul 3. If page is not present create new page and return */ - log.debug("Fetching page from application {}, defaultPageId {}, branchName {}", defaultApplicationId, defaultPageId, branchName); + log.debug( + "Fetching page from application {}, defaultPageId {}, branchName {}", + defaultApplicationId, + defaultPageId, + branchName); if (defaultPageId != null) { - return newPageService.findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) + return newPageService + .findByBranchNameAndDefaultPageId(branchName, defaultPageId, pagePermission.getEditPermission()) .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, defaultPageId)) - ) + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE, defaultPageId))) .map(newPage -> { - Layout layout = newPage.getUnpublishedPage().getLayouts().get(0); - if (!CollectionUtils.isEmpty(layout.getWidgetNames()) && layout.getWidgetNames().size() > 1) { - throw new AppsmithException(AppsmithError.INVALID_CRUD_PAGE_REQUEST, "please use empty layout"); + Layout layout = + newPage.getUnpublishedPage().getLayouts().get(0); + if (!CollectionUtils.isEmpty(layout.getWidgetNames()) + && layout.getWidgetNames().size() > 1) { + throw new AppsmithException( + AppsmithError.INVALID_CRUD_PAGE_REQUEST, "please use empty layout"); } return newPage; }); } - return applicationService.findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) - .flatMapMany(childApplicationId -> newPageService.findByApplicationId(childApplicationId, pagePermission.getEditPermission(), false)) + return applicationService + .findBranchedApplicationId(branchName, defaultApplicationId, applicationPermission.getEditPermission()) + .flatMapMany(childApplicationId -> newPageService.findByApplicationId( + childApplicationId, pagePermission.getEditPermission(), false)) .collectList() .flatMap(pages -> { // Avoid duplicating page names @@ -481,7 +505,6 @@ private Mono<NewPage> getOrCreatePage(String defaultApplicationId, String defaul } maxCount = maxCount <= count ? count + 1 : maxCount; } - } pageName = maxCount != 0 ? pageName + maxCount : pageName; PageDTO page = new PageDTO(); @@ -507,8 +530,7 @@ private Table getTable(DatasourceStructure datasourceStructure, String tableName 2. Filter by tableName */ if (datasourceStructure != null) { - return datasourceStructure.getTables() - .stream() + return datasourceStructure.getTables().stream() .filter(table1 -> StringUtils.equals(table1.getName(), tableName)) .findAny() .orElse(null); @@ -526,15 +548,13 @@ private Table getTable(DatasourceStructure datasourceStructure, String tableName private ApplicationJson fetchTemplateApplication(String filePath) throws IOException { /* - 1. Fetch the content from the template json file - 2. De-Serialise data from the file - 3. Store the data in the application resource format - */ + 1. Fetch the content from the template json file + 2. De-Serialise data from the file + 3. Store the data in the application resource format + */ log.debug("Going to fetch template application"); final String jsonContent = StreamUtils.copyToString( - new DefaultResourceLoader().getResource(filePath).getInputStream(), - Charset.defaultCharset() - ); + new DefaultResourceLoader().getResource(filePath).getInputStream(), Charset.defaultCharset()); ApplicationJson applicationJson = gson.fromJson(jsonContent, ApplicationJson.class); return JsonSchemaMigration.migrateApplicationToLatestSchema(applicationJson); @@ -552,91 +572,95 @@ private ApplicationJson fetchTemplateApplication(String filePath) throws IOExcep * @param deletedWidgetNames Deleted column ref when template application have more # of columns than the users table * @return cloned and updated actions from template application actions */ - private Flux<ActionDTO> cloneActionsFromTemplateApplication(DatasourceStorage datasourceStorage, - String tableName, - String pageId, - List<NewAction> templateActionList, - Map<String, String> mappedColumns, - Set<String> deletedWidgetNames, - Map<String, String> pluginSpecificTemplateParams, - final String templateAutogeneratedKey) { + private Flux<ActionDTO> cloneActionsFromTemplateApplication( + DatasourceStorage datasourceStorage, + String tableName, + String pageId, + List<NewAction> templateActionList, + Map<String, String> mappedColumns, + Set<String> deletedWidgetNames, + Map<String, String> pluginSpecificTemplateParams, + final String templateAutogeneratedKey) { /* - 1. Clone actions from the template pages - 2. Update actionConfiguration to replace the template table fields with users datasource fields - stored in mapped columns - 3. Create new action - */ + 1. Clone actions from the template pages + 2. Update actionConfiguration to replace the template table fields with users datasource fields + stored in mapped columns + 3. Create new action + */ log.debug("Cloning actions from template application for pageId {}", pageId); - return Flux.fromIterable(templateActionList) - .flatMap(templateAction -> { - ActionDTO actionDTO = new ActionDTO(); - ActionConfiguration templateActionConfiguration = templateAction.getUnpublishedAction().getActionConfiguration(); - actionDTO.setPluginId(datasourceStorage.getPluginId()); - actionDTO.setId(null); - actionDTO.setDatasource(datasourceService.createDatasourceFromDatasourceStorage(datasourceStorage)); - actionDTO.setPageId(pageId); - actionDTO.setName(templateAction.getUnpublishedAction().getName()); - actionDTO.setDefaultResources(templateAction.getDefaultResources()); - - - String actionBody = templateActionConfiguration.getBody(); - actionDTO.setActionConfiguration(templateActionConfiguration); - ActionConfiguration actionConfiguration = actionDTO.getActionConfiguration(); - - List<Property> pluginSpecifiedTemplates = actionConfiguration.getPluginSpecifiedTemplates(); - if (actionBody != null) { - // If the primary key is autogenerated remove primaryKey's reference from InsertQuery - final String temp = mappedColumns.get(templateAutogeneratedKey); - if (!templateAutogeneratedKey.isEmpty() && INSERT_QUERY.equals(actionDTO.getName())) { - mappedColumns.put(templateAutogeneratedKey, DELETE_FIELD); - } - String body = actionBody.replaceFirst(TEMPLATE_TABLE_NAME, tableName); - final Matcher matcher = WORD_PATTERN.matcher(body); - actionConfiguration.setBody(matcher.replaceAll(key -> - mappedColumns.get(key.group()) == null ? key.group() : mappedColumns.get(key.group())) - ); - - // Reassign the previous column mapping - if (!templateAutogeneratedKey.isEmpty() && INSERT_QUERY.equals(actionDTO.getName())) { - mappedColumns.put(templateAutogeneratedKey, temp); - } - } + return Flux.fromIterable(templateActionList).flatMap(templateAction -> { + ActionDTO actionDTO = new ActionDTO(); + ActionConfiguration templateActionConfiguration = + templateAction.getUnpublishedAction().getActionConfiguration(); + actionDTO.setPluginId(datasourceStorage.getPluginId()); + actionDTO.setId(null); + actionDTO.setDatasource(datasourceService.createDatasourceFromDatasourceStorage(datasourceStorage)); + actionDTO.setPageId(pageId); + actionDTO.setName(templateAction.getUnpublishedAction().getName()); + actionDTO.setDefaultResources(templateAction.getDefaultResources()); + + String actionBody = templateActionConfiguration.getBody(); + actionDTO.setActionConfiguration(templateActionConfiguration); + ActionConfiguration actionConfiguration = actionDTO.getActionConfiguration(); + + List<Property> pluginSpecifiedTemplates = actionConfiguration.getPluginSpecifiedTemplates(); + if (actionBody != null) { + // If the primary key is autogenerated remove primaryKey's reference from InsertQuery + final String temp = mappedColumns.get(templateAutogeneratedKey); + if (!templateAutogeneratedKey.isEmpty() && INSERT_QUERY.equals(actionDTO.getName())) { + mappedColumns.put(templateAutogeneratedKey, DELETE_FIELD); + } + String body = actionBody.replaceFirst(TEMPLATE_TABLE_NAME, tableName); + final Matcher matcher = WORD_PATTERN.matcher(body); + actionConfiguration.setBody(matcher.replaceAll( + key -> mappedColumns.get(key.group()) == null ? key.group() : mappedColumns.get(key.group()))); + + // Reassign the previous column mapping + if (!templateAutogeneratedKey.isEmpty() && INSERT_QUERY.equals(actionDTO.getName())) { + mappedColumns.put(templateAutogeneratedKey, temp); + } + } - log.debug("Cloning plugin specified templates for action "); - if (!CollectionUtils.isEmpty(pluginSpecifiedTemplates)) { - pluginSpecifiedTemplates.forEach(property -> { - if (property != null && property.getValue() instanceof String) { - if (Entity.S3_PLUGIN_PACKAGE_NAME.equals(templateAction.getPluginId()) && mappedColumns.containsKey(property.getValue().toString())) { - // Replace template S3 bucket with user's bucket. Here we can't apply WORD_PATTERN - // matcher as the bucket name can be test.appsmith etc - property.setValue(mappedColumns.get(property.getValue().toString())); - } else if (property.getKey() != null && !CollectionUtils.isEmpty(pluginSpecificTemplateParams) - && pluginSpecificTemplateParams.get(property.getKey()) != null) { - property.setValue(pluginSpecificTemplateParams.get(property.getKey())); - } else { - final Matcher matcher = WORD_PATTERN.matcher(property.getValue().toString()); - property.setValue(matcher.replaceAll(key -> - mappedColumns.get(key.group()) == null ? key.group() : mappedColumns.get(key.group())) - ); - } - } - }); + log.debug("Cloning plugin specified templates for action "); + if (!CollectionUtils.isEmpty(pluginSpecifiedTemplates)) { + pluginSpecifiedTemplates.forEach(property -> { + if (property != null && property.getValue() instanceof String) { + if (Entity.S3_PLUGIN_PACKAGE_NAME.equals(templateAction.getPluginId()) + && mappedColumns.containsKey(property.getValue().toString())) { + // Replace template S3 bucket with user's bucket. Here we can't apply WORD_PATTERN + // matcher as the bucket name can be test.appsmith etc + property.setValue( + mappedColumns.get(property.getValue().toString())); + } else if (property.getKey() != null + && !CollectionUtils.isEmpty(pluginSpecificTemplateParams) + && pluginSpecificTemplateParams.get(property.getKey()) != null) { + property.setValue(pluginSpecificTemplateParams.get(property.getKey())); + } else { + final Matcher matcher = + WORD_PATTERN.matcher(property.getValue().toString()); + property.setValue(matcher.replaceAll(key -> mappedColumns.get(key.group()) == null + ? key.group() + : mappedColumns.get(key.group()))); + } } - - - log.debug("Cloning form data for action "); - Map<String, Object> formData = actionConfiguration.getFormData(); - return pluginExecutorHelper - .getPluginExecutorFromPackageName(templateAction.getPluginId()) - .map(pluginExecutor -> { - if (!CollectionUtils.isEmpty(formData)) { - pluginExecutor.updateCrudTemplateFormData(formData, mappedColumns, pluginSpecificTemplateParams); - } - actionDTO.setActionConfiguration(deleteUnwantedWidgetReferenceInActions(actionConfiguration, deletedWidgetNames)); - return actionDTO; - }) - .flatMap(action -> layoutActionService.createSingleAction(action, Boolean.FALSE)); }); + } + + log.debug("Cloning form data for action "); + Map<String, Object> formData = actionConfiguration.getFormData(); + return pluginExecutorHelper + .getPluginExecutorFromPackageName(templateAction.getPluginId()) + .map(pluginExecutor -> { + if (!CollectionUtils.isEmpty(formData)) { + pluginExecutor.updateCrudTemplateFormData( + formData, mappedColumns, pluginSpecificTemplateParams); + } + actionDTO.setActionConfiguration( + deleteUnwantedWidgetReferenceInActions(actionConfiguration, deletedWidgetNames)); + return actionDTO; + }) + .flatMap(action -> layoutActionService.createSingleAction(action, Boolean.FALSE)); + }); } /** @@ -648,16 +672,17 @@ private Flux<ActionDTO> cloneActionsFromTemplateApplication(DatasourceStorage da * @param tableColumns Specific columns provided by higher order function to act as values for Map * @return */ - private Map<String, String> mapTableColumnNames(Table sourceTable, - Table destTable, - final String searchColumn, - Set<String> tableColumns, - StringBuffer templateAutogeneratedKey) { + private Map<String, String> mapTableColumnNames( + Table sourceTable, + Table destTable, + final String searchColumn, + Set<String> tableColumns, + StringBuffer templateAutogeneratedKey) { /* - 1. Fetch and map primary keys for source and destination columns if available - 2. Map remaining column names between the sourceTable(key) and destinationTable(value) - */ + 1. Fetch and map primary keys for source and destination columns if available + 2. Map remaining column names between the sourceTable(key) and destinationTable(value) + */ log.debug("Mapping column names with template application for table {}", destTable.getName()); Map<String, String> mappedTableColumns = new HashMap<>(); @@ -667,11 +692,9 @@ private Map<String, String> mapTableColumnNames(Table sourceTable, sourceTable.getColumns().removeIf(column -> DEFAULT_SEARCH_COLUMN.equals(column.getName())); destTable.getColumns().removeIf(column -> searchColumn.equals(column.getName())); } else { - final String tempSearchColumn = destTable.getColumns() - .stream() - .filter(column -> ALLOWED_TYPE_FOR_WHERE_CLAUSE - .contains(column.getType().replaceAll("[^A-Za-z]+", "").toLowerCase()) - ) + final String tempSearchColumn = destTable.getColumns().stream() + .filter(column -> ALLOWED_TYPE_FOR_WHERE_CLAUSE.contains( + column.getType().replaceAll("[^A-Za-z]+", "").toLowerCase())) .findAny() .map(Column::getName) .orElse(null); @@ -697,14 +720,16 @@ private Map<String, String> mapTableColumnNames(Table sourceTable, int idx = 0; while (idx < sourceTableColumns.size() && idx < destTableColumns.size()) { if (!mappedTableColumns.containsKey(sourceTableColumns.get(idx).getName())) { - mappedTableColumns.put(sourceTableColumns.get(idx).getName(), destTableColumns.get(idx).getName()); + mappedTableColumns.put( + sourceTableColumns.get(idx).getName(), + destTableColumns.get(idx).getName()); } idx++; } if (idx < sourceTableColumns.size()) { while (idx < sourceTableColumns.size()) { - //This will act as a ref to delete the unwanted fields from actions and layout + // This will act as a ref to delete the unwanted fields from actions and layout mappedTableColumns.put(sourceTableColumns.get(idx).getName(), DELETE_FIELD); idx++; } @@ -719,7 +744,6 @@ private Map<String, String> mapTableColumnNames(Table sourceTable, * @param destTable Table from the users datasource whose keys will act as values for the MAP * @return Map of <sourceKeyColumnName, destinationKeyColumnName> */ - private Map<String, String> mapKeys(Table sourceTable, Table destTable, StringBuffer templateAutogeneratedKey) { /* @@ -730,8 +754,7 @@ private Map<String, String> mapKeys(Table sourceTable, Table destTable, StringBu // Map keys for SQL datasources if (DatasourceStructure.TableType.TABLE.equals(sourceTable.getType())) { final String sourceKey = "col1"; - DatasourceStructure.Key primaryKey = destTable.getKeys() - .stream() + DatasourceStructure.Key primaryKey = destTable.getKeys().stream() .filter(key -> key instanceof PrimaryKey) .findAny() .orElse(null); @@ -741,15 +764,18 @@ private Map<String, String> mapKeys(Table sourceTable, Table destTable, StringBu final String destKey = key.getColumnNames().get(0); primaryKeyNameMap.put(sourceKey, destKey); - // In updated template we are using __primaryKey__ inside JsonForm to omit the field which will prevent the + // In updated template we are using __primaryKey__ inside JsonForm to omit the field which will prevent + // the // duplicate key exception primaryKeyNameMap.put(PRIMARY_KEY, destKey); - // Check if the destKey is autogenerated, and save source column name which will be used to remove reference + // Check if the destKey is autogenerated, and save source column name which will be used to remove + // reference // from InsertQuery otherwise InsertQuery will fail with error : Trying to insert autogenerated field - templateAutogeneratedKey.append(destTable.getColumns() - .stream() - .filter(column -> column.getIsAutogenerated() != null && column.getIsAutogenerated() && destKey.equals(column.getName())) + templateAutogeneratedKey.append(destTable.getColumns().stream() + .filter(column -> column.getIsAutogenerated() != null + && column.getIsAutogenerated() + && destKey.equals(column.getName())) .findAny() .map(column -> sourceKey) .orElse("")); @@ -758,22 +784,22 @@ private Map<String, String> mapKeys(Table sourceTable, Table destTable, StringBu // Map keys for NoSQL datasources like MongoDB else if (DatasourceStructure.TableType.COLLECTION.equals(sourceTable.getType())) { final String sourceKey = FieldName.MONGO_UNESCAPED_ID; - List<Column> autogeneratedColumns = destTable.getColumns() - .stream() - // This makes sure only keys with instance of objectId will be considered as we don't have definitive + List<Column> autogeneratedColumns = destTable.getColumns().stream() + // This makes sure only keys with instance of objectId will be considered as we don't have + // definitive // structure like primaryKey in SQL for MongoDB. We can safely assume that these field will act as a // unique key which will then be used for update query .filter(column -> FieldName.OBJECT_ID.equals(column.getType())) .collect(Collectors.toList()); - String destKey = autogeneratedColumns - .stream() + String destKey = autogeneratedColumns.stream() .filter(column -> sourceKey.equals(column.getName())) .findAny() .map(Column::getName) .orElse(null); - // If column name "_id" is present in user's collection then map template datasource key "_id" with column name , + // If column name "_id" is present in user's collection then map template datasource key "_id" with column + // name , // else map template datasource key "_id" to any autogenerated field from user's collection if (destKey != null) { primaryKeyNameMap.put(sourceKey, destKey); @@ -796,17 +822,18 @@ else if (DatasourceStructure.TableType.COLLECTION.equals(sourceTable.getType())) * @param deletedWidgets store the widgets those are deleted from the dsl * @return updated dsl for the widget */ - private JSONObject extractAndUpdateAllWidgetFromDSL(JSONObject dsl, - Map<String, String> mappedColumnsAndTableNames, - Set<String> deletedWidgets, - final String templateAutogeneratedKey) { + private JSONObject extractAndUpdateAllWidgetFromDSL( + JSONObject dsl, + Map<String, String> mappedColumnsAndTableNames, + Set<String> deletedWidgets, + final String templateAutogeneratedKey) { /* - 1. Update dsl : Replace names of template columns with the user connected datasource columns - 2. Fetch the children of the current node in the DSL and recursively iterate over them - 3. Delete unwanted children - 4. Save and return updated dsl - */ + 1. Update dsl : Replace names of template columns with the user connected datasource columns + 2. Fetch the children of the current node in the DSL and recursively iterate over them + 3. Delete unwanted children + 4. Save and return updated dsl + */ if (dsl.get(FieldName.WIDGET_NAME) == null) { // This isn't a valid widget configuration. No need to traverse this. return dsl; @@ -829,16 +856,15 @@ private JSONObject extractAndUpdateAllWidgetFromDSL(JSONObject dsl, // If the children tag exists and there are entries within it if (!CollectionUtils.isEmpty(data)) { object.putAll(data); - JSONObject child = - extractAndUpdateAllWidgetFromDSL(object, mappedColumnsAndTableNames, deletedWidgets, templateAutogeneratedKey); + JSONObject child = extractAndUpdateAllWidgetFromDSL( + object, mappedColumnsAndTableNames, deletedWidgets, templateAutogeneratedKey); String widgetType = child.getAsString(FieldName.WIDGET_TYPE); if (FieldName.TABLE_WIDGET.equals(widgetType) || FieldName.CONTAINER_WIDGET.equals(widgetType) || FieldName.CANVAS_WIDGET.equals(widgetType) || FieldName.FORM_WIDGET.equals(widgetType) || FieldName.JSON_FORM_WIDGET.equals(widgetType) - || !child.toString().contains(DELETE_FIELD) - ) { + || !child.toString().contains(DELETE_FIELD)) { newChildren.add(child); } else { deletedWidgets.add(child.getAsString(FieldName.WIDGET_NAME)); @@ -854,24 +880,28 @@ private JSONObject extractAndUpdateAllWidgetFromDSL(JSONObject dsl, /** * This function will update the widget dsl fields mentioned in WIDGET_FIELDS */ - private JSONObject updateTemplateWidgets(JSONObject widgetDsl, Map<String, String> mappedColumnsAndTableNames, String templateAutogeneratedKey) { + private JSONObject updateTemplateWidgets( + JSONObject widgetDsl, Map<String, String> mappedColumnsAndTableNames, String templateAutogeneratedKey) { /* 1. Check the keys in widget dsl if needs to be changed 2. Replace the template column names with the user connected datasource column names using mappedColumnsAndTableNames */ - List<String> keys = widgetDsl.keySet().stream().filter(WIDGET_FIELDS::contains).collect(Collectors.toList()); + List<String> keys = + widgetDsl.keySet().stream().filter(WIDGET_FIELDS::contains).collect(Collectors.toList()); // This field will be used to check the default dropdown value for SelectWidget and only required SelectWidget's // options will be updated - String defaultDropdownValue = widgetDsl.containsKey(FieldName.DEFAULT_OPTION) - ? widgetDsl.getAsString(FieldName.DEFAULT_OPTION) : ""; + String defaultDropdownValue = + widgetDsl.containsKey(FieldName.DEFAULT_OPTION) ? widgetDsl.getAsString(FieldName.DEFAULT_OPTION) : ""; - // Handle special case for insert_modal for JSON form when auto-update is disabled for primary key. Don't exclude + // Handle special case for insert_modal for JSON form when auto-update is disabled for primary key. Don't + // exclude // the primary key from JSON form. InsertQuery also needs to add primary key in such events final String temp = mappedColumnsAndTableNames.get(PRIMARY_KEY); - if (StringUtils.isEmpty(templateAutogeneratedKey) && widgetDsl.getAsString(FieldName.WIDGET_NAME).equals(INSERT_FORM)) { + if (StringUtils.isEmpty(templateAutogeneratedKey) + && widgetDsl.getAsString(FieldName.WIDGET_NAME).equals(INSERT_FORM)) { mappedColumnsAndTableNames.remove(PRIMARY_KEY); } @@ -896,7 +926,7 @@ private JSONObject updateTemplateWidgets(JSONObject widgetDsl, Map<String, Strin } } else if (FieldName.DROP_DOWN_WIDGET.equals(widgetDsl.getAsString(FieldName.TYPE)) && !(SQL_DEFAULT_DROPDOWN_VALUE.equalsIgnoreCase(defaultDropdownValue) - || MONGO_DEFAULT_DROPDOWN_VALUE.equals(defaultDropdownValue))) { + || MONGO_DEFAULT_DROPDOWN_VALUE.equals(defaultDropdownValue))) { if (FieldName.OPTIONS.equals(key)) { // This will update the options field to include all the column names as label and value @@ -914,14 +944,19 @@ private JSONObject updateTemplateWidgets(JSONObject widgetDsl, Map<String, Strin widgetDsl.put(key, mappedColumnsAndTableNames.get(widgetDsl.getAsString(key))); } } else { - //Get separate words and map to tableColumns from widgetDsl + // Get separate words and map to tableColumns from widgetDsl Matcher matcher = WORD_PATTERN.matcher(widgetDsl.getAsString(key)); - widgetDsl.put(key, matcher.replaceAll(field -> - // Replace any special characters with "_" as all the special characters are replaced with "_" in - // table column widget - mappedColumnsAndTableNames.get(field.group()) == null ? - field.group() : mappedColumnsAndTableNames.get(field.group()).replaceAll("\\W+", "_") - )); + widgetDsl.put( + key, + matcher.replaceAll(field -> + // Replace any special characters with "_" as all the special characters are replaced + // with "_" in + // table column widget + mappedColumnsAndTableNames.get(field.group()) == null + ? field.group() + : mappedColumnsAndTableNames + .get(field.group()) + .replaceAll("\\W+", "_"))); } } @@ -938,27 +973,26 @@ private JSONObject updateTemplateWidgets(JSONObject widgetDsl, Map<String, Strin * @param deletedWidgetNames widgets for which references to be removed from the actionConfiguration * @return updated ActionConfiguration with deleteWidgets ref removed */ - private ActionConfiguration deleteUnwantedWidgetReferenceInActions(ActionConfiguration actionConfiguration, - Set<String> deletedWidgetNames) { - + private ActionConfiguration deleteUnwantedWidgetReferenceInActions( + ActionConfiguration actionConfiguration, Set<String> deletedWidgetNames) { /* - 1. Check for any delete widget reference within actionConfiguration - 2. Remove the fields related to delete widget from actionBody and pluginSpecifiedTemplates - 3. Return updated actionConfiguration - */ + 1. Check for any delete widget reference within actionConfiguration + 2. Remove the fields related to delete widget from actionBody and pluginSpecifiedTemplates + 3. Return updated actionConfiguration + */ // We need to check this for insertQuery for SQL if (StringUtils.containsIgnoreCase(actionConfiguration.getBody(), "VALUES")) { // Get separate words and map to tableColumns from widgetDsl Matcher matcher = WORD_PATTERN.matcher(actionConfiguration.getBody()); - actionConfiguration.setBody(matcher.replaceAll(field -> deletedWidgetNames.contains(field.group()) - ? DELETE_FIELD : field.group() - )); + actionConfiguration.setBody(matcher.replaceAll( + field -> deletedWidgetNames.contains(field.group()) ? DELETE_FIELD : field.group())); } - // When the connected datasource have less number of columns than template datasource, delete the unwanted fields + // When the connected datasource have less number of columns than template datasource, delete the unwanted + // fields /* Example 1: SQL UPDATE PUBLIC.USER SET @@ -1043,7 +1077,6 @@ else if (actionConfiguration.getBody().matches("(?s).*,[\\W]*?(?i)WHERE.*")) { return actionConfiguration; } - /** * This method removes the unwanted fields like column names and widget names from formData. * @@ -1051,8 +1084,7 @@ else if (actionConfiguration.getBody().matches("(?s).*,[\\W]*?(?i)WHERE.*")) { * @param regex to replace the unwanted field this will be useful when the connected datasource have less number of * columns than template datasource */ - private void removeUnwantedFieldRefFromFormData(Map<String, Object> formData, - String regex) { + private void removeUnwantedFieldRefFromFormData(Map<String, Object> formData, String regex) { for (Map.Entry<String, Object> property : formData.entrySet()) { if (property.getValue() != null) { if (property.getValue() instanceof String) { @@ -1075,40 +1107,39 @@ private void createSuccessMessageAndSetAsset(Plugin plugin, CRUDPageResponseDTO String displayWidget = Entity.S3_PLUGIN_PACKAGE_NAME.equals(plugin.getPackageName()) ? "List" : "Table"; String updateWidget = Entity.S3_PLUGIN_PACKAGE_NAME.equals(plugin.getPackageName()) ? "Filepicker" : "Form"; - String successUrl = Entity.S3_PLUGIN_PACKAGE_NAME.equals(plugin.getPackageName()) ? - Assets.GENERATE_CRUD_PAGE_SUCCESS_URL_S3 : Assets.GENERATE_CRUD_PAGE_SUCCESS_URL_TABULAR; + String successUrl = Entity.S3_PLUGIN_PACKAGE_NAME.equals(plugin.getPackageName()) + ? Assets.GENERATE_CRUD_PAGE_SUCCESS_URL_S3 + : Assets.GENERATE_CRUD_PAGE_SUCCESS_URL_TABULAR; crudPage.setSuccessImageUrl(successUrl); - // Field used to send success message after the successful page creation String successMessage = "We have generated the <b>" + displayWidget + "</b> from the <b>" + plugin.getName() - + " datasource</b>. You can use the <b>" + updateWidget + "</b> to modify it. Since all your " + - "data is already connected you can add more queries and modify the bindings"; + + " datasource</b>. You can use the <b>" + updateWidget + "</b> to modify it. Since all your " + + "data is already connected you can add more queries and modify the bindings"; crudPage.setSuccessMessage(successMessage); } - private Mono<CRUDPageResponseDTO> sendGenerateCRUDPageAnalyticsEvent(CRUDPageResponseDTO crudPage, DatasourceStorage datasourceStorage, String pluginName) { + private Mono<CRUDPageResponseDTO> sendGenerateCRUDPageAnalyticsEvent( + CRUDPageResponseDTO crudPage, DatasourceStorage datasourceStorage, String pluginName) { PageDTO page = crudPage.getPage(); - return sessionUserService.getCurrentUser() - .flatMap(currentUser -> { - try { - final Map<String, Object> data = Map.of( - "applicationId", page.getApplicationId(), - "pageId", page.getId(), - "pageName", page.getName(), - "pluginName", pluginName, - "datasourceId", datasourceStorage.getDatasourceId(), - "organizationId", datasourceStorage.getWorkspaceId(), - "orgId", datasourceStorage.getWorkspaceId() - ); - return analyticsService.sendEvent(AnalyticsEvents.GENERATE_CRUD_PAGE.getEventName(), currentUser.getUsername(), data) - .thenReturn(crudPage); - } catch (Exception e) { - log.warn("Error sending generate CRUD DB table page data point", e); - } - return Mono.just(crudPage); - }); + return sessionUserService.getCurrentUser().flatMap(currentUser -> { + try { + final Map<String, Object> data = Map.of( + "applicationId", page.getApplicationId(), + "pageId", page.getId(), + "pageName", page.getName(), + "pluginName", pluginName, + "datasourceId", datasourceStorage.getDatasourceId(), + "organizationId", datasourceStorage.getWorkspaceId(), + "orgId", datasourceStorage.getWorkspaceId()); + return analyticsService + .sendEvent(AnalyticsEvents.GENERATE_CRUD_PAGE.getEventName(), currentUser.getUsername(), data) + .thenReturn(crudPage); + } catch (Exception e) { + log.warn("Error sending generate CRUD DB table page data point", e); + } + return Mono.just(crudPage); + }); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStorageTransferSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStorageTransferSolutionCE.java index b8aee2935ced..6e183a8a0d84 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStorageTransferSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStorageTransferSolutionCE.java @@ -2,7 +2,6 @@ import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceStorage; -import com.appsmith.server.acl.AclPermission; import reactor.core.publisher.Mono; public interface DatasourceStorageTransferSolutionCE { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStorageTransferSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStorageTransferSolutionCEImpl.java index 991050698bd4..3a228963449f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStorageTransferSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStorageTransferSolutionCEImpl.java @@ -20,15 +20,15 @@ public class DatasourceStorageTransferSolutionCEImpl implements DatasourceStorag private final DatasourceStorageRepository datasourceStorageRepository; private final WorkspaceService workspaceService; - public DatasourceStorageTransferSolutionCEImpl(DatasourceRepository datasourceRepository, - DatasourceStorageRepository datasourceStorageRepository, - WorkspaceService workspaceService) { + public DatasourceStorageTransferSolutionCEImpl( + DatasourceRepository datasourceRepository, + DatasourceStorageRepository datasourceStorageRepository, + WorkspaceService workspaceService) { this.datasourceRepository = datasourceRepository; this.datasourceStorageRepository = datasourceStorageRepository; this.workspaceService = workspaceService; } - @Override public DatasourceStorage initializeDatasourceStorage(Datasource datasource, String environmentId) { return new DatasourceStorage(datasource, FieldName.UNUSED_ENVIRONMENT_ID); @@ -40,13 +40,13 @@ public Mono<DatasourceStorage> transferAndGetDatasourceStorage(Datasource dataso return this.transferDatasourceStorage(datasource, environmentId); } - @NotNull - private Mono<DatasourceStorage> transferDatasourceStorage(Datasource datasource, String environmentId) { + @NotNull private Mono<DatasourceStorage> transferDatasourceStorage(Datasource datasource, String environmentId) { final DatasourceStorage datasourceStorage = this.initializeDatasourceStorage(datasource, environmentId); datasource.setDatasourceConfiguration(null); datasource.setInvalids(null); datasource.setHasDatasourceStorage(true); - return datasourceStorageRepository.save(datasourceStorage) + return datasourceStorageRepository + .save(datasourceStorage) .zipWhen(datasourceStorage1 -> datasourceRepository.save(datasource)) .map(Tuple2::getT1); } @@ -55,7 +55,8 @@ private Mono<DatasourceStorage> transferDatasourceStorage(Datasource datasource, @Override public Mono<DatasourceStorage> transferToFallbackEnvironmentAndGetDatasourceStorage(Datasource datasource) { - return workspaceService.getDefaultEnvironmentId(datasource.getWorkspaceId()) + return workspaceService + .getDefaultEnvironmentId(datasource.getWorkspaceId()) .flatMap(environmentId -> transferDatasourceStorage(datasource, environmentId)); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCE.java index 4159c9abfcfb..ff763fe45865 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCE.java @@ -1,6 +1,5 @@ package com.appsmith.server.solutions.ce; -import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceStorage; import com.appsmith.external.models.DatasourceStructure; import reactor.core.publisher.Mono; @@ -9,6 +8,5 @@ public interface DatasourceStructureSolutionCE { Mono<DatasourceStructure> getStructure(String datasourceId, boolean ignoreCache, String environmentName); - Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorage, - boolean ignoreCache); + Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorage, boolean ignoreCache); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCEImpl.java index e680a0b1d4b8..8deb01dbb836 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCEImpl.java @@ -46,24 +46,21 @@ public class DatasourceStructureSolutionCEImpl implements DatasourceStructureSol @Override public Mono<DatasourceStructure> getStructure(String datasourceId, boolean ignoreCache, String environmentId) { - return datasourceService.findById(datasourceId, datasourcePermission.getExecutePermission()) - .zipWhen(datasource -> datasourceService - .getTrueEnvironmentId(datasource.getWorkspaceId(), environmentId)) - .flatMap(tuple2 -> datasourceStorageService.findByDatasourceAndEnvironmentId( - tuple2.getT1(), - tuple2.getT2())) + return datasourceService + .findById(datasourceId, datasourcePermission.getExecutePermission()) + .zipWhen(datasource -> + datasourceService.getTrueEnvironmentId(datasource.getWorkspaceId(), environmentId)) + .flatMap(tuple2 -> + datasourceStorageService.findByDatasourceAndEnvironmentId(tuple2.getT1(), tuple2.getT2())) .flatMap(datasourceStorage -> getStructure(datasourceStorage, ignoreCache)) .onErrorMap( IllegalArgumentException.class, - error -> - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - error.getMessage() - ) - ) + error -> new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, error.getMessage())) .onErrorMap(e -> { if (!(e instanceof AppsmithPluginException)) { - return new AppsmithPluginException(AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, e.getMessage()); + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, e.getMessage()); } return e; @@ -76,80 +73,82 @@ public Mono<DatasourceStructure> getStructure(String datasourceId, boolean ignor } @Override - public Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorage, - boolean ignoreCache) { + public Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorage, boolean ignoreCache) { if (Boolean.FALSE.equals(datasourceStorage.getIsValid())) { - return analyticsService.sendObjectEvent(AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED, - datasourceStorage, getAnalyticsPropertiesForTestEventStatus(datasourceStorage, false)) + return analyticsService + .sendObjectEvent( + AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED, + datasourceStorage, + getAnalyticsPropertiesForTestEventStatus(datasourceStorage, false)) .then(Mono.just(new DatasourceStructure())); } - Mono<DatasourceStorageStructure> configurationStructureMono = datasourceStructureService - .getByDatasourceIdAndEnvironmentId(datasourceStorage.getDatasourceId(), datasourceStorage.getEnvironmentId()); + Mono<DatasourceStorageStructure> configurationStructureMono = + datasourceStructureService.getByDatasourceIdAndEnvironmentId( + datasourceStorage.getDatasourceId(), datasourceStorage.getEnvironmentId()); Mono<DatasourceStructure> fetchAndStoreNewStructureMono = pluginExecutorHelper .getPluginExecutor(pluginService.findById(datasourceStorage.getPluginId())) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasourceStorage.getPluginId()))) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasourceStorage.getPluginId()))) .flatMap(pluginExecutor -> { - return datasourceContextService - .retryOnce(datasourceStorage, - resourceContext -> ((PluginExecutor<Object>) pluginExecutor) - .getStructure(resourceContext.getConnection(), - datasourceStorage.getDatasourceConfiguration())); + return datasourceContextService.retryOnce( + datasourceStorage, resourceContext -> ((PluginExecutor<Object>) pluginExecutor) + .getStructure( + resourceContext.getConnection(), + datasourceStorage.getDatasourceConfiguration())); }) .timeout(Duration.ofSeconds(GET_STRUCTURE_TIMEOUT_SECONDS)) .onErrorMap( TimeoutException.class, error -> new AppsmithPluginException( AppsmithPluginError.PLUGIN_GET_STRUCTURE_TIMEOUT_ERROR, - "Appsmith server timed out when fetching structure. Please reach out to appsmith " + - "customer support to resolve this." - ) - ) + "Appsmith server timed out when fetching structure. Please reach out to appsmith " + + "customer support to resolve this.")) .onErrorMap( StaleConnectionException.class, error -> new AppsmithPluginException( AppsmithPluginError.PLUGIN_ERROR, - "Appsmith server found a secondary stale connection. Please reach out to appsmith " + - "customer support to resolve this." - ) - ) + "Appsmith server found a secondary stale connection. Please reach out to appsmith " + + "customer support to resolve this.")) .onErrorMap( IllegalArgumentException.class, - error -> - new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - error.getMessage() - ) - ) + error -> new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, error.getMessage())) .onErrorMap(e -> { log.error("In the datasourceStorage structure error mode.", e); if (!(e instanceof AppsmithPluginException)) { - return new AppsmithPluginException(AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, e.getMessage()); + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, e.getMessage()); } return e; - }) - .onErrorResume(error -> analyticsService.sendObjectEvent(AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED, datasourceStorage, - getAnalyticsPropertiesForTestEventStatus(datasourceStorage, false, error)).then(Mono.error(error))) + .onErrorResume(error -> analyticsService + .sendObjectEvent( + AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED, + datasourceStorage, + getAnalyticsPropertiesForTestEventStatus(datasourceStorage, false, error)) + .then(Mono.error(error))) .flatMap(structure -> { String datasourceId = datasourceStorage.getDatasourceId(); String environmentId = datasourceStorage.getEnvironmentId(); - return analyticsService.sendObjectEvent(AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_SUCCESS, - datasourceStorage, getAnalyticsPropertiesForTestEventStatus(datasourceStorage, true, null)) - .then(!hasText(datasourceId) - ? Mono.empty() - : datasourceStructureService - .saveStructure(datasourceId, environmentId, structure) - .thenReturn(structure) - ); + return analyticsService + .sendObjectEvent( + AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_SUCCESS, + datasourceStorage, + getAnalyticsPropertiesForTestEventStatus(datasourceStorage, true, null)) + .then( + !hasText(datasourceId) + ? Mono.empty() + : datasourceStructureService + .saveStructure(datasourceId, environmentId, structure) + .thenReturn(structure)); }); - // This mono, when computed, will load the structure of the datasourceStorage by calling the plugin method. return configurationStructureMono .flatMap(configurationStructure -> { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCE.java index 85cd6179c114..a3cb7ade3dd7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCE.java @@ -4,9 +4,7 @@ import com.appsmith.external.models.TriggerResultDTO; import reactor.core.publisher.Mono; - public interface DatasourceTriggerSolutionCE { Mono<TriggerResultDTO> trigger(String datasourceId, String environmentId, TriggerRequestDTO triggerRequestDTO); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCEImpl.java index 3ed9c862eca6..c3322b5966de 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCEImpl.java @@ -47,15 +47,18 @@ public class DatasourceTriggerSolutionCEImpl implements DatasourceTriggerSolutio private final DatasourceContextService datasourceContextService; private final DatasourcePermission datasourcePermission; - public Mono<TriggerResultDTO> trigger(String datasourceId, String environmentId, TriggerRequestDTO triggerRequestDTO) { + public Mono<TriggerResultDTO> trigger( + String datasourceId, String environmentId, TriggerRequestDTO triggerRequestDTO) { Mono<Datasource> datasourceMonoCached = datasourceService - .findById(datasourceId, datasourcePermission.getExecutePermission()).cache(); + .findById(datasourceId, datasourcePermission.getExecutePermission()) + .cache(); Mono<DatasourceStorage> datasourceStorageMonoCached = datasourceMonoCached - .flatMap(datasource1 -> datasourceService.getTrueEnvironmentId(datasource1.getWorkspaceId(), environmentId) - .zipWhen(trueEnvironmentId -> - datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, trueEnvironmentId)) + .flatMap(datasource1 -> datasourceService + .getTrueEnvironmentId(datasource1.getWorkspaceId(), environmentId) + .zipWhen(trueEnvironmentId -> datasourceStorageService.findByDatasourceAndEnvironmentId( + datasource1, trueEnvironmentId)) .map(Tuple2::getT2)) .cache(); @@ -78,32 +81,33 @@ public Mono<TriggerResultDTO> trigger(String datasourceId, String environmentId, final ClientDataDisplayType displayType = triggerRequestDTO.getDisplayType(); - Mono<DatasourceStorage> validatedDatasourceStorageMono = datasourceStorageMonoCached - .flatMap(authenticationValidator::validateAuthentication); + Mono<DatasourceStorage> validatedDatasourceStorageMono = + datasourceStorageMonoCached.flatMap(authenticationValidator::validateAuthentication); // If the plugin has overridden and implemented the same, use the plugin result Mono<TriggerResultDTO> resultFromPluginMono = Mono.zip( - validatedDatasourceStorageMono, - pluginMono, - pluginExecutorMono) + validatedDatasourceStorageMono, pluginMono, pluginExecutorMono) .flatMap(tuple -> { final DatasourceStorage datasourceStorage = tuple.getT1(); final Plugin plugin = tuple.getT2(); final PluginExecutor pluginExecutor = tuple.getT3(); - return datasourceContextService.getDatasourceContext(datasourceStorage, plugin) + return datasourceContextService + .getDatasourceContext(datasourceStorage, plugin) // Now that we have the context (connection details), execute the action. // datasource remains unevaluated for datasource of DBAuth Type Authentication, // However the context comes from evaluated datasource. .flatMap(resourceContext -> ((PluginExecutor<Object>) pluginExecutor) - .trigger(resourceContext.getConnection(), + .trigger( + resourceContext.getConnection(), datasourceStorage.getDatasourceConfiguration(), triggerRequestDTO)); }); // If the plugin hasn't implemented the trigger function, go for the default implementation Mono<TriggerResultDTO> defaultResultMono = datasourceMonoCached - .flatMap(datasource1 -> datasourceService.getTrueEnvironmentId(datasource1.getWorkspaceId(), environmentId) + .flatMap(datasource1 -> datasourceService + .getTrueEnvironmentId(datasource1.getWorkspaceId(), environmentId) .zipWhen(trueEnvironmentId -> entitySelectorTriggerSolution(datasourceId, triggerRequestDTO, trueEnvironmentId)) .map(Tuple2::getT2)) @@ -123,53 +127,49 @@ public Mono<TriggerResultDTO> trigger(String datasourceId, String environmentId, return new TriggerResultDTO(result); }); - return resultFromPluginMono - .switchIfEmpty(defaultResultMono); + return resultFromPluginMono.switchIfEmpty(defaultResultMono); } - private Mono<Set<String>> entitySelectorTriggerSolution(String datasourceId, - TriggerRequestDTO request, - String environmentId) { + private Mono<Set<String>> entitySelectorTriggerSolution( + String datasourceId, TriggerRequestDTO request, String environmentId) { if (request.getDisplayType() == null) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, DISPLAY_TYPE)); } final Map<String, Object> parameters = request.getParameters(); - Mono<DatasourceStructure> structureMono = datasourceStructureSolution.getStructure(datasourceId, false, - environmentId); - - return structureMono - .map(structure -> { - Set<String> entityNames = new HashSet<>(); - List<DatasourceStructure.Table> tables = structure.getTables(); - if (tables != null && !tables.isEmpty()) { - - if (parameters == null || parameters.isEmpty()) { - // Top level entity requested. - for (DatasourceStructure.Table table : tables) { - entityNames.add(table.getName()); - } - - } else if (parameters.size() == 1) { - // Given a table name, return all the columns - String tableName = (String) parameters.get("tableName"); - Optional<DatasourceStructure.Table> tableNamePresent = tables - .stream() - .filter(table -> table.getName().equals(tableName)) - .findFirst(); - - if (tableNamePresent.isPresent()) { - DatasourceStructure.Table table = tableNamePresent.get(); - List<DatasourceStructure.Column> columns = table.getColumns(); - for (DatasourceStructure.Column column : columns) { - entityNames.add(column.getName()); - } - } + Mono<DatasourceStructure> structureMono = + datasourceStructureSolution.getStructure(datasourceId, false, environmentId); + + return structureMono.map(structure -> { + Set<String> entityNames = new HashSet<>(); + List<DatasourceStructure.Table> tables = structure.getTables(); + if (tables != null && !tables.isEmpty()) { + + if (parameters == null || parameters.isEmpty()) { + // Top level entity requested. + for (DatasourceStructure.Table table : tables) { + entityNames.add(table.getName()); + } + + } else if (parameters.size() == 1) { + // Given a table name, return all the columns + String tableName = (String) parameters.get("tableName"); + Optional<DatasourceStructure.Table> tableNamePresent = tables.stream() + .filter(table -> table.getName().equals(tableName)) + .findFirst(); + + if (tableNamePresent.isPresent()) { + DatasourceStructure.Table table = tableNamePresent.get(); + List<DatasourceStructure.Column> columns = table.getColumns(); + for (DatasourceStructure.Column column : columns) { + entityNames.add(column.getName()); } } + } + } - return entityNames; - }); + return entityNames; + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EnvManagerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EnvManagerCE.java index 185563d0b257..2f7970e4b0f6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EnvManagerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EnvManagerCE.java @@ -11,7 +11,6 @@ import java.util.List; import java.util.Map; - public interface EnvManagerCE { List<String> transformEnvContent(String envContent, Map<String, String> changes); @@ -20,7 +19,8 @@ public interface EnvManagerCE { Mono<EnvChangesResponseDTO> applyChangesFromMultipartFormData(MultiValueMap<String, Part> formData); - void setAnalyticsEventAction(Map<String, Object> properties, String newVariable, String originalVariable, String authEnv); + void setAnalyticsEventAction( + Map<String, Object> properties, String newVariable, String originalVariable, String authEnv); Mono<Map.Entry<String, String>> handleFileUpload(String key, List<Part> parts); @@ -37,5 +37,4 @@ public interface EnvManagerCE { Mono<Boolean> sendTestEmail(TestEmailConfigRequestDTO requestDTO); Mono<Void> download(ServerWebExchange exchange); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EnvManagerCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EnvManagerCEImpl.java index ab5dce2bc376..9ff482088659 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EnvManagerCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EnvManagerCEImpl.java @@ -121,29 +121,27 @@ public class EnvManagerCEImpl implements EnvManagerCE { * `VAR_NAME=`. It also defines two named capture groups, `name` and `value`, for the variable's name and value * respectively. */ - private static final Pattern ENV_VARIABLE_PATTERN = Pattern.compile( - "^(?<name>[A-Z\\d_]+)\\s*=\\s*(?<value>.*)$" - ); - - private static final Set<String> VARIABLE_WHITELIST = Stream.of(EnvVariables.values()) - .map(Enum::name) - .collect(Collectors.toUnmodifiableSet()); - - public EnvManagerCEImpl(SessionUserService sessionUserService, - UserService userService, - AnalyticsService analyticsService, - UserRepository userRepository, - EmailSender emailSender, - CommonConfig commonConfig, - EmailConfig emailConfig, - JavaMailSender javaMailSender, - GoogleRecaptchaConfig googleRecaptchaConfig, - FileUtils fileUtils, - PermissionGroupService permissionGroupService, - ConfigService configService, - UserUtils userUtils, - TenantService tenantService, - ObjectMapper objectMapper) { + private static final Pattern ENV_VARIABLE_PATTERN = Pattern.compile("^(?<name>[A-Z\\d_]+)\\s*=\\s*(?<value>.*)$"); + + private static final Set<String> VARIABLE_WHITELIST = + Stream.of(EnvVariables.values()).map(Enum::name).collect(Collectors.toUnmodifiableSet()); + + public EnvManagerCEImpl( + SessionUserService sessionUserService, + UserService userService, + AnalyticsService analyticsService, + UserRepository userRepository, + EmailSender emailSender, + CommonConfig commonConfig, + EmailConfig emailConfig, + JavaMailSender javaMailSender, + GoogleRecaptchaConfig googleRecaptchaConfig, + FileUtils fileUtils, + PermissionGroupService permissionGroupService, + ConfigService configService, + UserUtils userUtils, + TenantService tenantService, + ObjectMapper objectMapper) { this.sessionUserService = sessionUserService; this.userService = userService; @@ -188,20 +186,19 @@ public List<String> transformEnvContent(String envContent, Map<String, String> c if (changes.containsKey(APPSMITH_MAIL_HOST.name())) { changes.put( APPSMITH_MAIL_ENABLED.name(), - Boolean.toString(StringUtils.hasText(changes.get(APPSMITH_MAIL_HOST.name()))) - ); + Boolean.toString(StringUtils.hasText(changes.get(APPSMITH_MAIL_HOST.name())))); } if (changes.containsKey(APPSMITH_MAIL_USERNAME.name())) { changes.put( APPSMITH_MAIL_SMTP_AUTH.name(), - Boolean.toString(StringUtils.hasText(changes.get(APPSMITH_MAIL_USERNAME.name()))) - ); + Boolean.toString(StringUtils.hasText(changes.get(APPSMITH_MAIL_USERNAME.name())))); } final Set<String> remainingChangedNames = new HashSet<>(changes.keySet()); - final List<String> outLines = envContent.lines() + final List<String> outLines = envContent + .lines() .map(line -> { final Matcher matcher = ENV_VARIABLE_PATTERN.matcher(line); if (!matcher.matches()) { @@ -260,7 +257,6 @@ private String unescapeFromShell(String input) { } else { valueBuilder.append(c); - } } @@ -278,8 +274,7 @@ private Mono<Void> validateChanges(User user, Map<String, String> changes) { Set<String> adminEmails = TextUtils.csvToSet(emailCsv); if (!adminEmails.contains(user.getEmail())) { // user can not remove own email address return Mono.error(new AppsmithException( - AppsmithError.GENERIC_BAD_REQUEST, "Removing own email from Admin Email is not allowed" - )); + AppsmithError.GENERIC_BAD_REQUEST, "Removing own email from Admin Email is not allowed")); } } } @@ -297,7 +292,8 @@ private Set<String> allowedTenantConfiguration() { .map(field -> { JsonProperty jsonProperty = field.getDeclaredAnnotation(JsonProperty.class); return jsonProperty == null ? field.getName() : jsonProperty.value(); - }).collect(Collectors.toSet()); + }) + .collect(Collectors.toSet()); } /** @@ -318,13 +314,13 @@ private void setConfigurationByKey(TenantConfiguration tenantConfiguration, Stri field.set(tenantConfiguration, value); } catch (IllegalAccessException e) { // Catch the error, log it and then do nothing. - log.error("Got error while parsing the JSON annotations from TenantConfiguration class. Cause: ", e); + log.error( + "Got error while parsing the JSON annotations from TenantConfiguration class. Cause: ", e); } } } } - private Mono<Tenant> updateTenantConfiguration(String tenantId, Map<String, String> changes) { TenantConfiguration tenantConfiguration = new TenantConfiguration(); // Write the changes to the tenant collection in configuration field @@ -341,7 +337,8 @@ private Mono<Tenant> updateTenantConfiguration(String tenantId, Map<String, Stri @Override public Mono<EnvChangesResponseDTO> applyChanges(Map<String, String> changes) { - // This flow is pertinent for any variables that need to change in the .env file or be saved in the tenant configuration + // This flow is pertinent for any variables that need to change in the .env file or be saved in the tenant + // configuration return verifyCurrentUserIsSuper() .flatMap(user -> validateChanges(user, changes).thenReturn(user)) .flatMap(user -> { @@ -374,7 +371,8 @@ public Mono<EnvChangesResponseDTO> applyChanges(Map<String, String> changes) { } // For configuration variables, save the variables to the config collection instead of .env file - // We ideally want to migrate all variables from .env file to the config collection for better scalability + // We ideally want to migrate all variables from .env file to the config collection for better + // scalability // Write the changes to the tenant collection in configuration field return updateTenantConfiguration(user.getTenantId(), changes) .then(sendAnalyticsEvent(user, originalVariables, changes)) @@ -391,13 +389,16 @@ public Mono<EnvChangesResponseDTO> applyChanges(Map<String, String> changes) { } if (changesCopy.containsKey(APPSMITH_SIGNUP_ALLOWED_DOMAINS.name())) { - commonConfig.setAllowedDomainsString(changesCopy.remove(APPSMITH_SIGNUP_ALLOWED_DOMAINS.name())); + commonConfig.setAllowedDomainsString( + changesCopy.remove(APPSMITH_SIGNUP_ALLOWED_DOMAINS.name())); } if (changesCopy.containsKey(APPSMITH_ADMIN_EMAILS.name())) { commonConfig.setAdminEmails(changesCopy.remove(APPSMITH_ADMIN_EMAILS.name())); String oldAdminEmailsCsv = originalValues.get(APPSMITH_ADMIN_EMAILS.name()); - dependentTasks = dependentTasks.then(updateAdminUserPolicies(oldAdminEmailsCsv)).then(); + dependentTasks = dependentTasks + .then(updateAdminUserPolicies(oldAdminEmailsCsv)) + .then(); } if (changesCopy.containsKey(APPSMITH_MAIL_FROM.name())) { @@ -441,7 +442,8 @@ public Mono<EnvChangesResponseDTO> applyChanges(Map<String, String> changes) { } if (changesCopy.containsKey(APPSMITH_DISABLE_TELEMETRY.name())) { - commonConfig.setTelemetryDisabled("true".equals(changesCopy.remove(APPSMITH_DISABLE_TELEMETRY.name()))); + commonConfig.setTelemetryDisabled( + "true".equals(changesCopy.remove(APPSMITH_DISABLE_TELEMETRY.name()))); } return dependentTasks.thenReturn(new EnvChangesResponseDTO(true)); @@ -460,15 +462,15 @@ public Mono<EnvChangesResponseDTO> applyChangesFromMultipartFormData(MultiValueM return handleFileUpload(key, parts); } - return DataBufferUtils - .join(Flux.fromIterable(parts).flatMapSequential(Part::content)) + return DataBufferUtils.join(Flux.fromIterable(parts).flatMapSequential(Part::content)) .flatMap(dataBuffer -> { final byte[] content; try (InputStream inputStream = dataBuffer.asInputStream(true)) { content = inputStream.readAllBytes(); } catch (IOException e) { log.error("Unable to read multipart form data, in env change API", e); - return Mono.error(new AppsmithException(AppsmithError.IO_ERROR, "unable to read data")); + return Mono.error( + new AppsmithException(AppsmithError.IO_ERROR, "unable to read data")); } return Mono.just(Map.entry(key, new String(content, StandardCharsets.UTF_8))); }); @@ -478,8 +480,7 @@ public Mono<EnvChangesResponseDTO> applyChangesFromMultipartFormData(MultiValueM } @Override - @NotNull - public Mono<Map.Entry<String, String>> handleFileUpload(String key, List<Part> parts) { + @NotNull public Mono<Map.Entry<String, String>> handleFileUpload(String key, List<Part> parts) { return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION, "File upload is not supported")); } @@ -491,19 +492,25 @@ public Mono<Map.Entry<String, String>> handleFileUpload(String key, List<Part> p * @param changes Changes in the env variables * @return Mono of User */ - private Mono<Void> sendAnalyticsEvent(User user, Map<String, String> originalVariables, Map<String, String> changes) { + private Mono<Void> sendAnalyticsEvent( + User user, Map<String, String> originalVariables, Map<String, String> changes) { // Generate analytics event properties template(s) according to the env variable changes List<Map<String, Object>> analyticsEvents = getAnalyticsEvents(originalVariables, changes, new ArrayList<>()); // Currently supporting only one authentication method update in one env update call if (!analyticsEvents.isEmpty()) { - return analyticsService.sendObjectEvent(AnalyticsEvents.AUTHENTICATION_METHOD_CONFIGURATION, user, analyticsEvents.get(0)).then(); + return analyticsService + .sendObjectEvent(AnalyticsEvents.AUTHENTICATION_METHOD_CONFIGURATION, user, analyticsEvents.get(0)) + .then(); } // We cannot send sensitive information present as values in env to the analytics // Values are filtered and only variable names are sent Map<String, Object> analyticsProperties = Map.of(FieldName.UPDATED_INSTANCE_SETTINGS, changes.keySet()); - // A general INSTANCE_SETTING_UPDATED event is also sent for all admin settings changes other than Authentication method added/removed event - return analyticsService.sendObjectEvent(AnalyticsEvents.INSTANCE_SETTING_UPDATED, user, analyticsProperties).then(); + // A general INSTANCE_SETTING_UPDATED event is also sent for all admin settings changes other than + // Authentication method added/removed event + return analyticsService + .sendObjectEvent(AnalyticsEvents.INSTANCE_SETTING_UPDATED, user, analyticsProperties) + .then(); } /** @@ -514,8 +521,10 @@ private Mono<Void> sendAnalyticsEvent(User user, Map<String, String> originalVar * @param extraAuthEnvs To incorporate extra authentication methods in enterprise edition * @return A list of analytics event properties mappings. */ - public List<Map<String, Object>> getAnalyticsEvents(Map<String, String> originalVariables, Map<String, String> changes, List<String> extraAuthEnvs) { - List<String> authEnvs = new ArrayList<>(List.of(APPSMITH_OAUTH2_GOOGLE_CLIENT_ID.name(), APPSMITH_OAUTH2_GITHUB_CLIENT_ID.name())); + public List<Map<String, Object>> getAnalyticsEvents( + Map<String, String> originalVariables, Map<String, String> changes, List<String> extraAuthEnvs) { + List<String> authEnvs = new ArrayList<>( + List.of(APPSMITH_OAUTH2_GOOGLE_CLIENT_ID.name(), APPSMITH_OAUTH2_GITHUB_CLIENT_ID.name())); // Add extra authentication methods authEnvs.addAll(extraAuthEnvs); @@ -545,7 +554,8 @@ public List<Map<String, Object>> getAnalyticsEvents(Map<String, String> original * @param authEnv Env variable name */ @Override - public void setAnalyticsEventAction(Map<String, Object> properties, String newVariable, String originalVariable, String authEnv) { + public void setAnalyticsEventAction( + Map<String, Object> properties, String newVariable, String originalVariable, String authEnv) { // Authentication configuration added if (!newVariable.isEmpty() && (originalVariable == null || originalVariable.isEmpty())) { properties.put("action", "Added"); @@ -573,55 +583,54 @@ private Mono<Boolean> updateAdminUserPolicies(String oldAdminEmailsCsv) { Set<String> newUsers = new HashSet<>(newAdminEmails); newUsers.removeAll(oldAdminEmails); - Mono<Boolean> removedUsersMono = Flux.fromIterable(removedUsers).flatMap(userService::findByEmail) + Mono<Boolean> removedUsersMono = Flux.fromIterable(removedUsers) + .flatMap(userService::findByEmail) .collectList() .flatMap(users -> userUtils.removeSuperUser(users)); - Mono<Boolean> newUsersMono = Flux.fromIterable(newUsers).flatMap(userService::findByEmail) + Mono<Boolean> newUsersMono = Flux.fromIterable(newUsers) + .flatMap(userService::findByEmail) .collectList() .flatMap(users -> userUtils.makeSuperUser(users)); - return Mono.when(removedUsersMono, newUsersMono) - .then(Mono.just(TRUE)); + return Mono.when(removedUsersMono, newUsersMono).then(Mono.just(TRUE)); } @Override public Map<String, String> parseToMap(String content) { final Map<String, String> data = new HashMap<>(); - content.lines() - .forEach(line -> { - final Matcher matcher = ENV_VARIABLE_PATTERN.matcher(line); - if (matcher.matches()) { - final String name = matcher.group("name"); - if (VARIABLE_WHITELIST.contains(name)) { - data.put(name, unescapeFromShell(matcher.group("value"))); - } - } - }); + content.lines().forEach(line -> { + final Matcher matcher = ENV_VARIABLE_PATTERN.matcher(line); + if (matcher.matches()) { + final String name = matcher.group("name"); + if (VARIABLE_WHITELIST.contains(name)) { + data.put(name, unescapeFromShell(matcher.group("value"))); + } + } + }); return data; } @Override public Mono<Map<String, String>> getAll() { - return verifyCurrentUserIsSuper() - .flatMap(user -> { - final String originalContent; - try { - originalContent = Files.readString(Path.of(commonConfig.getEnvFilePath())); - } catch (NoSuchFileException e) { - return Mono.error(new AppsmithException(AppsmithError.ENV_FILE_NOT_FOUND)); - } catch (IOException e) { - log.error("Unable to read env file " + commonConfig.getEnvFilePath(), e); - return Mono.error(e); - } + return verifyCurrentUserIsSuper().flatMap(user -> { + final String originalContent; + try { + originalContent = Files.readString(Path.of(commonConfig.getEnvFilePath())); + } catch (NoSuchFileException e) { + return Mono.error(new AppsmithException(AppsmithError.ENV_FILE_NOT_FOUND)); + } catch (IOException e) { + log.error("Unable to read env file " + commonConfig.getEnvFilePath(), e); + return Mono.error(e); + } - // set the default values to response - Map<String, String> envKeyValueMap = parseToMap(originalContent); + // set the default values to response + Map<String, String> envKeyValueMap = parseToMap(originalContent); - return Mono.justOrEmpty(envKeyValueMap); - }); + return Mono.justOrEmpty(envKeyValueMap); + }); } /** @@ -643,105 +652,98 @@ public Mono<Map<String, String>> getAllNonEmpty() { @Override public Mono<User> verifyCurrentUserIsSuper() { - return userUtils.isCurrentUserSuperUser() - .flatMap(isSuperUser -> { - if (isSuperUser) { - return sessionUserService.getCurrentUser(); - } else { - return Mono.error(new AppsmithException(AppsmithError.UNAUTHORIZED_ACCESS)); - } - }); + return userUtils.isCurrentUserSuperUser().flatMap(isSuperUser -> { + if (isSuperUser) { + return sessionUserService.getCurrentUser(); + } else { + return Mono.error(new AppsmithException(AppsmithError.UNAUTHORIZED_ACCESS)); + } + }); } @Override public Mono<Void> restart() { - return verifyCurrentUserIsSuper() - .flatMap(user -> { - log.warn("Initiating restart via supervisor."); - try { - Runtime.getRuntime().exec(new String[]{ - "supervisorctl", - "restart", - "backend", - "editor", - "rts", - }); - } catch (IOException e) { - log.error("Error invoking supervisorctl to restart.", e); - return Mono.error(new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR)); - } - return Mono.empty(); + return verifyCurrentUserIsSuper().flatMap(user -> { + log.warn("Initiating restart via supervisor."); + try { + Runtime.getRuntime().exec(new String[] { + "supervisorctl", "restart", "backend", "editor", "rts", }); + } catch (IOException e) { + log.error("Error invoking supervisorctl to restart.", e); + return Mono.error(new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR)); + } + return Mono.empty(); + }); } @Override public Mono<Boolean> sendTestEmail(TestEmailConfigRequestDTO requestDTO) { - return verifyCurrentUserIsSuper() - .flatMap(user -> { - JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); - mailSender.setHost(requestDTO.getSmtpHost()); - mailSender.setPort(requestDTO.getSmtpPort()); - - Properties props = mailSender.getJavaMailProperties(); - props.put("mail.transport.protocol", "smtp"); + return verifyCurrentUserIsSuper().flatMap(user -> { + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost(requestDTO.getSmtpHost()); + mailSender.setPort(requestDTO.getSmtpPort()); - props.put("mail.smtp.starttls.enable", requestDTO.getStarttlsEnabled().toString()); + Properties props = mailSender.getJavaMailProperties(); + props.put("mail.transport.protocol", "smtp"); - props.put("mail.smtp.timeout", 7000); // 7 seconds + props.put( + "mail.smtp.starttls.enable", requestDTO.getStarttlsEnabled().toString()); - if (StringUtils.hasLength(requestDTO.getUsername())) { - props.put("mail.smtp.auth", "true"); - mailSender.setUsername(requestDTO.getUsername()); - mailSender.setPassword(requestDTO.getPassword()); - } else { - props.put("mail.smtp.auth", "false"); - } - props.put("mail.debug", "true"); - - SimpleMailMessage message = new SimpleMailMessage(); - message.setFrom(requestDTO.getFromEmail()); - message.setTo(user.getEmail()); - message.setSubject("Test email from Appsmith"); - message.setText("This is a test email from Appsmith, initiated from Admin Settings page. If you are seeing this, your email configuration is working!\n"); + props.put("mail.smtp.timeout", 7000); // 7 seconds - try { - mailSender.testConnection(); - } catch (MessagingException e) { - return Mono.error(new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, e.getMessage().trim())); - } + if (StringUtils.hasLength(requestDTO.getUsername())) { + props.put("mail.smtp.auth", "true"); + mailSender.setUsername(requestDTO.getUsername()); + mailSender.setPassword(requestDTO.getPassword()); + } else { + props.put("mail.smtp.auth", "false"); + } + props.put("mail.debug", "true"); + + SimpleMailMessage message = new SimpleMailMessage(); + message.setFrom(requestDTO.getFromEmail()); + message.setTo(user.getEmail()); + message.setSubject("Test email from Appsmith"); + message.setText( + "This is a test email from Appsmith, initiated from Admin Settings page. If you are seeing this, your email configuration is working!\n"); + + try { + mailSender.testConnection(); + } catch (MessagingException e) { + return Mono.error(new AppsmithException( + AppsmithError.GENERIC_BAD_REQUEST, e.getMessage().trim())); + } - try { - mailSender.send(message); - } catch (MailException mailException) { - log.error("failed to send test email", mailException); - return Mono.error(new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, mailException.getMessage())); - } - return Mono.just(TRUE); - }); + try { + mailSender.send(message); + } catch (MailException mailException) { + log.error("failed to send test email", mailException); + return Mono.error(new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, mailException.getMessage())); + } + return Mono.just(TRUE); + }); } @Override public Mono<Void> download(ServerWebExchange exchange) { - return verifyCurrentUserIsSuper() - .flatMap(user -> { - try { - File envFile = Path.of(commonConfig.getEnvFilePath()).toFile(); - FileInputStream envFileInputStream = new FileInputStream(envFile); - InputStream resourceFile = new ClassPathResource("docker-compose.yml").getInputStream(); - byte[] byteArray = fileUtils.createZip( - new FileUtils.ZipSourceFile(envFileInputStream, "stacks/configuration/docker.env"), - new FileUtils.ZipSourceFile(resourceFile, "docker-compose.yml") - ); - final ServerHttpResponse response = exchange.getResponse(); - response.setStatusCode(HttpStatus.OK); - response.getHeaders().set(HttpHeaders.CONTENT_TYPE, "application/zip"); - response.getHeaders().set("Content-Disposition", "attachment; filename=\"appsmith-config.zip\""); - return response.writeWith(Mono.just(new DefaultDataBufferFactory().wrap(byteArray))); - } catch (IOException e) { - log.error("failed to generate zip file", e); - return Mono.error(new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR)); - } - }); + return verifyCurrentUserIsSuper().flatMap(user -> { + try { + File envFile = Path.of(commonConfig.getEnvFilePath()).toFile(); + FileInputStream envFileInputStream = new FileInputStream(envFile); + InputStream resourceFile = new ClassPathResource("docker-compose.yml").getInputStream(); + byte[] byteArray = fileUtils.createZip( + new FileUtils.ZipSourceFile(envFileInputStream, "stacks/configuration/docker.env"), + new FileUtils.ZipSourceFile(resourceFile, "docker-compose.yml")); + final ServerHttpResponse response = exchange.getResponse(); + response.setStatusCode(HttpStatus.OK); + response.getHeaders().set(HttpHeaders.CONTENT_TYPE, "application/zip"); + response.getHeaders().set("Content-Disposition", "attachment; filename=\"appsmith-config.zip\""); + return response.writeWith(Mono.just(new DefaultDataBufferFactory().wrap(byteArray))); + } catch (IOException e) { + log.error("failed to generate zip file", e); + return Mono.error(new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR)); + } + }); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ForkExamplesWorkspaceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ForkExamplesWorkspaceCE.java index 5651e7076d73..e3bf92f22c27 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ForkExamplesWorkspaceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ForkExamplesWorkspaceCE.java @@ -9,19 +9,15 @@ import java.util.List; - public interface ForkExamplesWorkspaceCE { Mono<Workspace> forkExamplesWorkspace(); Mono<Workspace> forkWorkspaceForUser( - String templateWorkspaceId, - User user, - Flux<Application> applicationFlux, - Flux<Datasource> datasourceFlux - ); + String templateWorkspaceId, User user, Flux<Application> applicationFlux, Flux<Datasource> datasourceFlux); - Mono<List<String>> forkApplications(String toWorkspaceId, Flux<Application> applicationFlux, String sourceEnvironmentId); + Mono<List<String>> forkApplications( + String toWorkspaceId, Flux<Application> applicationFlux, String sourceEnvironmentId); Mono<List<String>> forkApplications( String toWorkspaceId, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ForkExamplesWorkspaceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ForkExamplesWorkspaceServiceCEImpl.java index 374be9e56aa7..ff755c145a8e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ForkExamplesWorkspaceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ForkExamplesWorkspaceServiceCEImpl.java @@ -80,9 +80,7 @@ public class ForkExamplesWorkspaceServiceCEImpl implements ForkExamplesWorkspace private final PagePermission pagePermission; public Mono<Workspace> forkExamplesWorkspace() { - return sessionUserService - .getCurrentUser() - .flatMap(this::forkExamplesWorkspace); + return sessionUserService.getCurrentUser().flatMap(this::forkExamplesWorkspace); } /** @@ -100,14 +98,14 @@ private Mono<Workspace> forkExamplesWorkspace(User user) { return Mono.empty(); } - return configService.getTemplateWorkspaceId() + return configService + .getTemplateWorkspaceId() .doOnError(error -> log.error("Error loading template workspace id config.", error)) .flatMap(templateWorkspaceId -> forkWorkspaceForUser( templateWorkspaceId, user, configService.getTemplateApplications(), - configService.getTemplateDatasources() - )); + configService.getTemplateDatasources())); } /** @@ -120,11 +118,7 @@ private Mono<Workspace> forkExamplesWorkspace(User user) { * @return Publishes the newly created workspace. */ public Mono<Workspace> forkWorkspaceForUser( - String templateWorkspaceId, - User user, - Flux<Application> applicationFlux, - Flux<Datasource> datasourceFlux - ) { + String templateWorkspaceId, User user, Flux<Application> applicationFlux, Flux<Datasource> datasourceFlux) { log.info("Cloning workspace id {}", templateWorkspaceId); @@ -138,8 +132,7 @@ public Mono<Workspace> forkWorkspaceForUser( if (workspace == null) { log.error( "Template examples workspace not found. Not creating a clone for user {}.", - user.getEmail() - ); + user.getEmail()); } }) .flatMap(workspace -> { @@ -161,19 +154,17 @@ public Mono<Workspace> forkWorkspaceForUser( userUpdate.setSource(user.getSource()); userUpdate.setGroupIds(null); userUpdate.setPolicies(null); - return Mono - .when( + return Mono.when( userService.update(user.getId(), userUpdate), - forkApplications(newWorkspace.getId(), applicationFlux, datasourceFlux, sourceEnvironmentId) - ) + forkApplications( + newWorkspace.getId(), applicationFlux, datasourceFlux, sourceEnvironmentId)) .thenReturn(newWorkspace); }) .doOnError(error -> log.error("Error cloning examples workspace.", error)); } - public Mono<List<String>> forkApplications(String toWorkspaceId, - Flux<Application> applicationFlux, - String sourceEnvironmentId) { + public Mono<List<String>> forkApplications( + String toWorkspaceId, Flux<Application> applicationFlux, String sourceEnvironmentId) { return forkApplications(toWorkspaceId, applicationFlux, Flux.empty(), sourceEnvironmentId); } @@ -186,10 +177,11 @@ public Mono<List<String>> forkApplications(String toWorkspaceId, * @param sourceEnvironmentId * @return Empty Mono. */ - public Mono<List<String>> forkApplications(String toWorkspaceId, - Flux<Application> applicationFlux, - Flux<Datasource> datasourceFlux, - String sourceEnvironmentId) { + public Mono<List<String>> forkApplications( + String toWorkspaceId, + Flux<Application> applicationFlux, + Flux<Datasource> datasourceFlux, + String sourceEnvironmentId) { final List<NewPage> clonedPages = new ArrayList<>(); final List<String> newApplicationIds = new ArrayList<>(); @@ -207,7 +199,8 @@ public Mono<List<String>> forkApplications(String toWorkspaceId, // The use case for this is: In the example workspace, we need a welcome tour which is based on // one of the datasource, to get the credentials of that datasource, we have set this value as True - final Mono<Datasource> clonerMono = forkDatasource(datasourceId, toWorkspaceId, Boolean.TRUE, sourceEnvironmentId); + final Mono<Datasource> clonerMono = + forkDatasource(datasourceId, toWorkspaceId, Boolean.TRUE, sourceEnvironmentId); clonedDatasourceMonos.put(datasourceId, clonerMono.cache()); return clonerMono; }) @@ -228,21 +221,18 @@ public Mono<List<String>> forkApplications(String toWorkspaceId, application.setExportWithConfiguration(null); application.setForkingEnabled(null); - final String defaultPageId = application.getPages() - .stream() + final String defaultPageId = application.getPages().stream() .filter(ApplicationPage::isDefault) .map(ApplicationPage::getId) .findFirst() .orElse(""); - return doOnlyForkApplicationObjectWithoutItsDependenciesAndReturnNonDeletedPages(application, newApplicationIds) - .flatMap(page -> - Mono.zip( - Mono.just(page), - Mono.just(defaultPageId.equals(page.getId())), - Mono.just(forkWithConfig) - ) - ); + return doOnlyForkApplicationObjectWithoutItsDependenciesAndReturnNonDeletedPages( + application, newApplicationIds) + .flatMap(page -> Mono.zip( + Mono.just(page), + Mono.just(defaultPageId.equals(page.getId())), + Mono.just(forkWithConfig))); }) .flatMap(tuple -> { final NewPage newPage = tuple.getT1(); @@ -265,10 +255,11 @@ public Mono<List<String>> forkApplications(String toWorkspaceId, page.setDefaultResources(defaults); return applicationPageService .createPage(page) - .flatMap(savedPage -> - isDefault - ? applicationPageService.makePageDefault(savedPage).thenReturn(savedPage) - : Mono.just(savedPage)) + .flatMap(savedPage -> isDefault + ? applicationPageService + .makePageDefault(savedPage) + .thenReturn(savedPage) + : Mono.just(savedPage)) .flatMap(savedPage -> newPageRepository.findById(savedPage.getId())) .flatMap(savedPage -> { clonedPages.add(savedPage); @@ -276,7 +267,10 @@ public Mono<List<String>> forkApplications(String toWorkspaceId, .findByPageId(templatePageId) .map(newAction -> { ActionDTO action = newAction.getUnpublishedAction(); - log.info("Preparing action for cloning {} {}.", action.getName(), newAction.getId()); + log.info( + "Preparing action for cloning {} {}.", + action.getName(), + newAction.getId()); action.setPageId(savedPage.getId()); action.setDefaultResources(null); return newAction; @@ -295,31 +289,42 @@ public Mono<List<String>> forkApplications(String toWorkspaceId, if (datasourceInsideAction.getId() != null) { final String datasourceId = datasourceInsideAction.getId(); if (!clonedDatasourceMonos.containsKey(datasourceId)) { - Mono<Datasource> datasourceMono = - forkDatasource(datasourceId, toWorkspaceId, forkWithConfig, sourceEnvironmentId) - .cache(); + Mono<Datasource> datasourceMono = forkDatasource( + datasourceId, + toWorkspaceId, + forkWithConfig, + sourceEnvironmentId) + .cache(); clonedDatasourceMonos.put(datasourceId, datasourceMono); } - actionMono = clonedDatasourceMonos.get(datasourceId) + actionMono = clonedDatasourceMonos + .get(datasourceId) .map(newDatasource -> { action.setDatasource(newDatasource); return action; }); } else { - // If this is an embedded datasource, the config will get forked along with the action + // If this is an embedded datasource, the config will get forked + // along with the action datasourceInsideAction.setWorkspaceId(toWorkspaceId); } } - return Mono.zip(actionMono + return Mono.zip( + actionMono .flatMap(actionDTO -> layoutActionService.createAction( - actionDTO, new AppsmithEventContext(AppsmithEventContextType.CLONE_PAGE), Boolean.FALSE) - ) + actionDTO, + new AppsmithEventContext( + AppsmithEventContextType.CLONE_PAGE), + Boolean.FALSE)) .map(ActionDTO::getId), Mono.justOrEmpty(originalActionId)); }) - // This call to `collectMap` will wait for all actions in all pages to have been processed, and so the + // This call to `collectMap` will wait for all actions in all pages to have been + // processed, and so the // `clonedPages` list will also contain all pages cloned. - .collect(HashMap<String, String>::new, (map, tuple2) -> map.put(tuple2.getT2(), tuple2.getT1())) + .collect( + HashMap<String, String>::new, + (map, tuple2) -> map.put(tuple2.getT2(), tuple2.getT1())) .flatMap(actionIdsMap -> { // Map of <originalCollectionId, clonedActionCollectionIds> HashMap<String, String> collectionIdsMap = new HashMap<>(); @@ -329,11 +334,14 @@ actionDTO, new AppsmithEventContext(AppsmithEventContextType.CLONE_PAGE), Boolea .flatMap(actionCollection -> { // Keep a record of the original collection id final String originalCollectionId = actionCollection.getId(); - log.info("Creating clone of action collection {}", originalCollectionId); + log.info( + "Creating clone of action collection {}", + originalCollectionId); // Sanitize them actionCollection.makePristine(); actionCollection.setPublishedCollection(null); - final ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); + final ActionCollectionDTO unpublishedCollection = + actionCollection.getUnpublishedCollection(); unpublishedCollection.setPageId(savedPage.getId()); DefaultResources defaultResources = new DefaultResources(); @@ -344,58 +352,88 @@ actionDTO, new AppsmithEventContext(AppsmithEventContextType.CLONE_PAGE), Boolea actionCollection.setApplicationId(savedPage.getApplicationId()); DefaultResources defaultResources1 = new DefaultResources(); - defaultResources1.setApplicationId(savedPage.getApplicationId()); + defaultResources1.setApplicationId( + savedPage.getApplicationId()); actionCollection.setDefaultResources(defaultResources1); - actionCollectionService.generateAndSetPolicies(savedPage, actionCollection); + actionCollectionService.generateAndSetPolicies( + savedPage, actionCollection); - // Replace all action Ids from map and replace with newly created actionIds + // Replace all action Ids from map and replace with newly + // created actionIds final Map<String, String> newActionIds = new HashMap<>(); unpublishedCollection .getDefaultToBranchedActionIdsMap() .forEach((defaultActionId, oldActionId) -> { if (StringUtils.hasLength(oldActionId) - && StringUtils.hasLength(actionIdsMap.get(oldActionId))) { + && StringUtils.hasLength( + actionIdsMap.get(oldActionId))) { - // As this is a new application and not connected + // As this is a new application and not + // connected // through git branch, the default and newly // created actionId will be same - newActionIds.put(actionIdsMap.get(oldActionId), + newActionIds.put( + actionIdsMap.get(oldActionId), actionIdsMap.get(oldActionId)); } else { - log.debug("Unable to find action {} while forking inside ID map: {}", - oldActionId, actionIdsMap); + log.debug( + "Unable to find action {} while forking inside ID map: {}", + oldActionId, + actionIdsMap); } }); - unpublishedCollection.setDefaultToBranchedActionIdsMap(newActionIds); + unpublishedCollection.setDefaultToBranchedActionIdsMap( + newActionIds); - return actionCollectionService.create(actionCollection) + return actionCollectionService + .create(actionCollection) .flatMap(clonedActionCollection -> { - if (StringUtils.isEmpty(clonedActionCollection.getDefaultResources().getCollectionId())) { - ActionCollection updates = new ActionCollection(); - DefaultResources defaultResources2 = clonedActionCollection.getDefaultResources(); - defaultResources2.setCollectionId(clonedActionCollection.getId()); + if (StringUtils.isEmpty(clonedActionCollection + .getDefaultResources() + .getCollectionId())) { + ActionCollection updates = + new ActionCollection(); + DefaultResources defaultResources2 = + clonedActionCollection + .getDefaultResources(); + defaultResources2.setCollectionId( + clonedActionCollection.getId()); updates.setDefaultResources(defaultResources2); - return actionCollectionService.update(clonedActionCollection.getId(), updates); + return actionCollectionService.update( + clonedActionCollection.getId(), + updates); } return Mono.just(clonedActionCollection); }) .flatMap(clonedActionCollection -> { - collectionIdsMap.put(originalCollectionId, clonedActionCollection.getId()); + collectionIdsMap.put( + originalCollectionId, + clonedActionCollection.getId()); return Flux.fromIterable(newActionIds.values()) .flatMap(newActionService::findById) .flatMap(newlyCreatedAction -> { - ActionDTO unpublishedAction = newlyCreatedAction.getUnpublishedAction(); - unpublishedAction.setCollectionId(clonedActionCollection.getId()); - unpublishedAction.getDefaultResources().setCollectionId(clonedActionCollection.getId()); - return newActionService.update(newlyCreatedAction.getId(), newlyCreatedAction); + ActionDTO unpublishedAction = + newlyCreatedAction + .getUnpublishedAction(); + unpublishedAction.setCollectionId( + clonedActionCollection.getId()); + unpublishedAction + .getDefaultResources() + .setCollectionId( + clonedActionCollection + .getId()); + return newActionService.update( + newlyCreatedAction.getId(), + newlyCreatedAction); }) .collectList(); }); }) .collectList() - .then(Mono.zip(Mono.just(actionIdsMap), Mono.just(collectionIdsMap))); + .then(Mono.zip( + Mono.just(actionIdsMap), Mono.just(collectionIdsMap))); }); }); }) @@ -408,9 +446,8 @@ actionDTO, new AppsmithEventContext(AppsmithEventContextType.CLONE_PAGE), Boolea .collectList(); } - private Flux<NewPage> updateActionAndCollectionsIdsInForkedPages(List<NewPage> clonedPages, - Map<String, String> actionIdsMap, - Map<String, String> actionCollectionIdsMap) { + private Flux<NewPage> updateActionAndCollectionsIdsInForkedPages( + List<NewPage> clonedPages, Map<String, String> actionIdsMap, Map<String, String> actionCollectionIdsMap) { final List<Mono<NewPage>> pageSaveMonos = new ArrayList<>(); for (final NewPage page : clonedPages) { @@ -424,7 +461,8 @@ private Flux<NewPage> updateActionAndCollectionsIdsInForkedPages(List<NewPage> c for (final Layout layout : page.getUnpublishedPage().getLayouts()) { if (layout.getLayoutOnLoadActions() != null) { - shouldSave = updateOnLoadActionsWithNewActionAndCollectionIds(actionIdsMap, actionCollectionIdsMap, page.getId(), shouldSave, layout); + shouldSave = updateOnLoadActionsWithNewActionAndCollectionIds( + actionIdsMap, actionCollectionIdsMap, page.getId(), shouldSave, layout); } } @@ -436,11 +474,12 @@ private Flux<NewPage> updateActionAndCollectionsIdsInForkedPages(List<NewPage> c return Flux.concat(pageSaveMonos); } - private boolean updateOnLoadActionsWithNewActionAndCollectionIds(Map<String, String> actionIdsMap, - Map<String, String> collectionIdsMap, - String pageId, - boolean shouldSave, - Layout layout) { + private boolean updateOnLoadActionsWithNewActionAndCollectionIds( + Map<String, String> actionIdsMap, + Map<String, String> collectionIdsMap, + String pageId, + boolean shouldSave, + Layout layout) { for (final Set<DslActionDTO> actionSet : layout.getLayoutOnLoadActions()) { for (final DslActionDTO actionDTO : actionSet) { if (actionIdsMap.containsKey(actionDTO.getId())) { @@ -457,8 +496,7 @@ private boolean updateOnLoadActionsWithNewActionAndCollectionIds(Map<String, Str log.error( "Couldn't find cloned action ID for publishedLayoutOnLoadAction {} in page {}", actionDTO.getId(), - pageId - ); + pageId); } } } @@ -473,42 +511,39 @@ private boolean updateOnLoadActionsWithNewActionAndCollectionIds(Map<String, Str * @param applicationIds : List where the cloned new application's id would be stored * @return A flux that yields all the pages in the template application */ - private Flux<NewPage> doOnlyForkApplicationObjectWithoutItsDependenciesAndReturnNonDeletedPages(Application application, List<String> applicationIds) { + private Flux<NewPage> doOnlyForkApplicationObjectWithoutItsDependenciesAndReturnNonDeletedPages( + Application application, List<String> applicationIds) { final String templateApplicationId = application.getId(); - return forkApplicationDocument(application) - .flatMapMany( - savedApplication -> { - applicationIds.add(savedApplication.getId()); - return forkThemes(application, savedApplication) - .thenMany(newPageRepository - .findByApplicationIdAndNonDeletedEditMode( - templateApplicationId, - pagePermission.getReadPermission()) - .map(newPage -> { - log.info("Preparing page for cloning {} {}.", - newPage.getUnpublishedPage().getName(), newPage.getId()); - newPage.setApplicationId(savedApplication.getId()); - return newPage; - }) - ); - } - ); + return forkApplicationDocument(application).flatMapMany(savedApplication -> { + applicationIds.add(savedApplication.getId()); + return forkThemes(application, savedApplication) + .thenMany(newPageRepository + .findByApplicationIdAndNonDeletedEditMode( + templateApplicationId, pagePermission.getReadPermission()) + .map(newPage -> { + log.info( + "Preparing page for cloning {} {}.", + newPage.getUnpublishedPage().getName(), + newPage.getId()); + newPage.setApplicationId(savedApplication.getId()); + return newPage; + })); + }); } private Mono<UpdateResult> forkThemes(Application srcApplication, Application destApplication) { return Mono.zip( - themeService.cloneThemeToApplication(srcApplication.getEditModeThemeId(), destApplication), - themeService.cloneThemeToApplication(srcApplication.getPublishedModeThemeId(), destApplication) - ).flatMap(themes -> { - Theme editModeTheme = themes.getT1(); - Theme publishedModeTheme = themes.getT2(); - return applicationService.setAppTheme( - destApplication.getId(), - editModeTheme.getId(), - publishedModeTheme.getId(), - applicationPermission.getEditPermission() - ); - }); + themeService.cloneThemeToApplication(srcApplication.getEditModeThemeId(), destApplication), + themeService.cloneThemeToApplication(srcApplication.getPublishedModeThemeId(), destApplication)) + .flatMap(themes -> { + Theme editModeTheme = themes.getT1(); + Theme publishedModeTheme = themes.getT2(); + return applicationService.setAppTheme( + destApplication.getId(), + editModeTheme.getId(), + publishedModeTheme.getId(), + applicationPermission.getEditPermission()); + }); } private Mono<Application> forkApplicationDocument(Application application) { @@ -531,15 +566,15 @@ private Mono<Application> forkApplicationDocument(Application application) { Mono<User> userMono = sessionUserService.getCurrentUser(); - return applicationPageService.setApplicationPolicies(userMono, workspaceId, application) + return applicationPageService + .setApplicationPolicies(userMono, workspaceId, application) .flatMap(applicationService::createDefaultApplication); } - // forkWithConfiguration parameter if TRUE, returns the datasource with credentials else returns datasources without credentials - public Mono<Datasource> forkDatasource(String datasourceId, - String toWorkspaceId, - Boolean forkWithConfiguration, - String sourceEnvironmentId) { + // forkWithConfiguration parameter if TRUE, returns the datasource with credentials else returns datasources without + // credentials + public Mono<Datasource> forkDatasource( + String datasourceId, String toWorkspaceId, Boolean forkWithConfiguration, String sourceEnvironmentId) { final Mono<String> destinationEnvironmentIdMono = workspaceService.getDefaultEnvironmentId(toWorkspaceId); @@ -548,7 +583,8 @@ public Mono<Datasource> forkDatasource(String datasourceId, .collectList(); // this datasource is in workspace from which it's getting forked - Mono<Datasource> datasourceToForkMono = datasourceService.findByIdAndEnvironmentId(datasourceId, sourceEnvironmentId); + Mono<Datasource> datasourceToForkMono = + datasourceService.findByIdAndEnvironmentId(datasourceId, sourceEnvironmentId); return Mono.zip(datasourceToForkMono, existingDatasourcesInNewWorkspaceMono) .flatMap(tuple -> { @@ -559,47 +595,52 @@ public Mono<Datasource> forkDatasource(String datasourceId, return Mono.just(datasourceToFork); } - DatasourceStorageDTO storageDTOToFork = datasourceToFork.getDatasourceStorages().get(sourceEnvironmentId); + DatasourceStorageDTO storageDTOToFork = + datasourceToFork.getDatasourceStorages().get(sourceEnvironmentId); final AuthenticationDTO authentication = storageDTOToFork.getDatasourceConfiguration() == null - ? null : storageDTOToFork.getDatasourceConfiguration().getAuthentication(); + ? null + : storageDTOToFork.getDatasourceConfiguration().getAuthentication(); if (authentication != null) { authentication.setIsAuthorized(null); } - return destinationEnvironmentIdMono - .flatMap(destinationEnvironmentId -> - Flux.fromIterable(existingDatasourcesWithoutStorages) - .filter(datasourceToFork::softEquals) - .filterWhen(existingDatasource -> { - Mono<DatasourceStorage> datasourceStorageMono = datasourceStorageService - .findStrictlyByDatasourceIdAndEnvironmentId( - existingDatasource.getId(), - destinationEnvironmentId); - - return datasourceStorageMono - .map(existingStorage -> { - final AuthenticationDTO auth = existingStorage.getDatasourceConfiguration() == null - ? null : existingStorage.getDatasourceConfiguration().getAuthentication(); - if (auth != null) { - auth.setIsAuthorized(null); - } - return storageDTOToFork.softEquals(new DatasourceStorageDTO(existingStorage)); - }) - .switchIfEmpty(Mono.just(false)); - }) - .next() // Get the first matching datasource, we don't need more than one here. - .switchIfEmpty(Mono.defer(() -> { - // No matching existing datasource found, so create a new one. - Datasource newDs = datasourceToFork.fork(forkWithConfiguration, toWorkspaceId); - DatasourceStorageDTO storageDTO = datasourceToFork.getDatasourceStorages() - .get(sourceEnvironmentId) - .fork(forkWithConfiguration, toWorkspaceId); - storageDTO.setEnvironmentId(destinationEnvironmentId); - newDs.getDatasourceStorages().put(destinationEnvironmentId, storageDTO); - return createSuffixedDatasource(newDs); - })) - ); + return destinationEnvironmentIdMono.flatMap( + destinationEnvironmentId -> Flux.fromIterable(existingDatasourcesWithoutStorages) + .filter(datasourceToFork::softEquals) + .filterWhen(existingDatasource -> { + Mono<DatasourceStorage> datasourceStorageMono = + datasourceStorageService.findStrictlyByDatasourceIdAndEnvironmentId( + existingDatasource.getId(), destinationEnvironmentId); + + return datasourceStorageMono + .map(existingStorage -> { + final AuthenticationDTO auth = + existingStorage.getDatasourceConfiguration() == null + ? null + : existingStorage + .getDatasourceConfiguration() + .getAuthentication(); + if (auth != null) { + auth.setIsAuthorized(null); + } + return storageDTOToFork.softEquals( + new DatasourceStorageDTO(existingStorage)); + }) + .switchIfEmpty(Mono.just(false)); + }) + .next() // Get the first matching datasource, we don't need more than one here. + .switchIfEmpty(Mono.defer(() -> { + // No matching existing datasource found, so create a new one. + Datasource newDs = datasourceToFork.fork(forkWithConfiguration, toWorkspaceId); + DatasourceStorageDTO storageDTO = datasourceToFork + .getDatasourceStorages() + .get(sourceEnvironmentId) + .fork(forkWithConfiguration, toWorkspaceId); + storageDTO.setEnvironmentId(destinationEnvironmentId); + newDs.getDatasourceStorages().put(destinationEnvironmentId, storageDTO); + return createSuffixedDatasource(newDs); + }))); }); } @@ -619,14 +660,13 @@ private Mono<Datasource> createSuffixedDatasource(Datasource datasource) { private Mono<Datasource> createSuffixedDatasource(Datasource datasource, String name, int suffix) { final String actualName = name + (suffix == 0 ? "" : " (" + suffix + ")"); datasource.setName(actualName); - return datasourceService.create(datasource) - .onErrorResume(DuplicateKeyException.class, error -> { - if (error.getMessage() != null - && error.getMessage().contains("workspace_datasource_deleted_compound_index")) { - // The duplicate key error is because of the `name` field. - return createSuffixedDatasource(datasource, name, 1 + suffix); - } - throw error; - }); + return datasourceService.create(datasource).onErrorResume(DuplicateKeyException.class, error -> { + if (error.getMessage() != null + && error.getMessage().contains("workspace_datasource_deleted_compound_index")) { + // The duplicate key error is because of the `name` field. + return createSuffixedDatasource(datasource, name, 1 + suffix); + } + throw error; + }); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCE.java index c9508f6d187e..539e5ff8064c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCE.java @@ -11,7 +11,6 @@ import java.util.List; - public interface ImportExportApplicationServiceCE { /** @@ -64,11 +63,12 @@ public interface ImportExportApplicationServiceCE { * @param pagesToImport list of page names to be imported. Null or empty list means all pages. * @return */ - Mono<Application> mergeApplicationJsonWithApplication(String workspaceId, - String applicationId, - String branchName, - ApplicationJson applicationJson, - List<String> pagesToImport); + Mono<Application> mergeApplicationJsonWithApplication( + String workspaceId, + String applicationId, + String branchName, + ApplicationJson applicationJson, + List<String> pagesToImport); /** * This function will save the application to workspace from the application resource @@ -87,7 +87,8 @@ Mono<Application> mergeApplicationJsonWithApplication(String workspaceId, * @param applicationId application which needs to be saved with the updated resources * @return Updated application */ - Mono<Application> importApplicationInWorkspaceFromGit(String workspaceId, ApplicationJson importedDoc, String applicationId, String branchName); + Mono<Application> importApplicationInWorkspaceFromGit( + String workspaceId, ApplicationJson importedDoc, String applicationId, String branchName); /** * This function will replace an existing application with the provided application json. It's the top level method @@ -98,10 +99,11 @@ Mono<Application> mergeApplicationJsonWithApplication(String workspaceId, * @param branchName * @return */ - Mono<Application> restoreSnapshot(String workspaceId, ApplicationJson importedDoc, String applicationId, String branchName); + Mono<Application> restoreSnapshot( + String workspaceId, ApplicationJson importedDoc, String applicationId, String branchName); Mono<List<Datasource>> findDatasourceByApplicationId(String applicationId, String orgId); - Mono<ApplicationImportDTO> getApplicationImportDTO(String applicationId, String workspaceId, Application application); - + Mono<ApplicationImportDTO> getApplicationImportDTO( + String applicationId, String workspaceId, Application application); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java index 2d0a0b2b0841..a9f3a390a12b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java @@ -155,18 +155,19 @@ public class ImportExportApplicationServiceCEImpl implements ImportExportApplica * @param applicationId which needs to be exported * @return application reference from which entire application can be rehydrated */ - public Mono<ApplicationJson> exportApplicationById(String applicationId, SerialiseApplicationObjective serialiseFor) { + public Mono<ApplicationJson> exportApplicationById( + String applicationId, SerialiseApplicationObjective serialiseFor) { // Start the stopwatch to log the execution time Stopwatch stopwatch = new Stopwatch(AnalyticsEvents.EXPORT.getEventName()); /* - 1. Fetch application by id - 2. Fetch pages from the application - 3. Fetch datasources from workspace - 4. Fetch actions from the application - 5. Filter out relevant datasources using actions reference - 6. Fetch action collections from the application - */ + 1. Fetch application by id + 2. Fetch pages from the application + 3. Fetch datasources from workspace + 4. Fetch actions from the application + 5. Filter out relevant datasources using actions reference + 6. Fetch action collections from the application + */ ApplicationJson applicationJson = new ApplicationJson(); Map<String, String> pluginMap = new HashMap<>(); Map<String, String> datasourceIdToNameMap = new HashMap<>(); @@ -188,18 +189,19 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali AtomicReference<Boolean> exportWithConfiguration = new AtomicReference<>(false); // If Git-sync, then use MANAGE_APPLICATIONS, else use EXPORT_APPLICATION permission to fetch application - AclPermission permission = isGitSync ? applicationPermission.getEditPermission() : applicationPermission.getExportPermission(); + AclPermission permission = + isGitSync ? applicationPermission.getEditPermission() : applicationPermission.getExportPermission(); Mono<User> currentUserMono = sessionUserService.getCurrentUser().cache(); Mono<Application> applicationMono = // Find the application with appropriate permission - applicationService.findById(applicationId, permission) + applicationService + .findById(applicationId, permission) // Find the application without permissions if it is a template application .switchIfEmpty(applicationService.findByIdAndExportWithConfiguration(applicationId, TRUE)) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION_ID, applicationId)) - ) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION_ID, applicationId))) .map(application -> { if (!TRUE.equals(application.getExportWithConfiguration())) { // Explicitly setting the boolean to avoid NPE for future checks @@ -210,53 +212,55 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali }) .cache(); - Mono<String> defaultEnvironmentIdMono = applicationService.findById(applicationId) + Mono<String> defaultEnvironmentIdMono = applicationService + .findById(applicationId) .flatMap(application -> workspaceService.getDefaultEnvironmentId(application.getWorkspaceId())); /** * Since we are exporting for git, we only consider unpublished JS libraries * Ref: https://theappsmith.slack.com/archives/CGBPVEJ5C/p1672225134025919 */ - Mono<List<CustomJSLib>> allCustomJSLibListMono = - customJSLibService.getAllJSLibsInApplicationForExport(applicationId, null, false) - .zipWith(applicationMono) - .map(tuple2 -> { - Application application = tuple2.getT2(); - GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); - Instant applicationLastCommittedAt = gitApplicationMetadata != null ? gitApplicationMetadata.getLastCommittedAt() : null; - - List<CustomJSLib> unpublishedCustomJSLibList = tuple2.getT1(); - List<String> updatedCustomJSLibList; - if (applicationLastCommittedAt != null) { - updatedCustomJSLibList = unpublishedCustomJSLibList - .stream() - .filter(lib -> lib.getUpdatedAt() == null || - applicationLastCommittedAt.isBefore(lib.getUpdatedAt())) - .map(lib -> lib.getUidString()) - .collect(Collectors.toList()); - } else { - updatedCustomJSLibList = unpublishedCustomJSLibList - .stream() - .map(lib -> lib.getUidString()) - .collect(Collectors.toList()); - } - applicationJson.getUpdatedResources().put(FieldName.CUSTOM_JS_LIB_LIST, - new HashSet<>(updatedCustomJSLibList)); - - /** - * Previously it was a Set and as Set is an unordered collection of elements that - * resulted in uncommitted changes. Making it a list and sorting it by the UidString - * ensure that the order will be maintained. And this solves the issue. - */ - Collections.sort(unpublishedCustomJSLibList, Comparator.comparing(CustomJSLib::getUidString)); - return unpublishedCustomJSLibList; - }); + Mono<List<CustomJSLib>> allCustomJSLibListMono = customJSLibService + .getAllJSLibsInApplicationForExport(applicationId, null, false) + .zipWith(applicationMono) + .map(tuple2 -> { + Application application = tuple2.getT2(); + GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); + Instant applicationLastCommittedAt = + gitApplicationMetadata != null ? gitApplicationMetadata.getLastCommittedAt() : null; + + List<CustomJSLib> unpublishedCustomJSLibList = tuple2.getT1(); + List<String> updatedCustomJSLibList; + if (applicationLastCommittedAt != null) { + updatedCustomJSLibList = unpublishedCustomJSLibList.stream() + .filter(lib -> lib.getUpdatedAt() == null + || applicationLastCommittedAt.isBefore(lib.getUpdatedAt())) + .map(lib -> lib.getUidString()) + .collect(Collectors.toList()); + } else { + updatedCustomJSLibList = unpublishedCustomJSLibList.stream() + .map(lib -> lib.getUidString()) + .collect(Collectors.toList()); + } + applicationJson + .getUpdatedResources() + .put(FieldName.CUSTOM_JS_LIB_LIST, new HashSet<>(updatedCustomJSLibList)); + + /** + * Previously it was a Set and as Set is an unordered collection of elements that + * resulted in uncommitted changes. Making it a list and sorting it by the UidString + * ensure that the order will be maintained. And this solves the issue. + */ + Collections.sort(unpublishedCustomJSLibList, Comparator.comparing(CustomJSLib::getUidString)); + return unpublishedCustomJSLibList; + }); // Set json schema version which will be used to check the compatibility while importing the JSON applicationJson.setServerSchemaVersion(JsonSchemaVersions.serverVersion); applicationJson.setClientSchemaVersion(JsonSchemaVersions.clientVersion); - Mono<Theme> defaultThemeMono = themeService.getSystemTheme(Theme.DEFAULT_THEME_NAME) + Mono<Theme> defaultThemeMono = themeService + .getSystemTheme(Theme.DEFAULT_THEME_NAME) .map(theme -> { log.debug("Default theme found: {}", theme.getName()); return theme; @@ -266,16 +270,20 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali return pluginRepository .findAll() .map(plugin -> { - pluginMap.put(plugin.getId(), plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName()); + pluginMap.put( + plugin.getId(), + plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName()); return plugin; }) .then(applicationMono) - .flatMap(application -> themeService.getThemeById(application.getEditModeThemeId(), READ_THEMES) + .flatMap(application -> themeService + .getThemeById(application.getEditModeThemeId(), READ_THEMES) .switchIfEmpty(defaultThemeMono) // setting default theme if theme is missing - .zipWith(themeService - .getThemeById(application.getPublishedModeThemeId(), READ_THEMES) - .switchIfEmpty(defaultThemeMono)// setting default theme if theme is missing - ) + .zipWith( + themeService + .getThemeById(application.getPublishedModeThemeId(), READ_THEMES) + .switchIfEmpty(defaultThemeMono) // setting default theme if theme is missing + ) .map(themesTuple -> { Theme editModeTheme = themesTuple.getT1(); Theme publishedModeTheme = themesTuple.getT2(); @@ -291,24 +299,29 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali // Refactor application to remove the ids final String workspaceId = application.getWorkspaceId(); GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); - Instant applicationLastCommittedAt = gitApplicationMetadata != null ? gitApplicationMetadata.getLastCommittedAt() : null; - boolean isClientSchemaMigrated = !JsonSchemaVersions.clientVersion.equals(application.getClientSchemaVersion()); - boolean isServerSchemaMigrated = !JsonSchemaVersions.serverVersion.equals(application.getServerSchemaVersion()); + Instant applicationLastCommittedAt = + gitApplicationMetadata != null ? gitApplicationMetadata.getLastCommittedAt() : null; + boolean isClientSchemaMigrated = + !JsonSchemaVersions.clientVersion.equals(application.getClientSchemaVersion()); + boolean isServerSchemaMigrated = + !JsonSchemaVersions.serverVersion.equals(application.getServerSchemaVersion()); application.makePristine(); application.sanitiseToExportDBObject(); applicationJson.setExportedApplication(application); Set<String> dbNamesUsedInActions = new HashSet<>(); - Optional<AclPermission> optionalPermission = isGitSync ? Optional.empty() : - TRUE.equals(exportWithConfiguration.get()) + Optional<AclPermission> optionalPermission = isGitSync + ? Optional.empty() + : TRUE.equals(exportWithConfiguration.get()) ? Optional.of(pagePermission.getReadPermission()) : Optional.of(pagePermission.getEditPermission()); Flux<NewPage> pageFlux = newPageRepository.findByApplicationId(applicationId, optionalPermission); - List<String> unPublishedPages = application.getPages().stream().map(ApplicationPage::getId).collect(Collectors.toList()); + List<String> unPublishedPages = application.getPages().stream() + .map(ApplicationPage::getId) + .collect(Collectors.toList()); - return pageFlux - .collectList() + return pageFlux.collectList() .flatMap(newPageList -> { // Extract mongoEscapedWidgets from pages and save it to applicationJson object as this // field is JsonIgnored. Also remove any ids those are present in the page objects @@ -316,13 +329,14 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali Set<String> updatedPageSet = new HashSet<String>(); // check the application object for the page reference in the page list - // Exclude the deleted pages that are present in view mode because the app is not published yet + // Exclude the deleted pages that are present in view mode because the app is not + // published yet newPageList.removeIf(newPage -> !unPublishedPages.contains(newPage.getId())); newPageList.forEach(newPage -> { if (newPage.getUnpublishedPage() != null) { pageIdToNameMap.put( - newPage.getId() + EDIT, newPage.getUnpublishedPage().getName() - ); + newPage.getId() + EDIT, + newPage.getUnpublishedPage().getName()); PageDTO unpublishedPageDTO = newPage.getUnpublishedPage(); if (!CollectionUtils.isEmpty(unpublishedPageDTO.getLayouts())) { unpublishedPageDTO.getLayouts().forEach(layout -> { @@ -333,8 +347,8 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali if (newPage.getPublishedPage() != null) { pageIdToNameMap.put( - newPage.getId() + VIEW, newPage.getPublishedPage().getName() - ); + newPage.getId() + VIEW, + newPage.getPublishedPage().getName()); PageDTO publishedPageDTO = newPage.getPublishedPage(); if (!CollectionUtils.isEmpty(publishedPageDTO.getLayouts())) { publishedPageDTO.getLayouts().forEach(layout -> { @@ -344,25 +358,36 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali } // Including updated pages list for git file storage Instant newPageUpdatedAt = newPage.getUpdatedAt(); - boolean isNewPageUpdated = isClientSchemaMigrated || isServerSchemaMigrated || applicationLastCommittedAt == null || newPageUpdatedAt == null || applicationLastCommittedAt.isBefore(newPageUpdatedAt); - String newPageName = newPage.getUnpublishedPage() != null ? newPage.getUnpublishedPage().getName() : newPage.getPublishedPage() != null ? newPage.getPublishedPage().getName() : null; + boolean isNewPageUpdated = isClientSchemaMigrated + || isServerSchemaMigrated + || applicationLastCommittedAt == null + || newPageUpdatedAt == null + || applicationLastCommittedAt.isBefore(newPageUpdatedAt); + String newPageName = newPage.getUnpublishedPage() != null + ? newPage.getUnpublishedPage().getName() + : newPage.getPublishedPage() != null + ? newPage.getPublishedPage().getName() + : null; if (isNewPageUpdated && newPageName != null) { updatedPageSet.add(newPageName); } newPage.sanitiseToExportDBObject(); }); applicationJson.setPageList(newPageList); - applicationJson.setUpdatedResources(new HashMap<>() {{ - put(FieldName.PAGE_LIST, updatedPageSet); - }}); + applicationJson.setUpdatedResources(new HashMap<>() { + { + put(FieldName.PAGE_LIST, updatedPageSet); + } + }); - Optional<AclPermission> optionalPermission3 = isGitSync ? Optional.empty() + Optional<AclPermission> optionalPermission3 = isGitSync + ? Optional.empty() : TRUE.equals(exportWithConfiguration.get()) - ? Optional.of(datasourcePermission.getReadPermission()) - : Optional.of(datasourcePermission.getEditPermission()); + ? Optional.of(datasourcePermission.getReadPermission()) + : Optional.of(datasourcePermission.getEditPermission()); - Flux<Datasource> datasourceFlux = - datasourceService.getAllByWorkspaceIdWithStorages(workspaceId, optionalPermission3); + Flux<Datasource> datasourceFlux = datasourceService.getAllByWorkspaceIdWithStorages( + workspaceId, optionalPermission3); return datasourceFlux.collectList().zipWith(defaultEnvironmentIdMono); }) .flatMapMany(tuple2 -> { @@ -371,16 +396,19 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali datasourceList.forEach(datasource -> datasourceIdToNameMap.put(datasource.getId(), datasource.getName())); List<DatasourceStorage> storageList = datasourceList.stream() - .map(datasource -> datasourceStorageService.getDatasourceStorageFromDatasource(datasource, environmentId)) + .map(datasource -> datasourceStorageService.getDatasourceStorageFromDatasource( + datasource, environmentId)) .collect(Collectors.toList()); applicationJson.setDatasourceList(storageList); - Optional<AclPermission> optionalPermission1 = isGitSync ? Optional.empty() : - TRUE.equals(exportWithConfiguration.get()) + Optional<AclPermission> optionalPermission1 = isGitSync + ? Optional.empty() + : TRUE.equals(exportWithConfiguration.get()) ? Optional.of(actionPermission.getReadPermission()) : Optional.of(actionPermission.getEditPermission()); Flux<ActionCollection> actionCollectionFlux = - actionCollectionRepository.findByListOfPageIds(unPublishedPages, optionalPermission1); + actionCollectionRepository.findByListOfPageIds( + unPublishedPages, optionalPermission1); return actionCollectionFlux; }) .map(actionCollection -> { @@ -391,21 +419,26 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali // Set unique ids for actionCollection, also populate collectionIdToName map which will // be used to replace collectionIds in action if (actionCollection.getUnpublishedCollection() != null) { - ActionCollectionDTO actionCollectionDTO = actionCollection.getUnpublishedCollection(); - actionCollectionDTO.setPageId(pageIdToNameMap.get(actionCollectionDTO.getPageId() + EDIT)); + ActionCollectionDTO actionCollectionDTO = + actionCollection.getUnpublishedCollection(); + actionCollectionDTO.setPageId( + pageIdToNameMap.get(actionCollectionDTO.getPageId() + EDIT)); actionCollectionDTO.setPluginId(pluginMap.get(actionCollectionDTO.getPluginId())); - final String updatedCollectionId = actionCollectionDTO.getPageId() + "_" + actionCollectionDTO.getName(); + final String updatedCollectionId = + actionCollectionDTO.getPageId() + "_" + actionCollectionDTO.getName(); collectionIdToNameMap.put(actionCollection.getId(), updatedCollectionId); actionCollection.setId(updatedCollectionId); } if (actionCollection.getPublishedCollection() != null) { ActionCollectionDTO actionCollectionDTO = actionCollection.getPublishedCollection(); - actionCollectionDTO.setPageId(pageIdToNameMap.get(actionCollectionDTO.getPageId() + VIEW)); + actionCollectionDTO.setPageId( + pageIdToNameMap.get(actionCollectionDTO.getPageId() + VIEW)); actionCollectionDTO.setPluginId(pluginMap.get(actionCollectionDTO.getPluginId())); if (!collectionIdToNameMap.containsValue(actionCollection.getId())) { - final String updatedCollectionId = actionCollectionDTO.getPageId() + "_" + actionCollectionDTO.getName(); + final String updatedCollectionId = + actionCollectionDTO.getPageId() + "_" + actionCollectionDTO.getName(); collectionIdToNameMap.put(actionCollection.getId(), updatedCollectionId); actionCollection.setId(updatedCollectionId); } @@ -419,12 +452,24 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali Set<String> updatedActionCollectionSet = new HashSet<>(); actionCollections.forEach(actionCollection -> { - ActionCollectionDTO publishedActionCollectionDTO = actionCollection.getPublishedCollection(); - ActionCollectionDTO unpublishedActionCollectionDTO = actionCollection.getUnpublishedCollection(); - ActionCollectionDTO actionCollectionDTO = unpublishedActionCollectionDTO != null ? unpublishedActionCollectionDTO : publishedActionCollectionDTO; - String actionCollectionName = actionCollectionDTO != null ? actionCollectionDTO.getName() + NAME_SEPARATOR + actionCollectionDTO.getPageId() : null; + ActionCollectionDTO publishedActionCollectionDTO = + actionCollection.getPublishedCollection(); + ActionCollectionDTO unpublishedActionCollectionDTO = + actionCollection.getUnpublishedCollection(); + ActionCollectionDTO actionCollectionDTO = unpublishedActionCollectionDTO != null + ? unpublishedActionCollectionDTO + : publishedActionCollectionDTO; + String actionCollectionName = actionCollectionDTO != null + ? actionCollectionDTO.getName() + + NAME_SEPARATOR + + actionCollectionDTO.getPageId() + : null; Instant actionCollectionUpdatedAt = actionCollection.getUpdatedAt(); - boolean isActionCollectionUpdated = isClientSchemaMigrated || isServerSchemaMigrated || applicationLastCommittedAt == null || actionCollectionUpdatedAt == null || applicationLastCommittedAt.isBefore(actionCollectionUpdatedAt); + boolean isActionCollectionUpdated = isClientSchemaMigrated + || isServerSchemaMigrated + || applicationLastCommittedAt == null + || actionCollectionUpdatedAt == null + || applicationLastCommittedAt.isBefore(actionCollectionUpdatedAt); if (isActionCollectionUpdated && actionCollectionName != null) { updatedActionCollectionSet.add(actionCollectionName); } @@ -432,12 +477,15 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali }); applicationJson.setActionCollectionList(actionCollections); - applicationJson.getUpdatedResources().put(FieldName.ACTION_COLLECTION_LIST, updatedActionCollectionSet); + applicationJson + .getUpdatedResources() + .put(FieldName.ACTION_COLLECTION_LIST, updatedActionCollectionSet); - Optional<AclPermission> optionalPermission2 = isGitSync ? Optional.empty() + Optional<AclPermission> optionalPermission2 = isGitSync + ? Optional.empty() : TRUE.equals(exportWithConfiguration.get()) - ? Optional.of(actionPermission.getReadPermission()) - : Optional.of(actionPermission.getEditPermission()); + ? Optional.of(actionPermission.getReadPermission()) + : Optional.of(actionPermission.getEditPermission()); Flux<NewAction> actionFlux = newActionRepository.findByListOfPageIds(unPublishedPages, optionalPermission2); @@ -448,12 +496,14 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali newAction.setWorkspaceId(null); newAction.setPolicies(null); newAction.setApplicationId(null); - dbNamesUsedInActions.add( - sanitizeDatasourceInActionDTO(newAction.getPublishedAction(), datasourceIdToNameMap, pluginMap, null, true) - ); - dbNamesUsedInActions.add( - sanitizeDatasourceInActionDTO(newAction.getUnpublishedAction(), datasourceIdToNameMap, pluginMap, null, true) - ); + dbNamesUsedInActions.add(sanitizeDatasourceInActionDTO( + newAction.getPublishedAction(), datasourceIdToNameMap, pluginMap, null, true)); + dbNamesUsedInActions.add(sanitizeDatasourceInActionDTO( + newAction.getUnpublishedAction(), + datasourceIdToNameMap, + pluginMap, + null, + true)); // Set unique id for action if (newAction.getUnpublishedAction() != null) { @@ -462,10 +512,12 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali if (!StringUtils.isEmpty(actionDTO.getCollectionId()) && collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) { - actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId())); + actionDTO.setCollectionId( + collectionIdToNameMap.get(actionDTO.getCollectionId())); } - final String updatedActionId = actionDTO.getPageId() + "_" + actionDTO.getValidName(); + final String updatedActionId = + actionDTO.getPageId() + "_" + actionDTO.getValidName(); actionIdToNameMap.put(newAction.getId(), updatedActionId); newAction.setId(updatedActionId); } @@ -475,11 +527,13 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali if (!StringUtils.isEmpty(actionDTO.getCollectionId()) && collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) { - actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId())); + actionDTO.setCollectionId( + collectionIdToNameMap.get(actionDTO.getCollectionId())); } if (!actionIdToNameMap.containsValue(newAction.getId())) { - final String updatedActionId = actionDTO.getPageId() + "_" + actionDTO.getValidName(); + final String updatedActionId = + actionDTO.getPageId() + "_" + actionDTO.getValidName(); actionIdToNameMap.put(newAction.getId(), updatedActionId); newAction.setId(updatedActionId); } @@ -492,10 +546,17 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali actionList.forEach(newAction -> { ActionDTO unpublishedActionDTO = newAction.getUnpublishedAction(); ActionDTO publishedActionDTO = newAction.getPublishedAction(); - ActionDTO actionDTO = unpublishedActionDTO != null ? unpublishedActionDTO : publishedActionDTO; - String newActionName = actionDTO != null ? actionDTO.getValidName() + NAME_SEPARATOR + actionDTO.getPageId() : null; + ActionDTO actionDTO = + unpublishedActionDTO != null ? unpublishedActionDTO : publishedActionDTO; + String newActionName = actionDTO != null + ? actionDTO.getValidName() + NAME_SEPARATOR + actionDTO.getPageId() + : null; Instant newActionUpdatedAt = newAction.getUpdatedAt(); - boolean isNewActionUpdated = isClientSchemaMigrated || isServerSchemaMigrated || applicationLastCommittedAt == null || newActionUpdatedAt == null || applicationLastCommittedAt.isBefore(newActionUpdatedAt); + boolean isNewActionUpdated = isClientSchemaMigrated + || isServerSchemaMigrated + || applicationLastCommittedAt == null + || newActionUpdatedAt == null + || applicationLastCommittedAt.isBefore(newActionUpdatedAt); if (isNewActionUpdated && newActionName != null) { updatedActionSet.add(newActionName); } @@ -508,19 +569,23 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali .getDatasourceList() .removeIf(datasource -> !dbNamesUsedInActions.contains(datasource.getName())); - // Save decrypted fields for datasources for internally used sample apps and templates only + // Save decrypted fields for datasources for internally used sample apps and templates + // only // when serialising for file sharing - if (TRUE.equals(exportWithConfiguration.get()) && SerialiseApplicationObjective.SHARE.equals(serialiseFor)) { + if (TRUE.equals(exportWithConfiguration.get()) + && SerialiseApplicationObjective.SHARE.equals(serialiseFor)) { // Save decrypted fields for datasources Map<String, DecryptedSensitiveFields> decryptedFields = new HashMap<>(); applicationJson.getDatasourceList().forEach(datasourceStorage -> { - decryptedFields.put(datasourceStorage.getName(), getDecryptedFields(datasourceStorage)); + decryptedFields.put( + datasourceStorage.getName(), getDecryptedFields(datasourceStorage)); datasourceStorage.sanitiseToExportResource(pluginMap); }); applicationJson.setDecryptedFields(decryptedFields); } else { applicationJson.getDatasourceList().forEach(datasourceStorage -> { - // Remove the datasourceConfiguration object as user will configure it once imported to other instance + // Remove the datasourceConfiguration object as user will configure it once + // imported to other instance datasourceStorage.setDatasourceConfiguration(null); datasourceStorage.sanitiseToExportResource(pluginMap); }); @@ -528,12 +593,15 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali // Update ids for layoutOnLoadAction for (NewPage newPage : applicationJson.getPageList()) { - updateIdsForLayoutOnLoadAction(newPage.getUnpublishedPage(), actionIdToNameMap, collectionIdToNameMap); - updateIdsForLayoutOnLoadAction(newPage.getPublishedPage(), actionIdToNameMap, collectionIdToNameMap); + updateIdsForLayoutOnLoadAction( + newPage.getUnpublishedPage(), actionIdToNameMap, collectionIdToNameMap); + updateIdsForLayoutOnLoadAction( + newPage.getPublishedPage(), actionIdToNameMap, collectionIdToNameMap); } application.exportApplicationPages(pageIdToNameMap); - // Disable exporting the application with datasource config once imported in destination instance + // Disable exporting the application with datasource config once imported in destination + // instance application.setExportWithConfiguration(null); return applicationJson; }); @@ -547,14 +615,20 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali .map(user -> { stopwatch.stopTimer(); final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, applicationId, - "pageCount", applicationJson.getPageList().size(), - "actionCount", applicationJson.getActionList().size(), - "JSObjectCount", applicationJson.getActionCollectionList().size(), - FieldName.FLOW_NAME, stopwatch.getFlow(), - "executionTime", stopwatch.getExecutionTime() - ); - analyticsService.sendEvent(AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), user.getUsername(), data); + FieldName.APPLICATION_ID, + applicationId, + "pageCount", + applicationJson.getPageList().size(), + "actionCount", + applicationJson.getActionList().size(), + "JSObjectCount", + applicationJson.getActionCollectionList().size(), + FieldName.FLOW_NAME, + stopwatch.getFlow(), + "executionTime", + stopwatch.getExecutionTime()); + analyticsService.sendEvent( + AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), user.getUsername(), data); return applicationJson; }) .then(sendImportExportApplicationAnalyticsEvent(applicationId, AnalyticsEvents.EXPORT)) @@ -562,51 +636,48 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali } public Mono<ApplicationJson> exportApplicationById(String applicationId, String branchName) { - return applicationService.findBranchedApplicationId(branchName, applicationId, applicationPermission.getExportPermission()) + return applicationService + .findBranchedApplicationId(branchName, applicationId, applicationPermission.getExportPermission()) .flatMap(branchedAppId -> exportApplicationById(branchedAppId, SerialiseApplicationObjective.SHARE)); } - private void updateIdsForLayoutOnLoadAction(PageDTO page, - Map<String, String> actionIdToNameMap, - Map<String, String> collectionIdToNameMap) { + private void updateIdsForLayoutOnLoadAction( + PageDTO page, Map<String, String> actionIdToNameMap, Map<String, String> collectionIdToNameMap) { if (page != null && !CollectionUtils.isEmpty(page.getLayouts())) { for (Layout layout : page.getLayouts()) { if (!CollectionUtils.isEmpty(layout.getLayoutOnLoadActions())) { - layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction - .forEach(actionDTO -> { + layout.getLayoutOnLoadActions() + .forEach(onLoadAction -> onLoadAction.forEach(actionDTO -> { if (actionIdToNameMap.containsKey(actionDTO.getId())) { actionDTO.setId(actionIdToNameMap.get(actionDTO.getId())); } if (collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) { actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId())); } - }) - ); + })); } } } } public Mono<ExportFileDTO> getApplicationFile(String applicationId, String branchName) { - return this.exportApplicationById(applicationId, branchName) - .map(applicationJson -> { - String stringifiedFile = gson.toJson(applicationJson); - String applicationName = applicationJson.getExportedApplication().getName(); - Object jsonObject = gson.fromJson(stringifiedFile, Object.class); - HttpHeaders responseHeaders = new HttpHeaders(); - ContentDisposition contentDisposition = ContentDisposition - .builder("attachment") - .filename(applicationName + ".json", StandardCharsets.UTF_8) - .build(); - responseHeaders.setContentDisposition(contentDisposition); - responseHeaders.setContentType(MediaType.APPLICATION_JSON); - - ExportFileDTO exportFileDTO = new ExportFileDTO(); - exportFileDTO.setApplicationResource(jsonObject); - exportFileDTO.setHttpHeaders(responseHeaders); - return exportFileDTO; - }); + return this.exportApplicationById(applicationId, branchName).map(applicationJson -> { + String stringifiedFile = gson.toJson(applicationJson); + String applicationName = applicationJson.getExportedApplication().getName(); + Object jsonObject = gson.fromJson(stringifiedFile, Object.class); + HttpHeaders responseHeaders = new HttpHeaders(); + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename(applicationName + ".json", StandardCharsets.UTF_8) + .build(); + responseHeaders.setContentDisposition(contentDisposition); + responseHeaders.setContentType(MediaType.APPLICATION_JSON); + + ExportFileDTO exportFileDTO = new ExportFileDTO(); + exportFileDTO.setApplicationResource(jsonObject); + exportFileDTO.setHttpHeaders(responseHeaders); + return exportFileDTO; + }); } public Mono<ApplicationImportDTO> extractFileAndSaveApplication(String workspaceId, Part filePart) { @@ -621,7 +692,8 @@ public Mono<ApplicationImportDTO> extractFileAndSaveApplication(String workspace * @return saved application in DB */ @Override - public Mono<ApplicationImportDTO> extractFileAndSaveApplication(String workspaceId, Part filePart, String applicationId) { + public Mono<ApplicationImportDTO> extractFileAndSaveApplication( + String workspaceId, Part filePart, String applicationId) { // workspace id must be present and valid if (StringUtils.isEmpty(workspaceId)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); @@ -635,11 +707,11 @@ public Mono<ApplicationImportDTO> extractFileAndSaveApplication(String workspace return updateNonGitConnectedAppFromJson(workspaceId, applicationId, applicationJson); } }) - .flatMap(application -> getApplicationImportDTO(application.getId(), application.getWorkspaceId(), application)); + .flatMap(application -> + getApplicationImportDTO(application.getId(), application.getWorkspaceId(), application)); - return Mono.create(sink -> importedApplicationMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> importedApplicationMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @Override @@ -658,25 +730,27 @@ public Mono<ApplicationJson> extractApplicationJson(Part filePart) { return new String(data); }) .map(jsonString -> { - Type fileType = new TypeToken<ApplicationJson>() { - }.getType(); + Type fileType = new TypeToken<ApplicationJson>() {}.getType(); ApplicationJson jsonFile = gson.fromJson(jsonString, fileType); return jsonFile; }); } private Mono<ImportApplicationPermissionProvider> getPermissionProviderForUpdateNonGitConnectedAppFromJson() { - return permissionGroupRepository.getCurrentUserPermissionGroups() - .map(permissionGroups -> { - ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) - .requiredPermissionOnTargetWorkspace(workspacePermission.getReadPermission()) - .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) - .allPermissionsRequired() - .currentUserPermissionGroups(permissionGroups) - .build(); - return permissionProvider; - }); + return permissionGroupRepository.getCurrentUserPermissionGroups().map(permissionGroups -> { + ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) + .requiredPermissionOnTargetWorkspace(workspacePermission.getReadPermission()) + .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) + .allPermissionsRequired() + .currentUserPermissionGroups(permissionGroups) + .build(); + return permissionProvider; + }); } /** @@ -688,13 +762,14 @@ private Mono<ImportApplicationPermissionProvider> getPermissionProviderForUpdate * @param applicationId Optional field for application ref which needs to be overridden by the incoming JSON file * @return saved application in DB */ - private Mono<Application> updateNonGitConnectedAppFromJson(String workspaceId, String applicationId, ApplicationJson applicationJson) { + private Mono<Application> updateNonGitConnectedAppFromJson( + String workspaceId, String applicationId, ApplicationJson applicationJson) { /* - 1. Verify if application is connected to git, in case if it's connected throw exception asking user to - update app via git ops like pull, merge etc. - 2. Check the validity of file part - 3. Depending upon availability of applicationId update/save application to workspace - */ + 1. Verify if application is connected to git, in case if it's connected throw exception asking user to + update app via git ops like pull, merge etc. + 2. Check the validity of file part + 3. Depending upon availability of applicationId update/save application to workspace + */ if (StringUtils.isEmpty(workspaceId)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); } @@ -710,35 +785,45 @@ private Mono<Application> updateNonGitConnectedAppFromJson(String workspaceId, S isConnectedToGitMono = applicationService.isApplicationConnectedToGit(applicationId); } - Mono<Application> importedApplicationMono = isConnectedToGitMono - .flatMap(isConnectedToGit -> { - if (isConnectedToGit) { - return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_IMPORT_OPERATION_FOR_GIT_CONNECTED_APPLICATION)); - } else { - return getPermissionProviderForUpdateNonGitConnectedAppFromJson() - .flatMap(permissionProvider -> { - if (!StringUtils.isEmpty(applicationId) && applicationJson.getExportedApplication() != null) { - // Remove the application name from JSON file as updating the application name is not supported - // via JSON import. This is to avoid name conflict during the import flow within the workspace - applicationJson.getExportedApplication().setName(null); - applicationJson.getExportedApplication().setSlug(null); - } - - return importApplicationInWorkspace(workspaceId, applicationJson, applicationId, null, false, permissionProvider) - .onErrorResume(error -> { - if (error instanceof AppsmithException) { - return Mono.error(error); - } - return Mono.error(new AppsmithException(AppsmithError.GENERIC_JSON_IMPORT_ERROR, workspaceId, error.getMessage())); - }); - }); - } - }); + Mono<Application> importedApplicationMono = isConnectedToGitMono.flatMap(isConnectedToGit -> { + if (isConnectedToGit) { + return Mono.error(new AppsmithException( + AppsmithError.UNSUPPORTED_IMPORT_OPERATION_FOR_GIT_CONNECTED_APPLICATION)); + } else { + return getPermissionProviderForUpdateNonGitConnectedAppFromJson() + .flatMap(permissionProvider -> { + if (!StringUtils.isEmpty(applicationId) + && applicationJson.getExportedApplication() != null) { + // Remove the application name from JSON file as updating the application name is not + // supported + // via JSON import. This is to avoid name conflict during the import flow within the + // workspace + applicationJson.getExportedApplication().setName(null); + applicationJson.getExportedApplication().setSlug(null); + } + return importApplicationInWorkspace( + workspaceId, + applicationJson, + applicationId, + null, + false, + permissionProvider) + .onErrorResume(error -> { + if (error instanceof AppsmithException) { + return Mono.error(error); + } + return Mono.error(new AppsmithException( + AppsmithError.GENERIC_JSON_IMPORT_ERROR, + workspaceId, + error.getMessage())); + }); + }); + } + }); - return Mono.create(sink -> importedApplicationMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + return Mono.create( + sink -> importedApplicationMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } /** @@ -756,8 +841,12 @@ public Mono<Application> importNewApplicationInWorkspaceFromJson(String workspac } return permissionGroupRepository.getCurrentUserPermissionGroups().flatMap(userPermissionGroups -> { - ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) + ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) .requiredPermissionOnTargetWorkspace(workspacePermission.getApplicationCreatePermission()) .permissionRequiredToCreateDatasource(true) .permissionRequiredToEditDatasource(true) @@ -778,42 +867,52 @@ public Mono<Application> importNewApplicationInWorkspaceFromJson(String workspac * @return saved application in DB */ @Override - public Mono<Application> importApplicationInWorkspaceFromGit(String workspaceId, ApplicationJson importedDoc, String applicationId, String branchName) { - return permissionGroupRepository.getCurrentUserPermissionGroups() - .flatMap(userPermissionGroups -> { - /** - * If the application is connected to git, then the user must have edit permission on the application. - * If user is importing application from Git, create application permission is already checked by the - * caller method, so it's not required here. - * Other permissions are not required because Git is the source of truth for the application and Git - * Sync is a system level operation to get the latest code from Git. If the user does not have some - * permissions on the Application e.g. create page, that'll be checked when the user tries to create a page. - */ - ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) - .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) - .currentUserPermissionGroups(userPermissionGroups) - .build(); - return importApplicationInWorkspace(workspaceId, importedDoc, applicationId, branchName, false, permissionProvider); - }); + public Mono<Application> importApplicationInWorkspaceFromGit( + String workspaceId, ApplicationJson importedDoc, String applicationId, String branchName) { + return permissionGroupRepository.getCurrentUserPermissionGroups().flatMap(userPermissionGroups -> { + /** + * If the application is connected to git, then the user must have edit permission on the application. + * If user is importing application from Git, create application permission is already checked by the + * caller method, so it's not required here. + * Other permissions are not required because Git is the source of truth for the application and Git + * Sync is a system level operation to get the latest code from Git. If the user does not have some + * permissions on the Application e.g. create page, that'll be checked when the user tries to create a page. + */ + ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) + .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) + .currentUserPermissionGroups(userPermissionGroups) + .build(); + return importApplicationInWorkspace( + workspaceId, importedDoc, applicationId, branchName, false, permissionProvider); + }); } @Override - public Mono<Application> restoreSnapshot(String workspaceId, ApplicationJson importedDoc, String applicationId, String branchName) { + public Mono<Application> restoreSnapshot( + String workspaceId, ApplicationJson importedDoc, String applicationId, String branchName) { /** * Like Git, restore snapshot is a system level operation. So, we're not checking for any permissions here. * Only permission required is to edit the application. */ - return permissionGroupRepository.getCurrentUserPermissionGroups() - .flatMap(userPermissionGroups -> { - ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) - .requiredPermissionOnTargetWorkspace(workspacePermission.getReadPermission()) - .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) - .currentUserPermissionGroups(userPermissionGroups) - .build(); - return importApplicationInWorkspace(workspaceId, importedDoc, applicationId, branchName, false, permissionProvider); - }); + return permissionGroupRepository.getCurrentUserPermissionGroups().flatMap(userPermissionGroups -> { + ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) + .requiredPermissionOnTargetWorkspace(workspacePermission.getReadPermission()) + .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) + .currentUserPermissionGroups(userPermissionGroups) + .build(); + return importApplicationInWorkspace( + workspaceId, importedDoc, applicationId, branchName, false, permissionProvider); + }); } /** @@ -847,21 +946,22 @@ private String validateApplicationJson(ApplicationJson importedDoc) { * @param appendToApp whether applicationJson will be appended to the existing app or not * @return Updated application */ - private Mono<Application> importApplicationInWorkspace(String workspaceId, - ApplicationJson applicationJson, - String applicationId, - String branchName, - boolean appendToApp, - ImportApplicationPermissionProvider permissionProvider) { + private Mono<Application> importApplicationInWorkspace( + String workspaceId, + ApplicationJson applicationJson, + String applicationId, + String branchName, + boolean appendToApp, + ImportApplicationPermissionProvider permissionProvider) { /* - 1. Migrate resource to latest schema - 2. Fetch workspace by id - 3. Extract datasources and update plugin information - 4. Create new datasource if same datasource is not present - 5. Extract and save application - 6. Extract and save pages in the application - 7. Extract and save actions in the application - */ + 1. Migrate resource to latest schema + 2. Fetch workspace by id + 3. Extract datasources and update plugin information + 4. Create new datasource if same datasource is not present + 5. Extract and save application + 6. Extract and save pages in the application + 7. Extract and save actions in the application + */ ApplicationJson importedDoc = JsonSchemaMigration.migrateApplicationToLatestSchema(applicationJson); // check for validation error and raise exception if error found @@ -880,19 +980,26 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, List<DatasourceStorage> importedDatasourceList = importedDoc.getDatasourceList(); List<NewPage> importedNewPageList = importedDoc.getPageList(); List<NewAction> importedNewActionList = importedDoc.getActionList(); - List<ActionCollection> importedActionCollectionList = CollectionUtils.isEmpty(importedDoc.getActionCollectionList()) ? - new ArrayList<>() : importedDoc.getActionCollectionList(); + List<ActionCollection> importedActionCollectionList = + CollectionUtils.isEmpty(importedDoc.getActionCollectionList()) + ? new ArrayList<>() + : importedDoc.getActionCollectionList(); - Mono<Workspace> workspaceMono = workspaceService.findById(workspaceId, permissionProvider.getRequiredPermissionOnTargetWorkspace()) + Mono<Workspace> workspaceMono = workspaceService + .findById(workspaceId, permissionProvider.getRequiredPermissionOnTargetWorkspace()) .switchIfEmpty(Mono.defer(() -> { - log.error("No workspace found with id: {} and permission: {}", workspaceId, permissionProvider.getRequiredPermissionOnTargetWorkspace()); - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId)); + log.error( + "No workspace found with id: {} and permission: {}", + workspaceId, + permissionProvider.getRequiredPermissionOnTargetWorkspace()); + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId)); })); /* We need to take care of the null case in case someone is trying to import an older app where JS libs did not exist */ - List<CustomJSLib> customJSLibs = importedDoc.getCustomJSLibList() == null ? new ArrayList<>() : - importedDoc.getCustomJSLibList(); + List<CustomJSLib> customJSLibs = + importedDoc.getCustomJSLibList() == null ? new ArrayList<>() : importedDoc.getCustomJSLibList(); Mono<Application> installedJSLibMono = Flux.fromIterable(customJSLibs) .flatMap(customJSLib -> { @@ -923,15 +1030,18 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, importedApplication.setPages(null); importedApplication.setPublishedPages(null); - //re-setting the properties + // re-setting the properties importedApplication.setForkWithConfiguration(null); importedApplication.setExportWithConfiguration(null); // Start the stopwatch to log the execution time Stopwatch stopwatch = new Stopwatch(AnalyticsEvents.IMPORT.getEventName()); - final Mono<Application> importedApplicationMono = pluginRepository.findAll() + final Mono<Application> importedApplicationMono = pluginRepository + .findAll() .map(plugin -> { - final String pluginReference = StringUtils.isEmpty(plugin.getPluginName()) ? plugin.getPackageName() : plugin.getPluginName(); + final String pluginReference = StringUtils.isEmpty(plugin.getPluginName()) + ? plugin.getPackageName() + : plugin.getPluginName(); pluginMap.put(pluginReference, plugin.getId()); return plugin; }) @@ -961,37 +1071,50 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, existingDatasources.stream() .filter(datasource -> datasource.getGitSyncId() != null) - .forEach(datasource -> savedDatasourcesGitIdToDatasourceMap.put(datasource.getGitSyncId(), datasource)); + .forEach(datasource -> + savedDatasourcesGitIdToDatasourceMap.put(datasource.getGitSyncId(), datasource)); // Check if the destination org have all the required plugins installed for (DatasourceStorage datasource : importedDatasourceList) { if (StringUtils.isEmpty(pluginMap.get(datasource.getPluginId()))) { - log.error("Unable to find the plugin: {}, available plugins are: {}", datasource.getPluginId(), pluginMap.keySet()); - return Mono.error(new AppsmithException(AppsmithError.UNKNOWN_PLUGIN_REFERENCE, datasource.getPluginId())); + log.error( + "Unable to find the plugin: {}, available plugins are: {}", + datasource.getPluginId(), + pluginMap.keySet()); + return Mono.error(new AppsmithException( + AppsmithError.UNKNOWN_PLUGIN_REFERENCE, datasource.getPluginId())); } } return Flux.fromIterable(importedDatasourceList) // Check for duplicate datasources to avoid duplicates in target workspace .flatMap(datasourceStorage -> { - final String importedDatasourceName = datasourceStorage.getName(); // Check if the datasource has gitSyncId and if it's already in DB if (datasourceStorage.getGitSyncId() != null - && savedDatasourcesGitIdToDatasourceMap.containsKey(datasourceStorage.getGitSyncId())) { + && savedDatasourcesGitIdToDatasourceMap.containsKey( + datasourceStorage.getGitSyncId())) { // Since the resource is already present in DB, just update resource - Datasource existingDatasource = savedDatasourcesGitIdToDatasourceMap.get(datasourceStorage.getGitSyncId()); + Datasource existingDatasource = + savedDatasourcesGitIdToDatasourceMap.get(datasourceStorage.getGitSyncId()); if (!permissionProvider.hasEditPermission(existingDatasource)) { - log.error("Trying to update datasource {} without edit permission", existingDatasource.getName()); - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.DATASOURCE, existingDatasource.getId())); + log.error( + "Trying to update datasource {} without edit permission", + existingDatasource.getName()); + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.DATASOURCE, + existingDatasource.getId())); } datasourceStorage.setId(null); - // Don't update datasource config as the saved datasource is already configured by user + // Don't update datasource config as the saved datasource is already configured by + // user // for this instance datasourceStorage.setDatasourceConfiguration(null); datasourceStorage.setPluginId(null); datasourceStorage.setEnvironmentId(environmentId); - Datasource newDatasource = datasourceService.createDatasourceFromDatasourceStorage(datasourceStorage); + Datasource newDatasource = + datasourceService.createDatasourceFromDatasourceStorage(datasourceStorage); newDatasource.setPolicies(null); copyNestedNonNullProperties(newDatasource, existingDatasource); @@ -1020,81 +1143,93 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, datasourceStorage, workspace, environmentId, - permissionProvider - ); + permissionProvider); }); }) .collectMap(Datasource::getName, Datasource::getId) .flatMap(map -> { - datasourceMap.putAll(map); - // 1. Assign the policies for the imported application - // 2. Check for possible duplicate names, - // 3. Save the updated application - - return Mono.just(importedApplication) - .zipWith(currUserMono) - .map(objects -> { - Application application = objects.getT1(); - application.setModifiedBy(objects.getT2().getUsername()); - return application; - }) - .flatMap(application -> { - importedApplication.setWorkspaceId(workspaceId); - // Application Id will be present for GIT sync - if (!StringUtils.isEmpty(applicationId)) { - return applicationService.findById(applicationId, permissionProvider.getRequiredPermissionOnTargetApplication()) - .switchIfEmpty(Mono.defer(() -> { - log.error("No application found with id: {} and permission: {}", applicationId, permissionProvider.getRequiredPermissionOnTargetApplication()); - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION, applicationId)); - })) - .flatMap(existingApplication -> { - if (appendToApp) { - // When we are appending the pages to the existing application - // e.g. import template we are only importing this in unpublished - // version. At the same time we want to keep the existing page ref - unpublishedPages.addAll(existingApplication.getPages()); - return Mono.just(existingApplication); - } - setPropertiesToExistingApplication(importedApplication, existingApplication); - // We are expecting the changes present in DB are committed to git directory - // so that these won't be lost when we are pulling changes from remote and - // rehydrate the application. We are now rehydrating the application with/without - // the changes from remote - // We are using the save instead of update as we are using @Encrypted - // for GitAuth - Mono<Application> parentApplicationMono; - if (existingApplication.getGitApplicationMetadata() != null) { - parentApplicationMono = applicationService.findById( - existingApplication.getGitApplicationMetadata().getDefaultApplicationId() - ); - } else { - parentApplicationMono = Mono.just(existingApplication); - } - - return parentApplicationMono - .flatMap(application1 -> { - // Set the policies from the defaultApplication - existingApplication.setPolicies(application1.getPolicies()); - importedApplication.setPolicies(application1.getPolicies()); - return applicationService.save(existingApplication) - .onErrorResume(DuplicateKeyException.class, error -> { - if (error.getMessage() != null) { - return applicationPageService - .createOrUpdateSuffixedApplication( - existingApplication, - existingApplication.getName(), - 0 - ); - } - throw error; - }); - }); - }); - } - return applicationPageService.createOrUpdateSuffixedApplication(application, application.getName(), 0); - }); - } - ) + datasourceMap.putAll(map); + // 1. Assign the policies for the imported application + // 2. Check for possible duplicate names, + // 3. Save the updated application + + return Mono.just(importedApplication) + .zipWith(currUserMono) + .map(objects -> { + Application application = objects.getT1(); + application.setModifiedBy(objects.getT2().getUsername()); + return application; + }) + .flatMap(application -> { + importedApplication.setWorkspaceId(workspaceId); + // Application Id will be present for GIT sync + if (!StringUtils.isEmpty(applicationId)) { + return applicationService + .findById( + applicationId, + permissionProvider.getRequiredPermissionOnTargetApplication()) + .switchIfEmpty(Mono.defer(() -> { + log.error( + "No application found with id: {} and permission: {}", + applicationId, + permissionProvider.getRequiredPermissionOnTargetApplication()); + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.APPLICATION, + applicationId)); + })) + .flatMap(existingApplication -> { + if (appendToApp) { + // When we are appending the pages to the existing application + // e.g. import template we are only importing this in unpublished + // version. At the same time we want to keep the existing page ref + unpublishedPages.addAll(existingApplication.getPages()); + return Mono.just(existingApplication); + } + setPropertiesToExistingApplication( + importedApplication, existingApplication); + // We are expecting the changes present in DB are committed to git + // directory + // so that these won't be lost when we are pulling changes from remote + // and + // rehydrate the application. We are now rehydrating the application + // with/without + // the changes from remote + // We are using the save instead of update as we are using @Encrypted + // for GitAuth + Mono<Application> parentApplicationMono; + if (existingApplication.getGitApplicationMetadata() != null) { + parentApplicationMono = + applicationService.findById(existingApplication + .getGitApplicationMetadata() + .getDefaultApplicationId()); + } else { + parentApplicationMono = Mono.just(existingApplication); + } + + return parentApplicationMono.flatMap(application1 -> { + // Set the policies from the defaultApplication + existingApplication.setPolicies(application1.getPolicies()); + importedApplication.setPolicies(application1.getPolicies()); + return applicationService + .save(existingApplication) + .onErrorResume(DuplicateKeyException.class, error -> { + if (error.getMessage() != null) { + return applicationPageService + .createOrUpdateSuffixedApplication( + existingApplication, + existingApplication.getName(), + 0); + } + throw error; + }); + }); + }); + } + return applicationPageService.createOrUpdateSuffixedApplication( + application, application.getName(), 0); + }); + }) .flatMap(savedApp -> importThemes(savedApp, importedDoc, appendToApp)) .flatMap(savedApp -> { importedApplication.setId(savedApp.getId()); @@ -1118,49 +1253,45 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, .cache(); Flux<NewPage> importNewPageFlux = importAndSavePages( - importedNewPageList, - savedApp, - branchName, - existingPagesMono, - permissionProvider - ); + importedNewPageList, savedApp, branchName, existingPagesMono, permissionProvider); Flux<NewPage> importedNewPagesMono; if (appendToApp) { // we need to rename page if there is a conflict // also need to remap the renamed page importedNewPagesMono = updateNewPagesBeforeMerge(existingPagesMono, importedNewPageList) - .flatMapMany(newToOldNameMap -> - importNewPageFlux.map(newPage -> { - // we need to map the newly created page with old name - // because other related resources e.g. actions will refer the page with old name - String newPageName = newPage.getUnpublishedPage().getName(); - String oldPageName = newToOldNameMap.get(newPageName); - if (!newPageName.equals(oldPageName)) { - renamePageInActions(importedNewActionList, oldPageName, newPageName); - renamePageInActionCollections(importedActionCollectionList, oldPageName, newPageName); - unpublishedPages.stream() - .filter(applicationPage -> oldPageName.equals(applicationPage.getId())) - .findAny() - .ifPresent(applicationPage -> applicationPage.setId(newPageName)); - } - return newPage; - }) - ); + .flatMapMany(newToOldNameMap -> importNewPageFlux.map(newPage -> { + // we need to map the newly created page with old name + // because other related resources e.g. actions will refer the page with old name + String newPageName = + newPage.getUnpublishedPage().getName(); + String oldPageName = newToOldNameMap.get(newPageName); + if (!newPageName.equals(oldPageName)) { + renamePageInActions(importedNewActionList, oldPageName, newPageName); + renamePageInActionCollections( + importedActionCollectionList, oldPageName, newPageName); + unpublishedPages.stream() + .filter(applicationPage -> oldPageName.equals(applicationPage.getId())) + .findAny() + .ifPresent(applicationPage -> applicationPage.setId(newPageName)); + } + return newPage; + })); } else { importedNewPagesMono = importNewPageFlux; } - importedNewPagesMono = importedNewPagesMono - .map(newPage -> { - // Save the map of pageName and NewPage - if (newPage.getUnpublishedPage() != null && newPage.getUnpublishedPage().getName() != null) { - pageNameMap.put(newPage.getUnpublishedPage().getName(), newPage); - } - if (newPage.getPublishedPage() != null && newPage.getPublishedPage().getName() != null) { - pageNameMap.put(newPage.getPublishedPage().getName(), newPage); - } - return newPage; - }); + importedNewPagesMono = importedNewPagesMono.map(newPage -> { + // Save the map of pageName and NewPage + if (newPage.getUnpublishedPage() != null + && newPage.getUnpublishedPage().getName() != null) { + pageNameMap.put(newPage.getUnpublishedPage().getName(), newPage); + } + if (newPage.getPublishedPage() != null + && newPage.getPublishedPage().getName() != null) { + pageNameMap.put(newPage.getPublishedPage().getName(), newPage); + } + return newPage; + }); return importedNewPagesMono .collectList() @@ -1180,11 +1311,15 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, // to the existing application continue; } - log.debug("Unable to find the page during import for appId {}, with name {}", applicationId, applicationPage.getId()); + log.debug( + "Unable to find the page during import for appId {}, with name {}", + applicationId, + applicationPage.getId()); unpublishedPageItr.remove(); } else { applicationPage.setId(newPage.getId()); - applicationPage.setDefaultPageId(newPage.getDefaultResources().getPageId()); + applicationPage.setDefaultPageId( + newPage.getDefaultResources().getPageId()); // Keep the existing page as the default one if (appendToApp) { applicationPage.setIsDefault(false); @@ -1193,10 +1328,16 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, } Iterator<ApplicationPage> publishedPagesItr; - // Remove the newly added pages from merge app flow. Keep only the existing page from the old app + // Remove the newly added pages from merge app flow. Keep only the existing page from + // the old app if (appendToApp) { - List<String> existingPagesId = savedApp.getPublishedPages().stream().map(applicationPage -> applicationPage.getId()).collect(Collectors.toList()); - List<ApplicationPage> publishedApplicationPages = publishedPages.stream().filter(applicationPage -> existingPagesId.contains(applicationPage.getId())).collect(Collectors.toList()); + List<String> existingPagesId = savedApp.getPublishedPages().stream() + .map(applicationPage -> applicationPage.getId()) + .collect(Collectors.toList()); + List<ApplicationPage> publishedApplicationPages = publishedPages.stream() + .filter(applicationPage -> + existingPagesId.contains(applicationPage.getId())) + .collect(Collectors.toList()); applicationPages.replace(VIEW, publishedApplicationPages); publishedPagesItr = publishedApplicationPages.iterator(); } else { @@ -1206,13 +1347,17 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, ApplicationPage applicationPage = publishedPagesItr.next(); NewPage newPage = pageNameMap.get(applicationPage.getId()); if (newPage == null) { - log.debug("Unable to find the page during import for appId {}, with name {}", applicationId, applicationPage.getId()); + log.debug( + "Unable to find the page during import for appId {}, with name {}", + applicationId, + applicationPage.getId()); if (!appendToApp) { publishedPagesItr.remove(); } } else { applicationPage.setId(newPage.getId()); - applicationPage.setDefaultPageId(newPage.getDefaultResources().getPageId()); + applicationPage.setDefaultPageId( + newPage.getDefaultResources().getPageId()); if (appendToApp) { applicationPage.setIsDefault(false); } @@ -1231,48 +1376,62 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, .map(ApplicationPage::getId) .collect(Collectors.toSet()); - validPageIds.addAll(applicationPages.get(VIEW) - .stream() + validPageIds.addAll(applicationPages.get(VIEW).stream() .map(ApplicationPage::getId) .collect(Collectors.toSet())); - return existingPagesMono - .flatMap(existingPagesList -> { - Set<String> invalidPageIds = new HashSet<>(); - for (NewPage newPage : existingPagesList) { - if (!validPageIds.contains(newPage.getId())) { - invalidPageIds.add(newPage.getId()); - } - } + return existingPagesMono.flatMap(existingPagesList -> { + Set<String> invalidPageIds = new HashSet<>(); + for (NewPage newPage : existingPagesList) { + if (!validPageIds.contains(newPage.getId())) { + invalidPageIds.add(newPage.getId()); + } + } - // Delete the pages which were removed during git merge operation - // This does not apply to the traditional import via file approach - return Flux.fromIterable(invalidPageIds) - .flatMap(applicationPageService::deleteWithoutPermissionUnpublishedPage) - .flatMap(page -> newPageService.archiveWithoutPermissionById(page.getId()) - .onErrorResume(e -> { - log.debug("Unable to archive page {} with error {}", page.getId(), e.getMessage()); - return Mono.empty(); - }) - ) - .then() - .thenReturn(applicationPages); - }); + // Delete the pages which were removed during git merge operation + // This does not apply to the traditional import via file approach + return Flux.fromIterable(invalidPageIds) + .flatMap(applicationPageService::deleteWithoutPermissionUnpublishedPage) + .flatMap(page -> newPageService + .archiveWithoutPermissionById(page.getId()) + .onErrorResume(e -> { + log.debug( + "Unable to archive page {} with error {}", + page.getId(), + e.getMessage()); + return Mono.empty(); + })) + .then() + .thenReturn(applicationPages); + }); } return Mono.just(applicationPages); }); }) .map(applicationPageMap -> { - log.info("Imported pages. Edit: {}, View: {}", applicationPageMap.get(EDIT).size(), applicationPageMap.get(VIEW).size()); + log.info( + "Imported pages. Edit: {}, View: {}", + applicationPageMap.get(EDIT).size(), + applicationPageMap.get(VIEW).size()); log.info("Importing actions for applicationId: {}, ", importedApplication.getId()); // Set page sequence based on the order for published and unpublished pages importedApplication.setPages(applicationPageMap.get(EDIT)); importedApplication.setPublishedPages(applicationPageMap.get(VIEW)); return applicationPageMap; }) - .then(newActionService.importActions(importedNewActionList, importedApplication, branchName, pageNameMap, pluginMap, datasourceMap, permissionProvider)) + .then(newActionService.importActions( + importedNewActionList, + importedApplication, + branchName, + pageNameMap, + pluginMap, + datasourceMap, + permissionProvider)) .flatMap(importActionResultDTO -> { - log.info("Actions imported. applicationId {}, result: {}", importedApplication.getId(), importActionResultDTO.getGist()); + log.info( + "Actions imported. applicationId {}, result: {}", + importedApplication.getId(), + importActionResultDTO.getGist()); // Updating the existing application for git-sync // During partial import/appending to the existing application keep the resources // attached to the application: @@ -1288,14 +1447,14 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, } log.info("Deleting {} actions which are no more used", invalidActionIds.size()); return Flux.fromIterable(invalidActionIds) - .flatMap(actionId -> newActionService.deleteUnpublishedAction(actionId) + .flatMap(actionId -> newActionService + .deleteUnpublishedAction(actionId) // return an empty action so that the filter can remove it from the list .onErrorResume(throwable -> { log.debug("Failed to delete action with id {} during import", actionId); log.error(throwable.getMessage()); return Mono.empty(); - }) - ) + })) .then() .thenReturn(importActionResultDTO); } @@ -1303,17 +1462,32 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, }) .flatMap(importActionResultDTO -> { log.info("Importing action collections for applicationId {}", importedApplication.getId()); - return actionCollectionService.importActionCollections(importActionResultDTO, importedApplication, branchName, importedActionCollectionList, pluginMap, pageNameMap, permissionProvider) + return actionCollectionService + .importActionCollections( + importActionResultDTO, + importedApplication, + branchName, + importedActionCollectionList, + pluginMap, + pageNameMap, + permissionProvider) .zipWith(Mono.just(importActionResultDTO)); }) .flatMap(resultDtos -> { ImportActionCollectionResultDTO importActionCollectionResultDTO = resultDtos.getT1(); ImportActionResultDTO importActionResultDTO = resultDtos.getT2(); List<String> savedCollectionIds = importActionCollectionResultDTO.getSavedActionCollectionIds(); - log.info("Action collections imported. applicationId {}, result: {}", importedApplication.getId(), importActionCollectionResultDTO.getGist()); - return newActionService.updateActionsWithImportedCollectionIds(importActionCollectionResultDTO, importActionResultDTO) + log.info( + "Action collections imported. applicationId {}, result: {}", + importedApplication.getId(), + importActionCollectionResultDTO.getGist()); + return newActionService + .updateActionsWithImportedCollectionIds( + importActionCollectionResultDTO, importActionResultDTO) .flatMap(actionAndCollectionMapsDTO -> { - log.info("Updated actions with imported collection ids. applicationId {}", importedApplication.getId()); + log.info( + "Updated actions with imported collection ids. applicationId {}", + importedApplication.getId()); // Updating the existing application for git-sync // During partial import/appending to the existing application keep the resources // attached to the application: @@ -1322,21 +1496,27 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, if (!StringUtils.isEmpty(applicationId) && !appendToApp) { // Remove unwanted action collections Set<String> invalidCollectionIds = new HashSet<>(); - for (ActionCollection collection : importActionCollectionResultDTO.getExistingActionCollections()) { + for (ActionCollection collection : + importActionCollectionResultDTO.getExistingActionCollections()) { if (!savedCollectionIds.contains(collection.getId())) { invalidCollectionIds.add(collection.getId()); } } - log.info("Deleting {} action collections which are no more used", invalidCollectionIds.size()); + log.info( + "Deleting {} action collections which are no more used", + invalidCollectionIds.size()); return Flux.fromIterable(invalidCollectionIds) - .flatMap(collectionId -> actionCollectionService.deleteWithoutPermissionUnpublishedActionCollection(collectionId) - // return an empty collection so that the filter can remove it from the list + .flatMap(collectionId -> actionCollectionService + .deleteWithoutPermissionUnpublishedActionCollection(collectionId) + // return an empty collection so that the filter can remove it from + // the list .onErrorResume(throwable -> { - log.debug("Failed to delete collection with id {} during import", collectionId); + log.debug( + "Failed to delete collection with id {} during import", + collectionId); log.error(throwable.getMessage()); return Mono.empty(); - }) - ) + })) .then() .thenReturn(actionAndCollectionMapsDTO); } @@ -1350,7 +1530,8 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, // Don't update gitAuth as we are using @Encrypted for private key importedApplication.setGitApplicationMetadata(null); // Map layoutOnLoadActions ids with relevant actions - return newPageService.findNewPagesByApplicationId(importedApplication.getId(), Optional.empty()) + return newPageService + .findNewPagesByApplicationId(importedApplication.getId(), Optional.empty()) .flatMap(newPage -> { if (newPage.getDefaultResources() != null) { newPage.getDefaultResources().setBranchName(branchName); @@ -1359,48 +1540,64 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId, newPage, importActionResultDTO.getActionIdMap(), actionAndCollectionMapsDTO.getUnpublishedActionIdToCollectionIdMap(), - actionAndCollectionMapsDTO.getPublishedActionIdToCollectionIdMap() - ); + actionAndCollectionMapsDTO.getPublishedActionIdToCollectionIdMap()); }) .collectList() .flatMapMany(newPageService::saveAll) .then(applicationService.update(importedApplication.getId(), importedApplication)) - .then(sendImportExportApplicationAnalyticsEvent(importedApplication.getId(), AnalyticsEvents.IMPORT)) + .then(sendImportExportApplicationAnalyticsEvent( + importedApplication.getId(), AnalyticsEvents.IMPORT)) .zipWith(currUserMono) .flatMap(tuple -> { Application application = tuple.getT1(); stopwatch.stopTimer(); stopwatch.stopAndLogTimeInMillis(); final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, application.getId(), - FieldName.WORKSPACE_ID, application.getWorkspaceId(), - "pageCount", applicationJson.getPageList().size(), - "actionCount", applicationJson.getActionList().size(), - "JSObjectCount", applicationJson.getActionCollectionList().size(), - FieldName.FLOW_NAME, stopwatch.getFlow(), - "executionTime", stopwatch.getExecutionTime() - ); - return analyticsService.sendEvent(AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), tuple.getT2().getUsername(), data) + FieldName.APPLICATION_ID, + application.getId(), + FieldName.WORKSPACE_ID, + application.getWorkspaceId(), + "pageCount", + applicationJson.getPageList().size(), + "actionCount", + applicationJson.getActionList().size(), + "JSObjectCount", + applicationJson + .getActionCollectionList() + .size(), + FieldName.FLOW_NAME, + stopwatch.getFlow(), + "executionTime", + stopwatch.getExecutionTime()); + return analyticsService + .sendEvent( + AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), + tuple.getT2().getUsername(), + data) .thenReturn(application); }); }) .onErrorResume(throwable -> { String errorMessage = ImportExportUtils.getErrorMessage(throwable); log.error("Error importing application. Error: {}", errorMessage, throwable); - return Mono.error(new AppsmithException(AppsmithError.GENERIC_JSON_IMPORT_ERROR, workspaceId, errorMessage)); + return Mono.error( + new AppsmithException(AppsmithError.GENERIC_JSON_IMPORT_ERROR, workspaceId, errorMessage)); }) .as(transactionalOperator::transactional); // Import Application is currently a slow API because it needs to import and create application, pages, actions - // and action collection. This process may take time and the client may cancel the request. This leads to the flow - // getting stopped midway producing corrupted objects in DB. The following ensures that even though the client may have - // cancelled the flow, the importing the application should proceed uninterrupted and whenever the user refreshes + // and action collection. This process may take time and the client may cancel the request. This leads to the + // flow + // getting stopped midway producing corrupted objects in DB. The following ensures that even though the client + // may have + // cancelled the flow, the importing the application should proceed uninterrupted and whenever the user + // refreshes // the page, the imported application is available and is in sane state. // To achieve this, we use a synchronous sink which does not take subscription cancellations into account. This - // means that even if the subscriber has cancelled its subscription, the create method still generates its event. - return Mono.create(sink -> importedApplicationMono - .subscribe(sink::success, sink::error, null, sink.currentContext()) - ); + // means that even if the subscriber has cancelled its subscription, the create method still generates its + // event. + return Mono.create( + sink -> importedApplicationMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } private void renamePageInActions(List<NewAction> newActionList, String oldPageName, String newPageName) { @@ -1411,7 +1608,8 @@ private void renamePageInActions(List<NewAction> newActionList, String oldPageNa } } - private void renamePageInActionCollections(List<ActionCollection> actionCollectionList, String oldPageName, String newPageName) { + private void renamePageInActionCollections( + List<ActionCollection> actionCollectionList, String oldPageName, String newPageName) { for (ActionCollection actionCollection : actionCollectionList) { if (actionCollection.getUnpublishedCollection().getPageId().equals(oldPageName)) { actionCollection.getUnpublishedCollection().setPageId(newPageName); @@ -1451,11 +1649,12 @@ private Mono<String> getUniqueSuffixForDuplicateNameEntity(BaseDomain sourceEnti * @param existingPages existing pages in DB if the application is connected to git * @return flux of saved pages in DB */ - private Flux<NewPage> importAndSavePages(List<NewPage> pages, - Application application, - String branchName, - Mono<List<NewPage>> existingPages, - ImportApplicationPermissionProvider permissionProvider) { + private Flux<NewPage> importAndSavePages( + List<NewPage> pages, + Application application, + String branchName, + Mono<List<NewPage>> existingPages, + ImportApplicationPermissionProvider permissionProvider) { Map<String, String> oldToNewLayoutIds = new HashMap<>(); pages.forEach(newPage -> { @@ -1474,7 +1673,8 @@ private Flux<NewPage> importAndSavePages(List<NewPage> pages, applicationPageService.generateAndSetPagePolicies(application, newPage.getPublishedPage()); newPage.getPublishedPage().getLayouts().forEach(layout -> { String layoutId = oldToNewLayoutIds.containsKey(layout.getId()) - ? oldToNewLayoutIds.get(layout.getId()) : new ObjectId().toString(); + ? oldToNewLayoutIds.get(layout.getId()) + : new ObjectId().toString(); layout.setId(layoutId); }); } @@ -1487,87 +1687,104 @@ private Flux<NewPage> importAndSavePages(List<NewPage> pages, .filter(newPage -> !StringUtils.isEmpty(newPage.getGitSyncId())) .forEach(newPage -> savedPagesGitIdToPageMap.put(newPage.getGitSyncId(), newPage)); - return Flux.fromIterable(pages) - .flatMap(newPage -> { + return Flux.fromIterable(pages).flatMap(newPage -> { - // Check if the page has gitSyncId and if it's already in DB - if (newPage.getGitSyncId() != null && savedPagesGitIdToPageMap.containsKey(newPage.getGitSyncId())) { - //Since the resource is already present in DB, just update resource - NewPage existingPage = savedPagesGitIdToPageMap.get(newPage.getGitSyncId()); - if (!permissionProvider.hasEditPermission(existingPage)) { - log.error("User does not have permission to edit page with id: {}", existingPage.getId()); - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, existingPage.getId())); - } - Set<Policy> existingPagePolicy = existingPage.getPolicies(); - copyNestedNonNullProperties(newPage, existingPage); - // Update branchName - existingPage.getDefaultResources().setBranchName(branchName); - // Recover the deleted state present in DB from imported page - existingPage.getUnpublishedPage().setDeletedAt(newPage.getUnpublishedPage().getDeletedAt()); - existingPage.setDeletedAt(newPage.getDeletedAt()); - existingPage.setDeleted(newPage.getDeleted()); - existingPage.setPolicies(existingPagePolicy); - return newPageService.save(existingPage); - } else { - // check if user has permission to add new page to the application - if (!permissionProvider.canCreatePage(application)) { - log.error("User does not have permission to create page in application with id: {}", application.getId()); - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION, application.getId())); - } - if (application.getGitApplicationMetadata() != null) { - final String defaultApplicationId = application.getGitApplicationMetadata().getDefaultApplicationId(); - return newPageService.findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, newPage.getGitSyncId(), Optional.empty()) - .switchIfEmpty(Mono.defer(() -> { - // This is the first page we are saving with given gitSyncId in this instance - DefaultResources defaultResources = new DefaultResources(); - defaultResources.setApplicationId(defaultApplicationId); - defaultResources.setBranchName(branchName); - newPage.setDefaultResources(defaultResources); - return saveNewPageAndUpdateDefaultResources(newPage, branchName); - })) - .flatMap(branchedPage -> { - DefaultResources defaultResources = branchedPage.getDefaultResources(); - // Create new page but keep defaultApplicationId and defaultPageId same for both the pages - defaultResources.setBranchName(branchName); - newPage.setDefaultResources(defaultResources); - newPage.getUnpublishedPage().setDeletedAt(branchedPage.getUnpublishedPage().getDeletedAt()); - newPage.setDeletedAt(branchedPage.getDeletedAt()); - newPage.setDeleted(branchedPage.getDeleted()); - // Set policies from existing branch object - newPage.setPolicies(branchedPage.getPolicies()); - return newPageService.save(newPage); - }); - } - return saveNewPageAndUpdateDefaultResources(newPage, branchName); - } - }); + // Check if the page has gitSyncId and if it's already in DB + if (newPage.getGitSyncId() != null && savedPagesGitIdToPageMap.containsKey(newPage.getGitSyncId())) { + // Since the resource is already present in DB, just update resource + NewPage existingPage = savedPagesGitIdToPageMap.get(newPage.getGitSyncId()); + if (!permissionProvider.hasEditPermission(existingPage)) { + log.error("User does not have permission to edit page with id: {}", existingPage.getId()); + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.PAGE, existingPage.getId())); + } + Set<Policy> existingPagePolicy = existingPage.getPolicies(); + copyNestedNonNullProperties(newPage, existingPage); + // Update branchName + existingPage.getDefaultResources().setBranchName(branchName); + // Recover the deleted state present in DB from imported page + existingPage + .getUnpublishedPage() + .setDeletedAt(newPage.getUnpublishedPage().getDeletedAt()); + existingPage.setDeletedAt(newPage.getDeletedAt()); + existingPage.setDeleted(newPage.getDeleted()); + existingPage.setPolicies(existingPagePolicy); + return newPageService.save(existingPage); + } else { + // check if user has permission to add new page to the application + if (!permissionProvider.canCreatePage(application)) { + log.error( + "User does not have permission to create page in application with id: {}", + application.getId()); + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.APPLICATION, application.getId())); + } + if (application.getGitApplicationMetadata() != null) { + final String defaultApplicationId = + application.getGitApplicationMetadata().getDefaultApplicationId(); + return newPageService + .findByGitSyncIdAndDefaultApplicationId( + defaultApplicationId, newPage.getGitSyncId(), Optional.empty()) + .switchIfEmpty(Mono.defer(() -> { + // This is the first page we are saving with given gitSyncId in this instance + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setApplicationId(defaultApplicationId); + defaultResources.setBranchName(branchName); + newPage.setDefaultResources(defaultResources); + return saveNewPageAndUpdateDefaultResources(newPage, branchName); + })) + .flatMap(branchedPage -> { + DefaultResources defaultResources = branchedPage.getDefaultResources(); + // Create new page but keep defaultApplicationId and defaultPageId same for both the + // pages + defaultResources.setBranchName(branchName); + newPage.setDefaultResources(defaultResources); + newPage.getUnpublishedPage() + .setDeletedAt(branchedPage + .getUnpublishedPage() + .getDeletedAt()); + newPage.setDeletedAt(branchedPage.getDeletedAt()); + newPage.setDeleted(branchedPage.getDeleted()); + // Set policies from existing branch object + newPage.setPolicies(branchedPage.getPolicies()); + return newPageService.save(newPage); + }); + } + return saveNewPageAndUpdateDefaultResources(newPage, branchName); + } + }); }); } private Mono<NewPage> saveNewPageAndUpdateDefaultResources(NewPage newPage, String branchName) { NewPage update = new NewPage(); - return newPageService.save(newPage) - .flatMap(page -> { - update.setDefaultResources(DefaultResourcesUtils.createDefaultIdsOrUpdateWithGivenResourceIds(page, branchName).getDefaultResources()); - return newPageService.update(page.getId(), update); - }); + return newPageService.save(newPage).flatMap(page -> { + update.setDefaultResources( + DefaultResourcesUtils.createDefaultIdsOrUpdateWithGivenResourceIds(page, branchName) + .getDefaultResources()); + return newPageService.update(page.getId(), update); + }); } - private Set<String> getLayoutOnLoadActionsForPage(NewPage page, - Map<String, String> actionIdMap, - Map<String, List<String>> unpublishedActionIdToCollectionIdsMap, - Map<String, List<String>> publishedActionIdToCollectionIdsMap) { + private Set<String> getLayoutOnLoadActionsForPage( + NewPage page, + Map<String, String> actionIdMap, + Map<String, List<String>> unpublishedActionIdToCollectionIdsMap, + Map<String, List<String>> publishedActionIdToCollectionIdsMap) { Set<String> layoutOnLoadActions = new HashSet<>(); if (page.getUnpublishedPage().getLayouts() != null) { page.getUnpublishedPage().getLayouts().forEach(layout -> { if (layout.getLayoutOnLoadActions() != null) { - layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction - .forEach(actionDTO -> { + layout.getLayoutOnLoadActions() + .forEach(onLoadAction -> onLoadAction.forEach(actionDTO -> { actionDTO.setId(actionIdMap.get(actionDTO.getId())); if (!CollectionUtils.sizeIsEmpty(unpublishedActionIdToCollectionIdsMap) - && !CollectionUtils.isEmpty(unpublishedActionIdToCollectionIdsMap.get(actionDTO.getId()))) { - actionDTO.setCollectionId(unpublishedActionIdToCollectionIdsMap.get(actionDTO.getId()).get(0)); + && !CollectionUtils.isEmpty( + unpublishedActionIdToCollectionIdsMap.get(actionDTO.getId()))) { + actionDTO.setCollectionId(unpublishedActionIdToCollectionIdsMap + .get(actionDTO.getId()) + .get(0)); } layoutOnLoadActions.add(actionDTO.getId()); })); @@ -1579,12 +1796,15 @@ private Set<String> getLayoutOnLoadActionsForPage(NewPage page, page.getPublishedPage().getLayouts().forEach(layout -> { if (layout.getLayoutOnLoadActions() != null) { - layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction - .forEach(actionDTO -> { + layout.getLayoutOnLoadActions() + .forEach(onLoadAction -> onLoadAction.forEach(actionDTO -> { actionDTO.setId(actionIdMap.get(actionDTO.getId())); if (!CollectionUtils.sizeIsEmpty(publishedActionIdToCollectionIdsMap) - && !CollectionUtils.isEmpty(publishedActionIdToCollectionIdsMap.get(actionDTO.getId()))) { - actionDTO.setCollectionId(publishedActionIdToCollectionIdsMap.get(actionDTO.getId()).get(0)); + && !CollectionUtils.isEmpty( + publishedActionIdToCollectionIdsMap.get(actionDTO.getId()))) { + actionDTO.setCollectionId(publishedActionIdToCollectionIdsMap + .get(actionDTO.getId()) + .get(0)); } layoutOnLoadActions.add(actionDTO.getId()); })); @@ -1597,56 +1817,68 @@ private Set<String> getLayoutOnLoadActionsForPage(NewPage page, } // This method will update the action id in saved page for layoutOnLoadAction - private Mono<NewPage> mapActionAndCollectionIdWithPageLayout(NewPage newPage, - Map<String, String> actionIdMap, - Map<String, List<String>> unpublishedActionIdToCollectionIdsMap, - Map<String, List<String>> publishedActionIdToCollectionIdsMap) { - - return Mono.just(newPage) - .flatMap(page -> { - return newActionService.findAllById(getLayoutOnLoadActionsForPage(page, actionIdMap, unpublishedActionIdToCollectionIdsMap, publishedActionIdToCollectionIdsMap)) - .map(newAction -> { - final String defaultActionId = newAction.getDefaultResources().getActionId(); - if (page.getUnpublishedPage().getLayouts() != null) { - final String defaultCollectionId = newAction.getUnpublishedAction().getDefaultResources().getCollectionId(); - page.getUnpublishedPage().getLayouts().forEach(layout -> { - if (layout.getLayoutOnLoadActions() != null) { - layout.getLayoutOnLoadActions() - .forEach(onLoadAction -> onLoadAction - .stream() - .filter(actionDTO -> StringUtils.equals(actionDTO.getId(), newAction.getId())) - .forEach(actionDTO -> { - actionDTO.setDefaultActionId(defaultActionId); - actionDTO.setDefaultCollectionId(defaultCollectionId); - }) - ); - } - }); + private Mono<NewPage> mapActionAndCollectionIdWithPageLayout( + NewPage newPage, + Map<String, String> actionIdMap, + Map<String, List<String>> unpublishedActionIdToCollectionIdsMap, + Map<String, List<String>> publishedActionIdToCollectionIdsMap) { + + return Mono.just(newPage).flatMap(page -> { + return newActionService + .findAllById(getLayoutOnLoadActionsForPage( + page, + actionIdMap, + unpublishedActionIdToCollectionIdsMap, + publishedActionIdToCollectionIdsMap)) + .map(newAction -> { + final String defaultActionId = + newAction.getDefaultResources().getActionId(); + if (page.getUnpublishedPage().getLayouts() != null) { + final String defaultCollectionId = newAction + .getUnpublishedAction() + .getDefaultResources() + .getCollectionId(); + page.getUnpublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction.stream() + .filter(actionDTO -> + StringUtils.equals(actionDTO.getId(), newAction.getId())) + .forEach(actionDTO -> { + actionDTO.setDefaultActionId(defaultActionId); + actionDTO.setDefaultCollectionId(defaultCollectionId); + })); } + }); + } - if (page.getPublishedPage() != null && page.getPublishedPage().getLayouts() != null) { - page.getPublishedPage().getLayouts().forEach(layout -> { - if (layout.getLayoutOnLoadActions() != null) { - layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction - .stream() - .filter(actionDTO -> StringUtils.equals(actionDTO.getId(), newAction.getId())) - .forEach(actionDTO -> { - actionDTO.setDefaultActionId(defaultActionId); - if (newAction.getPublishedAction() != null - && newAction.getPublishedAction().getDefaultResources() != null) { - actionDTO.setDefaultCollectionId( - newAction.getPublishedAction().getDefaultResources().getCollectionId() - ); - } - }) - ); - } - }); + if (page.getPublishedPage() != null + && page.getPublishedPage().getLayouts() != null) { + page.getPublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction.stream() + .filter(actionDTO -> + StringUtils.equals(actionDTO.getId(), newAction.getId())) + .forEach(actionDTO -> { + actionDTO.setDefaultActionId(defaultActionId); + if (newAction.getPublishedAction() != null + && newAction + .getPublishedAction() + .getDefaultResources() + != null) { + actionDTO.setDefaultCollectionId(newAction + .getPublishedAction() + .getDefaultResources() + .getCollectionId()); + } + })); } - return newAction; - }).collectList() - .thenReturn(page); - }); + }); + } + return newAction; + }) + .collectList() + .thenReturn(page); + }); } /** @@ -1657,52 +1889,60 @@ private Mono<NewPage> mapActionAndCollectionIdWithPageLayout(NewPage newPage, * @param workspace workspace where duplicate datasource should be checked * @return already present or brand new datasource depending upon the equality check */ - private Mono<Datasource> createUniqueDatasourceIfNotPresent(Flux<Datasource> existingDatasourceFlux, - DatasourceStorage datasourceStorage, - Workspace workspace, - String environmentId, - ImportApplicationPermissionProvider permissionProvider) { + private Mono<Datasource> createUniqueDatasourceIfNotPresent( + Flux<Datasource> existingDatasourceFlux, + DatasourceStorage datasourceStorage, + Workspace workspace, + String environmentId, + ImportApplicationPermissionProvider permissionProvider) { /* - 1. If same datasource is present return - 2. If unable to find the datasource create a new datasource with unique name and return - */ + 1. If same datasource is present return + 2. If unable to find the datasource create a new datasource with unique name and return + */ final DatasourceConfiguration datasourceConfig = datasourceStorage.getDatasourceConfiguration(); AuthenticationResponse authResponse = new AuthenticationResponse(); if (datasourceConfig != null && datasourceConfig.getAuthentication() != null) { - copyNestedNonNullProperties( - datasourceConfig.getAuthentication().getAuthenticationResponse(), authResponse); + copyNestedNonNullProperties(datasourceConfig.getAuthentication().getAuthenticationResponse(), authResponse); datasourceConfig.getAuthentication().setAuthenticationResponse(null); datasourceConfig.getAuthentication().setAuthenticationType(null); } return existingDatasourceFlux // For git import exclude datasource configuration - .filter(ds -> ds.getName().equals(datasourceStorage.getName()) && datasourceStorage.getPluginId().equals(ds.getPluginId())) - .next() // Get the first matching datasource, we don't need more than one here. + .filter(ds -> ds.getName().equals(datasourceStorage.getName()) + && datasourceStorage.getPluginId().equals(ds.getPluginId())) + .next() // Get the first matching datasource, we don't need more than one here. .switchIfEmpty(Mono.defer(() -> { // check if user has permission to create datasource if (!permissionProvider.canCreateDatasource(workspace)) { - log.error("Unauthorized to create datasource: {} in workspace: {}", datasourceStorage.getName(), workspace.getName()); - return Mono.error(new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.DATASOURCE, datasourceStorage.getName())); + log.error( + "Unauthorized to create datasource: {} in workspace: {}", + datasourceStorage.getName(), + workspace.getName()); + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.DATASOURCE, + datasourceStorage.getName())); } if (datasourceConfig != null && datasourceConfig.getAuthentication() != null) { datasourceConfig.getAuthentication().setAuthenticationResponse(authResponse); } // No matching existing datasource found, so create a new one. - datasourceStorage.setIsConfigured(datasourceConfig != null && datasourceConfig.getAuthentication() != null); + datasourceStorage.setIsConfigured( + datasourceConfig != null && datasourceConfig.getAuthentication() != null); datasourceStorage.setEnvironmentId(environmentId); return datasourceService .findByNameAndWorkspaceId(datasourceStorage.getName(), workspace.getId(), Optional.empty()) .flatMap(duplicateNameDatasource -> - getUniqueSuffixForDuplicateNameEntity(duplicateNameDatasource, workspace.getId()) - ) + getUniqueSuffixForDuplicateNameEntity(duplicateNameDatasource, workspace.getId())) .map(dsName -> { datasourceStorage.setName(datasourceStorage.getName() + dsName); return datasourceService.createDatasourceFromDatasourceStorage(datasourceStorage); }) - .switchIfEmpty(Mono.just(datasourceService.createDatasourceFromDatasourceStorage(datasourceStorage))) + .switchIfEmpty(Mono.just( + datasourceService.createDatasourceFromDatasourceStorage(datasourceStorage))) .flatMap(datasourceService::createWithoutPermissions); })); } @@ -1714,7 +1954,8 @@ private Mono<Datasource> createUniqueDatasourceIfNotPresent(Flux<Datasource> exi * @param decryptedFields sensitive fields * @return updated datasourceStorage with rehydrated sensitive fields */ - private DatasourceStorage updateAuthenticationDTO(DatasourceStorage datasourceStorage, DecryptedSensitiveFields decryptedFields) { + private DatasourceStorage updateAuthenticationDTO( + DatasourceStorage datasourceStorage, DecryptedSensitiveFields decryptedFields) { final DatasourceConfiguration dsConfig = datasourceStorage.getDatasourceConfiguration(); String authType = decryptedFields.getAuthType(); @@ -1748,7 +1989,8 @@ private DatasourceStorage updateAuthenticationDTO(DatasourceStorage datasourceSt return datasourceStorage; } - private Mono<Application> importThemes(Application application, ApplicationJson importedApplicationJson, boolean appendToApp) { + private Mono<Application> importThemes( + Application application, ApplicationJson importedApplicationJson, boolean appendToApp) { if (appendToApp) { // appending to existing app, theme should not change return Mono.just(application); @@ -1764,13 +2006,13 @@ private Mono<Application> importThemes(Application application, ApplicationJson */ private DecryptedSensitiveFields getDecryptedFields(DatasourceStorage datasourceStorage) { final AuthenticationDTO authentication = datasourceStorage.getDatasourceConfiguration() == null - ? null : datasourceStorage.getDatasourceConfiguration().getAuthentication(); + ? null + : datasourceStorage.getDatasourceConfiguration().getAuthentication(); if (authentication != null) { - DecryptedSensitiveFields dsDecryptedFields = - authentication.getAuthenticationResponse() == null - ? new DecryptedSensitiveFields() - : new DecryptedSensitiveFields(authentication.getAuthenticationResponse()); + DecryptedSensitiveFields dsDecryptedFields = authentication.getAuthenticationResponse() == null + ? new DecryptedSensitiveFields() + : new DecryptedSensitiveFields(authentication.getAuthenticationResponse()); if (authentication instanceof DBAuth) { DBAuth auth = (DBAuth) authentication; @@ -1798,18 +2040,18 @@ public Mono<List<Datasource>> findDatasourceByApplicationId(String applicationId Mono<List<Datasource>> listMono = datasourceService .getAllByWorkspaceIdWithStorages(workspaceId, Optional.empty()) .collectList(); - return newActionService.findAllByApplicationIdAndViewMode( - applicationId, - false, - Optional.empty(), - Optional.empty()) + return newActionService + .findAllByApplicationIdAndViewMode(applicationId, false, Optional.empty(), Optional.empty()) .collectList() .zipWith(listMono) .flatMap(objects -> { List<Datasource> datasourceList = objects.getT2(); List<NewAction> actionList = objects.getT1(); List<String> usedDatasource = actionList.stream() - .map(newAction -> newAction.getUnpublishedAction().getDatasource().getId()) + .map(newAction -> newAction + .getUnpublishedAction() + .getDatasource() + .getId()) .collect(Collectors.toList()); datasourceList.removeIf(datasource -> !usedDatasource.contains(datasource.getId())); @@ -1819,9 +2061,8 @@ public Mono<List<Datasource>> findDatasourceByApplicationId(String applicationId } @Override - public Mono<ApplicationImportDTO> getApplicationImportDTO(String applicationId, - String workspaceId, - Application application) { + public Mono<ApplicationImportDTO> getApplicationImportDTO( + String applicationId, String workspaceId, Application application) { return findDatasourceByApplicationId(applicationId, workspaceId) .zipWith(workspaceService.getDefaultEnvironmentId(workspaceId)) .map(tuple2 -> { @@ -1829,12 +2070,11 @@ public Mono<ApplicationImportDTO> getApplicationImportDTO(String applicationId, String environmentId = tuple2.getT2(); ApplicationImportDTO applicationImportDTO = new ApplicationImportDTO(); applicationImportDTO.setApplication(application); - Boolean isUnConfiguredDatasource = datasources.stream() - .anyMatch(datasource -> { - DatasourceStorageDTO datasourceStorageDTO = - datasource.getDatasourceStorages().get(environmentId); - return Boolean.FALSE.equals(datasourceStorageDTO.getIsConfigured()); - }); + Boolean isUnConfiguredDatasource = datasources.stream().anyMatch(datasource -> { + DatasourceStorageDTO datasourceStorageDTO = + datasource.getDatasourceStorages().get(environmentId); + return Boolean.FALSE.equals(datasourceStorageDTO.getIsConfigured()); + }); if (Boolean.TRUE.equals(isUnConfiguredDatasource)) { applicationImportDTO.setIsPartialImport(true); applicationImportDTO.setUnConfiguredDatasourceList(datasources); @@ -1854,11 +2094,12 @@ public Mono<ApplicationImportDTO> getApplicationImportDTO(String applicationId, * @return Merged Application */ @Override - public Mono<Application> mergeApplicationJsonWithApplication(String workspaceId, - String applicationId, - String branchName, - ApplicationJson applicationJson, - List<String> pagesToImport) { + public Mono<Application> mergeApplicationJsonWithApplication( + String workspaceId, + String applicationId, + String branchName, + ApplicationJson applicationJson, + List<String> pagesToImport) { // Update the application JSON to prepare it for merging inside an existing application if (applicationJson.getExportedApplication() != null) { // setting some properties to null so that target application is not updated by these properties @@ -1872,13 +2113,15 @@ public Mono<Application> mergeApplicationJsonWithApplication(String workspaceId, // need to remove git sync id. Also filter pages if pageToImport is not empty if (applicationJson.getPageList() != null) { - List<ApplicationPage> applicationPageList = new ArrayList<>(applicationJson.getPageList().size()); - List<String> pageNames = new ArrayList<>(applicationJson.getPageList().size()); + List<ApplicationPage> applicationPageList = + new ArrayList<>(applicationJson.getPageList().size()); + List<String> pageNames = + new ArrayList<>(applicationJson.getPageList().size()); List<NewPage> importedNewPageList = applicationJson.getPageList().stream() - .filter(newPage -> newPage.getUnpublishedPage() != null && - (CollectionUtils.isEmpty(pagesToImport) || - pagesToImport.contains(newPage.getUnpublishedPage().getName())) - ) + .filter(newPage -> newPage.getUnpublishedPage() != null + && (CollectionUtils.isEmpty(pagesToImport) + || pagesToImport.contains( + newPage.getUnpublishedPage().getName()))) .peek(newPage -> { ApplicationPage applicationPage = new ApplicationPage(); applicationPage.setId(newPage.getUnpublishedPage().getName()); @@ -1895,37 +2138,45 @@ public Mono<Application> mergeApplicationJsonWithApplication(String workspaceId, } if (applicationJson.getActionList() != null) { List<NewAction> importedNewActionList = applicationJson.getActionList().stream() - .filter(newAction -> - newAction.getUnpublishedAction() != null && - (CollectionUtils.isEmpty(pagesToImport) || - pagesToImport.contains(newAction.getUnpublishedAction().getPageId())) - ).peek(newAction -> newAction.setGitSyncId(null)) // setting this null so that this action can be imported again + .filter(newAction -> newAction.getUnpublishedAction() != null + && (CollectionUtils.isEmpty(pagesToImport) + || pagesToImport.contains( + newAction.getUnpublishedAction().getPageId()))) + .peek(newAction -> + newAction.setGitSyncId(null)) // setting this null so that this action can be imported again .collect(Collectors.toList()); applicationJson.setActionList(importedNewActionList); } if (applicationJson.getActionCollectionList() != null) { List<ActionCollection> importedActionCollectionList = applicationJson.getActionCollectionList().stream() - .filter(actionCollection -> - (CollectionUtils.isEmpty(pagesToImport) || - pagesToImport.contains(actionCollection.getUnpublishedCollection().getPageId())) - ).peek(actionCollection -> actionCollection.setGitSyncId(null)) // setting this null so that this action collection can be imported again + .filter(actionCollection -> (CollectionUtils.isEmpty(pagesToImport) + || pagesToImport.contains( + actionCollection.getUnpublishedCollection().getPageId()))) + .peek(actionCollection -> actionCollection.setGitSyncId( + null)) // setting this null so that this action collection can be imported again .collect(Collectors.toList()); applicationJson.setActionCollectionList(importedActionCollectionList); } - return permissionGroupRepository.getCurrentUserPermissionGroups() - .flatMap(userPermissionGroups -> { - ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider.builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) - .requiredPermissionOnTargetWorkspace(workspacePermission.getReadPermission()) - .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) - .allPermissionsRequired() - .currentUserPermissionGroups(userPermissionGroups) - .build(); - return importApplicationInWorkspace(workspaceId, applicationJson, applicationId, branchName, true, permissionProvider); - }); + return permissionGroupRepository.getCurrentUserPermissionGroups().flatMap(userPermissionGroups -> { + ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) + .requiredPermissionOnTargetWorkspace(workspacePermission.getReadPermission()) + .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) + .allPermissionsRequired() + .currentUserPermissionGroups(userPermissionGroups) + .build(); + return importApplicationInWorkspace( + workspaceId, applicationJson, applicationId, branchName, true, permissionProvider); + }); } - private Mono<Map<String, String>> updateNewPagesBeforeMerge(Mono<List<NewPage>> existingPagesMono, List<NewPage> newPagesList) { + private Mono<Map<String, String>> updateNewPagesBeforeMerge( + Mono<List<NewPage>> existingPagesMono, List<NewPage> newPagesList) { return existingPagesMono.map(newPages -> { Map<String, String> newToOldToPageNameMap = new HashMap<>(); // maps new names with old names @@ -1963,23 +2214,20 @@ private Mono<Map<String, String>> updateNewPagesBeforeMerge(Mono<List<NewPage>> * @param event AnalyticsEvents event * @return The application which is imported or exported */ - - private Mono<Application> sendImportExportApplicationAnalyticsEvent(Application application, AnalyticsEvents event) { - return workspaceService.getById(application.getWorkspaceId()) - .flatMap(workspace -> { - final Map<String, Object> eventData = Map.of( - FieldName.APPLICATION, application, - FieldName.WORKSPACE, workspace - ); - - final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, application.getId(), - FieldName.WORKSPACE_ID, workspace.getId(), - FieldName.EVENT_DATA, eventData - ); - - return analyticsService.sendObjectEvent(event, application, data); - }); + private Mono<Application> sendImportExportApplicationAnalyticsEvent( + Application application, AnalyticsEvents event) { + return workspaceService.getById(application.getWorkspaceId()).flatMap(workspace -> { + final Map<String, Object> eventData = Map.of( + FieldName.APPLICATION, application, + FieldName.WORKSPACE, workspace); + + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, application.getId(), + FieldName.WORKSPACE_ID, workspace.getId(), + FieldName.EVENT_DATA, eventData); + + return analyticsService.sendObjectEvent(event, application, data); + }); } /** @@ -1990,7 +2238,8 @@ private Mono<Application> sendImportExportApplicationAnalyticsEvent(Application * @return The application which is imported or exported */ private Mono<Application> sendImportExportApplicationAnalyticsEvent(String applicationId, AnalyticsEvents event) { - return applicationService.findById(applicationId, Optional.empty()) + return applicationService + .findById(applicationId, Optional.empty()) .flatMap(application -> sendImportExportApplicationAnalyticsEvent(application, event)); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PageLoadActionsUtilCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PageLoadActionsUtilCE.java index 3099ffb103d6..2f3ef255d960 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PageLoadActionsUtilCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PageLoadActionsUtilCE.java @@ -11,12 +11,12 @@ public interface PageLoadActionsUtilCE { - Mono<List<Set<DslActionDTO>>> findAllOnLoadActions(String pageId, - Integer evaluatedVersion, - Set<String> widgetNames, - Set<ActionDependencyEdge> edges, - Map<String, Set<String>> widgetDynamicBindingsMap, - List<ActionDTO> flatPageLoadActions, - Set<String> actionsUsedInDSL); - + Mono<List<Set<DslActionDTO>>> findAllOnLoadActions( + String pageId, + Integer evaluatedVersion, + Set<String> widgetNames, + Set<ActionDependencyEdge> edges, + Map<String, Set<String>> widgetDynamicBindingsMap, + List<ActionDTO> flatPageLoadActions, + Set<String> actionsUsedInDSL); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PageLoadActionsUtilCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PageLoadActionsUtilCEImpl.java index f665fd9dae9a..bb37f18d5699 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PageLoadActionsUtilCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PageLoadActionsUtilCEImpl.java @@ -61,13 +61,13 @@ public class PageLoadActionsUtilCEImpl implements PageLoadActionsUtilCE { * Dropdown1.options -> Dropdown1 */ private final String IMMEDIATE_PARENT_REGEX = "^(.*)(\\..*|\\[.*\\])$"; + private final Pattern parentPattern = Pattern.compile(IMMEDIATE_PARENT_REGEX); // TODO : This should contain all the static global variables present on the page like `appsmith`, etc. // TODO : Add all the global variables exposed on the client side. private final Set<String> APPSMITH_GLOBAL_VARIABLES = Set.of(); - /** * This function computes the sequenced on page load actions. * <p> @@ -90,13 +90,14 @@ public class PageLoadActionsUtilCEImpl implements PageLoadActionsUtilCE { * in parallel. But one set of actions MUST finish execution before the next set of actions can be executed * in the list. */ - public Mono<List<Set<DslActionDTO>>> findAllOnLoadActions(String pageId, - Integer evaluatedVersion, - Set<String> widgetNames, - Set<ActionDependencyEdge> edges, - Map<String, Set<String>> widgetDynamicBindingsMap, - List<ActionDTO> flatPageLoadActions, - Set<String> actionsUsedInDSL) { + public Mono<List<Set<DslActionDTO>>> findAllOnLoadActions( + String pageId, + Integer evaluatedVersion, + Set<String> widgetNames, + Set<ActionDependencyEdge> edges, + Map<String, Set<String>> widgetDynamicBindingsMap, + List<ActionDTO> flatPageLoadActions, + Set<String> actionsUsedInDSL) { Set<String> onPageLoadActionSet = new HashSet<>(); Set<String> explicitUserSetOnLoadActions = new HashSet<>(); @@ -104,7 +105,8 @@ public Mono<List<Set<DslActionDTO>>> findAllOnLoadActions(String pageId, // Function `extractAndSetActionBindingsInGraphEdges` updates this map to keep a track of all the actions which // have been discovered while walking the actions to ensure that we don't end up in a recursive infinite loop - // in case of a cyclical relationship between actions (and not specific paths) and helps us exit at the appropriate + // in case of a cyclical relationship between actions (and not specific paths) and helps us exit at the + // appropriate // junction. // e.g : Consider the following relationships : // Api1.actionConfiguration.body <- Api2.data.users[0].name @@ -117,26 +119,31 @@ public Mono<List<Set<DslActionDTO>>> findAllOnLoadActions(String pageId, .flatMap(newAction -> newActionService.generateActionByViewMode(newAction, false)) .cache(); - Mono<Map<String, ActionDTO>> actionNameToActionMapMono = allActionsByPageIdFlux.collectMap(ActionDTO::getValidName, action -> action).cache(); + Mono<Map<String, ActionDTO>> actionNameToActionMapMono = allActionsByPageIdFlux + .collectMap(ActionDTO::getValidName, action -> action) + .cache(); - Mono<Set<String>> actionsInPageMono = allActionsByPageIdFlux.map(ActionDTO::getValidName).collect(Collectors.toSet()).cache(); + Mono<Set<String>> actionsInPageMono = allActionsByPageIdFlux + .map(ActionDTO::getValidName) + .collect(Collectors.toSet()) + .cache(); Set<EntityDependencyNode> actionBindingsInDsl = new HashSet<>(); - Mono<Set<ActionDependencyEdge>> directlyReferencedActionsAddedToGraphMono = - addDirectlyReferencedActionsToGraph( - edges, - actionsUsedInDSL, - bindingsFromActions, - actionsFoundDuringWalk, - widgetDynamicBindingsMap, - actionNameToActionMapMono, - actionBindingsInDsl, - evaluatedVersion); + Mono<Set<ActionDependencyEdge>> directlyReferencedActionsAddedToGraphMono = addDirectlyReferencedActionsToGraph( + edges, + actionsUsedInDSL, + bindingsFromActions, + actionsFoundDuringWalk, + widgetDynamicBindingsMap, + actionNameToActionMapMono, + actionBindingsInDsl, + evaluatedVersion); // This following `createAllEdgesForPageMono` publisher traverses the actions and widgets to add all possible // edges between all possible entity paths - // First find all the actions in the page whose name matches the possible entity names found in the bindings in the widget + // First find all the actions in the page whose name matches the possible entity names found in the bindings in + // the widget Mono<Set<ActionDependencyEdge>> createAllEdgesForPageMono = directlyReferencedActionsAddedToGraphMono // Add dependencies of all on page load actions set by the user in the graph .flatMap(updatedEdges -> addExplicitUserSetOnLoadActionsToGraph( @@ -148,7 +155,8 @@ public Mono<List<Set<DslActionDTO>>> findAllOnLoadActions(String pageId, actionNameToActionMapMono, actionBindingsInDsl, evaluatedVersion)) - // For all the actions found so far, recursively walk the dynamic bindings of the actions to find more relationships with other actions (& widgets) + // For all the actions found so far, recursively walk the dynamic bindings of the actions to find more + // relationships with other actions (& widgets) .flatMap(updatedEdges -> recursivelyAddActionsAndTheirDependentsToGraphFromBindings( updatedEdges, actionsFoundDuringWalk, @@ -162,22 +170,25 @@ public Mono<List<Set<DslActionDTO>>> findAllOnLoadActions(String pageId, return addWidgetRelationshipToGraph(updatedEdges, widgetDynamicBindingsMap, evaluatedVersion); }); - // Create a graph given edges - Mono<DirectedAcyclicGraph<String, DefaultEdge>> createGraphMono = Mono.zip(actionsInPageMono, createAllEdgesForPageMono) + Mono<DirectedAcyclicGraph<String, DefaultEdge>> createGraphMono = Mono.zip( + actionsInPageMono, createAllEdgesForPageMono) .map(tuple -> { Set<String> allActions = tuple.getT1(); Set<ActionDependencyEdge> updatedEdges = tuple.getT2(); return constructDAG(allActions, widgetNames, updatedEdges, actionBindingsInDsl); - }).cache(); + }) + .cache(); // Generate on page load schedule - Mono<List<Set<String>>> computeOnPageLoadScheduleNamesMono = Mono.zip(actionNameToActionMapMono, createGraphMono) + Mono<List<Set<String>>> computeOnPageLoadScheduleNamesMono = Mono.zip( + actionNameToActionMapMono, createGraphMono) .map(tuple -> { Map<String, ActionDTO> actionNameToActionMap = tuple.getT1(); DirectedAcyclicGraph<String, DefaultEdge> graph = tuple.getT2(); - return computeOnPageLoadActionsSchedulingOrder(graph, onPageLoadActionSet, actionNameToActionMap, explicitUserSetOnLoadActions); + return computeOnPageLoadActionsSchedulingOrder( + graph, onPageLoadActionSet, actionNameToActionMap, explicitUserSetOnLoadActions); }) .map(onPageLoadActionsSchedulingOrder -> { // Find all explicitly turned on actions which haven't found their way into the scheduling order @@ -204,27 +215,23 @@ public Mono<List<Set<DslActionDTO>>> findAllOnLoadActions(String pageId, return onPageLoadActionsSchedulingOrder; }); - // Transform the schedule order into client feasible DTO Mono<List<Set<DslActionDTO>>> computeCompletePageLoadActionScheduleMono = filterAndTransformSchedulingOrderToDTO( - onPageLoadActionSet, - actionNameToActionMapMono, - computeOnPageLoadScheduleNamesMono) + onPageLoadActionSet, actionNameToActionMapMono, computeOnPageLoadScheduleNamesMono) .cache(); - // With the final on page load scheduling order, also set the on page load actions which would be updated // by the caller function - Mono<List<ActionDTO>> flatPageLoadActionsMono = computeCompletePageLoadActionScheduleMono.then(actionNameToActionMapMono).map(actionMap -> { - onPageLoadActionSet.stream().forEach(actionName -> flatPageLoadActions.add(actionMap.get(actionName))); - return flatPageLoadActions; - }); - - return createGraphMono - .then(flatPageLoadActionsMono) - .then(computeCompletePageLoadActionScheduleMono); + Mono<List<ActionDTO>> flatPageLoadActionsMono = computeCompletePageLoadActionScheduleMono + .then(actionNameToActionMapMono) + .map(actionMap -> { + onPageLoadActionSet.stream() + .forEach(actionName -> flatPageLoadActions.add(actionMap.get(actionName))); + return flatPageLoadActions; + }); + return createGraphMono.then(flatPageLoadActionsMono).then(computeCompletePageLoadActionScheduleMono); } /** @@ -243,9 +250,10 @@ public Mono<List<Set<DslActionDTO>>> findAllOnLoadActions(String pageId, * @param computeOnPageLoadScheduleNamesMono * @return */ - private Mono<List<Set<DslActionDTO>>> filterAndTransformSchedulingOrderToDTO(Set<String> onPageLoadActionSet, - Mono<Map<String, ActionDTO>> actionNameToActionMapMono, - Mono<List<Set<String>>> computeOnPageLoadScheduleNamesMono) { + private Mono<List<Set<DslActionDTO>>> filterAndTransformSchedulingOrderToDTO( + Set<String> onPageLoadActionSet, + Mono<Map<String, ActionDTO>> actionNameToActionMapMono, + Mono<List<Set<String>>> computeOnPageLoadScheduleNamesMono) { return Mono.zip(computeOnPageLoadScheduleNamesMono, actionNameToActionMapMono) .map(tuple -> { @@ -285,9 +293,8 @@ private Mono<List<Set<DslActionDTO>>> filterAndTransformSchedulingOrderToDTO(Set * @param evalVersion : Depending on the evaluated version, the way the AST parsing logic picks entities in the dynamic binding will change * @return A set of any possible reference found in the binding that qualifies as a global entity reference */ - private Mono<Set<EntityDependencyNode>> getPossibleEntityReferences(Mono<Map<String, ActionDTO>> actionNameToActionMapMono, - Set<String> bindings, - int evalVersion) { + private Mono<Set<EntityDependencyNode>> getPossibleEntityReferences( + Mono<Map<String, ActionDTO>> actionNameToActionMapMono, Set<String> bindings, int evalVersion) { return getPossibleEntityReferences(actionNameToActionMapMono, bindings, evalVersion, null); } @@ -302,10 +309,11 @@ private Mono<Set<EntityDependencyNode>> getPossibleEntityReferences(Mono<Map<Str * @param bindingsInDsl : All references are also added to this set if they should be qualified to run on page load first. * @return A set of any possible reference found in the binding that qualifies as a global entity reference */ - private Mono<Set<EntityDependencyNode>> getPossibleEntityReferences(Mono<Map<String, ActionDTO>> actionNameToActionMapMono, - Set<String> bindings, - int evalVersion, - Set<EntityDependencyNode> bindingsInDsl) { + private Mono<Set<EntityDependencyNode>> getPossibleEntityReferences( + Mono<Map<String, ActionDTO>> actionNameToActionMapMono, + Set<String> bindings, + int evalVersion, + Set<EntityDependencyNode> bindingsInDsl) { // We want to be finding both type of references final int entityTypes = ACTION_ENTITY_REFERENCES | WIDGET_ENTITY_REFERENCES; @@ -322,47 +330,55 @@ private Mono<Set<EntityDependencyNode>> getPossibleEntityReferences(Mono<Map<Str // From these references, we will try to validate action references at this point // Each identified node is already annotated with the expected type of entity we need to search for - bindingToPossibleParentMap.entrySet() - .stream() - .forEach(entry -> { - Set<EntityDependencyNode> bindingsWithActionReference = new HashSet<>(); - entry.getValue() - .stream() - .forEach(binding -> { - // For each possible reference node, check if the reference was to an action - ActionDTO actionDTO = actionMap.get(binding.getValidEntityName()); - - if (actionDTO != null) { - // If it was, and had been identified as the same type of action as what exists in this app, - if ((PluginType.JS.equals(actionDTO.getPluginType()) && EntityReferenceType.JSACTION.equals(binding.getEntityReferenceType())) - || (!PluginType.JS.equals(actionDTO.getPluginType()) && EntityReferenceType.ACTION.equals(binding.getEntityReferenceType()))) { - // Copy over some data from the identified action, this ensures that we do not have to query the DB again later - binding.setIsAsync(actionDTO.getActionConfiguration().getIsAsync()); - binding.setActionDTO(actionDTO); - bindingsWithActionReference.add(binding); - // Only if this is not an async JS function action and is not a direct JS function call, - // add it to a possible on page load action call. - // This discards the following type: - // {{ JSObject1.asyncFunc() }} - if (!(TRUE.equals(binding.getIsAsync()) && TRUE.equals(binding.getIsFunctionCall()))) { - possibleEntitiesReferences.add(binding); - } - // We're ignoring any reference that was identified as a widget but actually matched an action - // We wouldn't have discarded JS collection names here, but this is just an optimization, so it's fine - } - } else { - // If the reference node was identified as a widget, directly add it as a possible reference - // Because we are not doing any validations for widget references at this point - if (EntityReferenceType.WIDGET.equals(binding.getEntityReferenceType())) { - possibleEntitiesReferences.add(binding); - } - } - }); - - if (!bindingsWithActionReference.isEmpty() && bindingsInDsl != null) { - bindingsInDsl.addAll(bindingsWithActionReference); + bindingToPossibleParentMap.entrySet().stream().forEach(entry -> { + Set<EntityDependencyNode> bindingsWithActionReference = new HashSet<>(); + entry.getValue().stream().forEach(binding -> { + // For each possible reference node, check if the reference was to an action + ActionDTO actionDTO = actionMap.get(binding.getValidEntityName()); + + if (actionDTO != null) { + // If it was, and had been identified as the same type of action as what exists in this + // app, + if ((PluginType.JS.equals(actionDTO.getPluginType()) + && EntityReferenceType.JSACTION.equals( + binding.getEntityReferenceType())) + || (!PluginType.JS.equals(actionDTO.getPluginType()) + && EntityReferenceType.ACTION.equals( + binding.getEntityReferenceType()))) { + // Copy over some data from the identified action, this ensures that we do not have + // to query the DB again later + binding.setIsAsync( + actionDTO.getActionConfiguration().getIsAsync()); + binding.setActionDTO(actionDTO); + bindingsWithActionReference.add(binding); + // Only if this is not an async JS function action and is not a direct JS function + // call, + // add it to a possible on page load action call. + // This discards the following type: + // {{ JSObject1.asyncFunc() }} + if (!(TRUE.equals(binding.getIsAsync()) + && TRUE.equals(binding.getIsFunctionCall()))) { + possibleEntitiesReferences.add(binding); + } + // We're ignoring any reference that was identified as a widget but actually matched + // an action + // We wouldn't have discarded JS collection names here, but this is just an + // optimization, so it's fine } - }); + } else { + // If the reference node was identified as a widget, directly add it as a possible + // reference + // Because we are not doing any validations for widget references at this point + if (EntityReferenceType.WIDGET.equals(binding.getEntityReferenceType())) { + possibleEntitiesReferences.add(binding); + } + } + }); + + if (!bindingsWithActionReference.isEmpty() && bindingsInDsl != null) { + bindingsInDsl.addAll(bindingsWithActionReference); + } + }); return possibleEntitiesReferences; }); @@ -377,7 +393,8 @@ private Mono<Set<EntityDependencyNode>> getPossibleEntityReferences(Mono<Map<Str * @param evalVersion : Depending on the evaluated version, the way the AST parsing logic picks entities in the dynamic binding will change * @return A mono of a map of each of the provided binding values to the possible set of EntityDependencyNodes found in the binding */ - private Mono<Map<String, Set<EntityDependencyNode>>> getPossibleEntityParentsMap(Set<String> bindings, int types, int evalVersion) { + private Mono<Map<String, Set<EntityDependencyNode>>> getPossibleEntityParentsMap( + Set<String> bindings, int types, int evalVersion) { Flux<Tuple2<String, Set<String>>> findingToReferencesFlux = astService.getPossibleReferencesFromDynamicBinding(new ArrayList<>(bindings), evalVersion); return MustacheHelper.getPossibleEntityParentsMap(findingToReferencesFlux, types); @@ -401,39 +418,47 @@ private Mono<Map<String, Set<EntityDependencyNode>>> getPossibleEntityParentsMap * @param evalVersion * @return */ - private Mono<Set<ActionDependencyEdge>> addDirectlyReferencedActionsToGraph(Set<ActionDependencyEdge> edges, - Set<String> actionsUsedInDSL, - Set<String> bindingsFromActions, - Map<String, EntityDependencyNode> actionsFoundDuringWalk, - Map<String, Set<String>> widgetDynamicBindingsMap, - Mono<Map<String, ActionDTO>> actionNameToActionMapMono, - Set<EntityDependencyNode> actionBindingsInDsl, - int evalVersion) { + private Mono<Set<ActionDependencyEdge>> addDirectlyReferencedActionsToGraph( + Set<ActionDependencyEdge> edges, + Set<String> actionsUsedInDSL, + Set<String> bindingsFromActions, + Map<String, EntityDependencyNode> actionsFoundDuringWalk, + Map<String, Set<String>> widgetDynamicBindingsMap, + Mono<Map<String, ActionDTO>> actionNameToActionMapMono, + Set<EntityDependencyNode> actionBindingsInDsl, + int evalVersion) { return Flux.fromIterable(widgetDynamicBindingsMap.entrySet()) .flatMap(entry -> { String widgetName = entry.getKey(); - // For each widget in the DSL that has a dynamic binding, we define an entity dependency node beforehand + // For each widget in the DSL that has a dynamic binding, we define an entity dependency node + // beforehand // This will be a leaf node in the DAG that is constructed for on page load dependencies - EntityDependencyNode widgetDependencyNode = new EntityDependencyNode(EntityReferenceType.WIDGET, widgetName, widgetName, null, null, null); + EntityDependencyNode widgetDependencyNode = new EntityDependencyNode( + EntityReferenceType.WIDGET, widgetName, widgetName, null, null, null); Set<String> bindingsInWidget = entry.getValue(); - return getPossibleEntityReferences(actionNameToActionMapMono, bindingsInWidget, evalVersion, actionBindingsInDsl) + return getPossibleEntityReferences( + actionNameToActionMapMono, bindingsInWidget, evalVersion, actionBindingsInDsl) .flatMapMany(Flux::fromIterable) // Add dependencies of the actions found in the DSL in the graph // We are ignoring the widget references at this point // TODO: Possible optimization in the future .flatMap(possibleEntity -> { if (EntityReferenceType.ACTION.equals(possibleEntity.getEntityReferenceType()) - || EntityReferenceType.JSACTION.equals(possibleEntity.getEntityReferenceType())) { + || EntityReferenceType.JSACTION.equals( + possibleEntity.getEntityReferenceType())) { edges.add(new ActionDependencyEdge(possibleEntity, widgetDependencyNode)); - // This action is directly referenced in the DSL. This action is an ideal candidate for on page load + // This action is directly referenced in the DSL. This action is an ideal candidate + // for on page load actionsUsedInDSL.add(possibleEntity.getValidEntityName()); ActionDTO actionDTO = possibleEntity.getActionDTO(); - return newActionService.fillSelfReferencingDataPaths(actionDTO) + return newActionService + .fillSelfReferencingDataPaths(actionDTO) .map(newActionDTO -> { possibleEntity.setActionDTO(newActionDTO); return newActionDTO; }) - .flatMap(newActionDTO -> extractAndSetActionBindingsInGraphEdges(possibleEntity, + .flatMap(newActionDTO -> extractAndSetActionBindingsInGraphEdges( + possibleEntity, edges, bindingsFromActions, actionNameToActionMapMono, @@ -471,10 +496,11 @@ private Mono<Set<ActionDependencyEdge>> addDirectlyReferencedActionsToGraph(Set< * @param actionBindingsInDsl * @return */ - private DirectedAcyclicGraph<String, DefaultEdge> constructDAG(Set<String> actionNames, - Set<String> widgetNames, - Set<ActionDependencyEdge> edges, - Set<EntityDependencyNode> actionBindingsInDsl) { + private DirectedAcyclicGraph<String, DefaultEdge> constructDAG( + Set<String> actionNames, + Set<String> widgetNames, + Set<ActionDependencyEdge> edges, + Set<EntityDependencyNode> actionBindingsInDsl) { DirectedAcyclicGraph<String, DefaultEdge> actionSchedulingGraph = new DirectedAcyclicGraph<>(DefaultEdge.class); @@ -490,7 +516,6 @@ private DirectedAcyclicGraph<String, DefaultEdge> constructDAG(Set<String> actio // TODO : Handle the above global variables provided by appsmith in the following filtering. edges = edges.stream() .filter(edge -> { - String source = edge.getSourceNode().getReferenceString(); String target = edge.getTargetNode().getReferenceString(); @@ -509,12 +534,16 @@ private DirectedAcyclicGraph<String, DefaultEdge> constructDAG(Set<String> actio // Assert that the vertices which are entire property paths have a possible parent which is either // an action or a widget or a static variable provided by appsmith at page/application level. vertices.stream().forEach(vertex -> { - Optional<String> validEntity = getPossibleParents(vertex).stream().filter(parent -> { - if (!actionNames.contains(parent) && !widgetNames.contains(parent) && !APPSMITH_GLOBAL_VARIABLES.contains(parent)) { - return false; - } - return true; - }).findFirst(); + Optional<String> validEntity = getPossibleParents(vertex).stream() + .filter(parent -> { + if (!actionNames.contains(parent) + && !widgetNames.contains(parent) + && !APPSMITH_GLOBAL_VARIABLES.contains(parent)) { + return false; + } + return true; + }) + .findFirst(); // If any of the generated entity names from the path are valid appsmith entity name, // the vertex is considered valid @@ -546,8 +575,8 @@ private DirectedAcyclicGraph<String, DefaultEdge> constructDAG(Set<String> actio Set<EntityDependencyNode> edgeVertices = Set.of(source, target); - edgeVertices.stream().forEach(vertex -> implicitParentChildEdges.addAll(generateParentChildRelationships(vertex))); - + edgeVertices.stream() + .forEach(vertex -> implicitParentChildEdges.addAll(generateParentChildRelationships(vertex))); } edges.addAll(implicitParentChildEdges); @@ -584,16 +613,24 @@ private DirectedAcyclicGraph<String, DefaultEdge> constructDAG(Set<String> actio * @param entityDependencyNode * @param actionDataFromConfigurationEdges */ - private void addImplicitActionConfigurationDependency(EntityDependencyNode entityDependencyNode, Set<ActionDependencyEdge> actionDataFromConfigurationEdges) { - if (Set.of(EntityReferenceType.ACTION, EntityReferenceType.JSACTION).contains(entityDependencyNode.getEntityReferenceType())) { + private void addImplicitActionConfigurationDependency( + EntityDependencyNode entityDependencyNode, Set<ActionDependencyEdge> actionDataFromConfigurationEdges) { + if (Set.of(EntityReferenceType.ACTION, EntityReferenceType.JSACTION) + .contains(entityDependencyNode.getEntityReferenceType())) { if (entityDependencyNode.isValidDynamicBinding()) { - EntityDependencyNode sourceDependencyNode = new EntityDependencyNode(entityDependencyNode.getEntityReferenceType(), entityDependencyNode.getValidEntityName(), entityDependencyNode.getValidEntityName() + ".actionConfiguration", entityDependencyNode.getIsAsync(), entityDependencyNode.getIsFunctionCall(), entityDependencyNode.getActionDTO()); - actionDataFromConfigurationEdges.add(new ActionDependencyEdge(sourceDependencyNode, entityDependencyNode)); + EntityDependencyNode sourceDependencyNode = new EntityDependencyNode( + entityDependencyNode.getEntityReferenceType(), + entityDependencyNode.getValidEntityName(), + entityDependencyNode.getValidEntityName() + ".actionConfiguration", + entityDependencyNode.getIsAsync(), + entityDependencyNode.getIsFunctionCall(), + entityDependencyNode.getActionDTO()); + actionDataFromConfigurationEdges.add( + new ActionDependencyEdge(sourceDependencyNode, entityDependencyNode)); } } } - /** * This function takes a Directed Acyclic Graph and computes on page load actions. The final results is a list of set * of actions. The set contains all the independent actions which can be executed in parallel. The List represents @@ -606,15 +643,18 @@ private void addImplicitActionConfigurationDependency(EntityDependencyNode entit * @param actionNameToActionMap : All the action names for the page * @return */ - private List<Set<String>> computeOnPageLoadActionsSchedulingOrder(DirectedAcyclicGraph<String, DefaultEdge> dag, - Set<String> onPageLoadActionSet, - Map<String, ActionDTO> actionNameToActionMap, - Set<String> explicitUserSetOnLoadActions) { + private List<Set<String>> computeOnPageLoadActionsSchedulingOrder( + DirectedAcyclicGraph<String, DefaultEdge> dag, + Set<String> onPageLoadActionSet, + Map<String, ActionDTO> actionNameToActionMap, + Set<String> explicitUserSetOnLoadActions) { Map<String, Integer> pageLoadActionAndLevelMap = new HashMap<>(); List<Set<String>> onPageLoadActions = new ArrayList<>(); // Find all root nodes to start the BFS traversal from - List<String> rootNodes = dag.vertexSet().stream().filter(key -> dag.incomingEdgesOf(key).size() == 0).collect(Collectors.toList()); + List<String> rootNodes = dag.vertexSet().stream() + .filter(key -> dag.incomingEdgesOf(key).size() == 0) + .collect(Collectors.toList()); BreadthFirstIterator<String, DefaultEdge> bfsIterator = new BreadthFirstIterator<>(dag, rootNodes); @@ -628,7 +668,12 @@ private List<Set<String>> computeOnPageLoadActionsSchedulingOrder(DirectedAcycli onPageLoadActions.add(new HashSet<>()); } - Set<String> actionsFromBinding = actionCandidatesForPageLoadFromBinding(actionNameToActionMap, vertex, pageLoadActionAndLevelMap, onPageLoadActions, explicitUserSetOnLoadActions); + Set<String> actionsFromBinding = actionCandidatesForPageLoadFromBinding( + actionNameToActionMap, + vertex, + pageLoadActionAndLevelMap, + onPageLoadActions, + explicitUserSetOnLoadActions); onPageLoadActions.get(level).addAll(actionsFromBinding); for (String action : actionsFromBinding) { pageLoadActionAndLevelMap.put(action, level); @@ -637,10 +682,11 @@ private List<Set<String>> computeOnPageLoadActionsSchedulingOrder(DirectedAcycli } // Trim all empty sets from the list before returning. - return onPageLoadActions.stream().filter(setOfActions -> !setOfActions.isEmpty()).collect(Collectors.toList()); + return onPageLoadActions.stream() + .filter(setOfActions -> !setOfActions.isEmpty()) + .collect(Collectors.toList()); } - /** * This function gets a set of binding names that come from other actions. It looks for actions in the page with * the same names as words in the binding names set. If yes, it creates a new set of dynamicBindingNames, adds these newly @@ -650,11 +696,12 @@ private List<Set<String>> computeOnPageLoadActionsSchedulingOrder(DirectedAcycli * * @return */ - private Mono<Set<ActionDependencyEdge>> recursivelyAddActionsAndTheirDependentsToGraphFromBindings(Set<ActionDependencyEdge> edges, - Map<String, EntityDependencyNode> actionsFoundDuringWalk, - Set<String> dynamicBindings, - Mono<Map<String, ActionDTO>> actionNameToActionMapMono, - int evalVersion) { + private Mono<Set<ActionDependencyEdge>> recursivelyAddActionsAndTheirDependentsToGraphFromBindings( + Set<ActionDependencyEdge> edges, + Map<String, EntityDependencyNode> actionsFoundDuringWalk, + Set<String> dynamicBindings, + Mono<Map<String, ActionDTO>> actionNameToActionMapMono, + int evalVersion) { if (dynamicBindings == null || dynamicBindings.isEmpty()) { return Mono.just(edges); } @@ -664,24 +711,40 @@ private Mono<Set<ActionDependencyEdge>> recursivelyAddActionsAndTheirDependentsT Set<String> newBindings = new HashSet<>(); // First fetch all the actions in the page whose name matches the words found in all the dynamic bindings - Mono<List<EntityDependencyNode>> findAndAddActionsInBindingsMono = getPossibleEntityReferences(actionNameToActionMapMono, dynamicBindings, evalVersion).flatMapMany(Flux::fromIterable) + Mono<List<EntityDependencyNode>> findAndAddActionsInBindingsMono = getPossibleEntityReferences( + actionNameToActionMapMono, dynamicBindings, evalVersion) + .flatMapMany(Flux::fromIterable) // Add dependencies of the actions found in the DSL in the graph. .flatMap(possibleEntity -> { - if (Set.of(EntityReferenceType.JSACTION, EntityReferenceType.ACTION).contains(possibleEntity.getEntityReferenceType())) { + if (Set.of(EntityReferenceType.JSACTION, EntityReferenceType.ACTION) + .contains(possibleEntity.getEntityReferenceType())) { ActionDTO actionDTO = possibleEntity.getActionDTO(); - return newActionService.fillSelfReferencingDataPaths(actionDTO).map(newActionDTO -> { - possibleEntity.setActionDTO(newActionDTO); - return newActionDTO; - }).then(extractAndSetActionBindingsInGraphEdges(possibleEntity, edges, newBindings, actionNameToActionMapMono, actionsFoundDuringWalk, null, evalVersion)).thenReturn(possibleEntity); + return newActionService + .fillSelfReferencingDataPaths(actionDTO) + .map(newActionDTO -> { + possibleEntity.setActionDTO(newActionDTO); + return newActionDTO; + }) + .then(extractAndSetActionBindingsInGraphEdges( + possibleEntity, + edges, + newBindings, + actionNameToActionMapMono, + actionsFoundDuringWalk, + null, + evalVersion)) + .thenReturn(possibleEntity); } else { return Mono.empty(); } - }).collectList(); + }) + .collectList(); return findAndAddActionsInBindingsMono.flatMap(entityDependencyNodes -> { // Now that the next set of bindings have been found, find recursively all actions by these names // and their bindings - return recursivelyAddActionsAndTheirDependentsToGraphFromBindings(edges, actionsFoundDuringWalk, newBindings, actionNameToActionMapMono, evalVersion); + return recursivelyAddActionsAndTheirDependentsToGraphFromBindings( + edges, actionsFoundDuringWalk, newBindings, actionNameToActionMapMono, evalVersion); }); } @@ -703,31 +766,41 @@ private Mono<Set<ActionDependencyEdge>> recursivelyAddActionsAndTheirDependentsT * @param bindingsFromActions * @return */ - private Mono<Set<ActionDependencyEdge>> addExplicitUserSetOnLoadActionsToGraph(String pageId, - Set<ActionDependencyEdge> edges, - Set<String> explicitUserSetOnLoadActions, - Map<String, EntityDependencyNode> actionsFoundDuringWalk, - Set<String> bindingsFromActions, - Mono<Map<String, ActionDTO>> actionNameToActionMapMono, - Set<EntityDependencyNode> actionBindingsInDsl, - int evalVersion) { - - //First fetch all the actions which have been tagged as on load by the user explicitly. - return newActionService.findUnpublishedOnLoadActionsExplicitSetByUserInPage(pageId) + private Mono<Set<ActionDependencyEdge>> addExplicitUserSetOnLoadActionsToGraph( + String pageId, + Set<ActionDependencyEdge> edges, + Set<String> explicitUserSetOnLoadActions, + Map<String, EntityDependencyNode> actionsFoundDuringWalk, + Set<String> bindingsFromActions, + Mono<Map<String, ActionDTO>> actionNameToActionMapMono, + Set<EntityDependencyNode> actionBindingsInDsl, + int evalVersion) { + + // First fetch all the actions which have been tagged as on load by the user explicitly. + return newActionService + .findUnpublishedOnLoadActionsExplicitSetByUserInPage(pageId) .flatMap(newAction -> newActionService.generateActionByViewMode(newAction, false)) .flatMap(newActionService::fillSelfReferencingDataPaths) // Add the vertices and edges to the graph for these actions .flatMap(actionDTO -> { - EntityDependencyNode entityDependencyNode = new EntityDependencyNode(actionDTO.getPluginType().equals(PluginType.JS) ? EntityReferenceType.JSACTION : EntityReferenceType.ACTION, actionDTO.getValidName(), null, null, false, actionDTO); + EntityDependencyNode entityDependencyNode = new EntityDependencyNode( + actionDTO.getPluginType().equals(PluginType.JS) + ? EntityReferenceType.JSACTION + : EntityReferenceType.ACTION, + actionDTO.getValidName(), + null, + null, + false, + actionDTO); explicitUserSetOnLoadActions.add(actionDTO.getValidName()); return extractAndSetActionBindingsInGraphEdges( - entityDependencyNode, - edges, - bindingsFromActions, - actionNameToActionMapMono, - actionsFoundDuringWalk, - actionBindingsInDsl, - evalVersion) + entityDependencyNode, + edges, + bindingsFromActions, + actionNameToActionMapMono, + actionsFoundDuringWalk, + actionBindingsInDsl, + evalVersion) .thenReturn(actionDTO); }) .collectList() @@ -750,13 +823,14 @@ private Mono<Set<ActionDependencyEdge>> addExplicitUserSetOnLoadActionsToGraph(S * @param bindingsFromActions * @param actionsFoundDuringWalk */ - private Mono<Void> extractAndSetActionBindingsInGraphEdges(EntityDependencyNode entityDependencyNode, - Set<ActionDependencyEdge> edges, - Set<String> bindingsFromActions, - Mono<Map<String, ActionDTO>> actionNameToActionMapMono, - Map<String, EntityDependencyNode> actionsFoundDuringWalk, - Set<EntityDependencyNode> bindingsInDsl, - int evalVersion) { + private Mono<Void> extractAndSetActionBindingsInGraphEdges( + EntityDependencyNode entityDependencyNode, + Set<ActionDependencyEdge> edges, + Set<String> bindingsFromActions, + Mono<Map<String, ActionDTO>> actionNameToActionMapMono, + Map<String, EntityDependencyNode> actionsFoundDuringWalk, + Set<EntityDependencyNode> bindingsInDsl, + int evalVersion) { ActionDTO action = entityDependencyNode.getActionDTO(); @@ -778,24 +852,40 @@ private Mono<Void> extractAndSetActionBindingsInGraphEdges(EntityDependencyNode Set<String> allBindings = new HashSet<>(); actionBindingMap.values().stream().forEach(bindings -> allBindings.addAll(bindings)); - // TODO : Throw an error on action save when bindings from dynamic binding path list do not match the json path keys + // TODO : Throw an error on action save when bindings from dynamic binding path list do not match the json path + // keys // and get the client to recompute the dynamic binding path list and try again. if (!allBindings.containsAll(action.getJsonPathKeys())) { Set<String> invalidBindings = new HashSet<>(action.getJsonPathKeys()); invalidBindings.removeAll(allBindings); - log.error("Invalid dynamic binding path list for action id {}. Not taking the following bindings in " + "consideration for computing on page load actions : {}", action.getId(), invalidBindings); + log.error( + "Invalid dynamic binding path list for action id {}. Not taking the following bindings in " + + "consideration for computing on page load actions : {}", + action.getId(), + invalidBindings); } Set<String> bindingPaths = actionBindingMap.keySet(); return Flux.fromIterable(bindingPaths) .flatMap(bindingPath -> { - EntityDependencyNode actionDependencyNode = new EntityDependencyNode(entityDependencyNode.getEntityReferenceType(), entityDependencyNode.getValidEntityName(), bindingPath, null, false, action); - return getPossibleEntityReferences(actionNameToActionMapMono, actionBindingMap.get(bindingPath), evalVersion, bindingsInDsl) + EntityDependencyNode actionDependencyNode = new EntityDependencyNode( + entityDependencyNode.getEntityReferenceType(), + entityDependencyNode.getValidEntityName(), + bindingPath, + null, + false, + action); + return getPossibleEntityReferences( + actionNameToActionMapMono, + actionBindingMap.get(bindingPath), + evalVersion, + bindingsInDsl) .flatMapMany(Flux::fromIterable) .map(relatedDependencyNode -> { bindingsFromActions.add(relatedDependencyNode.getReferenceString()); - ActionDependencyEdge edge = new ActionDependencyEdge(relatedDependencyNode, actionDependencyNode); + ActionDependencyEdge edge = + new ActionDependencyEdge(relatedDependencyNode, actionDependencyNode); edges.add(edge); return relatedDependencyNode; }) @@ -803,7 +893,6 @@ private Mono<Void> extractAndSetActionBindingsInGraphEdges(EntityDependencyNode }) .collectList() .then(); - } /** @@ -815,42 +904,39 @@ private Mono<Void> extractAndSetActionBindingsInGraphEdges(EntityDependencyNode * @param widgetBindingMap * @return */ - private Mono<Set<ActionDependencyEdge>> addWidgetRelationshipToGraph(Set<ActionDependencyEdge> edges, - Map<String, Set<String>> widgetBindingMap, - int evalVersion) { + private Mono<Set<ActionDependencyEdge>> addWidgetRelationshipToGraph( + Set<ActionDependencyEdge> edges, Map<String, Set<String>> widgetBindingMap, int evalVersion) { final int entityTypes = WIDGET_ENTITY_REFERENCES; // This part will ensure that we are discovering widget to widget relationships. return Flux.fromIterable(widgetBindingMap.entrySet()) - .flatMap(widgetBindingEntries -> getPossibleEntityParentsMap(widgetBindingEntries.getValue(), entityTypes, evalVersion) + .flatMap(widgetBindingEntries -> getPossibleEntityParentsMap( + widgetBindingEntries.getValue(), entityTypes, evalVersion) .map(possibleParentsMap -> { possibleParentsMap.entrySet().stream().forEach(entry -> { - if (entry.getValue() == null || entry.getValue().isEmpty()) { return; } - String widgetPath = widgetBindingEntries.getKey().trim(); + String widgetPath = + widgetBindingEntries.getKey().trim(); String[] widgetPathParts = widgetPath.split("\\."); String widgetName = widgetPath; if (widgetPathParts.length > 0) { widgetName = widgetPathParts[0]; } - EntityDependencyNode entityDependencyNode = new EntityDependencyNode(EntityReferenceType.WIDGET, widgetName, widgetPath, null, null, null); + EntityDependencyNode entityDependencyNode = new EntityDependencyNode( + EntityReferenceType.WIDGET, widgetName, widgetPath, null, null, null); entry.getValue().stream().forEach(widgetDependencyNode -> { - ActionDependencyEdge edge = new ActionDependencyEdge(widgetDependencyNode, entityDependencyNode); + ActionDependencyEdge edge = + new ActionDependencyEdge(widgetDependencyNode, entityDependencyNode); edges.add(edge); }); - - }); return possibleParentsMap; - })) .collectList() .then(Mono.just(edges)); - } - private boolean hasUserSetActionToNotRunOnPageLoad(ActionDTO unpublishedAction) { if (TRUE.equals(unpublishedAction.getUserSetOnLoad()) && !TRUE.equals(unpublishedAction.getExecuteOnLoad())) { return true; @@ -891,9 +977,12 @@ private Map<String, Set<String>> getActionBindingMap(ActionDTO action) { String[] fields = fieldPath.split("[].\\[]"); // For nested fields, the parent dsl to search in would shift by one level every iteration Object parent = configurationObj; - Iterator<String> fieldsIterator = Arrays.stream(fields).filter(fieldToken -> !fieldToken.isBlank()).iterator(); + Iterator<String> fieldsIterator = Arrays.stream(fields) + .filter(fieldToken -> !fieldToken.isBlank()) + .iterator(); boolean isLeafNode = false; - // This loop will end at either a leaf node, or the last identified JSON field (by throwing an exception) + // This loop will end at either a leaf node, or the last identified JSON field (by throwing an + // exception) // Valid forms of the fieldPath for this search could be: // root.field.list[index].childField.anotherList.indexWithDotOperator.multidimensionalList[index1][index2] while (fieldsIterator.hasNext()) { @@ -933,7 +1022,9 @@ private Map<String, Set<String>> getActionBindingMap(ActionDTO action) { Set<String> mustacheKeysFromFields; // Stricter extraction of dynamic bindings if (isBindingPresentInString) { - mustacheKeysFromFields = MustacheHelper.extractMustacheKeysFromFields(parent).stream().map(token -> token.getValue()).collect(Collectors.toSet()); + mustacheKeysFromFields = MustacheHelper.extractMustacheKeysFromFields(parent).stream() + .map(token -> token.getValue()) + .collect(Collectors.toSet()); } else { // this must be a JS function. No need to extract mustache. The entire string is JS body mustacheKeysFromFields = Set.of((String) parent); @@ -946,7 +1037,6 @@ private Map<String, Set<String>> getActionBindingMap(ActionDTO action) { } completePathToDynamicBindingMap.put(completePath, mustacheKeysFromFields); } - } } } @@ -976,7 +1066,13 @@ private Set<ActionDependencyEdge> generateParentChildRelationships(EntityDepende Matcher matcher = parentPattern.matcher(entityDependencyNode.getReferenceString()); matcher.find(); parent = matcher.group(1); - EntityDependencyNode parentDependencyNode = new EntityDependencyNode(entityDependencyNode.getEntityReferenceType(), entityDependencyNode.getValidEntityName(), parent, entityDependencyNode.getIsAsync(), entityDependencyNode.getIsFunctionCall(), entityDependencyNode.getActionDTO()); + EntityDependencyNode parentDependencyNode = new EntityDependencyNode( + entityDependencyNode.getEntityReferenceType(), + entityDependencyNode.getValidEntityName(), + parent, + entityDependencyNode.getIsAsync(), + entityDependencyNode.getIsFunctionCall(), + entityDependencyNode.getActionDTO()); edges.add(new ActionDependencyEdge(entityDependencyNode, parentDependencyNode)); entityDependencyNode = parentDependencyNode; } catch (IllegalStateException | IndexOutOfBoundsException e) { @@ -1003,11 +1099,12 @@ private Set<ActionDependencyEdge> generateParentChildRelationships(EntityDepende * @param existingPageLoadActions * @return */ - private Set<String> actionCandidatesForPageLoadFromBinding(Map<String, ActionDTO> actionNameToActionMap, - String vertex, - Map<String, Integer> pageLoadActionsLevelMap, - List<Set<String>> existingPageLoadActions, - Set<String> explicitUserSetOnLoadActions) { + private Set<String> actionCandidatesForPageLoadFromBinding( + Map<String, ActionDTO> actionNameToActionMap, + String vertex, + Map<String, Integer> pageLoadActionsLevelMap, + List<Set<String>> existingPageLoadActions, + Set<String> explicitUserSetOnLoadActions) { Set<String> onPageLoadCandidates = new HashSet<>(); @@ -1026,7 +1123,6 @@ private Set<String> actionCandidatesForPageLoadFromBinding(Map<String, ActionDTO * referenced in any widget or action) * o or, it is not a function call i.e. the data of this call is being referred to in the binding. */ - String validBinding; if (explicitUserSetOnLoadActions.contains(entity)) { validBinding = entity + "." + "actionConfiguration"; @@ -1036,7 +1132,8 @@ private Set<String> actionCandidatesForPageLoadFromBinding(Map<String, ActionDTO // If the reference is to a sync JS function, discard it from the scheduling order ActionDTO actionDTO = actionNameToActionMap.get(entity); - if (PluginType.JS.equals(actionDTO.getPluginType()) && FALSE.equals(actionDTO.getActionConfiguration().getIsAsync())) { + if (PluginType.JS.equals(actionDTO.getPluginType()) + && FALSE.equals(actionDTO.getActionConfiguration().getIsAsync())) { isCandidateForPageLoad = FALSE; } @@ -1078,10 +1175,10 @@ private DslActionDTO getDslAction(ActionDTO actionDTO) { } if (actionDTO.getActionConfiguration() != null) { - dslActionDTO.setTimeoutInMillisecond(actionDTO.getActionConfiguration().getTimeoutInMillisecond()); + dslActionDTO.setTimeoutInMillisecond( + actionDTO.getActionConfiguration().getTimeoutInMillisecond()); } return dslActionDTO; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PingScheduledTaskCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PingScheduledTaskCE.java index a81523d248a2..2ebc84445098 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PingScheduledTaskCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PingScheduledTaskCE.java @@ -3,5 +3,4 @@ public interface PingScheduledTaskCE { void pingSchedule(); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PingScheduledTaskCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PingScheduledTaskCEImpl.java index cabc4a6e3edf..79571c1b7353 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PingScheduledTaskCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PingScheduledTaskCEImpl.java @@ -83,18 +83,20 @@ private Mono<String> doPing(String instanceId, String ipAddress) { return Mono.empty(); } - return WebClientUtils - .create("https://api.segment.io") + return WebClientUtils.create("https://api.segment.io") .post() .uri("/v1/track") .headers(headers -> headers.setBasicAuth(ceKey, "")) .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(Map.of( - "userId", instanceId, - "context", Map.of("ip", ipAddress), - "properties", Map.of("instanceId", instanceId), - "event", "Instance Active" - ))) + "userId", + instanceId, + "context", + Map.of("ip", ipAddress), + "properties", + Map.of("instanceId", instanceId), + "event", + "Instance Active"))) .retrieve() .bodyToMono(String.class); } @@ -120,12 +122,10 @@ public void pingStats() { newPageRepository.countByDeletedAtNull().defaultIfEmpty(0L), newActionRepository.countByDeletedAtNull().defaultIfEmpty(0L), datasourceRepository.countByDeletedAtNull().defaultIfEmpty(0L), - userRepository.countByDeletedAtNull().defaultIfEmpty(0L) - ) + userRepository.countByDeletedAtNull().defaultIfEmpty(0L)) .flatMap(statsData -> { final String ipAddress = statsData.getT2(); - return WebClientUtils - .create("https://api.segment.io") + return WebClientUtils.create("https://api.segment.io") .post() .uri("/v1/track") .headers(headers -> headers.setBasicAuth(ceKey, "")) @@ -133,19 +133,18 @@ public void pingStats() { .body(BodyInserters.fromValue(Map.of( "userId", statsData.getT1(), "context", Map.of("ip", ipAddress), - "properties", Map.of( - "instanceId", statsData.getT1(), - "numOrgs", statsData.getT3(), - "numApps", statsData.getT4(), - "numPages", statsData.getT5(), - "numActions", statsData.getT6(), - "numDatasources", statsData.getT7(), - "numUsers", statsData.getT8(), - "version", projectProperties.getVersion(), - "edition", ProjectProperties.EDITION - ), - "event", "instance_stats" - ))) + "properties", + Map.of( + "instanceId", statsData.getT1(), + "numOrgs", statsData.getT3(), + "numApps", statsData.getT4(), + "numPages", statsData.getT5(), + "numActions", statsData.getT6(), + "numDatasources", statsData.getT7(), + "numUsers", statsData.getT8(), + "version", projectProperties.getVersion(), + "edition", ProjectProperties.EDITION), + "event", "instance_stats"))) .retrieve() .bodyToMono(String.class); }) @@ -153,5 +152,4 @@ public void pingStats() { .subscribeOn(Schedulers.boundedElastic()) .subscribe(); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PluginScheduledTaskCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PluginScheduledTaskCE.java index 768f95bd3593..365f1808bb3f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PluginScheduledTaskCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PluginScheduledTaskCE.java @@ -6,5 +6,4 @@ public interface PluginScheduledTaskCE { public void updateRemotePlugins(); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PluginScheduledTaskCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PluginScheduledTaskCEImpl.java index 108cd59bec27..d699a4c1a7d9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PluginScheduledTaskCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PluginScheduledTaskCEImpl.java @@ -22,13 +22,13 @@ public class PluginScheduledTaskCEImpl implements PluginScheduledTaskCE { private Instant lastUpdatedAt = null; - // Number of milliseconds between the start of each scheduled calls to this method. @Scheduled(initialDelay = 30 * 1000 /* 30 seconds */, fixedRate = 2 * 60 * 60 * 1000 /* two hours */) public void updateRemotePlugins() { // Moving the fetch and update remote plugins to helper classes to have custom implementation for business // edition - pluginScheduledTaskUtils.fetchAndUpdateRemotePlugins(lastUpdatedAt) + pluginScheduledTaskUtils + .fetchAndUpdateRemotePlugins(lastUpdatedAt) // Set new updated time .doOnSuccess(success -> this.lastUpdatedAt = Instant.now()) .subscribeOn(Schedulers.single()) diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCE.java index de2e8215f1c6..8be5b320c541 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCE.java @@ -24,21 +24,26 @@ public interface PolicySolutionCE { Map<String, Policy> generatePolicyFromPermissionGroupForObject(PermissionGroup permissionGroup, String objectId); - Map<String, Policy> generatePolicyFromPermissionWithPermissionGroup(AclPermission permission, String permissionGroupId); + Map<String, Policy> generatePolicyFromPermissionWithPermissionGroup( + AclPermission permission, String permissionGroupId); - Flux<Datasource> updateWithNewPoliciesToDatasourcesByDatasourceIdsWithoutPermission(Set<String> ids, - Map<String, Policy> datasourcePolicyMap, - boolean addPolicyToObject); + Flux<Datasource> updateWithNewPoliciesToDatasourcesByDatasourceIdsWithoutPermission( + Set<String> ids, Map<String, Policy> datasourcePolicyMap, boolean addPolicyToObject); - Flux<NewPage> updateWithApplicationPermissionsToAllItsPages(String applicationId, Map<String, Policy> newPagePoliciesMap, boolean addPolicyToObject); + Flux<NewPage> updateWithApplicationPermissionsToAllItsPages( + String applicationId, Map<String, Policy> newPagePoliciesMap, boolean addPolicyToObject); - Flux<Theme> updateThemePolicies(Application application, Map<String, Policy> themePolicyMap, boolean addPolicyToObject); + Flux<Theme> updateThemePolicies( + Application application, Map<String, Policy> themePolicyMap, boolean addPolicyToObject); - Flux<NewAction> updateWithPagePermissionsToAllItsActions(String applicationId, Map<String, Policy> newActionPoliciesMap, boolean addPolicyToObject); + Flux<NewAction> updateWithPagePermissionsToAllItsActions( + String applicationId, Map<String, Policy> newActionPoliciesMap, boolean addPolicyToObject); - Flux<ActionCollection> updateWithPagePermissionsToAllItsActionCollections(String applicationId, Map<String, Policy> newActionPoliciesMap, boolean addPolicyToObject); + Flux<ActionCollection> updateWithPagePermissionsToAllItsActionCollections( + String applicationId, Map<String, Policy> newActionPoliciesMap, boolean addPolicyToObject); - Map<String, Policy> generateInheritedPoliciesFromSourcePolicies(Map<String, Policy> sourcePolicyMap, - Class<? extends BaseDomain> sourceEntity, - Class<? extends BaseDomain> destinationEntity); + Map<String, Policy> generateInheritedPoliciesFromSourcePolicies( + Map<String, Policy> sourcePolicyMap, + Class<? extends BaseDomain> sourceEntity, + Class<? extends BaseDomain> destinationEntity); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCEImpl.java index 8a3506ce2e59..d6b1d71827f6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCEImpl.java @@ -35,14 +35,11 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import static com.appsmith.server.acl.AclPermission.READ_THEMES; -import static java.lang.Boolean.FALSE; -import static java.lang.Boolean.TRUE; @AllArgsConstructor @Slf4j @@ -112,7 +109,8 @@ public <T extends BaseDomain> T removePoliciesFromExistingObject(Map<String, Pol policy.setPermissionGroups(new HashSet<>()); } if (policyMap1.get(permission).getPermissionGroups() != null) { - policy.getPermissionGroups().removeAll(policyMap1.get(permission).getPermissionGroups()); + policy.getPermissionGroups() + .removeAll(policyMap1.get(permission).getPermissionGroups()); } // Remove this permission from the policyMap as this has been accounted for in the above code policyMap1.remove(permission); @@ -138,8 +136,10 @@ public Map<String, Policy> generatePolicyFromPermission(Set<AclPermission> permi return permissions.stream() .map(perm -> { // Create a policy for the invited user using the permission as per the role - Policy policyWithCurrentPermission = Policy.builder().permission(perm.getValue()) - .users(Set.of(username)).build(); + Policy policyWithCurrentPermission = Policy.builder() + .permission(perm.getValue()) + .users(Set.of(username)) + .build(); // Generate any and all lateral policies that might come with the current permission Set<Policy> policiesForUser = policyGenerator.getLateralPolicies(perm, Set.of(username), null); policiesForUser.add(policyWithCurrentPermission); @@ -150,17 +150,19 @@ public Map<String, Policy> generatePolicyFromPermission(Set<AclPermission> permi } @Override - public Map<String, Policy> generatePolicyFromPermissionGroupForObject(PermissionGroup permissionGroup, String objectId) { + public Map<String, Policy> generatePolicyFromPermissionGroupForObject( + PermissionGroup permissionGroup, String objectId) { Set<Permission> permissions = permissionGroup.getPermissions(); return permissions.stream() .filter(perm -> perm.getDocumentId().equals(objectId)) .map(perm -> { - - Policy policyWithCurrentPermission = Policy.builder().permission(perm.getAclPermission().getValue()) + Policy policyWithCurrentPermission = Policy.builder() + .permission(perm.getAclPermission().getValue()) .permissionGroups(Set.of(permissionGroup.getId())) .build(); // Generate any and all lateral policies that might come with the current permission - Set<Policy> policiesForPermissionGroup = policyGenerator.getLateralPolicies(perm.getAclPermission(), Set.of(permissionGroup.getId()), null); + Set<Policy> policiesForPermissionGroup = policyGenerator.getLateralPolicies( + perm.getAclPermission(), Set.of(permissionGroup.getId()), null); policiesForPermissionGroup.add(policyWithCurrentPermission); return policiesForPermissionGroup; }) @@ -169,27 +171,31 @@ public Map<String, Policy> generatePolicyFromPermissionGroupForObject(Permission } @Override - public Map<String, Policy> generatePolicyFromPermissionWithPermissionGroup(AclPermission permission, String permissionGroupId) { + public Map<String, Policy> generatePolicyFromPermissionWithPermissionGroup( + AclPermission permission, String permissionGroupId) { - Policy policyWithCurrentPermission = Policy.builder().permission(permission.getValue()) + Policy policyWithCurrentPermission = Policy.builder() + .permission(permission.getValue()) .permissionGroups(Set.of(permissionGroupId)) .build(); // Generate any and all lateral policies that might come with the current permission - Set<Policy> policiesForPermission = policyGenerator.getLateralPolicies(permission, Set.of(permissionGroupId), null); + Set<Policy> policiesForPermission = + policyGenerator.getLateralPolicies(permission, Set.of(permissionGroupId), null); policiesForPermission.add(policyWithCurrentPermission); - return policiesForPermission.stream() - .collect(Collectors.toMap(Policy::getPermission, Function.identity())); + return policiesForPermission.stream().collect(Collectors.toMap(Policy::getPermission, Function.identity())); } - - public Map<String, Policy> generatePolicyFromPermissionForMultipleUsers(Set<AclPermission> permissions, List<User> users) { + public Map<String, Policy> generatePolicyFromPermissionForMultipleUsers( + Set<AclPermission> permissions, List<User> users) { Set<String> usernames = users.stream().map(user -> user.getUsername()).collect(Collectors.toSet()); return permissions.stream() .map(perm -> { // Create a policy for the invited user using the permission as per the role - Policy policyWithCurrentPermission = Policy.builder().permission(perm.getValue()) - .users(usernames).build(); + Policy policyWithCurrentPermission = Policy.builder() + .permission(perm.getValue()) + .users(usernames) + .build(); // Generate any and all lateral policies that might come with the current permission Set<Policy> policiesForUser = policyGenerator.getLateralPolicies(perm, usernames, null); policiesForUser.add(policyWithCurrentPermission); @@ -199,12 +205,14 @@ public Map<String, Policy> generatePolicyFromPermissionForMultipleUsers(Set<AclP .collect(Collectors.toMap(Policy::getPermission, Function.identity())); } - public Flux<Datasource> updateWithNewPoliciesToDatasourcesByWorkspaceId(String workspaceId, Map<String, Policy> newPoliciesMap, boolean addPolicyToObject) { + public Flux<Datasource> updateWithNewPoliciesToDatasourcesByWorkspaceId( + String workspaceId, Map<String, Policy> newPoliciesMap, boolean addPolicyToObject) { return datasourceRepository // fetch datasources with execute permissions so that app viewers can invite other app viewers .findAllByWorkspaceId(workspaceId, datasourcePermission.getExecutePermission()) - // In case we have come across a datasource for this workspace that the current user is not allowed to manage, move on. + // In case we have come across a datasource for this workspace that the current user is not allowed to + // manage, move on. .switchIfEmpty(Mono.empty()) .map(datasource -> { if (addPolicyToObject) { @@ -217,7 +225,8 @@ public Flux<Datasource> updateWithNewPoliciesToDatasourcesByWorkspaceId(String w .flatMapMany(updatedDatasources -> datasourceRepository.saveAll(updatedDatasources)); } - public Flux<Datasource> updateWithNewPoliciesToDatasourcesByDatasourceIds(Set<String> ids, Map<String, Policy> datasourcePolicyMap, boolean addPolicyToObject) { + public Flux<Datasource> updateWithNewPoliciesToDatasourcesByDatasourceIds( + Set<String> ids, Map<String, Policy> datasourcePolicyMap, boolean addPolicyToObject) { return datasourceRepository .findAllByIds(ids, datasourcePermission.getEditPermission()) @@ -238,9 +247,8 @@ public Flux<Datasource> updateWithNewPoliciesToDatasourcesByDatasourceIds(Set<St } @Override - public Flux<Datasource> updateWithNewPoliciesToDatasourcesByDatasourceIdsWithoutPermission(Set<String> ids, - Map<String, Policy> datasourcePolicyMap, - boolean addPolicyToObject) { + public Flux<Datasource> updateWithNewPoliciesToDatasourcesByDatasourceIdsWithoutPermission( + Set<String> ids, Map<String, Policy> datasourcePolicyMap, boolean addPolicyToObject) { // Find all the datasources without permission to update the policies. return datasourceRepository @@ -260,12 +268,14 @@ public Flux<Datasource> updateWithNewPoliciesToDatasourcesByDatasourceIdsWithout .flatMapMany(datasources -> datasourceRepository.saveAll(datasources)); } - public Flux<Application> updateWithNewPoliciesToApplicationsByWorkspaceId(String workspaceId, Map<String, Policy> newAppPoliciesMap, boolean addPolicyToObject) { + public Flux<Application> updateWithNewPoliciesToApplicationsByWorkspaceId( + String workspaceId, Map<String, Policy> newAppPoliciesMap, boolean addPolicyToObject) { return applicationRepository // fetch applications with read permissions so that app viewers can invite other app viewers .findByWorkspaceId(workspaceId, applicationPermission.getReadPermission()) - // In case we have come across an application for this workspace that the current user is not allowed to manage, move on. + // In case we have come across an application for this workspace that the current user is not allowed to + // manage, move on. .switchIfEmpty(Mono.empty()) .map(application -> { if (addPolicyToObject) { @@ -279,11 +289,15 @@ public Flux<Application> updateWithNewPoliciesToApplicationsByWorkspaceId(String } @Override - public Flux<NewPage> updateWithApplicationPermissionsToAllItsPages(String applicationId, Map<String, Policy> newPagePoliciesMap, boolean addPolicyToObject) { - - // Instead of fetching pages from the application object, we fetch pages from the page repository. This ensures that all the published - // AND the unpublished pages are updated with the new policy change [This covers the edge cases where a page may exist - // in published app but has been deleted in the edit mode]. This means that we don't have to do any special treatment + public Flux<NewPage> updateWithApplicationPermissionsToAllItsPages( + String applicationId, Map<String, Policy> newPagePoliciesMap, boolean addPolicyToObject) { + + // Instead of fetching pages from the application object, we fetch pages from the page repository. This ensures + // that all the published + // AND the unpublished pages are updated with the new policy change [This covers the edge cases where a page may + // exist + // in published app but has been deleted in the edit mode]. This means that we don't have to do any special + // treatment // during deployment of the application to handle edge cases. return newPageRepository // fetch pages with read permissions so that app viewers can invite other app viewers @@ -297,22 +311,20 @@ public Flux<NewPage> updateWithApplicationPermissionsToAllItsPages(String applic } }) .collectList() - .flatMapMany(updatedPages -> newPageRepository - .saveAll(updatedPages)); + .flatMapMany(updatedPages -> newPageRepository.saveAll(updatedPages)); } @Override - public Flux<Theme> updateThemePolicies(Application application, Map<String, Policy> themePolicyMap, boolean addPolicyToObject) { + public Flux<Theme> updateThemePolicies( + Application application, Map<String, Policy> themePolicyMap, boolean addPolicyToObject) { Flux<Theme> applicationThemes = themeRepository.getApplicationThemes(application.getId(), READ_THEMES); if (StringUtils.hasLength(application.getEditModeThemeId())) { applicationThemes = applicationThemes.concatWith( - themeRepository.findById(application.getEditModeThemeId(), READ_THEMES) - ); + themeRepository.findById(application.getEditModeThemeId(), READ_THEMES)); } if (StringUtils.hasLength(application.getPublishedModeThemeId())) { applicationThemes = applicationThemes.concatWith( - themeRepository.findById(application.getPublishedModeThemeId(), READ_THEMES) - ); + themeRepository.findById(application.getPublishedModeThemeId(), READ_THEMES)); } return applicationThemes .filter(theme -> !theme.isSystemTheme()) // skip the system themes @@ -340,7 +352,8 @@ public Flux<Theme> updateThemePolicies(Application application, Map<String, Poli * @return */ @Override - public Flux<NewAction> updateWithPagePermissionsToAllItsActions(String applicationId, Map<String, Policy> newActionPoliciesMap, boolean addPolicyToObject) { + public Flux<NewAction> updateWithPagePermissionsToAllItsActions( + String applicationId, Map<String, Policy> newActionPoliciesMap, boolean addPolicyToObject) { return newActionRepository .findByApplicationId(applicationId) @@ -357,7 +370,8 @@ public Flux<NewAction> updateWithPagePermissionsToAllItsActions(String applicati } @Override - public Flux<ActionCollection> updateWithPagePermissionsToAllItsActionCollections(String applicationId, Map<String, Policy> newActionPoliciesMap, boolean addPolicyToObject) { + public Flux<ActionCollection> updateWithPagePermissionsToAllItsActionCollections( + String applicationId, Map<String, Policy> newActionPoliciesMap, boolean addPolicyToObject) { return actionCollectionRepository .findByApplicationId(applicationId) @@ -374,12 +388,14 @@ public Flux<ActionCollection> updateWithPagePermissionsToAllItsActionCollections } @Override - public Map<String, Policy> generateInheritedPoliciesFromSourcePolicies(Map<String, Policy> sourcePolicyMap, - Class<? extends BaseDomain> sourceEntity, - Class<? extends BaseDomain> destinationEntity) { + public Map<String, Policy> generateInheritedPoliciesFromSourcePolicies( + Map<String, Policy> sourcePolicyMap, + Class<? extends BaseDomain> sourceEntity, + Class<? extends BaseDomain> destinationEntity) { Set<Policy> extractedInterestingPolicySet = new HashSet<>(sourcePolicyMap.values()); - return policyGenerator.getAllChildPolicies(extractedInterestingPolicySet, sourceEntity, destinationEntity) + return policyGenerator + .getAllChildPolicies(extractedInterestingPolicySet, sourceEntity, destinationEntity) .stream() .collect(Collectors.toMap(Policy::getPermission, Function.identity())); } @@ -396,5 +412,4 @@ public Set<String> findUsernamesWithPermission(Set<Policy> policies, AclPermissi return Collections.emptySet(); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/RefactoringSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/RefactoringSolutionCE.java index 3ccbaefcb4f7..676b81a33962 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/RefactoringSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/RefactoringSolutionCE.java @@ -18,7 +18,8 @@ public interface RefactoringSolutionCE { Mono<LayoutDTO> refactorActionName(RefactorActionNameDTO refactorActionNameDTO, String branchName); - Mono<LayoutDTO> refactorActionCollectionName(String appId, String pageId, String layoutId, String oldName, String newName); + Mono<LayoutDTO> refactorActionCollectionName( + String appId, String pageId, String layoutId, String oldName, String newName); /** * This method is responsible for the core logic of refactoring a valid name inside an Appsmith page. diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/RefactoringSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/RefactoringSolutionCEImpl.java index 6bf23936a12c..546576996f45 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/RefactoringSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/RefactoringSolutionCEImpl.java @@ -80,19 +80,20 @@ public class RefactoringSolutionCEImpl implements RefactoringSolutionCE { private static final String preWord = "\\b("; private static final String postWord = ")\\b"; - public RefactoringSolutionCEImpl(ObjectMapper objectMapper, - NewPageService newPageService, - NewActionService newActionService, - ActionCollectionService actionCollectionService, - ResponseUtils responseUtils, - LayoutActionService layoutActionService, - ApplicationService applicationService, - AstService astService, - InstanceConfig instanceConfig, - AnalyticsService analyticsService, - SessionUserService sessionUserService, - PagePermission pagePermission, - ActionPermission actionPermission) { + public RefactoringSolutionCEImpl( + ObjectMapper objectMapper, + NewPageService newPageService, + NewActionService newActionService, + ActionCollectionService actionCollectionService, + ResponseUtils responseUtils, + LayoutActionService layoutActionService, + ApplicationService applicationService, + AstService astService, + InstanceConfig instanceConfig, + AnalyticsService analyticsService, + SessionUserService sessionUserService, + PagePermission pagePermission, + ActionPermission actionPermission) { this.objectMapper = objectMapper; this.newPageService = newPageService; this.newActionService = newActionService; @@ -115,16 +116,22 @@ public Mono<LayoutDTO> refactorWidgetName(RefactorNameDTO refactorNameDTO) { String layoutId = refactorNameDTO.getLayoutId(); String oldName = refactorNameDTO.getOldName(); String newName = refactorNameDTO.getNewName(); - return layoutActionService.isNameAllowed(pageId, layoutId, newName) + return layoutActionService + .isNameAllowed(pageId, layoutId, newName) .zipWith(newPageService.getById(pageId)) .flatMap(tuple -> { - analyticsProperties.put(FieldName.APPLICATION_ID, tuple.getT2().getApplicationId()); + analyticsProperties.put( + FieldName.APPLICATION_ID, tuple.getT2().getApplicationId()); analyticsProperties.put(FieldName.PAGE_ID, pageId); if (!tuple.getT1()) { - return Mono.error(new AppsmithException(AppsmithError.NAME_CLASH_NOT_ALLOWED_IN_REFACTOR, oldName, newName)); + return Mono.error(new AppsmithException( + AppsmithError.NAME_CLASH_NOT_ALLOWED_IN_REFACTOR, oldName, newName)); } return this.refactorName(pageId, layoutId, oldName, newName) - .flatMap(tuple2 -> this.sendRefactorAnalytics(AnalyticsEvents.REFACTOR_WIDGET.getEventName(), analyticsProperties, tuple2.getT2()) + .flatMap(tuple2 -> this.sendRefactorAnalytics( + AnalyticsEvents.REFACTOR_WIDGET.getEventName(), + analyticsProperties, + tuple2.getT2()) .thenReturn(tuple2.getT1())); }); } @@ -135,7 +142,9 @@ public Mono<LayoutDTO> refactorWidgetName(RefactorNameDTO refactorNameDTO, Strin return refactorWidgetName(refactorNameDTO); } - return newPageService.findByBranchNameAndDefaultPageId(branchName, refactorNameDTO.getPageId(), pagePermission.getEditPermission()) + return newPageService + .findByBranchNameAndDefaultPageId( + branchName, refactorNameDTO.getPageId(), pagePermission.getEditPermission()) .flatMap(branchedPage -> { refactorNameDTO.setPageId(branchedPage.getId()); return refactorWidgetName(refactorNameDTO); @@ -149,13 +158,13 @@ public Mono<LayoutDTO> refactorActionName(RefactorActionNameDTO refactorActionNa String pageId = refactorActionNameDTO.getPageId(); String layoutId = refactorActionNameDTO.getLayoutId(); String oldName = refactorActionNameDTO.getOldName(); - final String oldFullyQualifiedName = StringUtils.hasLength(refactorActionNameDTO.getCollectionName()) ? - refactorActionNameDTO.getCollectionName() + "." + oldName : - oldName; + final String oldFullyQualifiedName = StringUtils.hasLength(refactorActionNameDTO.getCollectionName()) + ? refactorActionNameDTO.getCollectionName() + "." + oldName + : oldName; String newName = refactorActionNameDTO.getNewName(); - final String newFullyQualifiedName = StringUtils.hasLength(refactorActionNameDTO.getCollectionName()) ? - refactorActionNameDTO.getCollectionName() + "." + newName : - newName; + final String newFullyQualifiedName = StringUtils.hasLength(refactorActionNameDTO.getCollectionName()) + ? refactorActionNameDTO.getCollectionName() + "." + newName + : newName; String actionId = refactorActionNameDTO.getActionId(); return Mono.just(newActionService.validateActionName(newName)) .flatMap(isValidName -> { @@ -166,10 +175,11 @@ public Mono<LayoutDTO> refactorActionName(RefactorActionNameDTO refactorActionNa }) .flatMap(allowed -> { if (!allowed) { - return Mono.error(new AppsmithException(AppsmithError.NAME_CLASH_NOT_ALLOWED_IN_REFACTOR, oldName, newName)); + return Mono.error(new AppsmithException( + AppsmithError.NAME_CLASH_NOT_ALLOWED_IN_REFACTOR, oldName, newName)); } - return newActionService - .findActionDTObyIdAndViewMode(actionId, false, actionPermission.getEditPermission()); + return newActionService.findActionDTObyIdAndViewMode( + actionId, false, actionPermission.getEditPermission()); }) .flatMap(action -> { analyticsProperties.put(FieldName.APPLICATION_ID, action.getApplicationId()); @@ -195,23 +205,26 @@ public Mono<LayoutDTO> refactorActionName(RefactorActionNameDTO refactorActionNa public Mono<LayoutDTO> refactorActionName(RefactorActionNameDTO refactorActionNameDTO, String branchName) { String defaultActionId = refactorActionNameDTO.getActionId(); - return newActionService.findByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getEditPermission()) + return newActionService + .findByBranchNameAndDefaultActionId(branchName, defaultActionId, actionPermission.getEditPermission()) .flatMap(branchedAction -> { refactorActionNameDTO.setActionId(branchedAction.getId()); - refactorActionNameDTO.setPageId(branchedAction.getUnpublishedAction().getPageId()); + refactorActionNameDTO.setPageId( + branchedAction.getUnpublishedAction().getPageId()); return refactorActionName(refactorActionNameDTO); }) .map(responseUtils::updateLayoutDTOWithDefaultResources); } @Override - public Mono<LayoutDTO> refactorActionCollectionName(String appId, String pageId, String layoutId, String oldName, String newName) { + public Mono<LayoutDTO> refactorActionCollectionName( + String appId, String pageId, String layoutId, String oldName, String newName) { final Map<String, String> analyticsProperties = new HashMap<>(); analyticsProperties.put(FieldName.APPLICATION_ID, appId); analyticsProperties.put(FieldName.PAGE_ID, pageId); - return this.refactorName(pageId, layoutId, oldName, newName) - .flatMap(tuple -> this.sendRefactorAnalytics(AnalyticsEvents.REFACTOR_JSOBJECT.getEventName(), analyticsProperties, tuple.getT2()) - .thenReturn(tuple.getT1())); + return this.refactorName(pageId, layoutId, oldName, newName).flatMap(tuple -> this.sendRefactorAnalytics( + AnalyticsEvents.REFACTOR_JSOBJECT.getEventName(), analyticsProperties, tuple.getT2()) + .thenReturn(tuple.getT1())); } /** @@ -226,7 +239,8 @@ public Mono<LayoutDTO> refactorActionCollectionName(String appId, String pageId, * @return : The DSL after refactor updates */ @Override - public Mono<Tuple2<LayoutDTO, Set<String>>> refactorName(String pageId, String layoutId, String oldName, String newName) { + public Mono<Tuple2<LayoutDTO, Set<String>>> refactorName( + String pageId, String layoutId, String oldName, String newName) { String regexPattern = preWord + oldName + postWord; Pattern oldNamePattern = Pattern.compile(regexPattern); final Set<String> updatedBindingPaths = new HashSet<>(); @@ -236,52 +250,49 @@ public Mono<Tuple2<LayoutDTO, Set<String>>> refactorName(String pageId, String l .findPageById(pageId, pagePermission.getEditPermission(), false) .cache(); - Mono<Integer> evalVersionMono = pageMono - .flatMap(page -> { - return applicationService.findById(page.getApplicationId()) - .map(application -> { - Integer evaluationVersion = application.getEvaluationVersion(); - if (evaluationVersion == null) { - evaluationVersion = EVALUATION_VERSION; - } - return evaluationVersion; - }); + Mono<Integer> evalVersionMono = pageMono.flatMap(page -> { + return applicationService.findById(page.getApplicationId()).map(application -> { + Integer evaluationVersion = application.getEvaluationVersion(); + if (evaluationVersion == null) { + evaluationVersion = EVALUATION_VERSION; + } + return evaluationVersion; + }); }) .cache(); - Mono<PageDTO> updatePageMono = Mono.zip(pageMono, evalVersionMono) - .flatMap(tuple -> { - PageDTO page = tuple.getT1(); - int evalVersion = tuple.getT2(); - - List<Layout> layouts = page.getLayouts(); - for (Layout layout : layouts) { - if (layoutId.equals(layout.getId()) && layout.getDsl() != null) { - // DSL has removed all the old names and replaced it with new name. If the change of name - // was one of the mongoEscaped widgets, then update the names in the set as well - Set<String> mongoEscapedWidgetNames = layout.getMongoEscapedWidgetNames(); - if (mongoEscapedWidgetNames != null && mongoEscapedWidgetNames.contains(oldName)) { - mongoEscapedWidgetNames.remove(oldName); - mongoEscapedWidgetNames.add(newName); - } - - final JsonNode dslNode = objectMapper.convertValue(layout.getDsl(), JsonNode.class); - Mono<PageDTO> refactorNameInDslMono = this.refactorNameInDsl(dslNode, oldName, newName, evalVersion, oldNamePattern) - .flatMap(dslBindingPaths -> { - updatedBindingPaths.addAll(dslBindingPaths); - layout.setDsl(objectMapper.convertValue(dslNode, JSONObject.class)); - page.setLayouts(layouts); - return Mono.just(page); - }); - - // Since the page has most probably changed, save the page and return. - return refactorNameInDslMono - .flatMap(newPageService::saveUnpublishedPage); - } + Mono<PageDTO> updatePageMono = Mono.zip(pageMono, evalVersionMono).flatMap(tuple -> { + PageDTO page = tuple.getT1(); + int evalVersion = tuple.getT2(); + + List<Layout> layouts = page.getLayouts(); + for (Layout layout : layouts) { + if (layoutId.equals(layout.getId()) && layout.getDsl() != null) { + // DSL has removed all the old names and replaced it with new name. If the change of name + // was one of the mongoEscaped widgets, then update the names in the set as well + Set<String> mongoEscapedWidgetNames = layout.getMongoEscapedWidgetNames(); + if (mongoEscapedWidgetNames != null && mongoEscapedWidgetNames.contains(oldName)) { + mongoEscapedWidgetNames.remove(oldName); + mongoEscapedWidgetNames.add(newName); } - // If we have reached here, the layout was not found and the page should be returned as is. - return Mono.just(page); - }); + + final JsonNode dslNode = objectMapper.convertValue(layout.getDsl(), JsonNode.class); + Mono<PageDTO> refactorNameInDslMono = this.refactorNameInDsl( + dslNode, oldName, newName, evalVersion, oldNamePattern) + .flatMap(dslBindingPaths -> { + updatedBindingPaths.addAll(dslBindingPaths); + layout.setDsl(objectMapper.convertValue(dslNode, JSONObject.class)); + page.setLayouts(layouts); + return Mono.just(page); + }); + + // Since the page has most probably changed, save the page and return. + return refactorNameInDslMono.flatMap(newPageService::saveUnpublishedPage); + } + } + // If we have reached here, the layout was not found and the page should be returned as is. + return Mono.just(page); + }); Set<String> updatableCollectionIds = new HashSet<>(); @@ -321,7 +332,6 @@ public Mono<Tuple2<LayoutDTO, Set<String>>> refactorName(String pageId, String l return newActionService.save(newAction); }); }); - }) .map(savedAction -> savedAction.getUnpublishedAction().getName()) .collect(toSet()) @@ -331,19 +341,23 @@ public Mono<Tuple2<LayoutDTO, Set<String>>> refactorName(String pageId, String l Integer evalVersion = tuple.getT2(); // If these actions belonged to collections, update the collection body return Flux.fromIterable(updatableCollectionIds) - .flatMap(collectionId -> actionCollectionService.findById(collectionId, actionPermission.getEditPermission())) + .flatMap(collectionId -> actionCollectionService.findById( + collectionId, actionPermission.getEditPermission())) .flatMap(actionCollection -> { - final ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); + final ActionCollectionDTO unpublishedCollection = + actionCollection.getUnpublishedCollection(); return this.replaceValueInMustacheKeys( - new HashSet<>(Collections.singletonList(new MustacheBindingToken(unpublishedCollection.getBody(), 0, true))), + new HashSet<>(Collections.singletonList(new MustacheBindingToken( + unpublishedCollection.getBody(), 0, true))), oldName, newName, evalVersion, oldNamePattern, true) .flatMap(replacedMap -> { - Optional<String> replacedValue = replacedMap.values().stream().findFirst(); + Optional<String> replacedValue = replacedMap.values().stream() + .findFirst(); // This value should always be there if (replacedValue.isPresent()) { unpublishedCollection.setBody(replacedValue.get()); @@ -351,30 +365,30 @@ public Mono<Tuple2<LayoutDTO, Set<String>>> refactorName(String pageId, String l } return Mono.just(actionCollection); }); - }) .collectList() .thenReturn(updatedActions); }); - return Mono.zip(updateActionsMono, updatePageMono) - .flatMap(tuple -> { - Set<String> updatedActionNames = tuple.getT1(); - PageDTO page = tuple.getT2(); - log.debug("Actions updated due to refactor name in page {} are : {}", pageId, updatedActionNames); - List<Layout> layouts = page.getLayouts(); - for (Layout layout : layouts) { - if (layoutId.equals(layout.getId())) { - layout.setDsl(layoutActionService.unescapeMongoSpecialCharacters(layout)); - return layoutActionService.updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout) - .zipWith(Mono.just(updatedBindingPaths)); - } - } - return Mono.empty(); - }); + return Mono.zip(updateActionsMono, updatePageMono).flatMap(tuple -> { + Set<String> updatedActionNames = tuple.getT1(); + PageDTO page = tuple.getT2(); + log.debug("Actions updated due to refactor name in page {} are : {}", pageId, updatedActionNames); + List<Layout> layouts = page.getLayouts(); + for (Layout layout : layouts) { + if (layoutId.equals(layout.getId())) { + layout.setDsl(layoutActionService.unescapeMongoSpecialCharacters(layout)); + return layoutActionService + .updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout) + .zipWith(Mono.just(updatedBindingPaths)); + } + } + return Mono.empty(); + }); } - Mono<Set<String>> refactorNameInDsl(JsonNode dsl, String oldName, String newName, int evalVersion, Pattern oldNamePattern) { + Mono<Set<String>> refactorNameInDsl( + JsonNode dsl, String oldName, String newName, int evalVersion, Pattern oldNamePattern) { Mono<Set<String>> refactorNameInWidgetMono = Mono.just(new HashSet<>()); Mono<Set<String>> recursiveRefactorNameInDslMono = Mono.just(new HashSet<>()); @@ -397,15 +411,14 @@ Mono<Set<String>> refactorNameInDsl(JsonNode dsl, String oldName, String newName }); } - return refactorNameInWidgetMono - .zipWith(recursiveRefactorNameInDslMono) - .map(tuple -> { - tuple.getT1().addAll(tuple.getT2()); - return tuple.getT1(); - }); + return refactorNameInWidgetMono.zipWith(recursiveRefactorNameInDslMono).map(tuple -> { + tuple.getT1().addAll(tuple.getT2()); + return tuple.getT1(); + }); } - Mono<Set<String>> refactorNameInWidget(JsonNode widgetDsl, String oldName, String newName, int evalVersion, Pattern oldNamePattern) { + Mono<Set<String>> refactorNameInWidget( + JsonNode widgetDsl, String oldName, String newName, int evalVersion, Pattern oldNamePattern) { boolean isRefactoredWidget = false; boolean isRefactoredTemplate = false; String widgetName = ""; @@ -423,7 +436,9 @@ Mono<Set<String>> refactorNameInWidget(JsonNode widgetDsl, String oldName, Strin // just the default widgets inside the list. This is required because for the list, the widget names // exist as keys at the location List1.template(.Text1) [Ref #9281] // Ideally, we should avoid any non-structural elements as keys. This will be improved in list widget v2 - if (widgetDsl.has(FieldName.WIDGET_TYPE) && FieldName.LIST_WIDGET.equals(widgetDsl.get(FieldName.WIDGET_TYPE).asText())) { + if (widgetDsl.has(FieldName.WIDGET_TYPE) + && FieldName.LIST_WIDGET.equals( + widgetDsl.get(FieldName.WIDGET_TYPE).asText())) { final JsonNode template = widgetDsl.get(FieldName.LIST_WIDGET_TEMPLATE); JsonNode newJsonNode = null; String fieldName = null; @@ -452,38 +467,29 @@ Mono<Set<String>> refactorNameInWidget(JsonNode widgetDsl, String oldName, Strin Mono<Set<String>> refactorTriggerBindingsMono = Mono.just(new HashSet<>()); // If there are dynamic bindings in this action configuration, inspect them - if (widgetDsl.has(FieldName.DYNAMIC_BINDING_PATH_LIST) && !widgetDsl.get(FieldName.DYNAMIC_BINDING_PATH_LIST).isEmpty()) { + if (widgetDsl.has(FieldName.DYNAMIC_BINDING_PATH_LIST) + && !widgetDsl.get(FieldName.DYNAMIC_BINDING_PATH_LIST).isEmpty()) { ArrayNode dslDynamicBindingPathList = (ArrayNode) widgetDsl.get(FieldName.DYNAMIC_BINDING_PATH_LIST); // recurse over each child refactorDynamicBindingsMono = refactorBindingsUsingBindingPaths( - widgetDsl, - oldName, - newName, - evalVersion, - oldNamePattern, - dslDynamicBindingPathList, - widgetName); + widgetDsl, oldName, newName, evalVersion, oldNamePattern, dslDynamicBindingPathList, widgetName); } // If there are dynamic triggers in this action configuration, inspect them - if (widgetDsl.has(FieldName.DYNAMIC_TRIGGER_PATH_LIST) && !widgetDsl.get(FieldName.DYNAMIC_TRIGGER_PATH_LIST).isEmpty()) { + if (widgetDsl.has(FieldName.DYNAMIC_TRIGGER_PATH_LIST) + && !widgetDsl.get(FieldName.DYNAMIC_TRIGGER_PATH_LIST).isEmpty()) { ArrayNode dslDynamicTriggerPathList = (ArrayNode) widgetDsl.get(FieldName.DYNAMIC_TRIGGER_PATH_LIST); // recurse over each child refactorTriggerBindingsMono = refactorBindingsUsingBindingPaths( - widgetDsl, - oldName, - newName, - evalVersion, - oldNamePattern, - dslDynamicTriggerPathList, - widgetName); + widgetDsl, oldName, newName, evalVersion, oldNamePattern, dslDynamicTriggerPathList, widgetName); } final String finalWidgetNamePath = widgetName + ".widgetName"; final boolean finalIsRefactoredWidget = isRefactoredWidget; final boolean finalIsRefactoredTemplate = isRefactoredTemplate; final String finalWidgetTemplatePath = widgetName + ".template"; - return refactorDynamicBindingsMono.zipWith(refactorTriggerBindingsMono) + return refactorDynamicBindingsMono + .zipWith(refactorTriggerBindingsMono) .map(tuple -> { tuple.getT1().addAll(tuple.getT2()); return tuple.getT1(); @@ -499,28 +505,38 @@ Mono<Set<String>> refactorNameInWidget(JsonNode widgetDsl, String oldName, Strin }); } - @NotNull - private Mono<Set<String>> refactorBindingsUsingBindingPaths(JsonNode widgetDsl, String oldName, String newName, int evalVersion, Pattern oldNamePattern, ArrayNode bindingPathList, String widgetName) { + @NotNull private Mono<Set<String>> refactorBindingsUsingBindingPaths( + JsonNode widgetDsl, + String oldName, + String newName, + int evalVersion, + Pattern oldNamePattern, + ArrayNode bindingPathList, + String widgetName) { Mono<Set<String>> refactorBindingsMono; refactorBindingsMono = Flux.fromStream(StreamSupport.stream(bindingPathList.spliterator(), true)) .flatMap(bindingPath -> { String key = bindingPath.get(FieldName.KEY).asText(); // This is inside a list widget, and the path starts with template.<oldName>., // We need to update the binding path list entry itself as well - if (widgetDsl.has(FieldName.WIDGET_TYPE) && - FieldName.LIST_WIDGET.equals(widgetDsl.get(FieldName.WIDGET_TYPE).asText()) && - key.startsWith("template." + oldName + ".")) { + if (widgetDsl.has(FieldName.WIDGET_TYPE) + && FieldName.LIST_WIDGET.equals( + widgetDsl.get(FieldName.WIDGET_TYPE).asText()) + && key.startsWith("template." + oldName + ".")) { key = key.replace(oldName, newName); ((ObjectNode) bindingPath).set(FieldName.KEY, new TextNode(key)); } // Find values inside mustache bindings in this path - Set<MustacheBindingToken> mustacheValues = DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath(widgetDsl, key); + Set<MustacheBindingToken> mustacheValues = + DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath(widgetDsl, key); final String finalKey = key; // Perform refactor for each mustache value - return this.replaceValueInMustacheKeys(mustacheValues, oldName, newName, evalVersion, oldNamePattern) + return this.replaceValueInMustacheKeys( + mustacheValues, oldName, newName, evalVersion, oldNamePattern) .flatMap(replacementMap -> { if (replacementMap.isEmpty()) { - // If the map is empty, it means that this path did not have anything that had to be refactored + // If the map is empty, it means that this path did not have anything that had to be + // refactored return Mono.empty(); } // Replace the binding path value with the new mustache values @@ -534,8 +550,8 @@ private Mono<Set<String>> refactorBindingsUsingBindingPaths(JsonNode widgetDsl, return refactorBindingsMono; } - Mono<Set<String>> refactorNameInAction(ActionDTO actionDTO, String oldName, String newName, - int evalVersion, Pattern oldNamePattern) { + Mono<Set<String>> refactorNameInAction( + ActionDTO actionDTO, String oldName, String newName, int evalVersion, Pattern oldNamePattern) { // If we're going the fallback route (without AST), we can first filter actions to be refactored // By performing a check on whether json path keys had a reference // This is not needed in the AST way since it would be costlier to make double the number of API calls @@ -566,7 +582,8 @@ Mono<Set<String>> refactorNameInAction(ActionDTO actionDTO, String oldName, Stri Mono<Set<String>> refactorDynamicBindingsMono = Mono.just(new HashSet<>()); // If there are dynamic bindings in this action configuration, inspect them - if (actionDTO.getDynamicBindingPathList() != null && !actionDTO.getDynamicBindingPathList().isEmpty()) { + if (actionDTO.getDynamicBindingPathList() != null + && !actionDTO.getDynamicBindingPathList().isEmpty()) { // recurse over each child refactorDynamicBindingsMono = Flux.fromIterable(actionDTO.getDynamicBindingPathList()) .flatMap(dynamicBindingPath -> { @@ -576,21 +593,27 @@ Mono<Set<String>> refactorNameInAction(ActionDTO actionDTO, String oldName, Stri mustacheValues.add(new MustacheBindingToken(actionConfiguration.getBody(), 0, false)); } else { - mustacheValues = DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath(actionConfigurationNode, key); + mustacheValues = DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath( + actionConfigurationNode, key); } - return this.replaceValueInMustacheKeys(mustacheValues, oldName, newName, evalVersion, oldNamePattern) + return this.replaceValueInMustacheKeys( + mustacheValues, oldName, newName, evalVersion, oldNamePattern) .flatMap(replacementMap -> { if (replacementMap.isEmpty()) { return Mono.empty(); } - DslUtils.replaceValuesInSpecificDynamicBindingPath(actionConfigurationNode, key, replacementMap); - String entityPath = StringUtils.hasLength(actionDTO.getValidName()) ? actionDTO.getValidName() + "." : ""; + DslUtils.replaceValuesInSpecificDynamicBindingPath( + actionConfigurationNode, key, replacementMap); + String entityPath = StringUtils.hasLength(actionDTO.getValidName()) + ? actionDTO.getValidName() + "." + : ""; return Mono.just(entityPath + key); }); }) .collect(Collectors.toSet()) .map(entityPaths -> { - actionDTO.setActionConfiguration(objectMapper.convertValue(actionConfigurationNode, ActionConfiguration.class)); + actionDTO.setActionConfiguration( + objectMapper.convertValue(actionConfigurationNode, ActionConfiguration.class)); return entityPaths; }); } @@ -598,21 +621,30 @@ Mono<Set<String>> refactorNameInAction(ActionDTO actionDTO, String oldName, Stri return refactorDynamicBindingsMono; } - Mono<Map<MustacheBindingToken, String>> replaceValueInMustacheKeys(Set<MustacheBindingToken> mustacheKeySet, String oldName, String - newName, int evalVersion, Pattern oldNamePattern) { + Mono<Map<MustacheBindingToken, String>> replaceValueInMustacheKeys( + Set<MustacheBindingToken> mustacheKeySet, + String oldName, + String newName, + int evalVersion, + Pattern oldNamePattern) { return this.replaceValueInMustacheKeys(mustacheKeySet, oldName, newName, evalVersion, oldNamePattern, false); } - Mono<Map<MustacheBindingToken, String>> replaceValueInMustacheKeys(Set<MustacheBindingToken> mustacheKeySet, String oldName, String - newName, int evalVersion, Pattern oldNamePattern, boolean isJSObject) { + Mono<Map<MustacheBindingToken, String>> replaceValueInMustacheKeys( + Set<MustacheBindingToken> mustacheKeySet, + String oldName, + String newName, + int evalVersion, + Pattern oldNamePattern, + boolean isJSObject) { if (Boolean.TRUE.equals(this.instanceConfig.getIsRtsAccessible())) { return astService.refactorNameInDynamicBindings(mustacheKeySet, oldName, newName, evalVersion, isJSObject); } return this.replaceValueInMustacheKeys(mustacheKeySet, oldNamePattern, newName); } - Mono<Map<MustacheBindingToken, String>> replaceValueInMustacheKeys(Set<MustacheBindingToken> mustacheKeySet, Pattern - oldNamePattern, String newName) { + Mono<Map<MustacheBindingToken, String>> replaceValueInMustacheKeys( + Set<MustacheBindingToken> mustacheKeySet, Pattern oldNamePattern, String newName) { return Flux.fromIterable(mustacheKeySet) .flatMap(mustacheKey -> { Matcher matcher = oldNamePattern.matcher(mustacheKey.getValue()); @@ -625,7 +657,8 @@ Mono<Map<MustacheBindingToken, String>> replaceValueInMustacheKeys(Set<MustacheB } Mono<Void> sendRefactorAnalytics(String event, Map<String, String> properties, Set<String> updatedPaths) { - return sessionUserService.getCurrentUser() + return sessionUserService + .getCurrentUser() .map(user -> { final Map<String, String> analyticsProperties = new HashMap<>(properties); analyticsProperties.put("updatedPaths", updatedPaths.toString()); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ReleaseNotesServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ReleaseNotesServiceCE.java index 78bdfe68ef11..a3aba8609611 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ReleaseNotesServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ReleaseNotesServiceCE.java @@ -20,5 +20,4 @@ public interface ReleaseNotesServiceCE { List<ReleaseNode> getReleaseNodesCache(); void setReleaseNodesCache(List<ReleaseNode> nodes); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ReleaseNotesServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ReleaseNotesServiceCEImpl.java index 82553ff1cdbb..7b04917d15cc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ReleaseNotesServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ReleaseNotesServiceCEImpl.java @@ -15,7 +15,6 @@ import java.util.ArrayList; import java.util.List; - @RequiredArgsConstructor @Slf4j public class ReleaseNotesServiceCEImpl implements ReleaseNotesServiceCE { @@ -78,7 +77,7 @@ public String getRunningVersion() { @Scheduled(initialDelay = 2 * 60 * 1000 /* two minutes */, fixedRate = 2 * 60 * 60 * 1000 /* two hours */) public void refreshReleaseNotes() { - cacheExpiryTime = null; // Bust the release notes cache to force fetching again. + cacheExpiryTime = null; // Bust the release notes cache to force fetching again. getReleaseNodes() .map(releaseNodes -> { cacheExpiryTime = Instant.now().plusSeconds(2 * 60 * 60); @@ -95,5 +94,4 @@ public List<ReleaseNode> getReleaseNodesCache() { public void setReleaseNodesCache(List<ReleaseNode> nodes) { this.releaseNodesCache = nodes; } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserAndAccessManagementServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserAndAccessManagementServiceCEImpl.java index 4ae3bd5f7550..e011cc012125 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserAndAccessManagementServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserAndAccessManagementServiceCEImpl.java @@ -43,14 +43,15 @@ public class UserAndAccessManagementServiceCEImpl implements UserAndAccessManage private final EmailSender emailSender; private final PermissionGroupPermission permissionGroupPermission; - public UserAndAccessManagementServiceCEImpl(SessionUserService sessionUserService, - PermissionGroupService permissionGroupService, - WorkspaceService workspaceService, - UserRepository userRepository, - AnalyticsService analyticsService, - UserService userService, - EmailSender emailSender, - PermissionGroupPermission permissionGroupPermission) { + public UserAndAccessManagementServiceCEImpl( + SessionUserService sessionUserService, + PermissionGroupService permissionGroupService, + WorkspaceService workspaceService, + UserRepository userRepository, + AnalyticsService analyticsService, + UserService userService, + EmailSender emailSender, + PermissionGroupPermission permissionGroupPermission) { this.sessionUserService = sessionUserService; this.permissionGroupService = permissionGroupService; @@ -100,26 +101,37 @@ public Mono<List<User>> inviteUsers(InviteUsersDTO inviteUsersDTO, String origin Mono<User> currentUserMono = sessionUserService.getCurrentUser().cache(); - // Check if the current user has assign permissions to the permission group and permission group is workspace's default permission group. - Mono<PermissionGroup> permissionGroupMono = permissionGroupService.getById(inviteUsersDTO.getPermissionGroupId(), permissionGroupPermission.getAssignPermission()) - .filter(permissionGroup -> permissionGroup.getDefaultDomainType().equals(Workspace.class.getSimpleName()) && StringUtils.hasText(permissionGroup.getDefaultDomainId())) + // Check if the current user has assign permissions to the permission group and permission group is workspace's + // default permission group. + Mono<PermissionGroup> permissionGroupMono = permissionGroupService + .getById(inviteUsersDTO.getPermissionGroupId(), permissionGroupPermission.getAssignPermission()) + .filter(permissionGroup -> + permissionGroup.getDefaultDomainType().equals(Workspace.class.getSimpleName()) + && StringUtils.hasText(permissionGroup.getDefaultDomainId())) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ROLE))) .cache(); // Get workspace from the default group. - Mono<Workspace> workspaceMono = permissionGroupMono.flatMap(permissionGroup -> workspaceService.getById(permissionGroup.getDefaultDomainId())).cache(); + Mono<Workspace> workspaceMono = permissionGroupMono + .flatMap(permissionGroup -> workspaceService.getById(permissionGroup.getDefaultDomainId())) + .cache(); // Get all the default permision groups of the workspace - Mono<List<PermissionGroup>> defaultPermissionGroupsMono = - workspaceMono.flatMap(workspace -> - permissionGroupService.findAllByIds(workspace.getDefaultPermissionGroups()) - .collectList() - ).cache(); + Mono<List<PermissionGroup>> defaultPermissionGroupsMono = workspaceMono + .flatMap(workspace -> permissionGroupService + .findAllByIds(workspace.getDefaultPermissionGroups()) + .collectList()) + .cache(); // Check if the invited user exists. If yes, return the user, else create a new user by triggering // createNewUserAndSendInviteEmail. In both the cases, send the appropriate emails Mono<List<User>> inviteUsersMono = Flux.fromIterable(usernames) - .flatMap(username -> Mono.zip(Mono.just(username), workspaceMono, currentUserMono, permissionGroupMono, defaultPermissionGroupsMono)) + .flatMap(username -> Mono.zip( + Mono.just(username), + workspaceMono, + currentUserMono, + permissionGroupMono, + defaultPermissionGroupsMono)) .flatMap(tuple -> { String username = tuple.getT1(); Workspace workspace = tuple.getT2(); @@ -128,7 +140,8 @@ public Mono<List<User>> inviteUsers(InviteUsersDTO inviteUsersDTO, String origin PermissionGroup permissionGroup = tuple.getT4(); List<PermissionGroup> defaultPermissionGroups = tuple.getT5(); - Mono<User> getUserFromDbAndCheckIfUserExists = userRepository.findByEmail(username) + Mono<User> getUserFromDbAndCheckIfUserExists = userRepository + .findByEmail(username) .flatMap(user -> { return throwErrorIfUserAlreadyExistsInWorkspace(user, defaultPermissionGroups) // If no errors, proceed forward @@ -139,24 +152,26 @@ public Mono<List<User>> inviteUsers(InviteUsersDTO inviteUsersDTO, String origin .flatMap(existingUser -> { // The user already existed, just send an email informing that the user has been added // to a new workspace - log.debug("Going to send email to user {} informing that the user has been added to new workspace {}", - existingUser.getEmail(), workspace.getName()); + log.debug( + "Going to send email to user {} informing that the user has been added to new workspace {}", + existingUser.getEmail(), + workspace.getName()); // Email template parameters initialization below. - Map<String, String> params = userService.getEmailParams(workspace, currentUser, originHeader, false); - - return userService.updateTenantLogoInParams(params, originHeader) - .flatMap(updatedParams -> - emailSender.sendMail( - existingUser.getEmail(), - "Appsmith: You have been added to a new workspace", - INVITE_USER_EMAIL_TEMPLATE, - updatedParams - ) - ) + Map<String, String> params = + userService.getEmailParams(workspace, currentUser, originHeader, false); + + return userService + .updateTenantLogoInParams(params, originHeader) + .flatMap(updatedParams -> emailSender.sendMail( + existingUser.getEmail(), + "Appsmith: You have been added to a new workspace", + INVITE_USER_EMAIL_TEMPLATE, + updatedParams)) .thenReturn(existingUser); }) - .switchIfEmpty(userService.createNewUserAndSendInviteEmail(username, originHeader, workspace, currentUser, permissionGroup.getName())); + .switchIfEmpty(userService.createNewUserAndSendInviteEmail( + username, originHeader, workspace, currentUser, permissionGroup.getName())); }) .collectList() .cache(); @@ -167,7 +182,8 @@ public Mono<List<User>> inviteUsers(InviteUsersDTO inviteUsersDTO, String origin PermissionGroup permissionGroup = tuple.getT1(); List<User> users = tuple.getT2(); return permissionGroupService.bulkAssignToUserAndSendEvent(permissionGroup, users); - }).cache(); + }) + .cache(); // Send analytics event Mono<Object> sendAnalyticsEventMono = Mono.zip(currentUserMono, inviteUsersMono) @@ -176,29 +192,33 @@ public Mono<List<User>> inviteUsers(InviteUsersDTO inviteUsersDTO, String origin List<User> users = tuple.getT2(); Map<String, Object> analyticsProperties = new HashMap<>(); long numberOfUsers = users.size(); - List<String> invitedUsers = users.stream().map(User::getEmail).collect(Collectors.toList()); + List<String> invitedUsers = + users.stream().map(User::getEmail).collect(Collectors.toList()); analyticsProperties.put(FieldName.NUMBER_OF_USERS_INVITED, numberOfUsers); eventData.put(FieldName.USER_EMAILS, invitedUsers); Map<String, Object> extraPropsForCloudHostedInstance = Map.of(FieldName.USER_EMAILS, invitedUsers); analyticsProperties.put(FieldName.EVENT_DATA, eventData); analyticsProperties.put(FieldName.CLOUD_HOSTED_EXTRA_PROPS, extraPropsForCloudHostedInstance); - return analyticsService.sendObjectEvent(AnalyticsEvents.EXECUTE_INVITE_USERS, currentUser, analyticsProperties); + return analyticsService.sendObjectEvent( + AnalyticsEvents.EXECUTE_INVITE_USERS, currentUser, analyticsProperties); }); return bulkAddUserResultMono.then(sendAnalyticsEventMono).then(inviteUsersMono); } - private Mono<Boolean> throwErrorIfUserAlreadyExistsInWorkspace(User user, - List<PermissionGroup> defaultPermissionGroups) { + private Mono<Boolean> throwErrorIfUserAlreadyExistsInWorkspace( + User user, List<PermissionGroup> defaultPermissionGroups) { return Flux.fromIterable(defaultPermissionGroups) .map(permissionGroup -> { if (permissionGroup.getAssignedToUserIds().contains(user.getId())) { - throw new AppsmithException(AppsmithError.USER_ALREADY_EXISTS_IN_WORKSPACE, user.getUsername(), permissionGroup.getName()); + throw new AppsmithException( + AppsmithError.USER_ALREADY_EXISTS_IN_WORKSPACE, + user.getUsername(), + permissionGroup.getName()); } return TRUE; }) .then(Mono.just(TRUE)); } - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserChangedHandlerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserChangedHandlerCE.java index 4c5d78fcf3ff..a3a354245041 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserChangedHandlerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserChangedHandlerCE.java @@ -3,7 +3,6 @@ import com.appsmith.server.domains.User; import com.appsmith.server.events.UserChangedEvent; - public interface UserChangedHandlerCE { User publish(User user); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserChangedHandlerCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserChangedHandlerCEImpl.java index 6310e2b8eb83..8cc83a2e92a6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserChangedHandlerCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserChangedHandlerCEImpl.java @@ -32,9 +32,7 @@ public void handle(UserChangedEvent event) { final User user = event.getUser(); log.debug("Handling user document changes {}", user); - updateNameInUserRoles(user) - .subscribeOn(Schedulers.boundedElastic()) - .subscribe(); + updateNameInUserRoles(user).subscribeOn(Schedulers.boundedElastic()).subscribe(); } private Mono<Void> updateNameInUserRoles(User user) { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserSignupCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserSignupCE.java index 5c1638f16f4f..d0170111553e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserSignupCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserSignupCE.java @@ -30,5 +30,4 @@ public interface UserSignupCE { Mono<User> signupAndLoginSuper(UserSignupRequestDTO userFromRequest, ServerWebExchange exchange); Mono<Void> signupAndLoginSuperFromFormData(ServerWebExchange exchange); - } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserSignupCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserSignupCEImpl.java index fc3ee9a9ed21..d9196668ee2d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserSignupCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserSignupCEImpl.java @@ -81,16 +81,17 @@ public class UserSignupCEImpl implements UserSignupCE { private static final WebFilterChain EMPTY_WEB_FILTER_CHAIN = serverWebExchange -> Mono.empty(); - public UserSignupCEImpl(UserService userService, - UserDataService userDataService, - CaptchaService captchaService, - AuthenticationSuccessHandler authenticationSuccessHandler, - ConfigService configService, - AnalyticsService analyticsService, - EnvManager envManager, - CommonConfig commonConfig, - UserUtils userUtils, - NetworkUtils networkUtils) { + public UserSignupCEImpl( + UserService userService, + UserDataService userDataService, + CaptchaService captchaService, + AuthenticationSuccessHandler authenticationSuccessHandler, + ConfigService configService, + AnalyticsService analyticsService, + EnvManager envManager, + CommonConfig commonConfig, + UserUtils userUtils, + NetworkUtils networkUtils) { this.userService = userService; this.userDataService = userDataService; @@ -122,24 +123,18 @@ public Mono<User> signupAndLogin(User user, ServerWebExchange exchange) { if (!validateLoginPassword(user.getPassword())) { return Mono.error(new AppsmithException( - AppsmithError.INVALID_PASSWORD_LENGTH, LOGIN_PASSWORD_MIN_LENGTH, LOGIN_PASSWORD_MAX_LENGTH) - ); + AppsmithError.INVALID_PASSWORD_LENGTH, LOGIN_PASSWORD_MIN_LENGTH, LOGIN_PASSWORD_MAX_LENGTH)); } - Mono<UserSignupDTO> createUserAndSendEmailMono = userService.createUserAndSendEmail(user, exchange.getRequest().getHeaders().getOrigin()) + Mono<UserSignupDTO> createUserAndSendEmailMono = userService + .createUserAndSendEmail(user, exchange.getRequest().getHeaders().getOrigin()) .elapsed() .map(pair -> { log.debug("UserSignupCEImpl::Time taken for create user and send email: {} ms", pair.getT1()); return pair.getT2(); }); - - return Mono - .zip( - createUserAndSendEmailMono, - exchange.getSession(), - ReactiveSecurityContextHolder.getContext() - ) + return Mono.zip(createUserAndSendEmailMono, exchange.getSession(), ReactiveSecurityContextHolder.getContext()) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR))) .flatMap(tuple -> { final User savedUser = tuple.getT1().getUser(); @@ -147,35 +142,37 @@ public Mono<User> signupAndLogin(User user, ServerWebExchange exchange) { final WebSession session = tuple.getT2(); final SecurityContext securityContext = tuple.getT3(); - Authentication authentication = new UsernamePasswordAuthenticationToken( - savedUser, null, savedUser.getAuthorities() - ); + Authentication authentication = + new UsernamePasswordAuthenticationToken(savedUser, null, savedUser.getAuthorities()); securityContext.setAuthentication(authentication); session.getAttributes().put(DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME, securityContext); final WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, EMPTY_WEB_FILTER_CHAIN); - MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); + MultiValueMap<String, String> queryParams = + exchange.getRequest().getQueryParams(); String redirectQueryParamValue = queryParams.getFirst(REDIRECT_URL_QUERY_PARAM); /* TODO - - Add testcases for SignUp service - - Verify that Workspace is created for the user - - Verify that first application is created inside created workspace when “redirectUrl” query parameter is not present in the request - - Verify that first application is not created when “redirectUrl” query parameter is present in the request - */ - boolean createApplication = StringUtils.isEmpty(redirectQueryParamValue) && !StringUtils.isEmpty(workspaceId); + - Add testcases for SignUp service + - Verify that Workspace is created for the user + - Verify that first application is created inside created workspace when “redirectUrl” query parameter is not present in the request + - Verify that first application is not created when “redirectUrl” query parameter is present in the request + */ + boolean createApplication = + StringUtils.isEmpty(redirectQueryParamValue) && !StringUtils.isEmpty(workspaceId); // need to create default application Mono<Integer> authenticationSuccessMono = authenticationSuccessHandler - .onAuthenticationSuccess(webFilterExchange, authentication, createApplication, true, workspaceId) + .onAuthenticationSuccess( + webFilterExchange, authentication, createApplication, true, workspaceId) .thenReturn(1) .elapsed() .flatMap(pair -> { - log.debug("UserSignupCEImpl::Time taken for authentication success: {} ms", pair.getT1()); + log.debug( + "UserSignupCEImpl::Time taken for authentication success: {} ms", pair.getT1()); return Mono.just(pair.getT2()); }); - return authenticationSuccessMono - .thenReturn(savedUser); + return authenticationSuccessMono.thenReturn(savedUser); }); } @@ -188,7 +185,9 @@ public Mono<User> signupAndLogin(User user, ServerWebExchange exchange) { public Mono<Void> signupAndLoginFromFormData(ServerWebExchange exchange) { String recaptchaToken = exchange.getRequest().getQueryParams().getFirst("recaptchaToken"); - return captchaService.verify(recaptchaToken).flatMap(verified -> { + return captchaService + .verify(recaptchaToken) + .flatMap(verified -> { if (!Boolean.TRUE.equals(verified)) { return Mono.error(new AppsmithException(AppsmithError.GOOGLE_RECAPTCHA_FAILED)); } @@ -219,7 +218,8 @@ public Mono<Void> signupAndLoginFromFormData(ServerWebExchange exchange) { if (referer == null) { referer = DEFAULT_ORIGIN_HEADER; } - final URIBuilder redirectUriBuilder = new URIBuilder(URI.create(referer)).setParameter("error", error.getMessage()); + final URIBuilder redirectUriBuilder = + new URIBuilder(URI.create(referer)).setParameter("error", error.getMessage()); URI redirectUri; try { redirectUri = redirectUriBuilder.build(); @@ -232,7 +232,8 @@ public Mono<Void> signupAndLoginFromFormData(ServerWebExchange exchange) { } public Mono<User> signupAndLoginSuper(UserSignupRequestDTO userFromRequest, ServerWebExchange exchange) { - Mono<User> userMono = userService.isUsersEmpty() + Mono<User> userMono = userService + .isUsersEmpty() .flatMap(isEmpty -> { if (!Boolean.TRUE.equals(isEmpty)) { return Mono.error(new AppsmithException(AppsmithError.UNAUTHORIZED_ACCESS)); @@ -247,18 +248,18 @@ public Mono<User> signupAndLoginSuper(UserSignupRequestDTO userFromRequest, Serv user.setPassword(userFromRequest.getPassword()); Mono<User> userMono1 = signupAndLogin(user, exchange); - return userMono1 - .elapsed() - .map(pair -> { - log.debug("UserSignupCEImpl::Time taken to complete signupAndLogin: {} ms", pair.getT1()); - return pair.getT2(); - }); + return userMono1.elapsed().map(pair -> { + log.debug("UserSignupCEImpl::Time taken to complete signupAndLogin: {} ms", pair.getT1()); + return pair.getT2(); + }); }) .flatMap(user -> { - Mono<Boolean> makeSuperUserMono = userUtils.makeSuperUser(List.of(user)) + Mono<Boolean> makeSuperUserMono = userUtils + .makeSuperUser(List.of(user)) .elapsed() .map(pair -> { - log.debug("UserSignupCEImpl::Time taken to complete makeSuperUser: {} ms", pair.getT1()); + log.debug( + "UserSignupCEImpl::Time taken to complete makeSuperUser: {} ms", pair.getT1()); return pair.getT2(); }); return makeSuperUserMono.thenReturn(user); @@ -268,19 +269,22 @@ public Mono<User> signupAndLoginSuper(UserSignupRequestDTO userFromRequest, Serv userData.setRole(userFromRequest.getRole()); userData.setUseCase(userFromRequest.getUseCase()); - Mono<UserData> userDataMono = userDataService.updateForUser(user, userData) + Mono<UserData> userDataMono = userDataService + .updateForUser(user, userData) .elapsed() .map(pair -> { - log.debug("UserSignupCEImpl::Time taken to update user data for user: {} ms", pair.getT1()); + log.debug( + "UserSignupCEImpl::Time taken to update user data for user: {} ms", + pair.getT1()); return pair.getT2(); }); - Mono<EnvChangesResponseDTO> applyEnvManagerChangesMono = envManager.applyChanges(Map.of( + Mono<EnvChangesResponseDTO> applyEnvManagerChangesMono = envManager + .applyChanges(Map.of( APPSMITH_DISABLE_TELEMETRY.name(), String.valueOf(!userFromRequest.isAllowCollectingAnonymousData()), APPSMITH_ADMIN_EMAILS.name(), - user.getEmail() - )) + user.getEmail())) .elapsed() .map(pair -> { log.debug("UserSignupCEImpl::Time taken to apply env changes: {} ms", pair.getT1()); @@ -297,28 +301,31 @@ public Mono<User> signupAndLoginSuper(UserSignupRequestDTO userFromRequest, Serv */ Mono<User> sendCreateSuperUserEvent = sendCreateSuperUserEventOnSeparateThreadMono(user); - // In the past, we have seen "Installation Setup Complete" not getting triggered if subscribed within - // secondary functions, hence subscribing this in a separate thread to avoid getting cancelled because + // In the past, we have seen "Installation Setup Complete" not getting triggered if subscribed + // within + // secondary functions, hence subscribing this in a separate thread to avoid getting cancelled + // because // of any other secondary function mono throwing an exception sendInstallationSetupAnalytics(userFromRequest, user, userData) .subscribeOn(commonConfig.scheduler()) .subscribe(); - Mono<Long> allSecondaryFunctions = Mono.when(userDataMono, applyEnvManagerChangesMono, sendCreateSuperUserEvent) + Mono<Long> allSecondaryFunctions = Mono.when( + userDataMono, applyEnvManagerChangesMono, sendCreateSuperUserEvent) .thenReturn(1L) .elapsed() .map(pair -> { - log.debug("UserSignupCEImpl::Time taken to complete all secondary functions: {} ms", pair.getT1()); + log.debug( + "UserSignupCEImpl::Time taken to complete all secondary functions: {} ms", + pair.getT1()); return pair.getT2(); }); return allSecondaryFunctions.thenReturn(user); }); - return userMono - .elapsed() - .map(pair -> { - log.debug("UserSignupCEImpl::Time taken for the user mono to complete: {} ms", pair.getT1()); - return pair.getT2(); - }); + return userMono.elapsed().map(pair -> { + log.debug("UserSignupCEImpl::Time taken for the user mono to complete: {} ms", pair.getT1()); + return pair.getT2(); + }); } public Mono<Void> signupAndLoginSuperFromFormData(ServerWebExchange exchange) { @@ -340,7 +347,8 @@ public Mono<Void> signupAndLoginSuperFromFormData(ServerWebExchange exchange) { user.setUseCase(formData.getFirst("useCase")); } if (formData.containsKey("allowCollectingAnonymousData")) { - user.setAllowCollectingAnonymousData("true".equals(formData.getFirst("allowCollectingAnonymousData"))); + user.setAllowCollectingAnonymousData( + "true".equals(formData.getFirst("allowCollectingAnonymousData"))); } if (formData.containsKey("signupForNewsletter")) { user.setSignupForNewsletter("true".equals(formData.getFirst("signupForNewsletter"))); @@ -354,7 +362,8 @@ public Mono<Void> signupAndLoginSuperFromFormData(ServerWebExchange exchange) { if (referer == null) { referer = DEFAULT_ORIGIN_HEADER; } - final URIBuilder redirectUriBuilder = new URIBuilder(URI.create(referer)).setParameter("error", error.getMessage()); + final URIBuilder redirectUriBuilder = + new URIBuilder(URI.create(referer)).setParameter("error", error.getMessage()); URI redirectUri; try { redirectUri = redirectUriBuilder.build(); @@ -366,18 +375,17 @@ public Mono<Void> signupAndLoginSuperFromFormData(ServerWebExchange exchange) { }); } - private Mono<Void> sendInstallationSetupAnalytics(UserSignupRequestDTO userFromRequest, - User user, - UserData userData) { + private Mono<Void> sendInstallationSetupAnalytics( + UserSignupRequestDTO userFromRequest, User user, UserData userData) { - Mono<String> getInstanceIdMono = configService.getInstanceId() - .elapsed() - .map(pair -> { - log.debug("UserSignupCEImpl::Time taken to get instance ID: {} ms", pair.getT1()); - return pair.getT2(); - }); + Mono<String> getInstanceIdMono = configService.getInstanceId().elapsed().map(pair -> { + log.debug("UserSignupCEImpl::Time taken to get instance ID: {} ms", pair.getT1()); + return pair.getT2(); + }); - Mono<String> getExternalAddressMono = networkUtils.getExternalAddress().defaultIfEmpty("unknown") + Mono<String> getExternalAddressMono = networkUtils + .getExternalAddress() + .defaultIfEmpty("unknown") .elapsed() .map(pair -> { log.debug("UserSignupCEImpl::Time taken to get external address: {} ms", pair.getT1()); @@ -414,28 +422,34 @@ private Mono<Void> sendInstallationSetupAnalytics(UserSignupRequestDTO userFromR newsletterSignedUpUserName, ip); - return analyticsService.sendEvent( + return analyticsService + .sendEvent( AnalyticsEvents.INSTALLATION_SETUP_COMPLETE.getEventName(), instanceId, analyticsProps, - false - ).thenReturn(1L) + false) + .thenReturn(1L) .elapsed() .map(pair -> { - log.debug("UserSignupCEImpl::Time taken to send installation setup complete analytics event: {} ms", pair.getT1()); + log.debug( + "UserSignupCEImpl::Time taken to send installation setup complete analytics event: {} ms", + pair.getT1()); return pair.getT2(); }); }) .elapsed() .map(pair -> { - log.debug("UserSignupCEImpl::Time taken to send installation setup analytics event: {} ms", pair.getT1()); + log.debug( + "UserSignupCEImpl::Time taken to send installation setup analytics event: {} ms", + pair.getT1()); return pair.getT2(); }) .then(); } private Mono<User> sendCreateSuperUserEventOnSeparateThreadMono(User user) { - analyticsService.sendObjectEvent(AnalyticsEvents.CREATE_SUPERUSER, user, null) + analyticsService + .sendObjectEvent(AnalyticsEvents.CREATE_SUPERUSER, user, null) .elapsed() .map(pair -> { log.debug("UserSignupCEImpl::Time taken to send create super user event: {} ms", pair.getT1()); @@ -446,4 +460,4 @@ private Mono<User> sendCreateSuperUserEventOnSeparateThreadMono(User user) { return Mono.just(user); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/ServerApplicationTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/ServerApplicationTests.java index 882b4a1c48dc..cf8eeaf28882 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/ServerApplicationTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/ServerApplicationTests.java @@ -3,7 +3,6 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; - @SpringBootTest public class ServerApplicationTests { @@ -11,5 +10,4 @@ public class ServerApplicationTests { public void contextLoads() { assert (true); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/acl/AclPermissionTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/acl/AclPermissionTest.java index b72d08b68af8..56a6db44c257 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/acl/AclPermissionTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/acl/AclPermissionTest.java @@ -18,17 +18,24 @@ class AclPermissionTest { @Test void testIsPermissionForEntity() { - assertThat(AclPermission.isPermissionForEntity(AclPermission.READ_APPLICATIONS, Application.class)).isTrue(); - assertThat(AclPermission.isPermissionForEntity(AclPermission.READ_APPLICATIONS, Theme.class)).isFalse(); + assertThat(AclPermission.isPermissionForEntity(AclPermission.READ_APPLICATIONS, Application.class)) + .isTrue(); + assertThat(AclPermission.isPermissionForEntity(AclPermission.READ_APPLICATIONS, Theme.class)) + .isFalse(); - - // Assert that Action related Permission should return True, when checked against Action, NewAction and Action Collection. - assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, Action.class)).isTrue(); - assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, NewAction.class)).isTrue(); - assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, ActionCollection.class)).isTrue(); + // Assert that Action related Permission should return True, when checked against Action, NewAction and Action + // Collection. + assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, Action.class)) + .isTrue(); + assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, NewAction.class)) + .isTrue(); + assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, ActionCollection.class)) + .isTrue(); // Assert that Page related Permission should return True, when checked against Page and NewPage. - assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_PAGES, Page.class)).isTrue(); - assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_PAGES, NewPage.class)).isTrue(); + assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_PAGES, Page.class)) + .isTrue(); + assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_PAGES, NewPage.class)) + .isTrue(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/authentication/handlers/CustomFormLoginServiceImplUnitTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/authentication/handlers/CustomFormLoginServiceImplUnitTest.java index d06af17ba4b4..58c887973c8c 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/authentication/handlers/CustomFormLoginServiceImplUnitTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/authentication/handlers/CustomFormLoginServiceImplUnitTest.java @@ -55,4 +55,4 @@ public void findByUsername_WhenUserNameExistsWithOtherCase_ReturnsUser() { }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/MDCConfigTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/MDCConfigTest.java index bfcfef2d53f5..397cde9c7d00 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/MDCConfigTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/MDCConfigTest.java @@ -47,8 +47,7 @@ public void testReactiveContextSwitch_forSingleMono_retainsThreadAcrossSignals() .subscribe(new BaseSubscriber<>() { @Override public Context currentContext() { - return Context.empty() - .put(LogHelper.CONTEXT_MAP, initialMap); + return Context.empty().put(LogHelper.CONTEXT_MAP, initialMap); } }); } @@ -58,10 +57,10 @@ public void testReactiveContextSwitch_forScheduledMono_switchesThreadAcrossSigna Mono.fromSupplier(() -> "testString") .flatMap((firstValue) -> { final String firstThread = MDC.get(MDCFilter.THREAD); - log.debug("First thread -> {} ; Context thread -> {}", + log.debug( + "First thread -> {} ; Context thread -> {}", Thread.currentThread().getName(), - firstThread - ); + firstThread); Assertions.assertFalse(MDC.getCopyOfContextMap().isEmpty()); Assertions.assertEquals(firstThread, "main"); Assertions.assertEquals(firstThread, Thread.currentThread().getName()); @@ -69,27 +68,26 @@ public void testReactiveContextSwitch_forScheduledMono_switchesThreadAcrossSigna return Mono.fromSupplier(() -> "secondString") .doOnEach((secondValue) -> { - final String secondThread = MDC.get(MDCFilter.THREAD); - log.debug("Second thread -> {} ; Context thread -> {} ; on signal {}", + log.debug( + "Second thread -> {} ; Context thread -> {} ; on signal {}", Thread.currentThread().getName(), secondThread, - secondValue.getType() - ); + secondValue.getType()); Assertions.assertFalse(MDC.getCopyOfContextMap().isEmpty()); Assertions.assertNotEquals(secondThread, "main"); - Assertions.assertEquals(secondThread, Thread.currentThread().getName()); + Assertions.assertEquals( + secondThread, Thread.currentThread().getName()); Assertions.assertEquals(MDC.get("constantKey"), "constantValue"); }) .subscribeOn(Schedulers.boundedElastic()); - }).subscribe(new BaseSubscriber<>() { + }) + .subscribe(new BaseSubscriber<>() { @Override public Context currentContext() { - return Context.empty() - .put(LogHelper.CONTEXT_MAP, initialMap); + return Context.empty().put(LogHelper.CONTEXT_MAP, initialMap); } }); - } @Test @@ -97,10 +95,10 @@ public void testReactiveContextSwitch_forScheduledErrorSignal_switchesThreadAcro Mono.fromSupplier(() -> "testString") .flatMap((firstValue) -> { final String firstThread = MDC.get(MDCFilter.THREAD); - log.debug("First thread -> {} ; Context thread -> {}", + log.debug( + "First thread -> {} ; Context thread -> {}", Thread.currentThread().getName(), - firstThread - ); + firstThread); Assertions.assertFalse(MDC.getCopyOfContextMap().isEmpty()); Assertions.assertEquals(firstThread, "main"); Assertions.assertEquals(firstThread, Thread.currentThread().getName()); @@ -108,33 +106,32 @@ public void testReactiveContextSwitch_forScheduledErrorSignal_switchesThreadAcro return Mono.error(() -> new AppsmithException(AppsmithError.INTERNAL_SERVER_ERROR)) .doOnEach((errorValue) -> { - final String secondThread = MDC.get(MDCFilter.THREAD); - log.debug("Error thread -> {} ; Context thread -> {} ; on signal {}", + log.debug( + "Error thread -> {} ; Context thread -> {} ; on signal {}", Thread.currentThread().getName(), secondThread, - errorValue.getType() - ); + errorValue.getType()); Assertions.assertFalse(MDC.getCopyOfContextMap().isEmpty()); Assertions.assertNotEquals(secondThread, "main"); - Assertions.assertEquals(secondThread, Thread.currentThread().getName()); + Assertions.assertEquals( + secondThread, Thread.currentThread().getName()); Assertions.assertEquals(MDC.get("constantKey"), "constantValue"); Assertions.assertEquals(errorValue.getType(), SignalType.ON_ERROR); - final Map<String, String> contextMap = ((BaseException) errorValue.get()).getContextMap(); + final Map<String, String> contextMap = + ((BaseException) errorValue.get()).getContextMap(); Assertions.assertEquals(contextMap.get("constantKey"), "constantValue"); Assertions.assertEquals(contextMap.get(MDCFilter.THREAD), secondThread); }) .subscribeOn(Schedulers.boundedElastic()); - }).subscribe(new BaseSubscriber<>() { + }) + .subscribe(new BaseSubscriber<>() { @Override public Context currentContext() { - return Context.empty() - .put(LogHelper.CONTEXT_MAP, initialMap); + return Context.empty().put(LogHelper.CONTEXT_MAP, initialMap); } }); - } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/RedisTestContainerConfig.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/RedisTestContainerConfig.java index e68485996382..667b9f549b26 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/RedisTestContainerConfig.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/RedisTestContainerConfig.java @@ -23,15 +23,15 @@ public class RedisTestContainerConfig { @Container - public static GenericContainer redisContainer = new GenericContainer(DockerImageName.parse("redis:6.2.6-alpine")) - .withExposedPorts(6379); + public static GenericContainer redisContainer = + new GenericContainer(DockerImageName.parse("redis:6.2.6-alpine")).withExposedPorts(6379); @Bean @Primary public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() { redisContainer.start(); - RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration(redisContainer.getHost(), - redisContainer.getMappedPort(6379)); + RedisStandaloneConfiguration redisConf = + new RedisStandaloneConfiguration(redisContainer.getHost(), redisContainer.getMappedPort(6379)); return new LettuceConnectionFactory(redisConf); } @@ -40,9 +40,11 @@ public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() { ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) { RedisSerializer<String> keySerializer = new StringRedisSerializer(); RedisSerializer<Object> defaultSerializer = new GenericJackson2JsonRedisSerializer(); - RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext - .<String, Object>newSerializationContext(defaultSerializer).key(keySerializer).hashKey(keySerializer) - .build(); + RedisSerializationContext<String, Object> serializationContext = + RedisSerializationContext.<String, Object>newSerializationContext(defaultSerializer) + .key(keySerializer) + .hashKey(keySerializer) + .build(); return new ReactiveRedisTemplate<>(factory, serializationContext); } @@ -52,7 +54,8 @@ ReactiveRedisOperations<String, String> reactiveRedisOperations(ReactiveRedisCon Jackson2JsonRedisSerializer<String> serializer = new Jackson2JsonRedisSerializer<>(String.class); RedisSerializationContext.RedisSerializationContextBuilder<String, String> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer()); - RedisSerializationContext<String, String> context = builder.value(serializer).build(); + RedisSerializationContext<String, String> context = + builder.value(serializer).build(); return new ReactiveRedisTemplate<>(factory, context); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/SeedMongoData.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/SeedMongoData.java index 4cccc409e261..396b432be568 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/SeedMongoData.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/SeedMongoData.java @@ -16,7 +16,6 @@ import com.appsmith.server.domains.WorkspacePlugin; import com.appsmith.server.dtos.Permission; import com.appsmith.server.dtos.WorkspacePluginStatus; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.PageRepository; import com.appsmith.server.repositories.PermissionGroupRepository; @@ -24,6 +23,7 @@ import com.appsmith.server.repositories.TenantRepository; import com.appsmith.server.repositories.UserRepository; import com.appsmith.server.repositories.WorkspaceRepository; +import com.appsmith.server.solutions.PolicySolution; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; @@ -60,15 +60,16 @@ public class SeedMongoData { @Bean - ApplicationRunner init(UserRepository userRepository, - WorkspaceRepository workspaceRepository, - ApplicationRepository applicationRepository, - PageRepository pageRepository, - PluginRepository pluginRepository, - ReactiveMongoTemplate mongoTemplate, - TenantRepository tenantRepository, - PermissionGroupRepository permissionGroupRepository, - PolicySolution policySolution) { + ApplicationRunner init( + UserRepository userRepository, + WorkspaceRepository workspaceRepository, + ApplicationRepository applicationRepository, + PageRepository pageRepository, + PluginRepository pluginRepository, + ReactiveMongoTemplate mongoTemplate, + TenantRepository tenantRepository, + PermissionGroupRepository permissionGroupRepository, + PolicySolution policySolution) { log.info("Seeding the data"); final String API_USER_EMAIL = "api_user"; @@ -76,92 +77,145 @@ ApplicationRunner init(UserRepository userRepository, final String ADMIN_USER_EMAIL = "[email protected]"; final String DEV_USER_EMAIL = "[email protected]"; - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy exportWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_EXPORT_APPLICATIONS.getValue()) + Policy exportWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_EXPORT_APPLICATIONS.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy userManageWorkspacePolicy = Policy.builder().permission(USER_MANAGE_WORKSPACES.getValue()) + Policy userManageWorkspacePolicy = Policy.builder() + .permission(USER_MANAGE_WORKSPACES.getValue()) .users(Set.of(API_USER_EMAIL, TEST_USER_EMAIL, ADMIN_USER_EMAIL, DEV_USER_EMAIL)) .build(); - Policy inviteUserWorkspacePolicy = Policy.builder().permission(WORKSPACE_INVITE_USERS.getValue()) + Policy inviteUserWorkspacePolicy = Policy.builder() + .permission(WORKSPACE_INVITE_USERS.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy readWorkspacePolicy = Policy.builder().permission(READ_WORKSPACES.getValue()) + Policy readWorkspacePolicy = Policy.builder() + .permission(READ_WORKSPACES.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy readApiUserPolicy = Policy.builder().permission(READ_USERS.getValue()) + Policy readApiUserPolicy = Policy.builder() + .permission(READ_USERS.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy manageApiUserPolicy = Policy.builder().permission(MANAGE_USERS.getValue()) + Policy manageApiUserPolicy = Policy.builder() + .permission(MANAGE_USERS.getValue()) .users(Set.of(API_USER_EMAIL)) .build(); - Policy readTestUserPolicy = Policy.builder().permission(READ_USERS.getValue()) + Policy readTestUserPolicy = Policy.builder() + .permission(READ_USERS.getValue()) .users(Set.of(TEST_USER_EMAIL)) .build(); - Policy readAdminUserPolicy = Policy.builder().permission(READ_USERS.getValue()) + Policy readAdminUserPolicy = Policy.builder() + .permission(READ_USERS.getValue()) .users(Set.of(ADMIN_USER_EMAIL)) .build(); - Policy readDevUserPolicy = Policy.builder().permission(READ_USERS.getValue()) + Policy readDevUserPolicy = Policy.builder() + .permission(READ_USERS.getValue()) .users(Set.of(DEV_USER_EMAIL)) .build(); Object[][] userData = { - {"user test", TEST_USER_EMAIL, UserState.ACTIVATED, new HashSet<>(Arrays.asList(readTestUserPolicy, userManageWorkspacePolicy))}, - {"api_user", API_USER_EMAIL, UserState.ACTIVATED, new HashSet<>(Arrays.asList(userManageWorkspacePolicy, readApiUserPolicy, manageApiUserPolicy))}, - {"admin test", ADMIN_USER_EMAIL, UserState.ACTIVATED, new HashSet<>(Arrays.asList(readAdminUserPolicy, userManageWorkspacePolicy))}, - {"developer test", DEV_USER_EMAIL, UserState.ACTIVATED, new HashSet<>(Arrays.asList(readDevUserPolicy, userManageWorkspacePolicy))}, + { + "user test", + TEST_USER_EMAIL, + UserState.ACTIVATED, + new HashSet<>(Arrays.asList(readTestUserPolicy, userManageWorkspacePolicy)) + }, + { + "api_user", + API_USER_EMAIL, + UserState.ACTIVATED, + new HashSet<>(Arrays.asList(userManageWorkspacePolicy, readApiUserPolicy, manageApiUserPolicy)) + }, + { + "admin test", + ADMIN_USER_EMAIL, + UserState.ACTIVATED, + new HashSet<>(Arrays.asList(readAdminUserPolicy, userManageWorkspacePolicy)) + }, + { + "developer test", + DEV_USER_EMAIL, + UserState.ACTIVATED, + new HashSet<>(Arrays.asList(readDevUserPolicy, userManageWorkspacePolicy)) + }, }; Object[][] workspaceData = { - {"Spring Test Workspace", "appsmith-spring-test.com", "appsmith.com", "spring-test-workspace", - Set.of(manageWorkspaceAppPolicy, manageWorkspacePolicy, readWorkspacePolicy, inviteUserWorkspacePolicy, exportWorkspaceAppPolicy)}, - {"Another Test Workspace", "appsmith-another-test.com", "appsmith.com", "another-test-workspace", - Set.of(manageWorkspaceAppPolicy, manageWorkspacePolicy, readWorkspacePolicy, inviteUserWorkspacePolicy, exportWorkspaceAppPolicy)} + { + "Spring Test Workspace", + "appsmith-spring-test.com", + "appsmith.com", + "spring-test-workspace", + Set.of( + manageWorkspaceAppPolicy, + manageWorkspacePolicy, + readWorkspacePolicy, + inviteUserWorkspacePolicy, + exportWorkspaceAppPolicy) + }, + { + "Another Test Workspace", + "appsmith-another-test.com", + "appsmith.com", + "another-test-workspace", + Set.of( + manageWorkspaceAppPolicy, + manageWorkspacePolicy, + readWorkspacePolicy, + inviteUserWorkspacePolicy, + exportWorkspaceAppPolicy) + } }; Object[][] appData = { - {"LayoutServiceTest TestApplications", Set.of(manageAppPolicy, readAppPolicy)}, - {"TestApplications", Set.of(manageAppPolicy, readAppPolicy)}, - {"Another TestApplications", Set.of(manageAppPolicy, readAppPolicy)} - }; - Object[][] pageData = { - {"validPageName", Set.of(managePagePolicy, readPagePolicy)} + {"LayoutServiceTest TestApplications", Set.of(manageAppPolicy, readAppPolicy)}, + {"TestApplications", Set.of(manageAppPolicy, readAppPolicy)}, + {"Another TestApplications", Set.of(manageAppPolicy, readAppPolicy)} }; + Object[][] pageData = {{"validPageName", Set.of(managePagePolicy, readPagePolicy)}}; Object[][] pluginData = { - {"Installed Plugin Name", PluginType.API, "installed-plugin"}, - {"Installed DB Plugin Name", PluginType.DB, "installed-db-plugin"}, - {"Installed JS Plugin Name", PluginType.JS, "installed-js-plugin"}, - {"Not Installed Plugin Name", PluginType.API, "not-installed-plugin"} + {"Installed Plugin Name", PluginType.API, "installed-plugin"}, + {"Installed DB Plugin Name", PluginType.DB, "installed-db-plugin"}, + {"Installed JS Plugin Name", PluginType.JS, "installed-js-plugin"}, + {"Not Installed Plugin Name", PluginType.API, "not-installed-plugin"} }; // Seed the plugin data into the DB @@ -174,7 +228,8 @@ ApplicationRunner init(UserRepository userRepository, plugin.setPackageName((String) array[2]); log.debug("Create plugin: {}", plugin); return plugin; - }).flatMap(pluginRepository::save) + }) + .flatMap(pluginRepository::save) .cache(); Tenant defaultTenant = new Tenant(); @@ -182,7 +237,8 @@ ApplicationRunner init(UserRepository userRepository, defaultTenant.setSlug("default"); defaultTenant.setPricingPlan(PricingPlan.FREE); - Mono<String> defaultTenantId = tenantRepository.findBySlug("default") + Mono<String> defaultTenantId = tenantRepository + .findBySlug("default") .switchIfEmpty(tenantRepository.save(defaultTenant)) .map(Tenant::getId) .cache(); @@ -202,34 +258,35 @@ ApplicationRunner init(UserRepository userRepository, permissionGroupUser.setPermissions(Set.of(new Permission(user.getId(), MANAGE_USERS))); permissionGroupUser.setName(user.getId() + "User Name"); permissionGroupUser.setAssignedToUserIds(Set.of(user.getId())); - return permissionGroupRepository.save(permissionGroupUser) - .flatMap(savedPermissionGroup -> { - Map<String, Policy> crudUserPolicies = policySolution.generatePolicyFromPermissionGroupForObject(savedPermissionGroup, - user.getId()); + return permissionGroupRepository.save(permissionGroupUser).flatMap(savedPermissionGroup -> { + Map<String, Policy> crudUserPolicies = + policySolution.generatePolicyFromPermissionGroupForObject( + savedPermissionGroup, user.getId()); - User updatedWithPolicies = policySolution.addPoliciesToExistingObject(crudUserPolicies, user); + User updatedWithPolicies = policySolution.addPoliciesToExistingObject(crudUserPolicies, user); - return userRepository.save(updatedWithPolicies); - }); + return userRepository.save(updatedWithPolicies); + }); }) .collectList() .zipWith(defaultTenantId) .flatMapMany(tuple -> { List<User> users = tuple.getT1(); String tenantId = tuple.getT2(); - return Flux.fromIterable(users) - .map(user -> { - user.setTenantId(tenantId); - log.debug("Creating user: {}", user); - return user; - }); + return Flux.fromIterable(users).map(user -> { + user.setTenantId(tenantId); + log.debug("Creating user: {}", user); + return user; + }); }) .flatMap(userRepository::save) .cache(); // Seed the workspace data into the DB Flux<Workspace> workspaceFlux = mongoTemplate - .find(new Query().addCriteria(where("name").in(pluginData[0][0], pluginData[1][0], pluginData[2][0])), Plugin.class) + .find( + new Query().addCriteria(where("name").in(pluginData[0][0], pluginData[1][0], pluginData[2][0])), + Plugin.class) .map(plugin -> new WorkspacePlugin(plugin.getId(), WorkspacePluginStatus.FREE)) .collect(Collectors.toSet()) .cache() @@ -261,39 +318,38 @@ ApplicationRunner init(UserRepository userRepository, }) .flatMap(workspaceRepository::save); - Flux<Workspace> workspaceFlux1 = workspaceRepository.deleteAll() + Flux<Workspace> workspaceFlux1 = workspaceRepository + .deleteAll() .thenMany(pluginFlux) .thenMany(userFlux) .thenMany(workspaceFlux); - Flux<User> addUserWorkspaceFlux = workspaceFlux1 - .flatMap(workspace -> userFlux - .flatMap(user -> { - log.debug("**** In the addUserWorkspaceFlux"); - log.debug("User: {}", user); - log.debug("Workspace: {}", workspace); - user.setCurrentWorkspaceId(workspace.getId()); - Set<String> workspaceIds = user.getWorkspaceIds(); - if (workspaceIds == null) { - workspaceIds = new HashSet<>(); - } - workspaceIds.add(workspace.getId()); - user.setWorkspaceIds(workspaceIds); - log.debug("AddUserWorkspace User: {}, Workspace: {}", user, workspace); - return userRepository.save(user) - .map(u -> { - log.debug("Saved the workspace to user. User: {}", u); - return u; - }); - }) - ); + Flux<User> addUserWorkspaceFlux = workspaceFlux1.flatMap(workspace -> userFlux.flatMap(user -> { + log.debug("**** In the addUserWorkspaceFlux"); + log.debug("User: {}", user); + log.debug("Workspace: {}", workspace); + user.setCurrentWorkspaceId(workspace.getId()); + Set<String> workspaceIds = user.getWorkspaceIds(); + if (workspaceIds == null) { + workspaceIds = new HashSet<>(); + } + workspaceIds.add(workspace.getId()); + user.setWorkspaceIds(workspaceIds); + log.debug("AddUserWorkspace User: {}, Workspace: {}", user, workspace); + return userRepository.save(user).map(u -> { + log.debug("Saved the workspace to user. User: {}", u); + return u; + }); + })); Query workspaceNameQuery = new Query(where("slug").is(workspaceData[0][3])); - Mono<Workspace> workspaceByNameMono = mongoTemplate.findOne(workspaceNameQuery, Workspace.class) + Mono<Workspace> workspaceByNameMono = mongoTemplate + .findOne(workspaceNameQuery, Workspace.class) .switchIfEmpty(Mono.error(new Exception("Can't find workspace"))); Query appNameQuery = new Query(where("name").is(appData[0][0])); - Mono<Application> appByNameMono = mongoTemplate.findOne(appNameQuery, Application.class) + Mono<Application> appByNameMono = mongoTemplate + .findOne(appNameQuery, Application.class) .switchIfEmpty(Mono.error(new Exception("Can't find app"))); return args -> { workspaceFlux1 @@ -302,7 +358,8 @@ ApplicationRunner init(UserRepository userRepository, .then(workspaceByNameMono) .map(workspace -> workspace.getId()) // Seed the user data into the DB - .flatMapMany(workspaceId -> + .flatMapMany( + workspaceId -> // Seed the application data into the DB Flux.just(appData) .map(array -> { @@ -314,7 +371,8 @@ ApplicationRunner init(UserRepository userRepository, }) .flatMap(applicationRepository::save) // Query the seed data to get the applicationId (required for page creation) - ).then(appByNameMono) + ) + .then(appByNameMono) .map(application -> application.getId()) .flatMapMany(appId -> Flux.just(pageData) // Seed the page data into the DB @@ -325,10 +383,8 @@ ApplicationRunner init(UserRepository userRepository, page.setPolicies((Set<Policy>) array[1]); return page; }) - .flatMap(pageRepository::save) - ) + .flatMap(pageRepository::save)) .blockLast(); }; - } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/WithMockAppsmithSecurityContextFactory.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/WithMockAppsmithSecurityContextFactory.java index c5d397c3767c..09a5625c4a15 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/WithMockAppsmithSecurityContextFactory.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/configurations/WithMockAppsmithSecurityContextFactory.java @@ -16,7 +16,8 @@ public SecurityContext createSecurityContext(WithMockAppsmithUser mockAppsmithUs principal.setId(mockAppsmithUser.username()); principal.setEmail(mockAppsmithUser.username()); principal.setName(mockAppsmithUser.name()); - Authentication auth = new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities()); + Authentication auth = + new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities()); context.setAuthentication(auth); return context; } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java index e1ba553c0ba3..e4b5f063e175 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java @@ -38,20 +38,28 @@ public class ApplicationControllerTest { @MockBean ApplicationService applicationService; + @MockBean ApplicationPageService applicationPageService; + @MockBean ApplicationFetcher applicationFetcher; + @MockBean ApplicationForkingService applicationForkingService; + @MockBean ImportExportApplicationService importExportApplicationService; + @MockBean ApplicationSnapshotService applicationSnapshotService; + @MockBean ThemeService themeService; + @MockBean UserDataService userDataService; + @Autowired private WebTestClient webTestClient; @@ -68,7 +76,11 @@ private MultipartBodyBuilder createBodyBuilder(String fileName) throws IOExcepti MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder(); bodyBuilder - .part("file", new ClassPathResource("test_assets/ImportExportServiceTest/invalid-json-without-app.json").getFile(), MediaType.APPLICATION_JSON) + .part( + "file", + new ClassPathResource("test_assets/ImportExportServiceTest/invalid-json-without-app.json") + .getFile(), + MediaType.APPLICATION_JSON) .header("Content-Disposition", "form-data; name=\"file\"; filename=" + fileName) .header("Content-Type", "application/json"); return bodyBuilder; @@ -84,7 +96,8 @@ public void whenFileUploadedWithLongHeader_thenVerifyErrorStatus() throws IOExce final String fileName = getFileName(130 * 1024); MultipartBodyBuilder bodyBuilder = createBodyBuilder(fileName); - webTestClient.post() + webTestClient + .post() .uri(Url.APPLICATION_URL + "/import/orgId") .contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData(bodyBuilder.build())) @@ -92,29 +105,31 @@ public void whenFileUploadedWithLongHeader_thenVerifyErrorStatus() throws IOExce .expectStatus() .isEqualTo(500) .expectBody() - .json("{\n" + - " \"responseMeta\": {\n" + - " \"status\": 500,\n" + - " \"success\": false,\n" + - " \"error\": {\n" + - " \"code\": " + AppsmithErrorCode.FILE_PART_DATA_BUFFER_ERROR.getCode() + ",\n" + - " \"message\": \"Failed to upload file with error: Part headers exceeded the memory usage limit of 131072 bytes\"\n" + - " }\n" + - " }\n" + - "}"); + .json("{\n" + " \"responseMeta\": {\n" + + " \"status\": 500,\n" + + " \"success\": false,\n" + + " \"error\": {\n" + + " \"code\": " + + AppsmithErrorCode.FILE_PART_DATA_BUFFER_ERROR.getCode() + ",\n" + + " \"message\": \"Failed to upload file with error: Part headers exceeded the memory usage limit of 131072 bytes\"\n" + + " }\n" + + " }\n" + + "}"); } @Test @WithMockUser public void whenFileUploadedWithShortHeader_thenVerifySuccessStatus() throws IOException { - Mockito.when(importExportApplicationService.extractFileAndSaveApplication(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(importExportApplicationService.extractFileAndSaveApplication( + Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(new ApplicationImportDTO())); final String fileName = getFileName(2 * 1024); MultipartBodyBuilder bodyBuilder = createBodyBuilder(fileName); - webTestClient.post() + webTestClient + .post() .uri(Url.APPLICATION_URL + "/import/orgId") .contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData(bodyBuilder.build())) diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/WorkspaceControllerTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/WorkspaceControllerTest.java index 76169ba19a0f..94267065d2bd 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/WorkspaceControllerTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/WorkspaceControllerTest.java @@ -25,26 +25,31 @@ public class WorkspaceControllerTest { @MockBean WorkspaceService workspaceService; + @Autowired private WebTestClient webTestClient; @Test @WithMockUser public void getWorkspaceNoName() { - webTestClient.post().uri("/api/v1/workspaces"). - contentType(MediaType.APPLICATION_JSON). - body(BodyInserters.fromValue("{}")). - exchange(). - expectStatus().isEqualTo(400). - expectBody().json("{\n" + - " \"responseMeta\": {\n" + - " \"status\": 400,\n" + - " \"success\": false,\n" + - " \"error\": {\n" + - " \"code\": " + AppsmithErrorCode.VALIDATION_FAILURE.getCode() + ",\n" + - " \"message\": \"Validation Failure(s): {name=Name is mandatory}\"\n" + - " }\n" + - " }\n" + - "}"); + webTestClient + .post() + .uri("/api/v1/workspaces") + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue("{}")) + .exchange() + .expectStatus() + .isEqualTo(400) + .expectBody() + .json("{\n" + " \"responseMeta\": {\n" + + " \"status\": 400,\n" + + " \"success\": false,\n" + + " \"error\": {\n" + + " \"code\": " + + AppsmithErrorCode.VALIDATION_FAILURE.getCode() + ",\n" + + " \"message\": \"Validation Failure(s): {name=Name is mandatory}\"\n" + + " }\n" + + " }\n" + + "}"); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/converters/ISOStringToInstantConverterTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/converters/ISOStringToInstantConverterTest.java index 690cb8f01722..f34e65c27c09 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/converters/ISOStringToInstantConverterTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/converters/ISOStringToInstantConverterTest.java @@ -1,6 +1,5 @@ package com.appsmith.server.converters; - import com.appsmith.external.converters.ISOStringToInstantConverter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -27,8 +26,7 @@ public void setUp() { @Test public void parse_WhenEmptyString_ParsesNull() { String data = "{\"instant\": \"\"}"; - Type fileType = new TypeToken<SameDateDTO>() { - }.getType(); + Type fileType = new TypeToken<SameDateDTO>() {}.getType(); SameDateDTO sameDateDTO = gson.fromJson(data, fileType); assertThat(sameDateDTO.getInstant()).isNull(); } @@ -36,8 +34,7 @@ public void parse_WhenEmptyString_ParsesNull() { @Test public void parse_WhenNull_ParsesNull() { String data = "{\"instant\": null}"; - Type fileType = new TypeToken<SameDateDTO>() { - }.getType(); + Type fileType = new TypeToken<SameDateDTO>() {}.getType(); SameDateDTO sameDateDTO = gson.fromJson(data, fileType); assertThat(sameDateDTO.getInstant()).isNull(); } @@ -45,8 +42,7 @@ public void parse_WhenNull_ParsesNull() { @Test public void parse_WhenValidIsoDate_ParsesDate() { String data = "{\"instant\": \"2021-12-30T08:58:31Z\"}"; - Type fileType = new TypeToken<SameDateDTO>() { - }.getType(); + Type fileType = new TypeToken<SameDateDTO>() {}.getType(); SameDateDTO sameDateDTO = gson.fromJson(data, fileType); assertThat(sameDateDTO.getInstant()).isNotNull(); assertThat(sameDateDTO.getInstant().toString()).isEqualTo("2021-12-30T08:58:31Z"); @@ -55,8 +51,7 @@ public void parse_WhenValidIsoDate_ParsesDate() { @Test public void parse_DateInDoublePrecisionTimestampFormat_ParsesDate() { String data = "{\"instant\": 1640854711.292000000}"; - Type fileType = new TypeToken<SameDateDTO>() { - }.getType(); + Type fileType = new TypeToken<SameDateDTO>() {}.getType(); SameDateDTO sameDateDTO = gson.fromJson(data, fileType); assertThat(sameDateDTO.getInstant()).isNotNull(); assertThat(sameDateDTO.getInstant().toString()).isEqualTo("2021-12-30T08:58:31Z"); @@ -66,4 +61,4 @@ public void parse_DateInDoublePrecisionTimestampFormat_ParsesDate() { public static class SameDateDTO { private Instant instant; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/DatasourceContextIdentifierTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/DatasourceContextIdentifierTest.java index c50c8c056af0..e096331bf0d4 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/DatasourceContextIdentifierTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/DatasourceContextIdentifierTest.java @@ -13,7 +13,7 @@ public class DatasourceContextIdentifierTest { public void verifyDsMapKeyEquality() { String dsId = new ObjectId().toHexString(); String defaultEnvironmentId = new ObjectId().toHexString(); - DatasourceContextIdentifier keyObj = new DatasourceContextIdentifier(dsId, defaultEnvironmentId ); + DatasourceContextIdentifier keyObj = new DatasourceContextIdentifier(dsId, defaultEnvironmentId); DatasourceContextIdentifier keyObj1 = new DatasourceContextIdentifier(dsId, defaultEnvironmentId); assertEquals(keyObj, keyObj1); } @@ -33,7 +33,7 @@ public void verifyDsMapKeyNotEqual() { assertNotEquals(keyObj, keyObj2); // with same datasource but different environment id - String differentEnvironmentId = new ObjectId().toHexString(); + String differentEnvironmentId = new ObjectId().toHexString(); DatasourceContextIdentifier keyObj3 = new DatasourceContextIdentifier(dsId, differentEnvironmentId); assertNotEquals(keyObj, keyObj3); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/UserTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/UserTest.java index dd5d94452541..ace3ee1e8a54 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/UserTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/UserTest.java @@ -29,5 +29,4 @@ public void testFirstNameFromFullNameAndEmail() { one.setEmail("[email protected]"); assertThat(one.computeFirstName()).isEqualTo("Sherlock"); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/featureflags/strategies/EmailBasedRolloutStrategyTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/featureflags/strategies/EmailBasedRolloutStrategyTest.java index 61c86e6d3eb4..1d23b826147b 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/featureflags/strategies/EmailBasedRolloutStrategyTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/featureflags/strategies/EmailBasedRolloutStrategyTest.java @@ -39,7 +39,8 @@ public void testValidFeatureCheck() { User user = new User(); user.setEmail("[email protected]"); - Mockito.when(executionContext.getValue(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(user); + Mockito.when(executionContext.getValue(Mockito.anyString(), Mockito.anyBoolean())) + .thenReturn(user); boolean evaluate = strategy.evaluate("test-feature", null, executionContext); assertTrue(evaluate); @@ -52,7 +53,8 @@ public void testInvalidFeatureCheck() { User user = new User(); user.setEmail("[email protected]"); - Mockito.when(executionContext.getValue(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(user); + Mockito.when(executionContext.getValue(Mockito.anyString(), Mockito.anyBoolean())) + .thenReturn(user); boolean evaluate = strategy.evaluate("test-feature", null, executionContext); assertFalse(evaluate); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/FileFormatMigrationTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/FileFormatMigrationTests.java index c7a3670d33ce..663bf3ec87e4 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/FileFormatMigrationTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/FileFormatMigrationTests.java @@ -40,26 +40,22 @@ public class FileFormatMigrationTests { @BeforeEach public void setUp() { - Mockito - .when(gitExecutor.checkoutToBranch(Mockito.any(), Mockito.any())) - .thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(), Mockito.any())).thenReturn(Mono.just(true)); - Mockito - .when(gitConfig.getGitRootPath()) - .thenReturn(""); + Mockito.when(gitConfig.getGitRootPath()).thenReturn(""); } @Test public void extractFiles_whenFilesInRepoWithFormatVersion1_success() { String version1DirPath = "src/test/resources/test_assets/GitExecutorTests/FileFormatVersions/v1"; Gson gson = new Gson(); - Mono<ApplicationGitReference> applicationRefMono = fileInterface - .reconstructApplicationReferenceFromGitRepo(version1DirPath, "", "", ""); - StepVerifier - .create(applicationRefMono) + Mono<ApplicationGitReference> applicationRefMono = + fileInterface.reconstructApplicationReferenceFromGitRepo(version1DirPath, "", "", ""); + StepVerifier.create(applicationRefMono) .assertNext(applicationGitReference -> { assertThat(applicationGitReference.getApplication()).isNotNull(); - JsonObject jsonObject = gson.fromJson(gson.toJson(applicationGitReference.getApplication()), JsonObject.class); + JsonObject jsonObject = + gson.fromJson(gson.toJson(applicationGitReference.getApplication()), JsonObject.class); assertThat(jsonObject.get("applicationKey").getAsString()).isEqualTo("applicationValue"); jsonObject = gson.fromJson(gson.toJson(applicationGitReference.getMetadata()), JsonObject.class); @@ -68,19 +64,40 @@ public void extractFiles_whenFilesInRepoWithFormatVersion1_success() { JsonObject pages = gson.fromJson(gson.toJson(applicationGitReference.getPages()), JsonObject.class); assertThat(pages.size()).isEqualTo(1); - assertThat(pages.get("Page1.json").getAsJsonObject().get("pageKey").getAsString()).isEqualTo("pageValue"); - - JsonObject actions = gson.fromJson(gson.toJson(applicationGitReference.getActions()), JsonObject.class); + assertThat(pages.get("Page1.json") + .getAsJsonObject() + .get("pageKey") + .getAsString()) + .isEqualTo("pageValue"); + + JsonObject actions = + gson.fromJson(gson.toJson(applicationGitReference.getActions()), JsonObject.class); assertThat(actions.size()).isEqualTo(1); - assertThat(actions.get("Query1_Page1.json").getAsJsonObject().get("queryKey").getAsString()).isEqualTo("queryValue"); - - JsonObject actionCollections = gson.fromJson(gson.toJson(applicationGitReference.getActionCollections()), JsonObject.class); + assertThat(actions.get("Query1_Page1.json") + .getAsJsonObject() + .get("queryKey") + .getAsString()) + .isEqualTo("queryValue"); + + JsonObject actionCollections = gson.fromJson( + gson.toJson(applicationGitReference.getActionCollections()), JsonObject.class); assertThat(actionCollections.size()).isEqualTo(1); - assertThat(actionCollections.get("JSObject1_Page1.json").getAsJsonObject().get("jsobjectKey").getAsString()).isEqualTo("jsobjectValue"); - - JsonObject datasources = gson.fromJson(gson.toJson(applicationGitReference.getDatasources()), JsonObject.class); + assertThat(actionCollections + .get("JSObject1_Page1.json") + .getAsJsonObject() + .get("jsobjectKey") + .getAsString()) + .isEqualTo("jsobjectValue"); + + JsonObject datasources = + gson.fromJson(gson.toJson(applicationGitReference.getDatasources()), JsonObject.class); assertThat(datasources.size()).isEqualTo(1); - assertThat(datasources.get("Datasource1.json").getAsJsonObject().get("datasourceKey").getAsString()).isEqualTo("datasourceValue"); + assertThat(datasources + .get("Datasource1.json") + .getAsJsonObject() + .get("datasourceKey") + .getAsString()) + .isEqualTo("datasourceValue"); }) .verifyComplete(); } @@ -89,13 +106,13 @@ public void extractFiles_whenFilesInRepoWithFormatVersion1_success() { public void extractFiles_whenFilesInRepoWithFormatVersion2_success() { String version1DirPath = "src/test/resources/test_assets/GitExecutorTests/FileFormatVersions/v2"; Gson gson = new Gson(); - Mono<ApplicationGitReference> applicationRefMono = fileInterface - .reconstructApplicationReferenceFromGitRepo(version1DirPath, "", "", ""); - StepVerifier - .create(applicationRefMono) + Mono<ApplicationGitReference> applicationRefMono = + fileInterface.reconstructApplicationReferenceFromGitRepo(version1DirPath, "", "", ""); + StepVerifier.create(applicationRefMono) .assertNext(applicationGitReference -> { assertThat(applicationGitReference.getApplication()).isNotNull(); - JsonObject jsonObject = gson.fromJson(gson.toJson(applicationGitReference.getApplication()), JsonObject.class); + JsonObject jsonObject = + gson.fromJson(gson.toJson(applicationGitReference.getApplication()), JsonObject.class); assertThat(jsonObject.get("applicationKey").getAsString()).isEqualTo("applicationValue"); jsonObject = gson.fromJson(gson.toJson(applicationGitReference.getMetadata()), JsonObject.class); @@ -104,19 +121,40 @@ public void extractFiles_whenFilesInRepoWithFormatVersion2_success() { JsonObject pages = gson.fromJson(gson.toJson(applicationGitReference.getPages()), JsonObject.class); assertThat(pages.size()).isEqualTo(1); - assertThat(pages.get("Page1").getAsJsonObject().get("pageKey").getAsString()).isEqualTo("pageValue"); - - JsonObject actions = gson.fromJson(gson.toJson(applicationGitReference.getActions()), JsonObject.class); + assertThat(pages.get("Page1") + .getAsJsonObject() + .get("pageKey") + .getAsString()) + .isEqualTo("pageValue"); + + JsonObject actions = + gson.fromJson(gson.toJson(applicationGitReference.getActions()), JsonObject.class); assertThat(actions.size()).isEqualTo(1); - assertThat(actions.get("Query1.jsonPage1").getAsJsonObject().get("queryKey").getAsString()).isEqualTo("queryValue"); - - JsonObject actionCollections = gson.fromJson(gson.toJson(applicationGitReference.getActionCollections()), JsonObject.class); + assertThat(actions.get("Query1.jsonPage1") + .getAsJsonObject() + .get("queryKey") + .getAsString()) + .isEqualTo("queryValue"); + + JsonObject actionCollections = gson.fromJson( + gson.toJson(applicationGitReference.getActionCollections()), JsonObject.class); assertThat(actionCollections.size()).isEqualTo(1); - assertThat(actionCollections.get("JSObject1.jsonPage1").getAsJsonObject().get("jsobjectKey").getAsString()).isEqualTo("jsobjectValue"); - - JsonObject datasources = gson.fromJson(gson.toJson(applicationGitReference.getDatasources()), JsonObject.class); + assertThat(actionCollections + .get("JSObject1.jsonPage1") + .getAsJsonObject() + .get("jsobjectKey") + .getAsString()) + .isEqualTo("jsobjectValue"); + + JsonObject datasources = + gson.fromJson(gson.toJson(applicationGitReference.getDatasources()), JsonObject.class); assertThat(datasources.size()).isEqualTo(1); - assertThat(datasources.get("Datasource1.json").getAsJsonObject().get("datasourceKey").getAsString()).isEqualTo("datasourceValue"); + assertThat(datasources + .get("Datasource1.json") + .getAsJsonObject() + .get("datasourceKey") + .getAsString()) + .isEqualTo("datasourceValue"); }) .verifyComplete(); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/GitExecutorTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/GitExecutorTest.java index ac51e8f5d57a..94db0c93c019 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/GitExecutorTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/GitExecutorTest.java @@ -71,27 +71,27 @@ private void createFileInThePath(String fileName) throws IOException { } private void commitToRepo() { - gitExecutor.commitApplication(path, "Test commit", "test", "[email protected]", false, false).block(); + gitExecutor + .commitApplication(path, "Test commit", "test", "[email protected]", false, false) + .block(); } @Test public void commit_validChange_Success() throws IOException { createFileInThePath("TestFIle2"); - String commitStatus = gitExecutor.commitApplication(path, "Test commit", "test", "[email protected]", false, false).block(); + String commitStatus = gitExecutor + .commitApplication(path, "Test commit", "test", "[email protected]", false, false) + .block(); Mono<List<GitLogDTO>> commitList = gitExecutor.getCommitHistory(path); - StepVerifier - .create(commitList) - .assertNext(list -> { - assertThat(commitStatus).isEqualTo("Committed successfully!"); - assertThat(list).isNotEmpty(); - assertThat(list.get(0).getCommitMessage()).isNotEmpty(); - assertThat(list.get(0).getCommitMessage()).isEqualTo("Test commit"); - assertThat(list.get(0).getAuthorEmail()).isEqualTo("[email protected]"); - assertThat(list.get(0).getAuthorName()).isEqualTo("test"); - - }); - + StepVerifier.create(commitList).assertNext(list -> { + assertThat(commitStatus).isEqualTo("Committed successfully!"); + assertThat(list).isNotEmpty(); + assertThat(list.get(0).getCommitMessage()).isNotEmpty(); + assertThat(list.get(0).getCommitMessage()).isEqualTo("Test commit"); + assertThat(list.get(0).getAuthorEmail()).isEqualTo("[email protected]"); + assertThat(list.get(0).getAuthorName()).isEqualTo("test"); + }); } @Test @@ -100,8 +100,7 @@ public void createBranch_validName_success() throws IOException { commitToRepo(); Mono<String> branchStatus = gitExecutor.createAndCheckoutToBranch(path, "branch/f1"); - StepVerifier - .create(branchStatus) + StepVerifier.create(branchStatus) .assertNext(status -> { assertThat(status).isEqualTo("branch/f1"); }) @@ -114,8 +113,7 @@ public void createBranch_duplicateName_ThrowError() throws IOException { commitToRepo(); Mono<String> branchStatus = gitExecutor.createAndCheckoutToBranch(path, "main"); - StepVerifier - .create(branchStatus) + StepVerifier.create(branchStatus) .assertNext(status -> { assertThat(status).isNotEmpty(); assertThat(status).isEqualTo("main"); @@ -128,20 +126,18 @@ public void isMergeBranch_NoChanges_CanBeMerged() throws IOException, GitAPIExce createFileInThePath("isMergeBranch_NoChanges_CanBeMerged"); commitToRepo(); - //create branch f1 + // create branch f1 gitExecutor.createAndCheckoutToBranch(path, "f1").block(); - //Create branch f2 from f1 + // Create branch f2 from f1 gitExecutor.createAndCheckoutToBranch(path, "f2").block(); Mono<MergeStatusDTO> mergeableStatus = gitExecutor.isMergeBranch(path, "f1", "f2"); - StepVerifier - .create(mergeableStatus) + StepVerifier.create(mergeableStatus) .assertNext(s -> { assertThat(s.isMergeAble()).isTrue(); }) .verifyComplete(); - } @Test @@ -149,24 +145,22 @@ public void isMergeBranch_NonConflictingChanges_CanBeMerged() throws IOException createFileInThePath("isMergeBranch_NonConflictingChanges_CanBeMerged"); commitToRepo(); - //create branch f1 and commit changes + // create branch f1 and commit changes String branch = gitExecutor.createAndCheckoutToBranch(path, "f1").block(); createFileInThePath("isMergeBranch_NonConflictingChanges_f1"); - //Create branch f2 from f1 + // Create branch f2 from f1 gitExecutor.checkoutToBranch(path, "main"); gitExecutor.createAndCheckoutToBranch(path, "f2").block(); createFileInThePath("isMergeBranch_NonConflictingChanges_f2"); Mono<MergeStatusDTO> mergeableStatus = gitExecutor.isMergeBranch(path, "f1", "f2"); - StepVerifier - .create(mergeableStatus) + StepVerifier.create(mergeableStatus) .assertNext(s -> { assertThat(s.isMergeAble()).isTrue(); }) .verifyComplete(); - } @Test @@ -177,8 +171,7 @@ public void checkoutBranch_InvalidBranchName_ThrowError() throws IOException { gitExecutor.createAndCheckoutToBranch(path, "main").block(); Mono<Boolean> branchStatus = gitExecutor.checkoutToBranch(path, "main1"); - StepVerifier - .create(branchStatus) + StepVerifier.create(branchStatus) .expectErrorMatches(throwable -> throwable instanceof RefNotFoundException && throwable.getMessage().contains("Ref main1 cannot be resolved")); } @@ -191,8 +184,7 @@ public void checkoutBranch_ValidBranchName_Success() throws IOException { gitExecutor.createAndCheckoutToBranch(path, "main").block(); Mono<Boolean> branchStatus = gitExecutor.checkoutToBranch(path, "main"); - StepVerifier - .create(branchStatus) + StepVerifier.create(branchStatus) .assertNext(status -> { assertThat(status).isEqualTo(Boolean.TRUE); }) @@ -207,8 +199,7 @@ public void checkoutBranch_NothingToCommit_Success() throws IOException { gitExecutor.createAndCheckoutToBranch(path, "main").block(); Mono<Boolean> branchStatus = gitExecutor.checkoutToBranch(path, "master"); - StepVerifier - .create(branchStatus) + StepVerifier.create(branchStatus) .assertNext(status -> { assertThat(status).isEqualTo(Boolean.TRUE); try { @@ -230,8 +221,7 @@ public void checkoutBranch_ModifiedFilesNonConflictingChanges_Success() throws I createFileInThePath("TestFile6"); Mono<Boolean> branchStatus = gitExecutor.checkoutToBranch(path, "master"); - StepVerifier - .create(branchStatus) + StepVerifier.create(branchStatus) .assertNext(status -> { assertThat(status).isEqualTo(Boolean.TRUE); try { @@ -254,8 +244,7 @@ public void checkoutBranch_ModifiedFileContent_Success() throws IOException { Mono<Boolean> branchStatus = gitExecutor.checkoutToBranch(path, "master"); - StepVerifier - .create(branchStatus) + StepVerifier.create(branchStatus) .assertNext(status -> { assertThat(status).isEqualTo(Boolean.TRUE); try { @@ -271,17 +260,15 @@ public void checkoutBranch_ModifiedFileContent_Success() throws IOException { public void listBranches_LocalMode_Success() throws IOException { createFileInThePath("listBranch"); commitToRepo(); - Mono<String> branchMono = gitExecutor.createAndCheckoutToBranch(path, "test1") + Mono<String> branchMono = gitExecutor + .createAndCheckoutToBranch(path, "test1") .flatMap(s -> gitExecutor.createAndCheckoutToBranch(path, "test2")); - Mono<List<GitBranchDTO>> gitBranchDTOMono = branchMono - .then(gitExecutor.listBranches(path, "remoteUrl", "publicKey", "privateKey", false)); - - StepVerifier - .create(gitBranchDTOMono) - .assertNext(gitBranchDTOS -> { - assertThat(gitBranchDTOS.stream().count()).isEqualTo(3); + Mono<List<GitBranchDTO>> gitBranchDTOMono = + branchMono.then(gitExecutor.listBranches(path, "remoteUrl", "publicKey", "privateKey", false)); - }); + StepVerifier.create(gitBranchDTOMono).assertNext(gitBranchDTOS -> { + assertThat(gitBranchDTOS.stream().count()).isEqualTo(3); + }); } @Test @@ -296,8 +283,7 @@ public void mergeBranch_WithOutConflicts_Success() throws IOException { Mono<String> mergeStatusDTOMono = gitExecutor.mergeBranch(path, defaultBranch, "master"); - StepVerifier - .create(mergeStatusDTOMono) + StepVerifier.create(mergeStatusDTOMono) .assertNext(s -> { assertThat(s).isEqualTo("FAST_FORWARD"); }) @@ -314,7 +300,7 @@ public void mergeBranch_WithConflicts_Failure() throws IOException { FileUtils.writeStringToFile(filePath.toFile(), "Conflicts added TestFIle4", "UTF-8", true); commitToRepo(); - //Create a 2nd branch + // Create a 2nd branch gitExecutor.checkoutToBranch(path, "master").block(); gitExecutor.createAndCheckoutToBranch(path, "test2").block(); filePath = Paths.get(String.valueOf(path).replace("/.git", ""), "TestFIle4"); @@ -325,11 +311,9 @@ public void mergeBranch_WithConflicts_Failure() throws IOException { Mono<String> mergeStatusDTOMono = gitExecutor.mergeBranch(path, "test1", "test2"); - StepVerifier - .create(mergeStatusDTOMono) + StepVerifier.create(mergeStatusDTOMono) .assertNext(s -> assertThat(s).isEqualTo("CONFLICTING")) .verifyComplete(); - } @Test @@ -341,7 +325,7 @@ public void mergeBranch_NoChanges_SuccessUpToDate() throws IOException { FileUtils.writeStringToFile(filePath.toFile(), "Conflicts added TestFIle4", "UTF-8", false); commitToRepo(); - //Create a 2nd branch + // Create a 2nd branch gitExecutor.createAndCheckoutToBranch(path, "test2").block(); filePath = Paths.get(String.valueOf(path).replace("/.git", ""), "TestFIle4"); FileUtils.writeStringToFile(filePath.toFile(), "Added test data", "UTF-8", false); @@ -351,11 +335,9 @@ public void mergeBranch_NoChanges_SuccessUpToDate() throws IOException { Mono<String> mergeStatusDTOMono = gitExecutor.mergeBranch(path, "test1", "test2"); - StepVerifier - .create(mergeStatusDTOMono) + StepVerifier.create(mergeStatusDTOMono) .assertNext(s -> assertThat(s).isEqualTo("ALREADY_UP_TO_DATE")) .verifyComplete(); - } @Test @@ -370,8 +352,7 @@ public void mergeBranchStatus_WithOutConflicts_Mergeable() throws IOException { Mono<MergeStatusDTO> mergeStatusDTOMono = gitExecutor.isMergeBranch(path, defaultBranch, "master"); - StepVerifier - .create(mergeStatusDTOMono) + StepVerifier.create(mergeStatusDTOMono) .assertNext(mergeStatusDTO -> { assertThat(mergeStatusDTO.isMergeAble()).isEqualTo(Boolean.TRUE); }) @@ -387,7 +368,7 @@ public void mergeBranchStatus_NoChanges_Mergeable() throws IOException { FileUtils.writeStringToFile(filePath.toFile(), "Conflicts added TestFIle4", "UTF-8", false); commitToRepo(); - //Create a 2nd branch + // Create a 2nd branch gitExecutor.createAndCheckoutToBranch(path, "test2").block(); filePath = Paths.get(String.valueOf(path).replace("/.git", ""), "TestFIle4"); FileUtils.writeStringToFile(filePath.toFile(), "Added test data", "UTF-8", false); @@ -395,8 +376,7 @@ public void mergeBranchStatus_NoChanges_Mergeable() throws IOException { Mono<MergeStatusDTO> mergeStatusDTOMono = gitExecutor.isMergeBranch(path, "test1", "test2"); - StepVerifier - .create(mergeStatusDTOMono) + StepVerifier.create(mergeStatusDTOMono) .assertNext(mergeStatusDTO -> { assertThat(mergeStatusDTO.isMergeAble()).isEqualTo(Boolean.TRUE); }) @@ -413,7 +393,7 @@ public void mergeBranchStatus_WithConflicts_ShowConflictFiles() throws IOExcepti FileUtils.writeStringToFile(filePath.toFile(), "Conflicts added TestFIle4", "UTF-8", true); commitToRepo(); - //Create a 2nd branch + // Create a 2nd branch gitExecutor.checkoutToBranch(path, "master").block(); gitExecutor.createAndCheckoutToBranch(path, "test2").block(); filePath = Paths.get(String.valueOf(path).replace("/.git", ""), "TestFIle4"); @@ -424,23 +404,20 @@ public void mergeBranchStatus_WithConflicts_ShowConflictFiles() throws IOExcepti Mono<MergeStatusDTO> mergeStatusDTOMono = gitExecutor.isMergeBranch(path, "test1", "test2"); - StepVerifier - .create(mergeStatusDTOMono) + StepVerifier.create(mergeStatusDTOMono) .assertNext(mergeStatusDTO -> { assertThat(mergeStatusDTO.isMergeAble()).isEqualTo(Boolean.FALSE); assertThat(mergeStatusDTO.getConflictingFiles().size()).isEqualTo(1); assertThat(mergeStatusDTO.getConflictingFiles().get(0)).isEqualTo("TestFIle4"); }) .verifyComplete(); - } @Test public void getCommitHistory_EmptyRepo_Error() { Mono<List<GitLogDTO>> status = gitExecutor.getCommitHistory(path); - StepVerifier - .create(status) + StepVerifier.create(status) .expectErrorMatches(throwable -> throwable instanceof NoHeadException) .verify(); } @@ -451,8 +428,7 @@ public void getCommitHistory_NonEmptyRepo_Success() throws IOException { commitToRepo(); Mono<List<GitLogDTO>> status = gitExecutor.getCommitHistory(path); - StepVerifier - .create(status) + StepVerifier.create(status) .assertNext(gitLogDTOS -> { assertThat(gitLogDTOS.size()).isEqualTo(1); assertThat(gitLogDTOS.get(0).getCommitMessage()).isEqualTo("Test commit"); @@ -470,8 +446,7 @@ public void deleteBranch_validBranch_Success() throws IOException { gitExecutor.checkoutToBranch(path, "master").block(); Mono<Boolean> deleteBranchMono = gitExecutor.deleteBranch(path, "test"); - StepVerifier - .create(deleteBranchMono) + StepVerifier.create(deleteBranchMono) .assertNext(deleteStatus -> assertThat(deleteStatus).isEqualTo(Boolean.TRUE)) .verifyComplete(); } @@ -481,8 +456,7 @@ public void deleteBranch_emptyRepo_Success() throws IOException { Mono<Boolean> deleteBranchMono = gitExecutor.deleteBranch(path, "master"); - StepVerifier - .create(deleteBranchMono) + StepVerifier.create(deleteBranchMono) .assertNext(deleteStatus -> assertThat(deleteStatus).isEqualTo(Boolean.FALSE)) .verifyComplete(); } @@ -495,8 +469,7 @@ public void deleteBranch_inValidBranch_Success() throws IOException { gitExecutor.checkoutToBranch(path, "master").block(); Mono<Boolean> deleteBranchMono = gitExecutor.deleteBranch(path, "**impossibleBranchName**"); - StepVerifier - .create(deleteBranchMono) + StepVerifier.create(deleteBranchMono) .assertNext(deleteStatus -> assertThat(deleteStatus).isEqualTo(Boolean.FALSE)) .verifyComplete(); } @@ -507,8 +480,7 @@ public void getStatus_noChangesInBranch_Success() throws IOException { commitToRepo(); Mono<GitStatusDTO> gitStatusDTOMono = gitExecutor.getStatus(path, "master"); - StepVerifier - .create(gitStatusDTOMono) + StepVerifier.create(gitStatusDTOMono) .assertNext(gitStatusDTO -> { assertThat(gitStatusDTO.getIsClean()).isEqualTo(Boolean.TRUE); assertThat(gitStatusDTO.getAheadCount()).isEqualTo(0); @@ -525,8 +497,7 @@ public void getStatus_ChangesInBranch_Success() throws IOException { createFileInThePath("testFile2"); Mono<GitStatusDTO> gitStatusDTOMono = gitExecutor.getStatus(path, "master"); - StepVerifier - .create(gitStatusDTOMono) + StepVerifier.create(gitStatusDTOMono) .assertNext(gitStatusDTO -> { assertThat(gitStatusDTO.getIsClean()).isEqualTo(Boolean.FALSE); assertThat(gitStatusDTO.getAheadCount()).isEqualTo(0); @@ -542,15 +513,13 @@ public void resetToLastCommit_WithOutStaged_CleanStateForRepo() throws IOExcepti commitToRepo(); Mono<Boolean> resetStatus = gitExecutor.resetToLastCommit(path, "master"); - StepVerifier - .create(resetStatus) + StepVerifier.create(resetStatus) .assertNext(status -> { assertThat(status).isEqualTo(Boolean.TRUE); }) .verifyComplete(); } - // TODO cover the below mentioned test cases /* * resetToLastCommit diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/AppsmithErrorTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/AppsmithErrorTest.java index e5bfde46360b..0f049328024d 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/AppsmithErrorTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/AppsmithErrorTest.java @@ -13,22 +13,29 @@ public class AppsmithErrorTest { @Test public void verifyUniquenessOfAppsmithErrorCode() { - assert (Arrays.stream(AppsmithError.values()).map(AppsmithError::getAppErrorCode).distinct().count() == AppsmithError.values().length); + assert (Arrays.stream(AppsmithError.values()) + .map(AppsmithError::getAppErrorCode) + .distinct() + .count() + == AppsmithError.values().length); } @Test public void verifyDuplicateKeyExceptionDoesnotDiscloseSensitiveInformation() { - //Context: https://github.com/appsmithorg/appsmith/issues/21568 - final DuplicateKeyException exception = assertThrows( - DuplicateKeyException.class, - () -> generateDuplicateKeyException()); + // Context: https://github.com/appsmithorg/appsmith/issues/21568 + final DuplicateKeyException exception = + assertThrows(DuplicateKeyException.class, () -> generateDuplicateKeyException()); AppsmithError appsmithError = AppsmithError.DUPLICATE_KEY; - assertEquals(appsmithError.getMessage("\\\"MyJSObject\\\""), appsmithError.getMessage(DuplicateKeyExceptionUtils.extractConflictingObjectName(exception.getMessage()))); + assertEquals( + appsmithError.getMessage("\\\"MyJSObject\\\""), + appsmithError.getMessage( + DuplicateKeyExceptionUtils.extractConflictingObjectName(exception.getMessage()))); } private void generateDuplicateKeyException() { - String originalErrorMessage = "Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: appsmith.actionCollection index: unpublishedCollection.name_1 dup key: { unpublishedCollection.name: \\\"MyJSObject\\\" }', details={}}."; + String originalErrorMessage = + "Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: appsmith.actionCollection index: unpublishedCollection.name_1 dup key: { unpublishedCollection.name: \\\"MyJSObject\\\" }', details={}}."; throw new DuplicateKeyException(originalErrorMessage); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CollectionUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CollectionUtilsTest.java index 65831878f057..2d8af12e2236 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CollectionUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CollectionUtilsTest.java @@ -18,7 +18,7 @@ public void testPutAtFirstWhenItemDoesNotExist() { sampleList.add("c"); CollectionUtils.putAtFirst(sampleList, "d"); assertEquals(4, sampleList.size()); - assertArrayEquals(new String[]{"d", "a", "b", "c"}, sampleList.toArray()); + assertArrayEquals(new String[] {"d", "a", "b", "c"}, sampleList.toArray()); } @Test @@ -29,7 +29,7 @@ public void testPutAtFirstWhenItemAlreadyAtFirst() { sampleList.add("c"); CollectionUtils.putAtFirst(sampleList, "a"); assertEquals(3, sampleList.size()); - assertArrayEquals(new String[]{"a", "b", "c"}, sampleList.toArray()); + assertArrayEquals(new String[] {"a", "b", "c"}, sampleList.toArray()); } @Test @@ -40,7 +40,7 @@ public void testPutAtFirstWhenItemExistsButNotAtFirst() { sampleList.add("c"); CollectionUtils.putAtFirst(sampleList, "b"); assertEquals(3, sampleList.size()); - assertArrayEquals(new String[]{"b", "a", "c"}, sampleList.toArray()); + assertArrayEquals(new String[] {"b", "a", "c"}, sampleList.toArray()); } @Test @@ -53,7 +53,7 @@ public void removeDuplicatesWhenThereAreDuplicates() { CollectionUtils.removeDuplicates(sampleList); assertEquals(3, sampleList.size()); - assertArrayEquals(new String[]{"a", "b", "c"}, sampleList.toArray()); + assertArrayEquals(new String[] {"a", "b", "c"}, sampleList.toArray()); } @Test @@ -65,7 +65,7 @@ public void removeDuplicatesWhenThereAreNoDuplicates() { CollectionUtils.removeDuplicates(sampleList); assertEquals(3, sampleList.size()); - assertArrayEquals(new String[]{"a", "b", "c"}, sampleList.toArray()); + assertArrayEquals(new String[] {"a", "b", "c"}, sampleList.toArray()); } @Test @@ -79,7 +79,7 @@ public void removeDuplicatesWhenThereAreMultipleDuplicates() { CollectionUtils.removeDuplicates(sampleList); assertEquals(3, sampleList.size()); - assertArrayEquals(new String[]{"a", "b", "c"}, sampleList.toArray()); + assertArrayEquals(new String[] {"a", "b", "c"}, sampleList.toArray()); } @Test @@ -93,7 +93,6 @@ public void removeDuplicates_WhenThereAreDuplicates_DuplicatesRemovedFromFirst() CollectionUtils.removeDuplicates(sampleList); assertEquals(3, sampleList.size()); - assertArrayEquals(new String[]{"a", "b", "c"}, sampleList.toArray()); + assertArrayEquals(new String[] {"a", "b", "c"}, sampleList.toArray()); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/DslUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/DslUtilsTest.java index 09969077d89c..a60038bff8f3 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/DslUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/DslUtilsTest.java @@ -16,44 +16,47 @@ class DslUtilsTest { @Test void getMustacheValueSetFromSpecificDynamicBindingPath_withNullOrEmptyDsl_returnsEmptySet() { - Set<MustacheBindingToken> tokensInNullDsl = DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath(null, "irrelevantPath"); - Set<MustacheBindingToken> tokensInEmptyDsl = DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath(new TextNode(""), "irrelevantPath"); + Set<MustacheBindingToken> tokensInNullDsl = + DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath(null, "irrelevantPath"); + Set<MustacheBindingToken> tokensInEmptyDsl = + DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath(new TextNode(""), "irrelevantPath"); Assertions.assertThat(tokensInNullDsl).isEmpty(); Assertions.assertThat(tokensInEmptyDsl).isEmpty(); } @Test - void getMustacheValueSetFromSpecificDynamicBindingPath_withComplicatedPathAndMultipleBindings_parsesDslCorrectly() throws JsonProcessingException { + void getMustacheValueSetFromSpecificDynamicBindingPath_withComplicatedPathAndMultipleBindings_parsesDslCorrectly() + throws JsonProcessingException { String fieldPath = "root.field.list[0].childField.anotherList.0.multidimensionalList[0][0]"; - String jsonString = "{ " + - "\"root\": { " + - " \"field\": { " + - " \"list\": [ " + - " { " + - " \"childField\": { " + - " \"anotherList\": [ " + - " { " + - " \"multidimensionalList\" : [ " + - " [\"{{ retrievedBinding1.text }} {{ retrievedBinding2.text }}\"]" + - " ] " + - " } " + - " ] " + - " } " + - " } " + - " ] " + - " } " + - " } " + - "}"; + String jsonString = "{ " + "\"root\": { " + + " \"field\": { " + + " \"list\": [ " + + " { " + + " \"childField\": { " + + " \"anotherList\": [ " + + " { " + + " \"multidimensionalList\" : [ " + + " [\"{{ retrievedBinding1.text }} {{ retrievedBinding2.text }}\"]" + + " ] " + + " } " + + " ] " + + " } " + + " } " + + " ] " + + " } " + + " } " + + "}"; ObjectMapper mapper = new ObjectMapper(); JsonNode dsl = mapper.readTree(jsonString); Set<MustacheBindingToken> tokens = DslUtils.getMustacheValueSetFromSpecificDynamicBindingPath(dsl, fieldPath); - Assertions.assertThat(tokens).containsExactlyInAnyOrder( - new MustacheBindingToken(" retrievedBinding1.text ", 2, false), - new MustacheBindingToken(" retrievedBinding2.text ", 31, false)); + Assertions.assertThat(tokens) + .containsExactlyInAnyOrder( + new MustacheBindingToken(" retrievedBinding1.text ", 2, false), + new MustacheBindingToken(" retrievedBinding2.text ", 31, false)); } @Test @@ -61,7 +64,8 @@ void replaceValuesInSpecificDynamicBindingPath_whenFieldPathNotFound() { ObjectMapper mapper = new ObjectMapper(); ObjectNode dsl = mapper.createObjectNode(); dsl.put("fieldKey", "fieldValue"); - JsonNode replacedDsl = DslUtils.replaceValuesInSpecificDynamicBindingPath(dsl, "nonExistentPath", new HashMap<>()); + JsonNode replacedDsl = + DslUtils.replaceValuesInSpecificDynamicBindingPath(dsl, "nonExistentPath", new HashMap<>()); Assertions.assertThat(replacedDsl).isEqualTo(dsl); } @@ -91,4 +95,4 @@ void replaceValuesInSpecificDynamicBindingPath_withSuccessfulMultipleReplacement newDsl.put("existingPath", "newFieldValue1 newFieldValue2"); Assertions.assertThat(replacedDsl).isEqualTo(dsl); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/FileUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/FileUtilsTest.java index 53aabfe64b82..7304c89bdca8 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/FileUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/FileUtilsTest.java @@ -32,9 +32,7 @@ public void createZip_WhenFileExists_ValidZipCreated() throws IOException { InputStream file2 = new ClassPathResource("FileUtilsTest/sample-file2.txt").getInputStream(); byte[] zipBytes = fileUtils.createZip( - new FileUtils.ZipSourceFile(file1, "file_one.txt"), - new FileUtils.ZipSourceFile(file2, "file_two.txt") - ); + new FileUtils.ZipSourceFile(file1, "file_one.txt"), new FileUtils.ZipSourceFile(file2, "file_two.txt")); // unzip and read the contents into a map. Key of the map is file name and value is file contents Map<String, String> fileNameAndContentMap = readZipFile(zipBytes); @@ -70,4 +68,4 @@ private Map<String, String> readZipFile(byte[] zipBytes) throws IOException { byteArrayInputStream.close(); return fileNameAndContentMap; } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java index 18b7cc7b8aa0..f9ef4c9e588d 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java @@ -47,36 +47,37 @@ public class GitFileUtilsTest { private static final Path localRepoPath = Path.of("localRepoPath"); private static final String filePath = "test_assets/ImportExportServiceTest/valid-application.json"; + @MockBean FileInterface fileInterface; + @Autowired GitFileUtils gitFileUtils; + @Autowired AnalyticsService analyticsService; + @Autowired SessionUserService userService; + @Autowired Gson gson; private Mono<ApplicationJson> createAppJson(String filePath) { FilePart filePart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read( - new ClassPathResource(filePath), - new DefaultDataBufferFactory(), - 4096) + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource(filePath), new DefaultDataBufferFactory(), 4096) .cache(); Mockito.when(filePart.content()).thenReturn(dataBufferFlux); Mockito.when(filePart.headers().getContentType()).thenReturn(MediaType.APPLICATION_JSON); - Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()) - .map(dataBuffer -> { - byte[] data = new byte[dataBuffer.readableByteCount()]; - dataBuffer.read(data); - DataBufferUtils.release(dataBuffer); - return new String(data); - }); + Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()).map(dataBuffer -> { + byte[] data = new byte[dataBuffer.readableByteCount()]; + dataBuffer.read(data); + DataBufferUtils.release(dataBuffer); + return new String(data); + }); return stringifiedFile .map(data -> { @@ -90,19 +91,18 @@ public void getSerializableResource_allEntitiesArePresentForApplication_keysIncl ApplicationJson validAppJson = createAppJson(filePath).block(); ApplicationGitReference applicationGitReference = gitFileUtils.createApplicationReference(validAppJson); - List<String> pageNames = validAppJson.getPageList() - .stream() + List<String> pageNames = validAppJson.getPageList().stream() .map(newPage -> newPage.getUnpublishedPage().getName()) .collect(Collectors.toList()); - List<String> actionNames = validAppJson.getActionList() - .stream() - .map(newAction -> newAction.getUnpublishedAction().getValidName().replace(".", "-")) + List<String> actionNames = validAppJson.getActionList().stream() + .map(newAction -> + newAction.getUnpublishedAction().getValidName().replace(".", "-")) .collect(Collectors.toList()); - List<String> collectionNames = validAppJson.getActionCollectionList() - .stream() - .map(actionCollection -> actionCollection.getUnpublishedCollection().getName()) + List<String> collectionNames = validAppJson.getActionCollectionList().stream() + .map(actionCollection -> + actionCollection.getUnpublishedCollection().getName()) .collect(Collectors.toList()); Map<String, Object> actions = applicationGitReference.getActions(); @@ -135,20 +135,18 @@ public void getSerializableResource_allEntitiesArePresentForApplication_keysIncl public void getSerializableResource_withDeletedEntities_excludeDeletedEntities() { ApplicationJson validAppJson = createAppJson(filePath).block(); - NewPage deletedPage = validAppJson.getPageList().get(validAppJson.getPageList().size() - 1); - deletedPage - .getUnpublishedPage() - .setDeletedAt(Instant.now()); + NewPage deletedPage = + validAppJson.getPageList().get(validAppJson.getPageList().size() - 1); + deletedPage.getUnpublishedPage().setDeletedAt(Instant.now()); - NewAction deletedAction = validAppJson.getActionList().get(validAppJson.getActionList().size() - 1); - deletedAction - .getUnpublishedAction() - .setDeletedAt(Instant.now()); + NewAction deletedAction = + validAppJson.getActionList().get(validAppJson.getActionList().size() - 1); + deletedAction.getUnpublishedAction().setDeletedAt(Instant.now()); - ActionCollection deletedCollection = validAppJson.getActionCollectionList().get(validAppJson.getActionCollectionList().size() - 1); - deletedCollection - .getUnpublishedCollection() - .setDeletedAt(Instant.now()); + ActionCollection deletedCollection = validAppJson + .getActionCollectionList() + .get(validAppJson.getActionCollectionList().size() - 1); + deletedCollection.getUnpublishedCollection().setDeletedAt(Instant.now()); ApplicationGitReference applicationGitReference = gitFileUtils.createApplicationReference(validAppJson); @@ -157,7 +155,8 @@ public void getSerializableResource_withDeletedEntities_excludeDeletedEntities() String[] names = entry.getKey().split(NAME_SEPARATOR); final String queryName = names[0].replace(".", "-"); assertThat(queryName).isNotEmpty(); - assertThat(deletedAction.getUnpublishedAction().getValidName().replace(".", "-")).isNotEqualTo(queryName); + assertThat(deletedAction.getUnpublishedAction().getValidName().replace(".", "-")) + .isNotEqualTo(queryName); } Map<String, Object> actionsCollections = applicationGitReference.getActionCollections(); @@ -183,13 +182,14 @@ public void getSerializableResource_withDeletedEntities_excludeDeletedEntities() public void saveApplicationToLocalRepo_allResourcesArePresent_removePublishedResources() { ApplicationJson validAppJson = createAppJson(filePath).block(); - Mockito.when(fileInterface.saveApplicationToGitRepo(Mockito.any(Path.class), Mockito.any(ApplicationGitReference.class), Mockito.anyString())) + Mockito.when(fileInterface.saveApplicationToGitRepo( + Mockito.any(Path.class), Mockito.any(ApplicationGitReference.class), Mockito.anyString())) .thenReturn(Mono.just(Path.of("orgId", "appId", "repoName"))); - Mono<Path> resultMono = gitFileUtils.saveApplicationToLocalRepo(Path.of("orgId/appId/repoName"), validAppJson, "gitFileTest"); + Mono<Path> resultMono = + gitFileUtils.saveApplicationToLocalRepo(Path.of("orgId/appId/repoName"), validAppJson, "gitFileTest"); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(path -> { validAppJson.getPageList().forEach(newPage -> { assertThat(newPage.getUnpublishedPage()).isNotNull(); @@ -235,16 +235,15 @@ public void reconstructApplicationFromLocalRepo_allResourcesArePresent_getCloned applicationReference.setActions(actionRef); applicationReference.setActionCollections(actionCollectionRef); - Mockito.when(fileInterface.reconstructApplicationReferenceFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(fileInterface.reconstructApplicationReferenceFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationReference)); - Mono<ApplicationJson> resultMono = gitFileUtils.reconstructApplicationJsonFromGitRepo( - "orgId", "appId", "repoName", "branch" - ) + Mono<ApplicationJson> resultMono = gitFileUtils + .reconstructApplicationJsonFromGitRepo("orgId", "appId", "repoName", "branch") .cache(); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(applicationJson1 -> { applicationJson1.getPageList().forEach(newPage -> { assertThat(newPage.getUnpublishedPage()).isNotNull(); @@ -254,7 +253,8 @@ public void reconstructApplicationFromLocalRepo_allResourcesArePresent_getCloned // Check if the published versions are deep copy of the unpublished version and updating any // will not affect the other - final String unpublishedName = newPage.getUnpublishedPage().getName(); + final String unpublishedName = + newPage.getUnpublishedPage().getName(); newPage.getUnpublishedPage().setName("updatedName"); assertThat(newPage.getPublishedPage().getName()).isEqualTo(unpublishedName); @@ -264,23 +264,26 @@ public void reconstructApplicationFromLocalRepo_allResourcesArePresent_getCloned assertThat(newAction.getUnpublishedAction()).isNotNull(); assertThat(newAction.getPublishedAction()).isNotEqualTo(newAction.getUnpublishedAction()); - final String unpublishedName = newAction.getUnpublishedAction().getName(); + final String unpublishedName = + newAction.getUnpublishedAction().getName(); newAction.getUnpublishedAction().setName("updatedName"); assertThat(newAction.getPublishedAction().getName()).isEqualTo(unpublishedName); assertThat(newAction.getUnpublishedAction().getName()).isNotEqualTo(unpublishedName); }); applicationJson1.getActionCollectionList().forEach(actionCollection -> { assertThat(actionCollection.getUnpublishedCollection()).isNotNull(); - assertThat(actionCollection.getPublishedCollection()).isNotEqualTo(actionCollection.getUnpublishedCollection()); + assertThat(actionCollection.getPublishedCollection()) + .isNotEqualTo(actionCollection.getUnpublishedCollection()); - final String unpublishedName = actionCollection.getUnpublishedCollection().getName(); + final String unpublishedName = + actionCollection.getUnpublishedCollection().getName(); actionCollection.getUnpublishedCollection().setName("updatedName"); - assertThat(actionCollection.getPublishedCollection().getName()).isEqualTo(unpublishedName); - assertThat(actionCollection.getUnpublishedCollection().getName()).isNotEqualTo(unpublishedName); + assertThat(actionCollection.getPublishedCollection().getName()) + .isEqualTo(unpublishedName); + assertThat(actionCollection.getUnpublishedCollection().getName()) + .isNotEqualTo(unpublishedName); }); }) .verifyComplete(); - } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitUtilsTest.java index e76ee3029b00..4e6c8b318bfb 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitUtilsTest.java @@ -17,15 +17,19 @@ public void convertSshUrlToBrowserSupportedUrl() { .isEqualTo("https://example.org/test/testRepo"); assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git")) .isEqualTo("https://example.in/test/testRepo"); - assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("ssh://[email protected]:user/test/tests/testRepo.git")) + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl( + "ssh://[email protected]:user/test/tests/testRepo.git")) .isEqualTo("https://example.test.net/user/test/tests/testRepo"); - assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:v3/sladeping/pyhe/SpaceJunk.git")) + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl( + "[email protected]:v3/sladeping/pyhe/SpaceJunk.git")) .isEqualTo("https://tim.tam.example.com/v3/sladeping/pyhe/SpaceJunk"); assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:v3/sladeping/pyhe/SpaceJunk")) .isEqualTo("https://tim.tam.example.com/v3/sladeping/pyhe/SpaceJunk"); - assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("ssh://[email protected]:v3/sladeping/pyhe/SpaceJunk.git")) + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl( + "ssh://[email protected]:v3/sladeping/pyhe/SpaceJunk.git")) .isEqualTo("https://tim.tam.example.com/v3/sladeping/pyhe/SpaceJunk"); - assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("ssh://[email protected]:v3/sladeping/pyhe/SpaceJunk")) + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl( + "ssh://[email protected]:v3/sladeping/pyhe/SpaceJunk")) .isEqualTo("https://tim.tam.example.com/v3/sladeping/pyhe/SpaceJunk"); assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/newRepo.git")) .isEqualTo("https://127.0.0.1/test/newRepo"); @@ -34,21 +38,20 @@ public void convertSshUrlToBrowserSupportedUrl() { @Test public void isRepoPrivate() { - StepVerifier - .create(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git"))) + StepVerifier.create(GitUtils.isRepoPrivate( + GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git"))) .assertNext(isRepoPrivate -> assertThat(isRepoPrivate).isEqualTo(Boolean.TRUE)) .verifyComplete(); - StepVerifier - .create(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("ssh://[email protected]:user/test/tests/testRepo.git"))) + StepVerifier.create(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl( + "ssh://[email protected]:user/test/tests/testRepo.git"))) .assertNext(isRepoPrivate -> assertThat(isRepoPrivate).isEqualTo(Boolean.TRUE)) .verifyComplete(); - StepVerifier - .create(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:appsmithorg/appsmith.git"))) + StepVerifier.create(GitUtils.isRepoPrivate( + GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:appsmithorg/appsmith.git"))) .assertNext(isRepoPrivate -> assertThat(isRepoPrivate).isEqualTo(Boolean.FALSE)) .verifyComplete(); - } @Test diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ImportExportUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ImportExportUtilsTest.java index bc09e50a0930..45003e0d8310 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ImportExportUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ImportExportUtilsTest.java @@ -10,7 +10,8 @@ class ImportExportUtilsTest { @Test void getErrorMessage_filterTransactionalError_returnEmptyString() { - Throwable throwable = new MongoTransactionException("Command failed with error 251 (NoSuchTransaction): 'Transaction 1 has been aborted."); + Throwable throwable = new MongoTransactionException( + "Command failed with error 251 (NoSuchTransaction): 'Transaction 1 has been aborted."); String errorMessage = ImportExportUtils.getErrorMessage(throwable); Assertions.assertEquals(errorMessage, ""); } @@ -21,4 +22,4 @@ void getErrorMessage_genericException_returnActualMessage() { String errorMessage = ImportExportUtils.getErrorMessage(throwable); Assertions.assertEquals(errorMessage, "Error: " + throwable.getMessage()); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/JacksonModelViewTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/JacksonModelViewTests.java index cb1c03871f4c..8168a4df5830 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/JacksonModelViewTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/JacksonModelViewTests.java @@ -50,12 +50,18 @@ public void test_withJsonView_measureSerializingPerformance() throws JsonProcess public void test_withJsonView_measureDeserializingPerformance() throws JsonProcessingException { // Warm up for (int i = 0; i < 1000000; i++) { - objectMapper.readerWithView(Views.Public.class).forType(TestModelJsonView.class).readValue(JSON_OUT); + objectMapper + .readerWithView(Views.Public.class) + .forType(TestModelJsonView.class) + .readValue(JSON_OUT); } // Measure long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { - objectMapper.readerWithView(Views.Public.class).forType(TestModelJsonView.class).readValue(JSON_OUT); + objectMapper + .readerWithView(Views.Public.class) + .forType(TestModelJsonView.class) + .readValue(JSON_OUT); } long end = System.currentTimeMillis(); log.info("test_withJsonView_measureDeserializingPerformance: {} ms for 1000000 iterations", end - start); @@ -93,22 +99,24 @@ public void test_withJsonIgnore_measureDeserializingPerformance() throws JsonPro } interface Views { - interface Public { - } + interface Public {} - interface Internal extends Public { - } + interface Internal extends Public {} } @Data public static class TestModelJsonIgnore { private String name = "name"; + @JsonIgnore private String password = "password"; + private String email = "email"; private String phone = "phone"; + @JsonIgnore private String address = "address"; + private String city = "city"; } @@ -116,14 +124,19 @@ public static class TestModelJsonIgnore { public static class TestModelJsonView { @JsonView(Views.Public.class) private String name = "name"; + @JsonView(Views.Internal.class) private String password = "password"; + @JsonView(Views.Public.class) private String email = "email"; + @JsonView(Views.Public.class) private String phone = "phone"; + @JsonView(Views.Internal.class) private String address = "address"; + @JsonView(Views.Public.class) private String city = "city"; } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/MockPluginExecutor.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/MockPluginExecutor.java index d204b0892fcb..75ec2bdc76d4 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/MockPluginExecutor.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/MockPluginExecutor.java @@ -15,7 +15,10 @@ public class MockPluginExecutor implements PluginExecutor { @Override - public Mono<ActionExecutionResult> execute(Object connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { + public Mono<ActionExecutionResult> execute( + Object connection, + DatasourceConfiguration datasourceConfiguration, + ActionConfiguration actionConfiguration) { if (actionConfiguration == null) { return Mono.error(new Exception("ActionConfiguration is null")); } @@ -36,8 +39,7 @@ public Mono<Object> datasourceCreate(DatasourceConfiguration datasourceConfigura } @Override - public void datasourceDestroy(Object connection) { - } + public void datasourceDestroy(Object connection) {} @Override public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) { @@ -50,8 +52,8 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasou } @Override - public Mono<TriggerResultDTO> trigger(Object connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) { + public Mono<TriggerResultDTO> trigger( + Object connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) { return Mono.empty(); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/NumberUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/NumberUtilsTest.java index 5be065dadd93..3d1376ec97fb 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/NumberUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/NumberUtilsTest.java @@ -13,4 +13,4 @@ public void parseInteger() { assertEquals(123, NumberUtils.parseInteger("abc", 0, 123)); assertEquals(123, NumberUtils.parseInteger("234.44", 0, 123)); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ResponseUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ResponseUtilsTest.java index 59a95d2ea4e5..2b531df77636 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ResponseUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ResponseUtilsTest.java @@ -30,11 +30,14 @@ @DirtiesContext public class ResponseUtilsTest { - private static final File mockObjects = new File("src/test/resources/test_assets/ResponseUtilsTest/mockObjects.json"); + private static final File mockObjects = + new File("src/test/resources/test_assets/ResponseUtilsTest/mockObjects.json"); private static final ObjectMapper objectMapper = new ObjectMapper(); private static JsonNode jsonNode; + @Autowired ResponseUtils responseUtils; + Gson gson = new Gson(); @SneakyThrows @@ -80,33 +83,54 @@ public void getAction_withDefaultIdsPresent_returnsUpdatedAction() { assertEquals(newActionCopy.getDefaultResources().getActionId(), newAction.getId()); assertEquals(newActionCopy.getDefaultResources().getApplicationId(), newAction.getApplicationId()); - assertEquals(newActionCopy.getUnpublishedAction().getDefaultResources().getPageId(), newAction.getUnpublishedAction().getPageId()); - assertEquals(newActionCopy.getUnpublishedAction().getDefaultResources().getCollectionId(), newAction.getUnpublishedAction().getCollectionId()); - - assertEquals(newActionCopy.getPublishedAction().getDefaultResources().getPageId(), newAction.getPublishedAction().getPageId()); - assertEquals(newActionCopy.getPublishedAction().getDefaultResources().getCollectionId(), newAction.getPublishedAction().getCollectionId()); + assertEquals( + newActionCopy.getUnpublishedAction().getDefaultResources().getPageId(), + newAction.getUnpublishedAction().getPageId()); + assertEquals( + newActionCopy.getUnpublishedAction().getDefaultResources().getCollectionId(), + newAction.getUnpublishedAction().getCollectionId()); + + assertEquals( + newActionCopy.getPublishedAction().getDefaultResources().getPageId(), + newAction.getPublishedAction().getPageId()); + assertEquals( + newActionCopy.getPublishedAction().getDefaultResources().getCollectionId(), + newAction.getPublishedAction().getCollectionId()); } @Test public void getActionCollection_whenDefaultIdsNull_returnsSameActionCollection() { - final ActionCollection actionCollection = objectMapper.convertValue(jsonNode.get("actionCollection"), ActionCollection.class); + final ActionCollection actionCollection = + objectMapper.convertValue(jsonNode.get("actionCollection"), ActionCollection.class); actionCollection.setDefaultResources(null); assertEquals(actionCollection, responseUtils.updateActionCollectionWithDefaultResources(actionCollection)); } @Test public void getActionCollection_withDefaultIdsPresent_returnsUpdatedActionCollection() { - ActionCollection actionCollection = gson.fromJson(String.valueOf(jsonNode.get("actionCollection")), ActionCollection.class); + ActionCollection actionCollection = + gson.fromJson(String.valueOf(jsonNode.get("actionCollection")), ActionCollection.class); final ActionCollection actionCollectionCopy = new ActionCollection(); AppsmithBeanUtils.copyNestedNonNullProperties(actionCollection, actionCollectionCopy); responseUtils.updateActionCollectionWithDefaultResources(actionCollection); assertNotEquals(actionCollectionCopy, actionCollection); assertEquals(actionCollectionCopy.getDefaultResources().getCollectionId(), actionCollection.getId()); - assertEquals(actionCollectionCopy.getDefaultResources().getApplicationId(), actionCollection.getApplicationId()); - - assertEquals(actionCollectionCopy.getUnpublishedCollection().getDefaultResources().getPageId(), actionCollection.getUnpublishedCollection().getPageId()); - assertEquals(actionCollectionCopy.getPublishedCollection().getDefaultResources().getPageId(), actionCollection.getPublishedCollection().getPageId()); + assertEquals( + actionCollectionCopy.getDefaultResources().getApplicationId(), actionCollection.getApplicationId()); + + assertEquals( + actionCollectionCopy + .getUnpublishedCollection() + .getDefaultResources() + .getPageId(), + actionCollection.getUnpublishedCollection().getPageId()); + assertEquals( + actionCollectionCopy + .getPublishedCollection() + .getDefaultResources() + .getPageId(), + actionCollection.getPublishedCollection().getPageId()); } @Test @@ -116,7 +140,8 @@ public void getApplication_withDefaultIdsPresent_returnsUpdatedApplication() { final Application applicationCopy = new Application(); AppsmithBeanUtils.copyNestedNonNullProperties(application, applicationCopy); - // Check if the id and defaultPage ids for pages are not same before we update the application using responseUtils + // Check if the id and defaultPage ids for pages are not same before we update the application using + // responseUtils for (ApplicationPage applicationPage : application.getPages()) { assertNotEquals(applicationPage.getId(), applicationPage.getDefaultPageId()); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/TextUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/TextUtilsTest.java index 5d75c4821bf7..602fd65a6b8b 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/TextUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/TextUtilsTest.java @@ -49,4 +49,4 @@ public void csvToSet() { checkFromCsv("", 0); checkFromCsv(null, 0); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ValidationUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ValidationUtilsTest.java index 22f86039c9a3..afc6883da3b9 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ValidationUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ValidationUtilsTest.java @@ -12,18 +12,27 @@ public void validateEmailCsv() { assertThat(ValidationUtils.validateEmailCsv(null)).isFalse(); assertThat(ValidationUtils.validateEmailCsv(" ")).isFalse(); assertThat(ValidationUtils.validateEmailCsv("[email protected]")).isTrue(); - assertThat(ValidationUtils.validateEmailCsv("[email protected],[email protected]")).isTrue(); - assertThat(ValidationUtils.validateEmailCsv("[email protected], [email protected]")).isTrue(); - assertThat(ValidationUtils.validateEmailCsv("[email protected] , [email protected]")).isTrue(); - assertThat(ValidationUtils.validateEmailCsv("[email protected] , [email protected]")).isTrue(); - assertThat(ValidationUtils.validateEmailCsv("[email protected] , [email protected] ,[email protected]")).isTrue(); - assertThat(ValidationUtils.validateEmailCsv(" [email protected] , [email protected] ")).isTrue(); + assertThat(ValidationUtils.validateEmailCsv("[email protected],[email protected]")) + .isTrue(); + assertThat(ValidationUtils.validateEmailCsv("[email protected], [email protected]")) + .isTrue(); + assertThat(ValidationUtils.validateEmailCsv("[email protected] , [email protected]")) + .isTrue(); + assertThat(ValidationUtils.validateEmailCsv("[email protected] , [email protected]")) + .isTrue(); + assertThat(ValidationUtils.validateEmailCsv("[email protected] , [email protected] ,[email protected]")) + .isTrue(); + assertThat(ValidationUtils.validateEmailCsv(" [email protected] , [email protected] ")) + .isTrue(); - assertThat(ValidationUtils.validateEmailCsv("[email protected],[email protected],xyz")).isFalse(); - assertThat(ValidationUtils.validateEmailCsv("[email protected],[email protected],,")).isFalse(); - assertThat(ValidationUtils.validateEmailCsv("[email protected],[email protected], ")).isFalse(); + assertThat(ValidationUtils.validateEmailCsv("[email protected],[email protected],xyz")) + .isFalse(); + assertThat(ValidationUtils.validateEmailCsv("[email protected],[email protected],,")) + .isFalse(); + assertThat(ValidationUtils.validateEmailCsv("[email protected],[email protected], ")) + .isFalse(); assertThat(ValidationUtils.validateEmailCsv(",,")).isFalse(); assertThat(ValidationUtils.validateEmailCsv(",")).isFalse(); assertThat(ValidationUtils.validateEmailCsv("[email protected],,")).isFalse(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ce/ImportApplicationPermissionProviderTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ce/ImportApplicationPermissionProviderTest.java index cfbb5b37e83e..91d45d8923d4 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ce/ImportApplicationPermissionProviderTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ce/ImportApplicationPermissionProviderTest.java @@ -41,9 +41,14 @@ class ImportApplicationPermissionProviderTest { @Test public void testCheckPermissionMethods_WhenNoPermissionProvided_ReturnsTrue() { - ImportApplicationPermissionProvider importApplicationPermissionProvider = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) - .build(); + ImportApplicationPermissionProvider importApplicationPermissionProvider = + ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) + .build(); assertTrue(importApplicationPermissionProvider.hasEditPermission(new NewPage())); assertTrue(importApplicationPermissionProvider.hasEditPermission(new NewAction())); @@ -66,12 +71,13 @@ public void tesHasEditPermissionOnDomains_WhenPermissionGroupDoesNotMatch_Return domainAndPermissionList.add(Tuples.of(new ActionCollection(), actionPermission)); domainAndPermissionList.add(Tuples.of(new Datasource(), datasourcePermission)); - for(Tuple2<BaseDomain, DomainPermission> domainAndPermission : domainAndPermissionList) { + for (Tuple2<BaseDomain, DomainPermission> domainAndPermission : domainAndPermissionList) { BaseDomain domain = domainAndPermission.getT1(); // create a permission provider that sets edit permission on the domain - ImportApplicationPermissionProvider provider = createPermissionProviderForDomainEditPermission(domain, domainAndPermission.getT2()); + ImportApplicationPermissionProvider provider = + createPermissionProviderForDomainEditPermission(domain, domainAndPermission.getT2()); - if(domain instanceof NewPage) { + if (domain instanceof NewPage) { assertFalse(provider.hasEditPermission((NewPage) domain)); } else if (domain instanceof NewAction) { assertFalse(provider.hasEditPermission((NewAction) domain)); @@ -92,12 +98,13 @@ public void tesHasCreatePermissionOnDomains_WhenPermissionGroupDoesNotMatch_Retu domainAndPermissionList.add(Tuples.of(new NewPage(), pagePermission.getActionCreatePermission())); domainAndPermissionList.add(Tuples.of(new Workspace(), workspacePermission.getDatasourceCreatePermission())); - for(Tuple2<BaseDomain, AclPermission> domainAndPermission : domainAndPermissionList) { + for (Tuple2<BaseDomain, AclPermission> domainAndPermission : domainAndPermissionList) { BaseDomain domain = domainAndPermission.getT1(); // create a permission provider that sets edit permission on the domain - ImportApplicationPermissionProvider provider = createPermissionProviderForDomainCreatePermission(domain, domainAndPermission.getT2()); + ImportApplicationPermissionProvider provider = + createPermissionProviderForDomainCreatePermission(domain, domainAndPermission.getT2()); - if(domain instanceof Application) { + if (domain instanceof Application) { assertFalse(provider.canCreatePage((Application) domain)); } else if (domain instanceof NewPage) { assertFalse(provider.canCreateAction((NewPage) domain)); @@ -109,16 +116,18 @@ public void tesHasCreatePermissionOnDomains_WhenPermissionGroupDoesNotMatch_Retu @Test public void tesBuilderIsSettingTheCorrectParametersToPermissionProvider() { - ImportApplicationPermissionProvider.Builder builder = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission); + ImportApplicationPermissionProvider.Builder builder = ImportApplicationPermissionProvider.builder( + applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission); assertThat(builder.requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) - .build().getRequiredPermissionOnTargetApplication() - ).isEqualTo(applicationPermission.getEditPermission()); + .build() + .getRequiredPermissionOnTargetApplication()) + .isEqualTo(applicationPermission.getEditPermission()); assertThat(builder.requiredPermissionOnTargetWorkspace(workspacePermission.getReadPermission()) - .build().getRequiredPermissionOnTargetWorkspace() - ).isEqualTo(workspacePermission.getReadPermission()); + .build() + .getRequiredPermissionOnTargetWorkspace()) + .isEqualTo(workspacePermission.getReadPermission()); assertTrue(builder.permissionRequiredToCreateDatasource(true).build().isPermissionRequiredToCreateDatasource()); assertTrue(builder.permissionRequiredToCreatePage(true).build().isPermissionRequiredToCreatePage()); @@ -131,8 +140,12 @@ public void tesBuilderIsSettingTheCorrectParametersToPermissionProvider() { @Test public void testAllPermissionsRequiredIsSettingAllPermissionsAsRequired() { - ImportApplicationPermissionProvider provider = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) + ImportApplicationPermissionProvider provider = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) .allPermissionsRequired() .build(); @@ -156,18 +169,23 @@ public void testAllPermissionsRequiredIsSettingAllPermissionsAsRequired() { * @param domainPermission * @return */ - private ImportApplicationPermissionProvider createPermissionProviderForDomainEditPermission(BaseDomain baseDomain, DomainPermission domainPermission) { + private ImportApplicationPermissionProvider createPermissionProviderForDomainEditPermission( + BaseDomain baseDomain, DomainPermission domainPermission) { setPoliciesToDomain(baseDomain, domainPermission.getEditPermission()); - ImportApplicationPermissionProvider.Builder builder = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) + ImportApplicationPermissionProvider.Builder builder = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) .currentUserPermissionGroups(Set.of()); - if(baseDomain instanceof NewPage) { + if (baseDomain instanceof NewPage) { builder.permissionRequiredToEditPage(true); - } else if(baseDomain instanceof NewAction) { + } else if (baseDomain instanceof NewAction) { builder.permissionRequiredToEditAction(true); - } else if(baseDomain instanceof Datasource) { + } else if (baseDomain instanceof Datasource) { builder.permissionRequiredToEditDatasource(true); } return builder.build(); @@ -185,18 +203,23 @@ private ImportApplicationPermissionProvider createPermissionProviderForDomainEdi * @param permission * @return */ - private ImportApplicationPermissionProvider createPermissionProviderForDomainCreatePermission(BaseDomain baseDomain, AclPermission permission) { + private ImportApplicationPermissionProvider createPermissionProviderForDomainCreatePermission( + BaseDomain baseDomain, AclPermission permission) { setPoliciesToDomain(baseDomain, permission); - ImportApplicationPermissionProvider.Builder builder = ImportApplicationPermissionProvider - .builder(applicationPermission, pagePermission, actionPermission, datasourcePermission, workspacePermission) + ImportApplicationPermissionProvider.Builder builder = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) .currentUserPermissionGroups(Set.of()); - if(baseDomain instanceof Application) { + if (baseDomain instanceof Application) { builder.permissionRequiredToCreatePage(true); - } else if(baseDomain instanceof NewPage) { + } else if (baseDomain instanceof NewPage) { builder.permissionRequiredToCreateAction(true); - } else if(baseDomain instanceof Workspace) { + } else if (baseDomain instanceof Workspace) { builder.permissionRequiredToCreateDatasource(true); } return builder.build(); @@ -212,4 +235,4 @@ private void setPoliciesToDomain(BaseDomain baseDomain, AclPermission aclPermiss Set<Policy> policies = Set.of(policy); baseDomain.setPolicies(policies); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/notifications/EmailSenderTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/notifications/EmailSenderTest.java index 9a63148e6f8a..cf30e214a1fa 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/notifications/EmailSenderTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/notifications/EmailSenderTest.java @@ -23,8 +23,7 @@ @ExtendWith(SpringExtension.class) @SpringBootTest @DirtiesContext -@TestPropertySource( - properties = {"management.health.mail.enabled=false"}) +@TestPropertySource(properties = {"management.health.mail.enabled=false"}) public class EmailSenderTest { @MockBean private JavaMailSender javaMailSender; @@ -52,12 +51,17 @@ public void itShouldNotSendMailsWithInvalidAddresses() { "[email protected] (Joe Smith)", "[email protected]", "[email protected]", - "[email protected]" - ); + "[email protected]"); for (String invalidAddress : invalidAddresses) { try { - emailSender.sendMail(invalidAddress, "test-subject", "email/welcomeUserTemplate.html", Collections.emptyMap()).block(); + emailSender + .sendMail( + invalidAddress, + "test-subject", + "email/welcomeUserTemplate.html", + Collections.emptyMap()) + .block(); verifyNoInteractions(javaMailSender); } catch (Throwable exc) { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ApplicationSnapshotRepositoryTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ApplicationSnapshotRepositoryTest.java index 6950e84bb19a..fc2ebf225e6f 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ApplicationSnapshotRepositoryTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ApplicationSnapshotRepositoryTest.java @@ -15,7 +15,6 @@ import static org.assertj.core.api.Assertions.assertThat; - @SpringBootTest public class ApplicationSnapshotRepositoryTest { @Autowired @@ -39,14 +38,17 @@ public void findWithoutData_WhenMatched_ReturnsMatchedDocumentWithoutData() { snapshot2.setApplicationId(testAppId2); snapshot2.setChunkOrder(1); - Mono<ApplicationSnapshot> snapshotMono = applicationSnapshotRepository.saveAll(List.of(snapshot1, snapshot2)) + Mono<ApplicationSnapshot> snapshotMono = applicationSnapshotRepository + .saveAll(List.of(snapshot1, snapshot2)) .then(applicationSnapshotRepository.findWithoutData(testAppId2)); - StepVerifier.create(snapshotMono).assertNext(applicationSnapshot -> { - assertThat(applicationSnapshot.getApplicationId()).isEqualTo(testAppId2); - assertThat(applicationSnapshot.getData()).isNull(); - assertThat(applicationSnapshot.getChunkOrder()).isEqualTo(1); - }).verifyComplete(); + StepVerifier.create(snapshotMono) + .assertNext(applicationSnapshot -> { + assertThat(applicationSnapshot.getApplicationId()).isEqualTo(testAppId2); + assertThat(applicationSnapshot.getData()).isNull(); + assertThat(applicationSnapshot.getChunkOrder()).isEqualTo(1); + }) + .verifyComplete(); } @Test @@ -63,13 +65,16 @@ public void findWithoutData_WhenMultipleChunksArePresent_ReturnsSingleOne() { snapshot2.setApplicationId(testAppId1); snapshot2.setChunkOrder(2); - Mono<ApplicationSnapshot> snapshotMono = applicationSnapshotRepository.saveAll(List.of(snapshot1, snapshot2)) + Mono<ApplicationSnapshot> snapshotMono = applicationSnapshotRepository + .saveAll(List.of(snapshot1, snapshot2)) .then(applicationSnapshotRepository.findWithoutData(testAppId1)); - StepVerifier.create(snapshotMono).assertNext(applicationSnapshot -> { - assertThat(applicationSnapshot.getApplicationId()).isEqualTo(testAppId1); - assertThat(applicationSnapshot.getChunkOrder()).isEqualTo(1); - }).verifyComplete(); + StepVerifier.create(snapshotMono) + .assertNext(applicationSnapshot -> { + assertThat(applicationSnapshot.getApplicationId()).isEqualTo(testAppId1); + assertThat(applicationSnapshot.getChunkOrder()).isEqualTo(1); + }) + .verifyComplete(); } @Test @@ -91,12 +96,12 @@ public void deleteAllByApplicationId_WhenMatched_ReturnsMatchedDocumentWithoutDa snapshot3.setApplicationId(testAppId2); snapshot3.setChunkOrder(1); - Flux<ApplicationSnapshot> applicationSnapshots = applicationSnapshotRepository.saveAll(List.of(snapshot1, snapshot2, snapshot3)) + Flux<ApplicationSnapshot> applicationSnapshots = applicationSnapshotRepository + .saveAll(List.of(snapshot1, snapshot2, snapshot3)) .then(applicationSnapshotRepository.deleteAllByApplicationId(testAppId1)) .thenMany(applicationSnapshotRepository.findByApplicationId(testAppId1)); - StepVerifier.create(applicationSnapshots) - .verifyComplete(); + StepVerifier.create(applicationSnapshots).verifyComplete(); StepVerifier.create(applicationSnapshotRepository.findByApplicationId(testAppId2)) .assertNext(applicationSnapshot -> { @@ -125,7 +130,8 @@ public void findByApplicationId_WhenMatched_ReturnsMatchedDocumentWithoutData() snapshot3.setApplicationId(testAppId2); snapshot3.setChunkOrder(1); - Flux<ApplicationSnapshot> applicationSnapshots = applicationSnapshotRepository.saveAll(List.of(snapshot1, snapshot2, snapshot3)) + Flux<ApplicationSnapshot> applicationSnapshots = applicationSnapshotRepository + .saveAll(List.of(snapshot1, snapshot2, snapshot3)) .thenMany(applicationSnapshotRepository.findByApplicationId(testAppId1)); StepVerifier.create(applicationSnapshots) @@ -137,4 +143,4 @@ public void findByApplicationId_WhenMatched_ReturnsMatchedDocumentWithoutData() }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CacheableRepositoryTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CacheableRepositoryTest.java index 051af638c6b6..c6f8fc4bc178 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CacheableRepositoryTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CacheableRepositoryTest.java @@ -35,7 +35,6 @@ public class CacheableRepositoryTest { @Autowired UserRepository userRepository; - @Test @WithUserDetails(value = "api_user") public void getUserPermissionsTest_onPermissionGroupDelete_valid() { @@ -46,8 +45,14 @@ public void getUserPermissionsTest_onPermissionGroupDelete_valid() { workspace.setName("getUserPermissionsTest_onPermissionGroupDelete_valid Workspace"); Workspace createdWorkspace = workspaceService.create(workspace).block(); - List<PermissionGroup> defaultPermissionGroups = permissionGroupRepository.findAllById(createdWorkspace.getDefaultPermissionGroups()).collectList().block(); - PermissionGroup adminPg = defaultPermissionGroups.stream().filter(pg -> pg.getName().startsWith(ADMINISTRATOR)).findFirst().get(); + List<PermissionGroup> defaultPermissionGroups = permissionGroupRepository + .findAllById(createdWorkspace.getDefaultPermissionGroups()) + .collectList() + .block(); + PermissionGroup adminPg = defaultPermissionGroups.stream() + .filter(pg -> pg.getName().startsWith(ADMINISTRATOR)) + .findFirst() + .get(); Mono<Set<String>> permissionGroupsOfUserMono = cacheableRepositoryHelper.getPermissionGroupsOfUser(api_user); @@ -61,7 +66,8 @@ public void getUserPermissionsTest_onPermissionGroupDelete_valid() { // Now delete the workspace and assert that user permission groups does not contain the admin pg workspaceService.archiveById(createdWorkspace.getId()).block(); - Set<String> userPermissionGroupsPostWorkspaceDelete = cacheableRepositoryHelper.getPermissionGroupsOfUser(api_user).block(); + Set<String> userPermissionGroupsPostWorkspaceDelete = + cacheableRepositoryHelper.getPermissionGroupsOfUser(api_user).block(); assertThat(userPermissionGroupsPostWorkspaceDelete).doesNotContain(adminPg.getId()); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomApplicationRepositoryImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomApplicationRepositoryImplTest.java index db933bd0625c..c38df6e05c09 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomApplicationRepositoryImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomApplicationRepositoryImplTest.java @@ -32,20 +32,25 @@ public void getAllApplicationId_WhenDataExists_ReturnsList() { application2.setWorkspaceId(randomWorkspaceId); application2.setName("my another test app"); - Mono<List<String>> appIds = applicationRepository.saveAll(List.of(application1, application2)) + Mono<List<String>> appIds = applicationRepository + .saveAll(List.of(application1, application2)) .then(applicationRepository.getAllApplicationId(randomWorkspaceId)); - StepVerifier.create(appIds).assertNext(strings -> { - assertThat(strings.size()).isEqualTo(2); - }).verifyComplete(); + StepVerifier.create(appIds) + .assertNext(strings -> { + assertThat(strings.size()).isEqualTo(2); + }) + .verifyComplete(); } @Test public void getAllApplicationId_WhenNoneExists_ReturnsEmptyList() { String randomWorkspaceId = UUID.randomUUID().toString(); Mono<List<String>> appIds = applicationRepository.getAllApplicationId(randomWorkspaceId); - StepVerifier.create(appIds).assertNext(strings -> { - assertThat(CollectionUtils.isEmpty(strings)).isTrue(); - }).verifyComplete(); + StepVerifier.create(appIds) + .assertNext(strings -> { + assertThat(CollectionUtils.isEmpty(strings)).isTrue(); + }) + .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomNotificationRepositoryImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomNotificationRepositoryImplTest.java index ebce79adb3bd..e4257f87f6b0 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomNotificationRepositoryImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomNotificationRepositoryImplTest.java @@ -19,7 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - @ExtendWith(SpringExtension.class) @SpringBootTest @Slf4j @@ -46,27 +45,32 @@ public void updateIsReadByForUsernameAndIdList_WhenUsernameNotMatched_UpdatesNon Mono<Notification> saveMono2 = notificationRepository.save(createNotification("efg", false)); // create the notifications and then try to update them by different username - Mono<Tuple2<Notification, Notification>> tuple2Mono = Mono.zip(saveMono1, saveMono2).flatMap(objects -> { - Notification n1 = objects.getT1(); - Notification n2 = objects.getT2(); - return notificationRepository.updateIsReadByForUsernameAndIdList( - "123", List.of(n1.getId(), n2.getId()), true - ).thenReturn(objects); - }); + Mono<Tuple2<Notification, Notification>> tuple2Mono = Mono.zip(saveMono1, saveMono2) + .flatMap(objects -> { + Notification n1 = objects.getT1(); + Notification n2 = objects.getT2(); + return notificationRepository + .updateIsReadByForUsernameAndIdList("123", List.of(n1.getId(), n2.getId()), true) + .thenReturn(objects); + }); // now get the notifications we created Mono<List<Notification>> listMono = tuple2Mono.flatMap(objects -> { Notification n1 = objects.getT1(); Notification n2 = objects.getT2(); - return notificationRepository.findAllById(List.of(n1.getId(), n2.getId())).collectList(); + return notificationRepository + .findAllById(List.of(n1.getId(), n2.getId())) + .collectList(); }); // check that fetched notifications have isRead=false - StepVerifier.create(listMono).assertNext(notifications -> { - assertEquals(2, notifications.size()); - assertEquals(false, notifications.get(0).getIsRead()); - assertEquals(false, notifications.get(1).getIsRead()); - }).verifyComplete(); + StepVerifier.create(listMono) + .assertNext(notifications -> { + assertEquals(2, notifications.size()); + assertEquals(false, notifications.get(0).getIsRead()); + assertEquals(false, notifications.get(1).getIsRead()); + }) + .verifyComplete(); } @Test @@ -75,27 +79,32 @@ public void updateIsReadByForUsernameAndIdList_WhenUsernameMatched_Updated() { Mono<Notification> saveMono2 = notificationRepository.save(createNotification("abc", false)); // create the notifications and then try to update them by same username - Mono<Tuple2<Notification, Notification>> tuple2Mono = Mono.zip(saveMono1, saveMono2).flatMap(objects -> { - Notification n1 = objects.getT1(); - Notification n2 = objects.getT2(); - return notificationRepository.updateIsReadByForUsernameAndIdList( - "abc", List.of(n1.getId(), n2.getId()), true - ).thenReturn(objects); - }); + Mono<Tuple2<Notification, Notification>> tuple2Mono = Mono.zip(saveMono1, saveMono2) + .flatMap(objects -> { + Notification n1 = objects.getT1(); + Notification n2 = objects.getT2(); + return notificationRepository + .updateIsReadByForUsernameAndIdList("abc", List.of(n1.getId(), n2.getId()), true) + .thenReturn(objects); + }); // now get the notifications we created Mono<List<Notification>> listMono = tuple2Mono.flatMap(objects -> { Notification n1 = objects.getT1(); Notification n2 = objects.getT2(); - return notificationRepository.findAllById(List.of(n1.getId(), n2.getId())).collectList(); + return notificationRepository + .findAllById(List.of(n1.getId(), n2.getId())) + .collectList(); }); // check that fetched notifications have isRead=true - StepVerifier.create(listMono).assertNext(notifications -> { - assertEquals(2, notifications.size()); - assertEquals(true, notifications.get(0).getIsRead()); - assertEquals(true, notifications.get(1).getIsRead()); - }).verifyComplete(); + StepVerifier.create(listMono) + .assertNext(notifications -> { + assertEquals(2, notifications.size()); + assertEquals(true, notifications.get(0).getIsRead()); + assertEquals(true, notifications.get(1).getIsRead()); + }) + .verifyComplete(); } @Test @@ -104,27 +113,32 @@ public void updateIsReadByForUsernameAndIdList_WhenIdNotMatched_UpdatesNone() { Mono<Notification> saveMono2 = notificationRepository.save(createNotification("abc", false)); // create the notifications and then try to update them by different username - Mono<Tuple2<Notification, Notification>> tuple2Mono = Mono.zip(saveMono1, saveMono2).flatMap(objects -> { - Notification n1 = objects.getT1(); - Notification n2 = objects.getT2(); - return notificationRepository.updateIsReadByForUsernameAndIdList( - "abc", List.of("test-id-1", "test-id-2"), true - ).thenReturn(objects); - }); + Mono<Tuple2<Notification, Notification>> tuple2Mono = Mono.zip(saveMono1, saveMono2) + .flatMap(objects -> { + Notification n1 = objects.getT1(); + Notification n2 = objects.getT2(); + return notificationRepository + .updateIsReadByForUsernameAndIdList("abc", List.of("test-id-1", "test-id-2"), true) + .thenReturn(objects); + }); // now get the notifications we created Mono<List<Notification>> listMono = tuple2Mono.flatMap(objects -> { Notification n1 = objects.getT1(); Notification n2 = objects.getT2(); - return notificationRepository.findAllById(List.of(n1.getId(), n2.getId())).collectList(); + return notificationRepository + .findAllById(List.of(n1.getId(), n2.getId())) + .collectList(); }); // check that fetched notifications have isRead=true - StepVerifier.create(listMono).assertNext(notifications -> { - assertEquals(2, notifications.size()); - assertEquals(false, notifications.get(0).getIsRead()); - assertEquals(false, notifications.get(1).getIsRead()); - }).verifyComplete(); + StepVerifier.create(listMono) + .assertNext(notifications -> { + assertEquals(2, notifications.size()); + assertEquals(false, notifications.get(0).getIsRead()); + assertEquals(false, notifications.get(1).getIsRead()); + }) + .verifyComplete(); } @Test @@ -134,32 +148,34 @@ public void updateIsReadByForUsername_WhenForUsernameMatched_UpdatesMatchedOnes( Mono<Notification> saveMono3 = notificationRepository.save(createNotification("efg", false)); // create the notifications and then try to update them by same username - Mono<Tuple3<Notification, Notification, Notification>> tuple2Mono = Mono.zip( - saveMono1, saveMono2, saveMono3 - ).flatMap(objects -> - notificationRepository.updateIsReadByForUsername("abc", true).thenReturn(objects) - ); + Mono<Tuple3<Notification, Notification, Notification>> tuple2Mono = Mono.zip(saveMono1, saveMono2, saveMono3) + .flatMap(objects -> notificationRepository + .updateIsReadByForUsername("abc", true) + .thenReturn(objects)); // now get the notifications we created Mono<Map<String, Collection<Notification>>> mapMono = tuple2Mono.flatMap(objects -> { Notification n1 = objects.getT1(); Notification n2 = objects.getT2(); Notification n3 = objects.getT3(); - return notificationRepository.findAllById( - List.of(n1.getId(), n2.getId(), n3.getId()) - ).collectMultimap(Notification::getForUsername); + return notificationRepository + .findAllById(List.of(n1.getId(), n2.getId(), n3.getId())) + .collectMultimap(Notification::getForUsername); }); // check that fetched notifications have isRead=true - StepVerifier.create(mapMono).assertNext(notificationCollectionMap -> { - assertEquals(2, notificationCollectionMap.size()); // should contain map of two keys - - Notification forEfg = notificationCollectionMap.get("efg").iterator().next(); - assertEquals(false, forEfg.getIsRead()); // this should be still unread - - notificationCollectionMap.get("abc").iterator().forEachRemaining(notification -> { - assertEquals(true, notification.getIsRead()); - }); - }).verifyComplete(); + StepVerifier.create(mapMono) + .assertNext(notificationCollectionMap -> { + assertEquals(2, notificationCollectionMap.size()); // should contain map of two keys + + Notification forEfg = + notificationCollectionMap.get("efg").iterator().next(); + assertEquals(false, forEfg.getIsRead()); // this should be still unread + + notificationCollectionMap.get("abc").iterator().forEachRemaining(notification -> { + assertEquals(true, notification.getIsRead()); + }); + }) + .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomPluginRepositoryTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomPluginRepositoryTest.java index d23ca6dc4c90..be30479fa492 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomPluginRepositoryTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomPluginRepositoryTest.java @@ -30,13 +30,16 @@ public void findDefaultPluginIcons_WhenResultFound_OnlyDefaultInstallPluginsRetu plugin.setDefaultInstall(false); plugin.setName("My Plugin"); - Mono<List<Plugin>> pluginListMono = pluginRepository.save(plugin).then( - pluginRepository.findDefaultPluginIcons().collectList() - ); - StepVerifier.create(pluginListMono).assertNext(plugins -> { - Optional<Plugin> createdPlugin = plugins.stream().filter(p -> p.getPackageName().equals(randomPackageId)) - .findAny(); - assertThat(createdPlugin.isPresent()).isFalse(); - }).verifyComplete(); + Mono<List<Plugin>> pluginListMono = pluginRepository + .save(plugin) + .then(pluginRepository.findDefaultPluginIcons().collectList()); + StepVerifier.create(pluginListMono) + .assertNext(plugins -> { + Optional<Plugin> createdPlugin = plugins.stream() + .filter(p -> p.getPackageName().equals(randomPackageId)) + .findAny(); + assertThat(createdPlugin.isPresent()).isFalse(); + }) + .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomUserDataRepositoryTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomUserDataRepositoryTest.java index 8a9933be18ec..bd7a7047fc31 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomUserDataRepositoryTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomUserDataRepositoryTest.java @@ -19,7 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; - @ExtendWith(SpringExtension.class) @SpringBootTest @Slf4j @@ -31,7 +30,8 @@ public class CustomUserDataRepositoryTest { private Mono<UserData> createUser(String userId, List<String> workspaceIds, List<String> appIds) { return userDataRepository .findByUserId(userId) - .defaultIfEmpty(new UserData()).flatMap(userData -> { + .defaultIfEmpty(new UserData()) + .flatMap(userData -> { userData.setUserId(userId); userData.setRecentlyUsedWorkspaceIds(workspaceIds); userData.setRecentlyUsedAppIds(appIds); @@ -47,9 +47,7 @@ public void removeIdFromRecentlyUsedList_WhenWorkspaceIdAlreadyExists_WorkspaceI // remove the 345 org id from the recently used workspaceId list Mono<UpdateResult> updateResultMono = createUserDataMono.flatMap( - userData -> userDataRepository.removeIdFromRecentlyUsedList( - userData.getUserId(), "345", List.of()) - ); + userData -> userDataRepository.removeIdFromRecentlyUsedList(userData.getUserId(), "345", List.of())); // read the userdata Mono<UserData> readUserDataMono = userDataRepository.findByUserId(sampleUserId); @@ -57,10 +55,14 @@ public void removeIdFromRecentlyUsedList_WhenWorkspaceIdAlreadyExists_WorkspaceI // add the read user data mono after the update mono Mono<UserData> userDataAfterUpdateMono = updateResultMono.then(readUserDataMono); - StepVerifier.create(userDataAfterUpdateMono).assertNext(userData -> { - assertEquals(2, userData.getRecentlyUsedWorkspaceIds().size()); - assertArrayEquals(List.of("123", "234").toArray(), userData.getRecentlyUsedWorkspaceIds().toArray()); - }).verifyComplete(); + StepVerifier.create(userDataAfterUpdateMono) + .assertNext(userData -> { + assertEquals(2, userData.getRecentlyUsedWorkspaceIds().size()); + assertArrayEquals( + List.of("123", "234").toArray(), + userData.getRecentlyUsedWorkspaceIds().toArray()); + }) + .verifyComplete(); } @Test @@ -71,10 +73,7 @@ public void removeIdFromRecentlyUsedList_WhenWorkspaceIdDoesNotExist_NothingRemo // remove the 345 org id from the recently used workspaceId list Mono<UpdateResult> updateResultMono = createUserDataMono.flatMap( - userData -> userDataRepository.removeIdFromRecentlyUsedList( - userData.getUserId(), "678", List.of() - ) - ); + userData -> userDataRepository.removeIdFromRecentlyUsedList(userData.getUserId(), "678", List.of())); // read the userdata Mono<UserData> readUserDataMono = userDataRepository.findByUserId(sampleUserId); @@ -82,10 +81,14 @@ public void removeIdFromRecentlyUsedList_WhenWorkspaceIdDoesNotExist_NothingRemo // add the read user data mono after the update mono Mono<UserData> userDataAfterUpdateMono = updateResultMono.then(readUserDataMono); - StepVerifier.create(userDataAfterUpdateMono).assertNext(userData -> { - assertEquals(3, userData.getRecentlyUsedWorkspaceIds().size()); - assertArrayEquals(List.of("123", "234", "345").toArray(), userData.getRecentlyUsedWorkspaceIds().toArray()); - }).verifyComplete(); + StepVerifier.create(userDataAfterUpdateMono) + .assertNext(userData -> { + assertEquals(3, userData.getRecentlyUsedWorkspaceIds().size()); + assertArrayEquals( + List.of("123", "234", "345").toArray(), + userData.getRecentlyUsedWorkspaceIds().toArray()); + }) + .verifyComplete(); } @Test @@ -99,7 +102,7 @@ public void removeIdFromRecentlyUsedList_WhenAppIdExists_AppIdRemoved() { // workspaceId does not matter userData -> userDataRepository.removeIdFromRecentlyUsedList( userData.getUserId(), "345", List.of("123", "789")) // remove 123 and 789 - ); + ); // read the userdata Mono<UserData> readUserDataMono = userDataRepository.findByUserId(sampleUserId); @@ -107,27 +110,28 @@ public void removeIdFromRecentlyUsedList_WhenAppIdExists_AppIdRemoved() { // add the read user data mono after the update mono Mono<UserData> userDataAfterUpdateMono = updateResultMono.then(readUserDataMono); - StepVerifier.create(userDataAfterUpdateMono).assertNext(userData -> { - List<String> recentlyUsedAppIds = userData.getRecentlyUsedAppIds(); - assertThat(recentlyUsedAppIds.size()).isEqualTo(1); - assertThat(recentlyUsedAppIds.get(0)).isEqualTo("456"); - }).verifyComplete(); + StepVerifier.create(userDataAfterUpdateMono) + .assertNext(userData -> { + List<String> recentlyUsedAppIds = userData.getRecentlyUsedAppIds(); + assertThat(recentlyUsedAppIds.size()).isEqualTo(1); + assertThat(recentlyUsedAppIds.get(0)).isEqualTo("456"); + }) + .verifyComplete(); } @Test public void removeIdFromRecentlyUsedList_WhenWorkspaceIdAndAppIdExists_BothAreRemoved() { // create a user data with 3 app id in the recently used appId list String sampleUserId = "abcd"; - Mono<UserData> createUserDataMono = createUser( - sampleUserId, List.of("abc", "efg", "hij"), List.of("123", "456", "789") - ); + Mono<UserData> createUserDataMono = + createUser(sampleUserId, List.of("abc", "efg", "hij"), List.of("123", "456", "789")); // remove the 345 org id from the recently used workspaceId list Mono<UpdateResult> updateResultMono = createUserDataMono.flatMap( // workspaceId does not matter userData -> userDataRepository.removeIdFromRecentlyUsedList( userData.getUserId(), "efg", List.of("123", "789")) // remove 123 and 789 - ); + ); // read the userdata Mono<UserData> readUserDataMono = userDataRepository.findByUserId(sampleUserId); @@ -135,23 +139,23 @@ public void removeIdFromRecentlyUsedList_WhenWorkspaceIdAndAppIdExists_BothAreRe // add the read user data mono after the update mono Mono<UserData> userDataAfterUpdateMono = updateResultMono.then(readUserDataMono); - StepVerifier.create(userDataAfterUpdateMono).assertNext(userData -> { - List<String> recentlyUsedAppIds = userData.getRecentlyUsedAppIds(); - List<String> recentlyUsedWorkspaceIds = userData.getRecentlyUsedWorkspaceIds(); - assertThat(recentlyUsedAppIds.size()).isEqualTo(1); - assertThat(recentlyUsedAppIds.get(0)).isEqualTo("456"); + StepVerifier.create(userDataAfterUpdateMono) + .assertNext(userData -> { + List<String> recentlyUsedAppIds = userData.getRecentlyUsedAppIds(); + List<String> recentlyUsedWorkspaceIds = userData.getRecentlyUsedWorkspaceIds(); + assertThat(recentlyUsedAppIds.size()).isEqualTo(1); + assertThat(recentlyUsedAppIds.get(0)).isEqualTo("456"); - assertThat(recentlyUsedWorkspaceIds.size()).isEqualTo(2); - assertThat(recentlyUsedWorkspaceIds).contains("abc", "hij"); - }).verifyComplete(); + assertThat(recentlyUsedWorkspaceIds.size()).isEqualTo(2); + assertThat(recentlyUsedWorkspaceIds).contains("abc", "hij"); + }) + .verifyComplete(); } @Test public void findPhotoAssetsByUserIds_WhenPhotoAssetIdExist_ReturnsPhotoAssetId() { String randomId = UUID.randomUUID().toString(); - String firstId = "first_" + randomId, - secondId = "second_" + randomId, - photoId = "photo_" + randomId; + String firstId = "first_" + randomId, secondId = "second_" + randomId, photoId = "photo_" + randomId; UserData userDataOne = new UserData(); userDataOne.setUserId(firstId); @@ -162,7 +166,8 @@ public void findPhotoAssetsByUserIds_WhenPhotoAssetIdExist_ReturnsPhotoAssetId() userDataTwo.setUserId(secondId); userDataTwo.setRecentlyUsedAppIds(List.of("abc")); - Flux<UserData> userDataFlux = userDataRepository.saveAll(List.of(userDataOne, userDataTwo)) + Flux<UserData> userDataFlux = userDataRepository + .saveAll(List.of(userDataOne, userDataTwo)) .map(UserData::getUserId) .collectList() .flatMapMany(userDataRepository::findPhotoAssetsByUserIds); @@ -180,6 +185,5 @@ public void findPhotoAssetsByUserIds_WhenPhotoAssetIdExist_ReturnsPhotoAssetId() assertThat(secondUserData.getRecentlyUsedAppIds()).isNull(); }) .verifyComplete(); - } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/UserRepositoryTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/UserRepositoryTest.java index 73cbe992e3db..ddc82a6c1287 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/UserRepositoryTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/UserRepositoryTest.java @@ -9,7 +9,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Sort; -import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.test.annotation.DirtiesContext; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -19,10 +18,8 @@ import java.util.HashSet; import java.util.List; import java.util.Optional; -import java.util.Set; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; -import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.fieldName; @@ -59,9 +56,11 @@ public void findByCaseInsensitiveEmail_WhenCaseIsSame_ReturnsResult() { Mono<User> findUserMono = userRepository.findByCaseInsensitiveEmail("[email protected]"); - StepVerifier.create(findUserMono).assertNext(u -> { - assertEquals(savedUser.getEmail(), u.getEmail()); - }).verifyComplete(); + StepVerifier.create(findUserMono) + .assertNext(u -> { + assertEquals(savedUser.getEmail(), u.getEmail()); + }) + .verifyComplete(); } @Test @@ -73,9 +72,11 @@ public void findByCaseInsensitiveEmail_WhenCaseIsDifferent_ReturnsResult() { Mono<User> findUserByEmailMono = userRepository.findByCaseInsensitiveEmail("[email protected]"); - StepVerifier.create(findUserByEmailMono).assertNext(u -> { - assertEquals(savedUser.getEmail(), u.getEmail()); - }).verifyComplete(); + StepVerifier.create(findUserByEmailMono) + .assertNext(u -> { + assertEquals(savedUser.getEmail(), u.getEmail()); + }) + .verifyComplete(); } @Test @@ -92,9 +93,11 @@ public void findByCaseInsensitiveEmail_WhenMultipleMatches_ReturnsResult() { Mono<User> findUserByEmailMono = userRepository.findByCaseInsensitiveEmail("[email protected]"); - StepVerifier.create(findUserByEmailMono).assertNext(u -> { - assertEquals(savedUser2.getEmail(), u.getEmail()); - }).verifyComplete(); + StepVerifier.create(findUserByEmailMono) + .assertNext(u -> { + assertEquals(savedUser2.getEmail(), u.getEmail()); + }) + .verifyComplete(); } @Test @@ -121,7 +124,10 @@ public void findByCaseInsensitiveEmail_WhenNoMatch_ReturnsNone() { void testSkipAndLimitForUserRepo() { String uuid = UUID.randomUUID().toString(); int countOfUsersToBeCreated = 50; - List<String> unsortedEmails = ThreadLocalRandom.current().ints(0, countOfUsersToBeCreated).distinct().limit(countOfUsersToBeCreated) + List<String> unsortedEmails = ThreadLocalRandom.current() + .ints(0, countOfUsersToBeCreated) + .distinct() + .limit(countOfUsersToBeCreated) .mapToObj(index -> uuid + "_" + index + "@gmail.com") .toList(); List<String> sortedEmails = new ArrayList<>(unsortedEmails); @@ -131,28 +137,49 @@ void testSkipAndLimitForUserRepo() { User user = new User(); user.setEmail(email); return userRepository.save(user).block(); - }).toList(); + }) + .toList(); - List<User> allCreatedUsers = userRepository.findAllByEmails(new HashSet<>(unsortedEmails)).collectList().block(); + List<User> allCreatedUsers = userRepository + .findAllByEmails(new HashSet<>(unsortedEmails)) + .collectList() + .block(); assertEquals(countOfUsersToBeCreated, allCreatedUsers.size()); Sort sortByEmailAsc = Sort.by(Sort.Direction.ASC, fieldName(QUser.user.email)); - final int skip1 = 0; int limit1 = 10; - List<User> usersFrom0To10 = userRepository.getAllByEmails(new HashSet<>(unsortedEmails), Optional.empty(), limit1, skip1, QUser.user.email, Sort.Direction.ASC).collectList().block(); + final int skip1 = 0; + int limit1 = 10; + List<User> usersFrom0To10 = userRepository + .getAllByEmails( + new HashSet<>(unsortedEmails), + Optional.empty(), + limit1, + skip1, + QUser.user.email, + Sort.Direction.ASC) + .collectList() + .block(); assertEquals(usersFrom0To10.size(), limit1); List<String> subList0To10 = sortedEmails.subList(skip1, skip1 + limit1); - IntStream.range(skip1, skip1 + limit1) - .forEach(index -> { - usersFrom0To10.get(index - skip1).getEmail().equals(subList0To10.get(index - skip1)); - }); + IntStream.range(skip1, skip1 + limit1).forEach(index -> { + usersFrom0To10.get(index - skip1).getEmail().equals(subList0To10.get(index - skip1)); + }); final int skip2 = 9, limit2 = 10; - List<User> usersFrom9To19 = userRepository.getAllByEmails(new HashSet<>(unsortedEmails), Optional.empty(), limit2, skip2, QUser.user.email, Sort.Direction.ASC).collectList().block(); + List<User> usersFrom9To19 = userRepository + .getAllByEmails( + new HashSet<>(unsortedEmails), + Optional.empty(), + limit2, + skip2, + QUser.user.email, + Sort.Direction.ASC) + .collectList() + .block(); assertEquals(usersFrom9To19.size(), limit2); List<String> subList9To19 = sortedEmails.subList(skip2, skip2 + limit2); - IntStream.range(skip2, skip2 + limit2) - .forEach(index -> { - usersFrom9To19.get(index - skip2).getEmail().equals(subList9To19.get(index - skip2)); - }); + IntStream.range(skip2, skip2 + limit2).forEach(index -> { + usersFrom9To19.get(index - skip2).getEmail().equals(subList9To19.get(index - skip2)); + }); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/WorkspaceRepositoryTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/WorkspaceRepositoryTest.java index f84ccee318b5..cff45c138582 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/WorkspaceRepositoryTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/WorkspaceRepositoryTest.java @@ -30,9 +30,7 @@ public class WorkspaceRepositoryTest { @Test public void updateUserRoleNames_WhenUserIdMatched_AllOrgsUpdated() { - String oldUserName = "Old name", - newUserName = "New name", - userId = "user1"; + String oldUserName = "Old name", newUserName = "New name", userId = "user1"; UserRole userRole = new UserRole(); userRole.setName(oldUserName); userRole.setUserId(userId); @@ -51,32 +49,37 @@ public void updateUserRoleNames_WhenUserIdMatched_AllOrgsUpdated() { org2.setUserRoles(userRoles); // create two orgs - Mono<Tuple2<Workspace, Workspace>> aveOrgsMonoZip = Mono.zip( - workspaceRepository.save(org1), workspaceRepository.save(org2) - ); + Mono<Tuple2<Workspace, Workspace>> aveOrgsMonoZip = + Mono.zip(workspaceRepository.save(org1), workspaceRepository.save(org2)); - Mono<Tuple2<Workspace, Workspace>> updatedOrgTupleMono = aveOrgsMonoZip.flatMap(objects -> { - // update the user names - return workspaceRepository.updateUserRoleNames(userId, newUserName).thenReturn(objects); - }).flatMap(workspaceTuple2 -> { - // fetch the two orgs again - Mono<Workspace> updatedOrg1Mono = workspaceRepository.findBySlug(org1.getId()); - Mono<Workspace> updatedOrg2Mono = workspaceRepository.findBySlug(org2.getId()); - return Mono.zip(updatedOrg1Mono, updatedOrg2Mono); - }); + Mono<Tuple2<Workspace, Workspace>> updatedOrgTupleMono = aveOrgsMonoZip + .flatMap(objects -> { + // update the user names + return workspaceRepository + .updateUserRoleNames(userId, newUserName) + .thenReturn(objects); + }) + .flatMap(workspaceTuple2 -> { + // fetch the two orgs again + Mono<Workspace> updatedOrg1Mono = workspaceRepository.findBySlug(org1.getId()); + Mono<Workspace> updatedOrg2Mono = workspaceRepository.findBySlug(org2.getId()); + return Mono.zip(updatedOrg1Mono, updatedOrg2Mono); + }); - StepVerifier.create(updatedOrgTupleMono).assertNext(orgTuple -> { - Workspace o1 = orgTuple.getT1(); - assertEquals(1, o1.getUserRoles().size()); - UserRole userRole1 = o1.getUserRoles().get(0); - assertEquals(userId, userRole1.getUserId()); - assertEquals(newUserName, userRole1.getName()); + StepVerifier.create(updatedOrgTupleMono) + .assertNext(orgTuple -> { + Workspace o1 = orgTuple.getT1(); + assertEquals(1, o1.getUserRoles().size()); + UserRole userRole1 = o1.getUserRoles().get(0); + assertEquals(userId, userRole1.getUserId()); + assertEquals(newUserName, userRole1.getName()); - Workspace o2 = orgTuple.getT2(); - assertEquals(1, o2.getUserRoles().size()); - UserRole userRole2 = o2.getUserRoles().get(0); - assertEquals(userId, userRole2.getUserId()); - assertEquals(newUserName, userRole2.getName()); - }).verifyComplete(); + Workspace o2 = orgTuple.getT2(); + assertEquals(1, o2.getUserRoles().size()); + UserRole userRole2 = o2.getUserRoles().get(0); + assertEquals(userId, userRole2.getUserId()); + assertEquals(newUserName, userRole2.getName()); + }) + .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImplTest.java index 4cc29ce0d290..a00fb88f7987 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImplTest.java @@ -29,14 +29,15 @@ public void bulkUpdate_WhenIdMatches_ActionCollectionsUpdated() { String applicationId = UUID.randomUUID().toString(); List<ActionCollection> actionCollections = new ArrayList<>(); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { ActionCollection actionCollection = new ActionCollection(); actionCollection.setWorkspaceId("action" + i + "workspace" + i); actionCollection.setApplicationId(applicationId); actionCollections.add(actionCollection); } - Flux<ActionCollection> actionCollectionFlux = actionCollectionRepository.saveAll(actionCollections) + Flux<ActionCollection> actionCollectionFlux = actionCollectionRepository + .saveAll(actionCollections) .collectList() .flatMap(actionCollections1 -> { actionCollections1.forEach(newAction -> { @@ -62,7 +63,7 @@ public void bulkInsert_WhenDuplicateId_ExceptionThrown() { String duplicateId = new ObjectId().toString(); List<ActionCollection> actionCollections = new ArrayList<>(); - for(int i = 0; i < 2; i++) { + for (int i = 0; i < 2; i++) { ActionCollection actionCollection = new ActionCollection(); actionCollection.setId(duplicateId); actionCollections.add(actionCollection); @@ -77,7 +78,7 @@ public void bulkInsert_WhenInsertedWithProvidedId_InsertedWithProvidedId() { List<ActionCollection> actionCollectionList = new ArrayList<>(); String applicationId = UUID.randomUUID().toString(); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { String generatedId = new ObjectId().toString(); ActionCollection actionCollection = new ActionCollection(); actionCollection.setId(generatedId); @@ -87,7 +88,8 @@ public void bulkInsert_WhenInsertedWithProvidedId_InsertedWithProvidedId() { actionCollectionList.add(actionCollection); } - Mono<List<ActionCollection>> actionCollectionsMono = actionCollectionRepository.bulkInsert(actionCollectionList) + Mono<List<ActionCollection>> actionCollectionsMono = actionCollectionRepository + .bulkInsert(actionCollectionList) .thenMany(actionCollectionRepository.findByApplicationId(applicationId)) .collectList(); @@ -100,4 +102,4 @@ public void bulkInsert_WhenInsertedWithProvidedId_InsertedWithProvidedId() { }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImplTest.java index 0f4e5b27f85b..adbb0b59d1bb 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImplTest.java @@ -30,14 +30,15 @@ public void bulkUpdate_WhenIdMatches_NewActionsUpdated() { String applicationId = UUID.randomUUID().toString(); List<NewAction> newActionList = new ArrayList<>(); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { NewAction newAction = new NewAction(); newAction.setWorkspaceId("action" + i + "workspace" + i); newAction.setApplicationId(applicationId); newActionList.add(newAction); } - Flux<NewAction> newActionFlux = newActionRepository.saveAll(newActionList) + Flux<NewAction> newActionFlux = newActionRepository + .saveAll(newActionList) .collectList() .flatMap(newActions -> { newActions.forEach(newAction -> { @@ -63,22 +64,21 @@ public void bulkInsert_WhenDuplicateId_ExceptionThrown() { String duplicateId = new ObjectId().toString(); List<NewAction> actionList = new ArrayList<>(); - for(int i = 0; i < 2; i++) { + for (int i = 0; i < 2; i++) { NewAction action = new NewAction(); action.setId(duplicateId); actionList.add(action); } - StepVerifier.create(newActionRepository.bulkInsert(actionList)) - .verifyError(); + StepVerifier.create(newActionRepository.bulkInsert(actionList)).verifyError(); } @Test public void bulkInsert_WhenInsertedWithProvidedId_InsertedWithProvidedId() { List<NewAction> actionList = new ArrayList<>(); - String applicationId = UUID.randomUUID().toString(); + String applicationId = UUID.randomUUID().toString(); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { String generatedId = new ObjectId().toString(); NewAction action = new NewAction(); action.setId(generatedId); @@ -88,7 +88,8 @@ public void bulkInsert_WhenInsertedWithProvidedId_InsertedWithProvidedId() { actionList.add(action); } - Mono<List<NewAction>> newActionsMono = newActionRepository.bulkInsert(actionList) + Mono<List<NewAction>> newActionsMono = newActionRepository + .bulkInsert(actionList) .thenMany(newActionRepository.findByApplicationId(applicationId)) .collectList(); @@ -101,4 +102,4 @@ public void bulkInsert_WhenInsertedWithProvidedId_InsertedWithProvidedId() { }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceImplTest.java index 8b2173ec1093..03b718ae3167 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceImplTest.java @@ -69,40 +69,57 @@ @Slf4j public class ActionCollectionServiceImplTest { - private final File mockObjects = new File("src/test/resources/test_assets/ActionCollectionServiceTest/mockObjects.json"); + private final File mockObjects = + new File("src/test/resources/test_assets/ActionCollectionServiceTest/mockObjects.json"); ActionCollectionService actionCollectionService; LayoutCollectionService layoutCollectionService; + @MockBean NewPageService newPageService; + @MockBean LayoutActionService layoutActionService; + @MockBean ActionCollectionRepository actionCollectionRepository; + @MockBean NewActionService newActionService; + @MockBean ApplicationService applicationService; + @MockBean ResponseUtils responseUtils; + @MockBean RefactoringSolution refactoringSolution; + ApplicationPermission applicationPermission; PagePermission pagePermission; ActionPermission actionPermission; + @MockBean private Scheduler scheduler; + @MockBean private Validator validator; + @MockBean private MongoConverter mongoConverter; + @MockBean private ReactiveMongoTemplate reactiveMongoTemplate; + @MockBean private AnalyticsService analyticsService; + @MockBean private SessionUserService sessionUserService; + @MockBean private CollectionService collectionService; + @MockBean private PolicyGenerator policyGenerator; @@ -123,8 +140,7 @@ public void setUp() { applicationService, responseUtils, applicationPermission, - actionPermission - ); + actionPermission); layoutCollectionService = new LayoutCollectionServiceImpl( newPageService, @@ -136,37 +152,35 @@ public void setUp() { responseUtils, actionCollectionRepository, pagePermission, - actionPermission - ); - - Mockito - .when(analyticsService.sendCreateEvent(Mockito.any())) - .thenAnswer(invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); + actionPermission); - Mockito - .when(analyticsService.sendCreateEvent(Mockito.any(), Mockito.any())) - .thenAnswer(invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); + Mockito.when(analyticsService.sendCreateEvent(Mockito.any())) + .thenAnswer( + invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); - Mockito - .when(analyticsService.sendUpdateEvent(Mockito.any())) - .thenAnswer(invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); + Mockito.when(analyticsService.sendCreateEvent(Mockito.any(), Mockito.any())) + .thenAnswer( + invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); - Mockito - .when(analyticsService.sendUpdateEvent(Mockito.any(), Mockito.any())) - .thenAnswer(invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); + Mockito.when(analyticsService.sendUpdateEvent(Mockito.any())) + .thenAnswer( + invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); - Mockito - .when(analyticsService.sendDeleteEvent(Mockito.any(), Mockito.any())) - .thenAnswer(invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); + Mockito.when(analyticsService.sendUpdateEvent(Mockito.any(), Mockito.any())) + .thenAnswer( + invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); - Mockito - .when(analyticsService.sendDeleteEvent(Mockito.any(), Mockito.any())) - .thenAnswer(invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); + Mockito.when(analyticsService.sendDeleteEvent(Mockito.any(), Mockito.any())) + .thenAnswer( + invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); - Mockito - .when(analyticsService.sendArchiveEvent(Mockito.any(), Mockito.any())) - .thenAnswer(invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); + Mockito.when(analyticsService.sendDeleteEvent(Mockito.any(), Mockito.any())) + .thenAnswer( + invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); + Mockito.when(analyticsService.sendArchiveEvent(Mockito.any(), Mockito.any())) + .thenAnswer( + invocationOnMock -> Mono.justOrEmpty(invocationOnMock.getArguments()[0])); } <T> DefaultResources setDefaultResources(T collection) { @@ -184,18 +198,20 @@ <T> DefaultResources setDefaultResources(T collection) { public void testCreateCollection_withId_throwsError() { ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); actionCollectionDTO.setId("testId"); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = layoutCollectionService.createCollection(actionCollectionDTO); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + layoutCollectionService.createCollection(actionCollectionDTO); StepVerifier.create(actionCollectionDTOMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ID))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ID))) .verify(); } @Test public void testCreateCollection_withoutOrgPageApplicationPluginIds_throwsError() { ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = layoutCollectionService.createCollection(actionCollectionDTO); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + layoutCollectionService.createCollection(actionCollectionDTO); StepVerifier.create(actionCollectionDTOMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException) @@ -215,31 +231,29 @@ public void testCreateCollection_withRepeatedActionName_throwsError() throws IOE ObjectMapper objectMapper = new ObjectMapper(); final JsonNode jsonNode = objectMapper.readValue(mockObjects, JsonNode.class); final NewPage newPage = objectMapper.convertValue(jsonNode.get("newPage"), NewPage.class); - Mockito - .when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); - Mockito - .when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(false)); - Mockito - .when(actionCollectionRepository - .findAllActionCollectionsByNamePageIdsViewModeAndBranch( - Mockito.any(), - Mockito.any(), - Mockito.anyBoolean(), - Mockito.any(), - Mockito.any(), - Mockito.any())) + Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( + Mockito.any(), + Mockito.any(), + Mockito.anyBoolean(), + Mockito.any(), + Mockito.any(), + Mockito.any())) .thenReturn(Flux.empty()); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = layoutCollectionService.createCollection(actionCollectionDTO); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + layoutCollectionService.createCollection(actionCollectionDTO); StepVerifier.create(actionCollectionDTOMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage() - .equals(AppsmithError.DUPLICATE_KEY_USER_ERROR - .getMessage(actionCollectionDTO.getName(), FieldName.NAME))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.DUPLICATE_KEY_USER_ERROR.getMessage( + actionCollectionDTO.getName(), FieldName.NAME))) .verify(); } @@ -258,51 +272,43 @@ public void testCreateCollection_createActionFailure_returnsWithIncompleteCollec final JsonNode jsonNode = objectMapper.readValue(mockObjects, JsonNode.class); final NewPage newPage = objectMapper.convertValue(jsonNode.get("newPage"), NewPage.class); - Mockito - .when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); - Mockito - .when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(true)); - Mockito - .when(actionCollectionRepository - .findAllActionCollectionsByNamePageIdsViewModeAndBranch( - Mockito.any(), - Mockito.any(), - Mockito.anyBoolean(), - Mockito.any(), - Mockito.any(), - Mockito.any())) + Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( + Mockito.any(), + Mockito.any(), + Mockito.anyBoolean(), + Mockito.any(), + Mockito.any(), + Mockito.any())) .thenReturn(Flux.empty()); - Mockito - .when(layoutActionService.createAction(Mockito.any())) - .thenReturn(Mono.just(new ActionDTO())); + Mockito.when(layoutActionService.createAction(Mockito.any())).thenReturn(Mono.just(new ActionDTO())); - Mockito - .when(layoutActionService.updatePageLayoutsByPageId(Mockito.anyString())) + Mockito.when(layoutActionService.updatePageLayoutsByPageId(Mockito.anyString())) .thenAnswer(invocationOnMock -> { return Mono.just(actionCollectionDTO.getPageId()); }); - Mockito - .when(actionCollectionRepository.save(Mockito.any())) - .thenAnswer(invocation -> { - final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; - argument.setId("testActionCollectionId"); - return Mono.just(argument); - }); - Mockito - .when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) + Mockito.when(actionCollectionRepository.save(Mockito.any())).thenAnswer(invocation -> { + final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; + argument.setId("testActionCollectionId"); + return Mono.just(argument); + }); + Mockito.when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) .thenAnswer(invocation -> { - final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; + final ActionCollection argument = + (ActionCollection) invocation.getArguments()[0]; argument.setId("testActionCollectionId"); argument.setUserPermissions(Set.of("test-user-permission1", "test-user-permission2")); return Mono.just(argument); }); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = layoutCollectionService.createCollection(actionCollectionDTO); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + layoutCollectionService.createCollection(actionCollectionDTO); StepVerifier.create(actionCollectionDTOMono) .assertNext(actionCollectionDTO1 -> { @@ -331,73 +337,68 @@ public void testCreateCollection_validCollection_returnsPopulatedCollection() th final JsonNode jsonNode = objectMapper.readValue(mockObjects, JsonNode.class); final NewPage newPage = objectMapper.convertValue(jsonNode.get("newPage"), NewPage.class); - Mockito - .when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); - Mockito - .when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(true)); - Mockito - .when(actionCollectionRepository - .findAllActionCollectionsByNamePageIdsViewModeAndBranch( - Mockito.any(), - Mockito.any(), - Mockito.anyBoolean(), - Mockito.any(), - Mockito.any(), - Mockito.any())) + Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( + Mockito.any(), + Mockito.any(), + Mockito.anyBoolean(), + Mockito.any(), + Mockito.any(), + Mockito.any())) .thenReturn(Flux.empty()); - Mockito - .when(layoutActionService.createSingleAction(Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.createSingleAction(Mockito.any(), Mockito.any())) .thenAnswer(invocation -> { final ActionDTO argument = (ActionDTO) invocation.getArguments()[0]; argument.setId("testActionId"); return Mono.just(argument); }); - Mockito - .when(layoutActionService.updatePageLayoutsByPageId(Mockito.anyString())) + Mockito.when(layoutActionService.updatePageLayoutsByPageId(Mockito.anyString())) .thenAnswer(invocationOnMock -> { return Mono.just(actionCollectionDTO.getPageId()); }); - Mockito - .when(actionCollectionRepository.save(Mockito.any())) - .thenAnswer(invocation -> { - final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; - argument.setId("testActionCollectionId"); - return Mono.just(argument); - }); + Mockito.when(actionCollectionRepository.save(Mockito.any())).thenAnswer(invocation -> { + final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; + argument.setId("testActionCollectionId"); + return Mono.just(argument); + }); - Mockito - .when(layoutActionService.updateSingleAction(Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.updateSingleAction(Mockito.any(), Mockito.any())) .thenAnswer(invocation -> { final ActionDTO argument = (ActionDTO) invocation.getArguments()[1]; return Mono.just(argument); }); - Mockito - .when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) + Mockito.when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) .thenAnswer(invocation -> { - final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; + final ActionCollection argument = + (ActionCollection) invocation.getArguments()[0]; argument.setId("testActionCollectionId"); argument.setUserPermissions(Set.of("test-user-permission1", "test-user-permission2")); return Mono.just(argument); }); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = layoutCollectionService.createCollection(actionCollectionDTO); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + layoutCollectionService.createCollection(actionCollectionDTO); StepVerifier.create(actionCollectionDTOMono) .assertNext(actionCollectionDTO1 -> { assertEquals(1, actionCollectionDTO1.getActions().size()); assertThat(actionCollectionDTO1.getUserPermissions()).hasSize(2); - final ActionDTO actionDTO = actionCollectionDTO1.getActions().get(0); + final ActionDTO actionDTO = + actionCollectionDTO1.getActions().get(0); assertEquals("testAction", actionDTO.getName()); assertEquals("testActionId", actionDTO.getId()); assertEquals("testCollection.testAction", actionDTO.getFullyQualifiedName()); - assertEquals("testActionCollectionId", actionDTO.getDefaultResources().getCollectionId()); + assertEquals( + "testActionCollectionId", + actionDTO.getDefaultResources().getCollectionId()); assertTrue(actionDTO.getClientSideExecution()); }) .verifyComplete(); @@ -411,8 +412,8 @@ public void testUpdateUnpublishedActionCollection_withoutId_throwsError() { layoutCollectionService.updateUnpublishedActionCollection(null, actionCollectionDTO, null); StepVerifier.create(actionCollectionDTOMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ID))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ID))) .verify(); } @@ -427,48 +428,53 @@ public void testUpdateUnpublishedActionCollection_withInvalidId_throwsError() th final JsonNode jsonNode = objectMapper.readValue(mockObjects, JsonNode.class); final NewPage newPage = objectMapper.convertValue(jsonNode.get("newPage"), NewPage.class); - Mockito - .when(actionCollectionRepository.findById(Mockito.anyString(), Mockito.<AclPermission>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.anyString(), Mockito.<AclPermission>any())) .thenReturn(Mono.empty()); - Mockito - .when(newPageService - .findByBranchNameAndDefaultPageId(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(newPageService.findByBranchNameAndDefaultPageId(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(newPage)); - - Mockito - .when(newPageService - .findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); final Mono<ActionCollectionDTO> actionCollectionDTOMono = layoutCollectionService.updateUnpublishedActionCollection("testId", actionCollectionDTO, null); StepVerifier.create(actionCollectionDTOMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.ACTION_COLLECTION, "testId"))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.ACTION_COLLECTION, "testId"))) .verify(); } @Test - public void testUpdateUnpublishedActionCollection_withModifiedCollection_returnsValidCollection() throws IOException { + public void testUpdateUnpublishedActionCollection_withModifiedCollection_returnsValidCollection() + throws IOException { ObjectMapper objectMapper = new ObjectMapper(); ObjectMapperUtils objectMapperUtils = new ObjectMapperUtils(objectMapper); final JsonNode jsonNode = objectMapperUtils.readFromFile(mockObjects, Views.Public.class, JsonNode.class); - String actionCollectionString = objectMapperUtils.writeAsString(jsonNode.get("actionCollectionWithAction"), Views.Public.class); - final ActionCollection actionCollection = objectMapperUtils.readFromString(actionCollectionString, Views.Public.class, ActionCollection.class); + String actionCollectionString = + objectMapperUtils.writeAsString(jsonNode.get("actionCollectionWithAction"), Views.Public.class); + final ActionCollection actionCollection = + objectMapperUtils.readFromString(actionCollectionString, Views.Public.class, ActionCollection.class); - String actionCollectionDTOWithModifiedActionsString = objectMapperUtils.writeAsString(jsonNode.get("actionCollectionDTOWithModifiedActions"), Views.Public.class); - final ActionCollectionDTO modifiedActionCollectionDTO = objectMapperUtils.readFromString(actionCollectionDTOWithModifiedActionsString, Views.Public.class, ActionCollectionDTO.class); + String actionCollectionDTOWithModifiedActionsString = objectMapperUtils.writeAsString( + jsonNode.get("actionCollectionDTOWithModifiedActions"), Views.Public.class); + final ActionCollectionDTO modifiedActionCollectionDTO = objectMapperUtils.readFromString( + actionCollectionDTOWithModifiedActionsString, Views.Public.class, ActionCollectionDTO.class); - String actionCollectionAfterModifiedActionsString = objectMapperUtils.writeAsString(jsonNode.get("actionCollectionAfterModifiedActions"), Views.Public.class); - final ActionCollection modifiedActionCollection = objectMapperUtils.readFromString(actionCollectionAfterModifiedActionsString, Views.Public.class, ActionCollection.class); + String actionCollectionAfterModifiedActionsString = objectMapperUtils.writeAsString( + jsonNode.get("actionCollectionAfterModifiedActions"), Views.Public.class); + final ActionCollection modifiedActionCollection = objectMapperUtils.readFromString( + actionCollectionAfterModifiedActionsString, Views.Public.class, ActionCollection.class); final ActionCollectionDTO unpublishedCollection = modifiedActionCollection.getUnpublishedCollection(); - unpublishedCollection.setDefaultToBranchedActionIdsMap(Map.of("defaultTestActionId1", "testActionId1", "defaultTestActionId3", "testActionId3")); + unpublishedCollection.setDefaultToBranchedActionIdsMap( + Map.of("defaultTestActionId1", "testActionId1", "defaultTestActionId3", "testActionId3")); unpublishedCollection.setDefaultToBranchedArchivedActionIdsMap(Map.of("defaultTestActionId2", "testActionId2")); actionCollection.setDefaultResources(setDefaultResources(actionCollection)); modifiedActionCollection.setDefaultResources(actionCollection.getDefaultResources()); @@ -478,8 +484,7 @@ public void testUpdateUnpublishedActionCollection_withModifiedCollection_returns final Instant archivedAfter = Instant.now(); Map<String, ActionDTO> updatedActions = new HashMap<>(); - Mockito - .when(layoutActionService.updateSingleAction(Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.updateSingleAction(Mockito.any(), Mockito.any())) .thenAnswer(invocation -> { final ActionDTO argument = (ActionDTO) invocation.getArguments()[1]; DefaultResources defaultResources = new DefaultResources(); @@ -490,100 +495,91 @@ public void testUpdateUnpublishedActionCollection_withModifiedCollection_returns return Mono.just(argument); }); - Mockito - .when(newActionService.deleteUnpublishedAction(Mockito.any())) - .thenAnswer(invocation -> { - final ActionDTO argument = (ActionDTO) invocation.getArguments()[1]; - return Mono.just(argument); - }); + Mockito.when(newActionService.deleteUnpublishedAction(Mockito.any())).thenAnswer(invocation -> { + final ActionDTO argument = (ActionDTO) invocation.getArguments()[1]; + return Mono.just(argument); + }); - Mockito - .when(reactiveMongoTemplate.updateFirst(Mockito.any(), Mockito.any(), Mockito.any(Class.class))) + Mockito.when(reactiveMongoTemplate.updateFirst(Mockito.any(), Mockito.any(), Mockito.any(Class.class))) .thenReturn(Mono.just((Mockito.mock(UpdateResult.class)))); - Mockito - .when(actionCollectionRepository.findById(Mockito.anyString(), Mockito.<AclPermission>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.anyString(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(actionCollection)); - Mockito - .when(actionCollectionRepository.findById(Mockito.anyString())) + Mockito.when(actionCollectionRepository.findById(Mockito.anyString())) .thenReturn(Mono.just(modifiedActionCollection)); - Mockito - .when(newActionService.findActionDTObyIdAndViewMode(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(newActionService.findActionDTObyIdAndViewMode(Mockito.any(), Mockito.any(), Mockito.any())) .thenAnswer(invocation -> { String id = (String) invocation.getArguments()[0]; return Mono.just(updatedActions.get(id)); }); - Mockito - .when(responseUtils.updateCollectionDTOWithDefaultResources(Mockito.any())) + Mockito.when(responseUtils.updateCollectionDTOWithDefaultResources(Mockito.any())) .thenReturn(modifiedActionCollectionDTO); final NewPage newPage = objectMapper.convertValue(jsonNode.get("newPage"), NewPage.class); - Mockito - .when(newPageService.findByBranchNameAndDefaultPageId(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(newPageService.findByBranchNameAndDefaultPageId(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(newPage)); - Mockito - .when(newPageService - .findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); Mockito.when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) .thenReturn(Mono.just(modifiedActionCollection)); - Mockito - .when(layoutActionService.updatePageLayoutsByPageId(Mockito.anyString())) + Mockito.when(layoutActionService.updatePageLayoutsByPageId(Mockito.anyString())) .thenAnswer(invocationOnMock -> { return Mono.just(actionCollection.getUnpublishedCollection().getPageId()); }); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = - layoutCollectionService.updateUnpublishedActionCollection("testCollectionId", modifiedActionCollectionDTO, null); + layoutCollectionService.updateUnpublishedActionCollection( + "testCollectionId", modifiedActionCollectionDTO, null); StepVerifier.create(actionCollectionDTOMono) .assertNext(actionCollectionDTO1 -> { assertEquals(2, actionCollectionDTO1.getActions().size()); assertEquals(1, actionCollectionDTO1.getArchivedActions().size()); - assertTrue( - actionCollectionDTO1 - .getActions() - .stream() - .map(ActionDTO::getId) - .collect(Collectors.toSet()) - .containsAll(Set.of("testActionId1", "testActionId3"))); - assertEquals("testActionId2", actionCollectionDTO1.getArchivedActions().get(0).getId()); - assertTrue(archivedAfter.isBefore(actionCollectionDTO1.getArchivedActions().get(0).getDeletedAt())); + assertTrue(actionCollectionDTO1.getActions().stream() + .map(ActionDTO::getId) + .collect(Collectors.toSet()) + .containsAll(Set.of("testActionId1", "testActionId3"))); + assertEquals( + "testActionId2", + actionCollectionDTO1.getArchivedActions().get(0).getId()); + assertTrue(archivedAfter.isBefore( + actionCollectionDTO1.getArchivedActions().get(0).getDeletedAt())); }) .verifyComplete(); } @Test public void testDeleteUnpublishedActionCollection_withInvalidId_throwsError() { - Mockito - .when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) .thenReturn(Mono.empty()); final Mono<ActionCollectionDTO> actionCollectionMono = actionCollectionService.deleteUnpublishedActionCollection("invalidId"); - StepVerifier - .create(actionCollectionMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable + StepVerifier.create(actionCollectionMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable .getMessage() - .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.ACTION_COLLECTION, "invalidId"))) + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.ACTION_COLLECTION, "invalidId"))) .verify(); } @Test - public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndNoActions_returnsActionCollectionDTO() throws IOException { + public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndNoActions_returnsActionCollectionDTO() + throws IOException { ObjectMapper objectMapper = new ObjectMapper(); final JsonNode jsonNode = objectMapper.readValue(mockObjects, JsonNode.class); - final ActionCollection actionCollection = objectMapper.readerWithView(Views.Public.class).readValue(jsonNode.get("actionCollectionWithAction"), ActionCollection.class); + final ActionCollection actionCollection = objectMapper + .readerWithView(Views.Public.class) + .readValue(jsonNode.get("actionCollectionWithAction"), ActionCollection.class); final ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); unpublishedCollection.setActions(List.of()); actionCollection.setDefaultResources(setDefaultResources(actionCollection)); @@ -591,21 +587,18 @@ public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndNoAc Instant deletedAt = Instant.now(); - Mockito - .when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) .thenReturn(Mono.just(actionCollection)); - Mockito - .when(actionCollectionRepository.save(Mockito.any())) - .thenAnswer(invocation -> { - final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; - return Mono.just(argument); - }); + Mockito.when(actionCollectionRepository.save(Mockito.any())).thenAnswer(invocation -> { + final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; + return Mono.just(argument); + }); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); - StepVerifier - .create(actionCollectionDTOMono) + StepVerifier.create(actionCollectionDTOMono) .assertNext(actionCollectionDTO -> { assertEquals("testCollection", actionCollectionDTO.getName()); assertEquals(0, actionCollectionDTO.getActions().size()); @@ -615,35 +608,41 @@ public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndNoAc } @Test - public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndActions_returnsActionCollectionDTO() throws IOException { + public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndActions_returnsActionCollectionDTO() + throws IOException { ObjectMapper objectMapper = new ObjectMapper(); - final JsonNode jsonNode = objectMapper.readerWithView(Views.Public.class).readValue(mockObjects, JsonNode.class); - final ActionCollection actionCollection = objectMapper.readerWithView(Views.Public.class).readValue(objectMapper.writerWithView(Views.Public.class).writeValueAsString(jsonNode.get("actionCollectionWithAction")), ActionCollection.class); + final JsonNode jsonNode = + objectMapper.readerWithView(Views.Public.class).readValue(mockObjects, JsonNode.class); + final ActionCollection actionCollection = objectMapper + .readerWithView(Views.Public.class) + .readValue( + objectMapper + .writerWithView(Views.Public.class) + .writeValueAsString(jsonNode.get("actionCollectionWithAction")), + ActionCollection.class); ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); - unpublishedCollection.setDefaultToBranchedActionIdsMap(Map.of("defaultTestActionId1", "testActionId1", "defaultTestActionId2", "testActionId2")); + unpublishedCollection.setDefaultToBranchedActionIdsMap( + Map.of("defaultTestActionId1", "testActionId1", "defaultTestActionId2", "testActionId2")); actionCollection.setDefaultResources(setDefaultResources(actionCollection)); unpublishedCollection.setDefaultResources(setDefaultResources(unpublishedCollection)); Instant deletedAt = Instant.now(); - Mockito - .when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) .thenReturn(Mono.just(actionCollection)); - Mockito - .when(newActionService.deleteUnpublishedAction(Mockito.any())) - .thenReturn(Mono.just(actionCollection.getUnpublishedCollection().getActions().get(0))); + Mockito.when(newActionService.deleteUnpublishedAction(Mockito.any())) + .thenReturn(Mono.just( + actionCollection.getUnpublishedCollection().getActions().get(0))); - Mockito - .when(actionCollectionRepository.save(Mockito.any())) - .thenAnswer(invocation -> { - final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; - return Mono.just(argument); - }); + Mockito.when(actionCollectionRepository.save(Mockito.any())).thenAnswer(invocation -> { + final ActionCollection argument = (ActionCollection) invocation.getArguments()[0]; + return Mono.just(argument); + }); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); - StepVerifier - .create(actionCollectionDTOMono) + StepVerifier.create(actionCollectionDTOMono) .assertNext(actionCollectionDTO -> { assertEquals("testCollection", actionCollectionDTO.getName()); assertEquals(2, actionCollectionDTO.getActions().size()); @@ -653,68 +652,81 @@ public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndActi } @Test - public void testDeleteUnpublishedActionCollection_withoutPublishedCollectionAndNoActions_returnsActionCollectionDTO() throws IOException { + public void + testDeleteUnpublishedActionCollection_withoutPublishedCollectionAndNoActions_returnsActionCollectionDTO() + throws IOException { ObjectMapper objectMapper = new ObjectMapper(); - final JsonNode jsonNode = objectMapper.readerWithView(Views.Public.class).readValue(mockObjects, JsonNode.class); - final ActionCollection actionCollection = objectMapper.readerWithView(Views.Public.class).readValue(objectMapper.writerWithView(Views.Public.class).writeValueAsString(jsonNode.get("actionCollectionWithAction")), ActionCollection.class); + final JsonNode jsonNode = + objectMapper.readerWithView(Views.Public.class).readValue(mockObjects, JsonNode.class); + final ActionCollection actionCollection = objectMapper + .readerWithView(Views.Public.class) + .readValue( + objectMapper + .writerWithView(Views.Public.class) + .writeValueAsString(jsonNode.get("actionCollectionWithAction")), + ActionCollection.class); actionCollection.setPublishedCollection(null); actionCollection.setDefaultResources(setDefaultResources(actionCollection)); - actionCollection.getUnpublishedCollection().setDefaultResources(setDefaultResources(actionCollection.getUnpublishedCollection())); + actionCollection + .getUnpublishedCollection() + .setDefaultResources(setDefaultResources(actionCollection.getUnpublishedCollection())); - Mockito - .when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) .thenReturn(Mono.just(actionCollection)); - Mockito - .when(actionCollectionRepository.findById(Mockito.anyString())) - .thenReturn(Mono.just(actionCollection)); + Mockito.when(actionCollectionRepository.findById(Mockito.anyString())).thenReturn(Mono.just(actionCollection)); - Mockito - .when(actionCollectionRepository.archive(Mockito.any())) - .thenReturn(Mono.empty()); + Mockito.when(actionCollectionRepository.archive(Mockito.any())).thenReturn(Mono.empty()); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); - StepVerifier - .create(actionCollectionDTOMono) + StepVerifier.create(actionCollectionDTOMono) .assertNext(Assertions::assertNotNull) .verifyComplete(); } @Test - public void testDeleteUnpublishedActionCollection_withoutPublishedCollectionAndWithActions_returnsActionCollectionDTO() throws IOException { + public void + testDeleteUnpublishedActionCollection_withoutPublishedCollectionAndWithActions_returnsActionCollectionDTO() + throws IOException { ObjectMapper objectMapper = new ObjectMapper(); - final JsonNode jsonNode = objectMapper.readerWithView(Views.Public.class).readValue(mockObjects, JsonNode.class); - final ActionCollection actionCollection = objectMapper.readerWithView(Views.Public.class).readValue(objectMapper.writerWithView(Views.Public.class).writeValueAsString(jsonNode.get("actionCollectionWithAction")), ActionCollection.class); - actionCollection.getUnpublishedCollection().setDefaultToBranchedActionIdsMap(Map.of("defaultTestActionId1", "testActionId1", "defaultTestActionId2", "testActionId2")); + final JsonNode jsonNode = + objectMapper.readerWithView(Views.Public.class).readValue(mockObjects, JsonNode.class); + final ActionCollection actionCollection = objectMapper + .readerWithView(Views.Public.class) + .readValue( + objectMapper + .writerWithView(Views.Public.class) + .writeValueAsString(jsonNode.get("actionCollectionWithAction")), + ActionCollection.class); + actionCollection + .getUnpublishedCollection() + .setDefaultToBranchedActionIdsMap( + Map.of("defaultTestActionId1", "testActionId1", "defaultTestActionId2", "testActionId2")); actionCollection.setPublishedCollection(null); DefaultResources resources = new DefaultResources(); resources.setApplicationId("testApplicationId"); resources.setApplicationId("testCollectionId"); actionCollection.setDefaultResources(setDefaultResources(actionCollection)); - actionCollection.getUnpublishedCollection().setDefaultResources(setDefaultResources(actionCollection.getUnpublishedCollection())); + actionCollection + .getUnpublishedCollection() + .setDefaultResources(setDefaultResources(actionCollection.getUnpublishedCollection())); - Mockito - .when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) .thenReturn(Mono.just(actionCollection)); - Mockito - .when(actionCollectionRepository.findById(Mockito.anyString())) - .thenReturn(Mono.just(actionCollection)); + Mockito.when(actionCollectionRepository.findById(Mockito.anyString())).thenReturn(Mono.just(actionCollection)); - Mockito - .when(newActionService.archiveById(Mockito.any())) - .thenReturn(Mono.just(new NewAction())); + Mockito.when(newActionService.archiveById(Mockito.any())).thenReturn(Mono.just(new NewAction())); - Mockito - .when(actionCollectionRepository.archive(Mockito.any())) - .thenReturn(Mono.empty()); + Mockito.when(actionCollectionRepository.archive(Mockito.any())).thenReturn(Mono.empty()); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); - StepVerifier - .create(actionCollectionDTOMono) + StepVerifier.create(actionCollectionDTOMono) .assertNext(Assertions::assertNotNull) .verifyComplete(); } @@ -740,8 +752,7 @@ public void testRefactorCollectionName_withDuplicateName_throwsError() { duplicateUnpublishedCollection.setName("newName"); duplicateActionCollection.setUnpublishedCollection(duplicateUnpublishedCollection); - Mockito - .when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( + Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( Mockito.any(), Mockito.any(), Mockito.anyBoolean(), @@ -750,15 +761,16 @@ public void testRefactorCollectionName_withDuplicateName_throwsError() { Mockito.any())) .thenReturn(Flux.just(oldActionCollection, duplicateActionCollection)); - Mockito - .when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(false)); - final Mono<LayoutDTO> layoutDTOMono = layoutCollectionService.refactorCollectionName(refactorActionCollectionNameDTO, null); + final Mono<LayoutDTO> layoutDTOMono = + layoutCollectionService.refactorCollectionName(refactorActionCollectionNameDTO, null); - StepVerifier - .create(layoutDTOMono) - .expectErrorMatches(e -> AppsmithError.DUPLICATE_KEY_USER_ERROR.getMessage("newName", FieldName.NAME).equals(e.getMessage())) + StepVerifier.create(layoutDTOMono) + .expectErrorMatches(e -> AppsmithError.DUPLICATE_KEY_USER_ERROR + .getMessage("newName", FieldName.NAME) + .equals(e.getMessage())) .verify(); } @@ -780,8 +792,7 @@ public void testRefactorCollectionName_withEmptyActions_returnsValidLayout() { oldUnpublishedCollection.setDefaultResources(setDefaultResources(oldUnpublishedCollection)); oldActionCollection.setDefaultResources(setDefaultResources(oldActionCollection)); - Mockito - .when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( + Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( Mockito.any(), Mockito.any(), Mockito.anyBoolean(), @@ -790,42 +801,36 @@ public void testRefactorCollectionName_withEmptyActions_returnsValidLayout() { Mockito.any())) .thenReturn(Flux.just(oldActionCollection)); - Mockito - .when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(true)); - Mockito - .when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(oldActionCollection)); - Mockito - .when(actionCollectionRepository.findById(Mockito.anyString())) + Mockito.when(actionCollectionRepository.findById(Mockito.anyString())) .thenReturn(Mono.just(oldActionCollection)); - Mockito - .when(reactiveMongoTemplate.updateFirst(Mockito.any(), Mockito.any(), Mockito.any(Class.class))) + Mockito.when(reactiveMongoTemplate.updateFirst(Mockito.any(), Mockito.any(), Mockito.any(Class.class))) .thenReturn(Mono.just(UpdateResult.acknowledged(1, 1L, new BsonObjectId()))); LayoutDTO layout = new LayoutDTO(); final JSONObject jsonObject = new JSONObject(); jsonObject.put("key", "value"); layout.setDsl(jsonObject); - Mockito - .when(refactoringSolution.refactorActionCollectionName(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString())) + Mockito.when(refactoringSolution.refactorActionCollectionName( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString())) .thenReturn(Mono.just(layout)); - Mockito - .when(responseUtils.updateLayoutDTOWithDefaultResources(Mockito.any())) + Mockito.when(responseUtils.updateLayoutDTOWithDefaultResources(Mockito.any())) .thenReturn(layout); - Mockito - .when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) + Mockito.when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) .thenReturn(Mono.just(oldActionCollection)); - final Mono<LayoutDTO> layoutDTOMono = layoutCollectionService.refactorCollectionName(refactorActionCollectionNameDTO, null); + final Mono<LayoutDTO> layoutDTOMono = + layoutCollectionService.refactorCollectionName(refactorActionCollectionNameDTO, null); - StepVerifier - .create(layoutDTOMono) + StepVerifier.create(layoutDTOMono) .assertNext(layoutDTO -> { assertNotNull(layoutDTO.getDsl()); assertEquals("value", layoutDTO.getDsl().get("key")); @@ -852,8 +857,7 @@ public void testRefactorCollectionName_withActions_returnsValidLayout() { oldActionCollection.setDefaultResources(setDefaultResources(oldActionCollection)); oldUnpublishedCollection.setDefaultResources(setDefaultResources(oldUnpublishedCollection)); - Mockito - .when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( + Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( Mockito.any(), Mockito.any(), Mockito.anyBoolean(), @@ -862,32 +866,25 @@ public void testRefactorCollectionName_withActions_returnsValidLayout() { Mockito.any())) .thenReturn(Flux.just(oldActionCollection)); - Mockito - .when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(true)); - Mockito - .when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(oldActionCollection)); - Mockito - .when(newActionService.findActionDTObyIdAndViewMode(Mockito.any(), Mockito.anyBoolean(), Mockito.any())) + Mockito.when(newActionService.findActionDTObyIdAndViewMode(Mockito.any(), Mockito.anyBoolean(), Mockito.any())) .thenReturn(Mono.just(new ActionDTO())); - Mockito - .when(newActionService.updateUnpublishedAction(Mockito.any(), Mockito.any())) + Mockito.when(newActionService.updateUnpublishedAction(Mockito.any(), Mockito.any())) .thenReturn(Mono.just(new ActionDTO())); - Mockito - .when(actionCollectionRepository.findById(Mockito.anyString())) + Mockito.when(actionCollectionRepository.findById(Mockito.anyString())) .thenReturn(Mono.just(oldActionCollection)); - Mockito - .when(reactiveMongoTemplate.updateFirst(Mockito.any(), Mockito.any(), Mockito.any(Class.class))) + Mockito.when(reactiveMongoTemplate.updateFirst(Mockito.any(), Mockito.any(), Mockito.any(Class.class))) .thenReturn(Mono.just(UpdateResult.acknowledged(1, 1L, new BsonObjectId()))); - Mockito - .when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) + Mockito.when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) .thenReturn(Mono.just(oldActionCollection)); LayoutDTO layout = new LayoutDTO(); @@ -896,18 +893,17 @@ public void testRefactorCollectionName_withActions_returnsValidLayout() { layout.setDsl(jsonObject); layout.setActionUpdates(new ArrayList<>()); layout.setLayoutOnLoadActions(new ArrayList<>()); - Mockito - .when(refactoringSolution.refactorActionCollectionName(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString())) + Mockito.when(refactoringSolution.refactorActionCollectionName( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString())) .thenReturn(Mono.just(layout)); - Mockito - .when(responseUtils.updateLayoutDTOWithDefaultResources(Mockito.any())) + Mockito.when(responseUtils.updateLayoutDTOWithDefaultResources(Mockito.any())) .thenReturn(layout); - final Mono<LayoutDTO> layoutDTOMono = layoutCollectionService.refactorCollectionName(refactorActionCollectionNameDTO, null); + final Mono<LayoutDTO> layoutDTOMono = + layoutCollectionService.refactorCollectionName(refactorActionCollectionNameDTO, null); - StepVerifier - .create(layoutDTOMono) + StepVerifier.create(layoutDTOMono) .assertNext(layoutDTO -> { assertNotNull(layoutDTO.getDsl()); assertEquals("value", layoutDTO.getDsl().get("key")); @@ -938,24 +934,18 @@ public void testMoveCollection_toValidPage_returnsCollection() throws IOExceptio actionResources.setPageId("newPageId"); action.setDefaultResources(actionResources); - Mockito - .when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(actionCollection)); - Mockito - .when(newActionService.findActionDTObyIdAndViewMode(Mockito.any(), Mockito.anyBoolean(), Mockito.any())) + Mockito.when(newActionService.findActionDTObyIdAndViewMode(Mockito.any(), Mockito.anyBoolean(), Mockito.any())) .thenReturn(Mono.just(action)); - Mockito - .when(newActionService.updateUnpublishedAction(Mockito.any(), Mockito.any())) + Mockito.when(newActionService.updateUnpublishedAction(Mockito.any(), Mockito.any())) .thenReturn(Mono.just(new ActionDTO())); - Mockito - .when(actionCollectionRepository.findById(Mockito.anyString())) - .thenReturn(Mono.just(actionCollection)); + Mockito.when(actionCollectionRepository.findById(Mockito.anyString())).thenReturn(Mono.just(actionCollection)); - Mockito - .when(reactiveMongoTemplate.updateFirst(Mockito.any(), Mockito.any(), Mockito.any(Class.class))) + Mockito.when(reactiveMongoTemplate.updateFirst(Mockito.any(), Mockito.any(), Mockito.any(Class.class))) .thenReturn(Mono.just(UpdateResult.acknowledged(1, 1L, new BsonObjectId()))); PageDTO oldPageDTO = new PageDTO(); @@ -973,13 +963,11 @@ public void testMoveCollection_toValidPage_returnsCollection() throws IOExceptio pageDefaultResources.setPageId(newPage.getId()); newPage.setDefaultResources(pageDefaultResources); - Mockito - .when(newPageService.findPageById(Mockito.any(), Mockito.any(), Mockito.anyBoolean())) + Mockito.when(newPageService.findPageById(Mockito.any(), Mockito.any(), Mockito.anyBoolean())) .thenReturn(Mono.just(oldPageDTO)) .thenReturn(Mono.just(newPageDTO)); - Mockito - .when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) + Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); LayoutDTO layout = new LayoutDTO(); @@ -987,22 +975,19 @@ public void testMoveCollection_toValidPage_returnsCollection() throws IOExceptio jsonObject.put("key", "value"); layout.setDsl(jsonObject); - Mockito - .when(layoutActionService.unescapeMongoSpecialCharacters(Mockito.any())) + Mockito.when(layoutActionService.unescapeMongoSpecialCharacters(Mockito.any())) .thenReturn(jsonObject); - Mockito - .when(layoutActionService.updateLayout(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(layoutActionService.updateLayout(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(layout)); - Mockito - .when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) + Mockito.when(actionCollectionRepository.setUserPermissionsInObject(Mockito.any())) .thenReturn(Mono.just(actionCollection)); - final Mono<ActionCollectionDTO> actionCollectionDTOMono = layoutCollectionService.moveCollection(actionCollectionMoveDTO); + final Mono<ActionCollectionDTO> actionCollectionDTOMono = + layoutCollectionService.moveCollection(actionCollectionMoveDTO); - StepVerifier - .create(actionCollectionDTOMono) + StepVerifier.create(actionCollectionDTOMono) .assertNext(actionCollectionDTO -> { assertEquals("newPageId", actionCollectionDTO.getPageId()); }) @@ -1028,11 +1013,12 @@ public void testGenerateActionCollectionByViewModeTestTransientFields() { actionCollection.setUnpublishedCollection(mockApplicationCollectionDTO); actionCollection.setDefaultResources(mockDefaultResources); - Mono<ActionCollectionDTO> unpublishedActionCollectionDTOMono = actionCollectionService.generateActionCollectionByViewMode(actionCollection, false); - Mono<ActionCollectionDTO> publishedActionCollectionDTOMono = actionCollectionService.generateActionCollectionByViewMode(actionCollection, true); + Mono<ActionCollectionDTO> unpublishedActionCollectionDTOMono = + actionCollectionService.generateActionCollectionByViewMode(actionCollection, false); + Mono<ActionCollectionDTO> publishedActionCollectionDTOMono = + actionCollectionService.generateActionCollectionByViewMode(actionCollection, true); - StepVerifier - .create(Mono.zip(publishedActionCollectionDTOMono, unpublishedActionCollectionDTOMono)) + StepVerifier.create(Mono.zip(publishedActionCollectionDTOMono, unpublishedActionCollectionDTOMono)) .assertNext(tuple -> { ActionCollectionDTO publishedActionCollectionDTO = tuple.getT1(); ActionCollectionDTO unpublishedActionCollectionDTO = tuple.getT2(); @@ -1041,17 +1027,19 @@ public void testGenerateActionCollectionByViewModeTestTransientFields() { assertEquals(mockAppId, publishedActionCollectionDTO.getApplicationId()); assertEquals(mockWorkspaceId, publishedActionCollectionDTO.getWorkspaceId()); assertEquals(mockPermissions, publishedActionCollectionDTO.getUserPermissions()); - assertEquals(mockAppId, publishedActionCollectionDTO.getDefaultResources().getApplicationId()); + assertEquals( + mockAppId, + publishedActionCollectionDTO.getDefaultResources().getApplicationId()); assertNotNull(unpublishedActionCollectionDTO); assertEquals(mockId, unpublishedActionCollectionDTO.getId()); assertEquals(mockAppId, unpublishedActionCollectionDTO.getApplicationId()); assertEquals(mockWorkspaceId, unpublishedActionCollectionDTO.getWorkspaceId()); assertEquals(mockPermissions, unpublishedActionCollectionDTO.getUserPermissions()); - assertEquals(mockAppId, unpublishedActionCollectionDTO.getDefaultResources().getApplicationId()); + assertEquals( + mockAppId, + unpublishedActionCollectionDTO.getDefaultResources().getApplicationId()); }) .verifyComplete(); - - } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceTest.java index 7a7f03597bc8..8dc367506d6c 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceTest.java @@ -141,16 +141,19 @@ public void setup() { toCreate.setName("ActionCollectionServiceTest"); if (workspaceId == null) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); } if (testApp == null && testPage == null) { - //Create application and page which will be used by the tests to create actions for. + // Create application and page which will be used by the tests to create actions for. Application application = new Application(); application.setName(UUID.randomUUID().toString()); - testApp = applicationPageService.createApplication(application, workspaceId).block(); + testApp = applicationPageService + .createApplication(application, workspaceId) + .block(); assert testApp != null; final String pageId = testApp.getPages().get(0).getId(); @@ -180,7 +183,8 @@ public void setup() { layout.setPublishedDsl(dsl); } - Plugin installedJsPlugin = pluginRepository.findByPackageName("installed-js-plugin").block(); + Plugin installedJsPlugin = + pluginRepository.findByPackageName("installed-js-plugin").block(); PluginWorkspaceDTO pluginWorkspaceDTO = new PluginWorkspaceDTO(); pluginWorkspaceDTO.setPluginId(installedJsPlugin.getId()); pluginWorkspaceDTO.setWorkspaceId(workspaceId); @@ -235,7 +239,9 @@ public void testCreateActionCollection_verifySoftDeletedCollectionIsNotLoaded() Application application = new Application(); application.setName(UUID.randomUUID().toString()); - Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); assert createdApplication != null; final String pageId = createdApplication.getPages().get(0).getId(); @@ -249,19 +255,22 @@ public void testCreateActionCollection_verifySoftDeletedCollectionIsNotLoaded() actionCollectionDTO.setPluginType(PluginType.JS); actionCollectionDTO.setDeletedAt(Instant.now()); layoutCollectionService.createCollection(actionCollectionDTO).block(); - ActionCollection createdActionCollection = actionCollectionRepository.findByApplicationId(createdApplication.getId(), READ_ACTIONS, null).blockFirst(); + ActionCollection createdActionCollection = actionCollectionRepository + .findByApplicationId(createdApplication.getId(), READ_ACTIONS, null) + .blockFirst(); createdActionCollection.setDeletedAt(Instant.now()); actionCollectionRepository.save(createdActionCollection).block(); - StepVerifier.create(actionCollectionRepository.findByApplicationId(createdApplication.getId(), READ_ACTIONS, null)) + StepVerifier.create( + actionCollectionRepository.findByApplicationId(createdApplication.getId(), READ_ACTIONS, null)) .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void createValidActionCollectionAndCheckPermissions() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -280,40 +289,54 @@ public void createValidActionCollectionAndCheckPermissions() { actionCollectionDTO.setPluginId(datasource.getPluginId()); actionCollectionDTO.setPluginType(PluginType.JS); - Mono<ActionCollection> actionCollectionMono = layoutCollectionService.createCollection(actionCollectionDTO) - .flatMap(createdCollection -> actionCollectionService.findById(createdCollection.getId(), READ_ACTIONS)); + Mono<ActionCollection> actionCollectionMono = layoutCollectionService + .createCollection(actionCollectionDTO) + .flatMap( + createdCollection -> actionCollectionService.findById(createdCollection.getId(), READ_ACTIONS)); - StepVerifier - .create(Mono.zip(actionCollectionMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip(actionCollectionMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { ActionCollection createdActionCollection = tuple.getT1(); assertThat(createdActionCollection.getId()).isNotEmpty(); - assertThat(createdActionCollection.getUnpublishedCollection().getName()).isEqualTo(actionCollectionDTO.getName()); + assertThat(createdActionCollection + .getUnpublishedCollection() + .getName()) + .isEqualTo(actionCollectionDTO.getName()); List<PermissionGroup> permissionGroups = tuple.getT2(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageActionPolicy = Policy.builder().permission(MANAGE_ACTIONS.getValue()) + Policy manageActionPolicy = Policy.builder() + .permission(MANAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readActionPolicy = Policy.builder().permission(READ_ACTIONS.getValue()) + Policy readActionPolicy = Policy.builder() + .permission(READ_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeActionPolicy = Policy.builder().permission(EXECUTE_ACTIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeActionPolicy = Policy.builder() + .permission(EXECUTE_ACTIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - assertThat(createdActionCollection.getPolicies()).containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); + assertThat(createdActionCollection.getPolicies()) + .containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); }) .verifyComplete(); } @@ -344,7 +367,8 @@ public void refactorNameForActionRefactorsNameInCollection() { actionCollectionDTO1.setPluginType(PluginType.JS); actionCollectionDTO1.setBody("export default { x: 1 }"); - final ActionCollectionDTO createdActionCollectionDTO1 = layoutCollectionService.createCollection(actionCollectionDTO1).block(); + final ActionCollectionDTO createdActionCollectionDTO1 = + layoutCollectionService.createCollection(actionCollectionDTO1).block(); ActionCollectionDTO actionCollectionDTO2 = new ActionCollectionDTO(); actionCollectionDTO2.setName("testCollection2"); @@ -360,39 +384,48 @@ public void refactorNameForActionRefactorsNameInCollection() { actionCollectionDTO2.setPluginType(PluginType.JS); actionCollectionDTO2.setBody("export default { x: testCollection1.testAction1() }"); - final ActionCollectionDTO createdActionCollectionDTO2 = layoutCollectionService.createCollection(actionCollectionDTO2).block(); + final ActionCollectionDTO createdActionCollectionDTO2 = + layoutCollectionService.createCollection(actionCollectionDTO2).block(); RefactorActionNameDTO refactorActionNameDTO = new RefactorActionNameDTO(); assert createdActionCollectionDTO1 != null; - refactorActionNameDTO.setActionId(createdActionCollectionDTO1.getActions().stream().findFirst().get().getId()); + refactorActionNameDTO.setActionId(createdActionCollectionDTO1.getActions().stream() + .findFirst() + .get() + .getId()); refactorActionNameDTO.setPageId(testPage.getId()); refactorActionNameDTO.setLayoutId(testPage.getLayouts().get(0).getId()); refactorActionNameDTO.setCollectionName("testCollection1"); refactorActionNameDTO.setOldName("testAction1"); refactorActionNameDTO.setNewName("newTestAction1"); - final LayoutDTO layoutDTO = refactoringSolution.refactorActionName(refactorActionNameDTO).block(); + final LayoutDTO layoutDTO = + refactoringSolution.refactorActionName(refactorActionNameDTO).block(); assert createdActionCollectionDTO2 != null; - final Mono<ActionCollection> actionCollectionMono = actionCollectionService.getById(createdActionCollectionDTO2.getId()); + final Mono<ActionCollection> actionCollectionMono = + actionCollectionService.getById(createdActionCollectionDTO2.getId()); StepVerifier.create(actionCollectionMono) .assertNext(actionCollection -> { assertEquals( "export default { x: testCollection1.newTestAction1() }", - actionCollection.getUnpublishedCollection().getBody() - ); + actionCollection.getUnpublishedCollection().getBody()); }) .verifyComplete(); - final Mono<NewAction> actionMono = newActionService.getById(createdActionCollectionDTO2.getActions().stream().findFirst().get().getId()); + final Mono<NewAction> actionMono = newActionService.getById(createdActionCollectionDTO2.getActions().stream() + .findFirst() + .get() + .getId()); StepVerifier.create(actionMono) .assertNext(action -> { assertEquals( "testCollection1.newTestAction1()", - action.getUnpublishedAction().getActionConfiguration().getBody() - ); + action.getUnpublishedAction() + .getActionConfiguration() + .getBody()); }) .verifyComplete(); } @@ -423,7 +456,8 @@ public void testRefactorActionName_withActionNameEqualsRun_doesNotRefactorApiRun actionCollectionDTO1.setPluginType(PluginType.JS); actionCollectionDTO1.setBody("export default { x: 1 }"); - final ActionCollectionDTO createdActionCollectionDTO1 = layoutCollectionService.createCollection(actionCollectionDTO1).block(); + final ActionCollectionDTO createdActionCollectionDTO1 = + layoutCollectionService.createCollection(actionCollectionDTO1).block(); ActionCollectionDTO actionCollectionDTO2 = new ActionCollectionDTO(); actionCollectionDTO2.setName("testCollection2"); @@ -439,39 +473,48 @@ public void testRefactorActionName_withActionNameEqualsRun_doesNotRefactorApiRun actionCollectionDTO2.setPluginType(PluginType.JS); actionCollectionDTO2.setBody("export default { x: Api1.run() }"); - final ActionCollectionDTO createdActionCollectionDTO2 = layoutCollectionService.createCollection(actionCollectionDTO2).block(); + final ActionCollectionDTO createdActionCollectionDTO2 = + layoutCollectionService.createCollection(actionCollectionDTO2).block(); RefactorActionNameDTO refactorActionNameDTO = new RefactorActionNameDTO(); assert createdActionCollectionDTO1 != null; - refactorActionNameDTO.setActionId(createdActionCollectionDTO1.getActions().stream().findFirst().get().getId()); + refactorActionNameDTO.setActionId(createdActionCollectionDTO1.getActions().stream() + .findFirst() + .get() + .getId()); refactorActionNameDTO.setPageId(testPage.getId()); refactorActionNameDTO.setLayoutId(testPage.getLayouts().get(0).getId()); refactorActionNameDTO.setCollectionName("testCollection1"); refactorActionNameDTO.setOldName("run"); refactorActionNameDTO.setNewName("newRun"); - final LayoutDTO layoutDTO = refactoringSolution.refactorActionName(refactorActionNameDTO).block(); + final LayoutDTO layoutDTO = + refactoringSolution.refactorActionName(refactorActionNameDTO).block(); assert createdActionCollectionDTO2 != null; - final Mono<ActionCollection> actionCollectionMono = actionCollectionService.getById(createdActionCollectionDTO2.getId()); + final Mono<ActionCollection> actionCollectionMono = + actionCollectionService.getById(createdActionCollectionDTO2.getId()); StepVerifier.create(actionCollectionMono) .assertNext(actionCollection -> { assertEquals( "export default { x: Api1.run() }", - actionCollection.getUnpublishedCollection().getBody() - ); + actionCollection.getUnpublishedCollection().getBody()); }) .verifyComplete(); - final Mono<NewAction> actionMono = newActionService.getById(createdActionCollectionDTO2.getActions().stream().findFirst().get().getId()); + final Mono<NewAction> actionMono = newActionService.getById(createdActionCollectionDTO2.getActions().stream() + .findFirst() + .get() + .getId()); StepVerifier.create(actionMono) .assertNext(action -> { assertEquals( "Api1.run()", - action.getUnpublishedAction().getActionConfiguration().getBody() - ); + action.getUnpublishedAction() + .getActionConfiguration() + .getBody()); }) .verifyComplete(); } @@ -504,10 +547,12 @@ public void testActionCollectionInViewMode() { actionCollectionDTO.setActions(List.of(action1)); actionCollectionDTO.setPluginType(PluginType.JS); - final ActionCollectionDTO createdActionCollectionDTO = layoutCollectionService.createCollection(actionCollectionDTO).block(); + final ActionCollectionDTO createdActionCollectionDTO = + layoutCollectionService.createCollection(actionCollectionDTO).block(); assert createdActionCollectionDTO != null; - final Mono<List<ActionCollectionViewDTO>> viewModeCollectionsMono = applicationPageService.publish(testApp.getId(), true) + final Mono<List<ActionCollectionViewDTO>> viewModeCollectionsMono = applicationPageService + .publish(testApp.getId(), true) .thenMany(actionCollectionService.getActionCollectionsForViewMode(testApp.getId(), null)) .collectList(); @@ -520,7 +565,8 @@ public void testActionCollectionInViewMode() { // Actions final List<ActionDTO> actions = actionCollectionViewDTO.getActions(); assertThat(actions.size()).isEqualTo(1); - assertThat(actions.get(0).getActionConfiguration().getBody()).isEqualTo("mockBody"); + assertThat(actions.get(0).getActionConfiguration().getBody()) + .isEqualTo("mockBody"); // Variables final List<JSValue> variables = actionCollectionViewDTO.getVariables(); @@ -533,10 +579,8 @@ public void testActionCollectionInViewMode() { assertThat(actionCollectionViewDTO.getApplicationId()).isEqualTo(testApp.getId()); assertThat(actionCollectionViewDTO.getPageId()).isEqualTo(testPage.getId()); assertThat(actionCollectionViewDTO.getBody()).isEqualTo("collectionBody"); - }) .verifyComplete(); - } /** @@ -567,10 +611,12 @@ public void testDeleteActionCollection_afterApplicationPublish_clearsActionColle actionCollectionDTO.setActions(List.of(action1)); actionCollectionDTO.setPluginType(PluginType.JS); - final ActionCollectionDTO createdActionCollectionDTO = layoutCollectionService.createCollection(actionCollectionDTO).block(); + final ActionCollectionDTO createdActionCollectionDTO = + layoutCollectionService.createCollection(actionCollectionDTO).block(); assert createdActionCollectionDTO != null; - final Mono<List<ActionCollectionViewDTO>> viewModeCollectionsMono = applicationPageService.publish(testApp.getId(), true) + final Mono<List<ActionCollectionViewDTO>> viewModeCollectionsMono = applicationPageService + .publish(testApp.getId(), true) .then(actionCollectionService.deleteUnpublishedActionCollection(createdActionCollectionDTO.getId())) .then(applicationPageService.publish(testApp.getId(), true)) .thenMany(actionCollectionService.getActionCollectionsForViewMode(testApp.getId(), null)) @@ -581,7 +627,6 @@ public void testDeleteActionCollection_afterApplicationPublish_clearsActionColle assertThat(viewModeCollections).isEmpty(); }) .verifyComplete(); - } /** @@ -616,7 +661,8 @@ public void testUpdateActionCollection_fromAsyncToSync_resetsSyncFunctionFields( actionCollectionDTO.setPluginType(PluginType.JS); actionCollectionDTO.setActions(List.of(action1)); - ActionCollection createdActionCollection = layoutCollectionService.createCollection(actionCollectionDTO) + ActionCollection createdActionCollection = layoutCollectionService + .createCollection(actionCollectionDTO) .flatMap(createdCollection -> { // Delay after creating(before updating) record to get different updatedAt time try { @@ -625,10 +671,12 @@ public void testUpdateActionCollection_fromAsyncToSync_resetsSyncFunctionFields( e.printStackTrace(); } return actionCollectionService.findById(createdCollection.getId(), READ_ACTIONS); - }).block(); + }) + .block(); action1.getActionConfiguration().setIsAsync(false); - final Mono<List<ActionCollectionViewDTO>> viewModeCollectionsMono = layoutCollectionService.updateUnpublishedActionCollection(createdActionCollection.getId(), actionCollectionDTO, null) + final Mono<List<ActionCollectionViewDTO>> viewModeCollectionsMono = layoutCollectionService + .updateUnpublishedActionCollection(createdActionCollection.getId(), actionCollectionDTO, null) .flatMap(updatedCollection -> applicationPageService.publish(testApp.getId(), true)) .thenMany(actionCollectionService.getActionCollectionsForViewMode(testApp.getId(), null)) .collectList(); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationPageServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationPageServiceTest.java index 803245a2b1da..5446e5331b07 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationPageServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationPageServiceTest.java @@ -49,7 +49,8 @@ public class ApplicationPageServiceTest { private Mono<PageDTO> createPageMono(String uniquePrefix) { Workspace unsavedWorkspace = new Workspace(); unsavedWorkspace.setName(uniquePrefix + "_org"); - return workspaceService.create(unsavedWorkspace) + return workspaceService + .create(unsavedWorkspace) .flatMap(workspace -> { Application application = new Application(); application.setName(uniquePrefix + "_app"); @@ -70,16 +71,19 @@ public void deleteUnpublishedPage_WhenPageDeleted_ApplicationEditDateSet() { .flatMap(pageDTO -> { Application application = new Application(); application.setLastEditedAt(Instant.now().minus(10, ChronoUnit.DAYS)); - return applicationRepository.updateById(pageDTO.getApplicationId(), application, AclPermission.MANAGE_APPLICATIONS) + return applicationRepository + .updateById(pageDTO.getApplicationId(), application, AclPermission.MANAGE_APPLICATIONS) .then(applicationPageService.deleteUnpublishedPage(pageDTO.getId())) .then(applicationRepository.findById(pageDTO.getApplicationId())); }); - StepVerifier.create(applicationMono).assertNext(application -> { - assertThat(application.getLastEditedAt()).isNotNull(); - Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS); - assertThat(application.getLastEditedAt()).isAfter(yesterday); - }).verifyComplete(); + StepVerifier.create(applicationMono) + .assertNext(application -> { + assertThat(application.getLastEditedAt()).isNotNull(); + Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS); + assertThat(application.getLastEditedAt()).isAfter(yesterday); + }) + .verifyComplete(); } @Test @@ -88,8 +92,11 @@ public void cloneApplication_WhenClonedSuccessfully_ApplicationIsPublished() { Mono<Application> applicationMono = createPageMono(UUID.randomUUID().toString()) .flatMap(pageDTO -> applicationPageService.cloneApplication(pageDTO.getApplicationId(), null)); - StepVerifier.create(applicationMono).assertNext(application -> { - assertThat(application.getPages().size()).isEqualTo(application.getPublishedPages().size()); - }).verifyComplete(); + StepVerifier.create(applicationMono) + .assertNext(application -> { + assertThat(application.getPages().size()) + .isEqualTo(application.getPublishedPages().size()); + }) + .verifyComplete(); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationSnapshotServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationSnapshotServiceTest.java index fa15dcb64825..1517f6c750ad 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationSnapshotServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationSnapshotServiceTest.java @@ -47,7 +47,8 @@ public void createApplicationSnapshot_WhenNoPreviousSnapshotExists_NewCreated() Workspace workspace = new Workspace(); workspace.setName("Test workspace " + UUID.randomUUID()); - Mono<ApplicationSnapshot> snapshotMono = workspaceService.create(workspace) + Mono<ApplicationSnapshot> snapshotMono = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application testApplication = new Application(); testApplication.setName("Test app for snapshot"); @@ -56,10 +57,12 @@ public void createApplicationSnapshot_WhenNoPreviousSnapshotExists_NewCreated() }) .flatMap(application -> { assert application.getId() != null; - return applicationSnapshotService.createApplicationSnapshot(application.getId(), "") + return applicationSnapshotService + .createApplicationSnapshot(application.getId(), "") .thenReturn(application.getId()); }) - .flatMap(applicationId -> applicationSnapshotService.getWithoutDataByApplicationId(applicationId, null)); + .flatMap( + applicationId -> applicationSnapshotService.getWithoutDataByApplicationId(applicationId, null)); StepVerifier.create(snapshotMono) .assertNext(snapshot -> { @@ -76,7 +79,8 @@ public void createApplicationSnapshot_WhenSnapshotExists_ExistingSnapshotUpdated Workspace workspace = new Workspace(); workspace.setName("Test workspace " + UUID.randomUUID()); - Mono<ApplicationSnapshot> snapshotMono = workspaceService.create(workspace) + Mono<ApplicationSnapshot> snapshotMono = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application testApplication = new Application(); testApplication.setName("Test app for snapshot"); @@ -86,11 +90,13 @@ public void createApplicationSnapshot_WhenSnapshotExists_ExistingSnapshotUpdated .flatMap(application -> { assert application.getId() != null; // create snapshot twice - return applicationSnapshotService.createApplicationSnapshot(application.getId(), "") + return applicationSnapshotService + .createApplicationSnapshot(application.getId(), "") .then(applicationSnapshotService.createApplicationSnapshot(application.getId(), "")) .thenReturn(application.getId()); }) - .flatMap(applicationId -> applicationSnapshotService.getWithoutDataByApplicationId(applicationId, null)); + .flatMap( + applicationId -> applicationSnapshotService.getWithoutDataByApplicationId(applicationId, null)); StepVerifier.create(snapshotMono) .assertNext(snapshot -> { @@ -110,7 +116,8 @@ public void createApplicationSnapshot_WhenGitBranchExists_SnapshotCreatedWithBra Workspace workspace = new Workspace(); workspace.setName("Test workspace " + uniqueString); - Mono<Tuple2<ApplicationSnapshot, Application>> tuple2Mono = workspaceService.create(workspace) + Mono<Tuple2<ApplicationSnapshot, Application>> tuple2Mono = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application testApplication = new Application(); testApplication.setName("Test app for snapshot"); @@ -124,8 +131,10 @@ public void createApplicationSnapshot_WhenGitBranchExists_SnapshotCreatedWithBra return applicationPageService.createApplication(testApplication); }) - .flatMap(application -> applicationSnapshotService.createApplicationSnapshot(testDefaultAppId, testBranchName) - .then(applicationSnapshotService.getWithoutDataByApplicationId(testDefaultAppId, testBranchName)) + .flatMap(application -> applicationSnapshotService + .createApplicationSnapshot(testDefaultAppId, testBranchName) + .then(applicationSnapshotService.getWithoutDataByApplicationId( + testDefaultAppId, testBranchName)) .zipWith(Mono.just(application))); StepVerifier.create(tuple2Mono) @@ -148,7 +157,8 @@ public void createApplicationSnapshot_OlderSnapshotExists_OlderSnapshotsRemoved( Workspace workspace = new Workspace(); workspace.setName("Test workspace " + uniqueString); - Flux<ApplicationSnapshot> applicationSnapshotFlux = workspaceService.create(workspace) + Flux<ApplicationSnapshot> applicationSnapshotFlux = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application testApplication = new Application(); testApplication.setName("Test app for snapshot"); @@ -160,12 +170,13 @@ public void createApplicationSnapshot_OlderSnapshotExists_OlderSnapshotsRemoved( applicationSnapshot.setApplicationId(application.getId()); applicationSnapshot.setChunkOrder(5); applicationSnapshot.setData("Hello".getBytes(StandardCharsets.UTF_8)); - return applicationSnapshotRepository.save(applicationSnapshot).thenReturn(application); + return applicationSnapshotRepository + .save(applicationSnapshot) + .thenReturn(application); }) - .flatMapMany(application -> - applicationSnapshotService.createApplicationSnapshot(application.getId(), null) - .thenMany(applicationSnapshotRepository.findByApplicationId(application.getId())) - ); + .flatMapMany(application -> applicationSnapshotService + .createApplicationSnapshot(application.getId(), null) + .thenMany(applicationSnapshotRepository.findByApplicationId(application.getId()))); StepVerifier.create(applicationSnapshotFlux) .assertNext(applicationSnapshot -> { @@ -185,44 +196,54 @@ public void restoreSnapshot_WhenNewPagesAddedAfterSnapshotTaken_NewPagesRemovedA Workspace workspace = new Workspace(); workspace.setName("Test workspace " + uniqueString); - Mono<Application> applicationMono = workspaceService.create(workspace) + Mono<Application> applicationMono = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application testApplication = new Application(); testApplication.setName("App before snapshot"); return applicationPageService.createApplication(testApplication, workspace.getId()); - }).cache(); - - Mono<ApplicationPagesDTO> pagesBeforeSnapshot = applicationMono - .flatMap(createdApp -> { - // add a page to the application - PageDTO pageDTO = new PageDTO(); - pageDTO.setName("Home"); - pageDTO.setApplicationId(createdApp.getId()); - return applicationPageService.createPage(pageDTO) - .then(newPageService.findApplicationPages(createdApp.getId(), null, null, ApplicationMode.EDIT)); - }); + }) + .cache(); - Mono<ApplicationPagesDTO> pagesAfterSnapshot = applicationMono.flatMap(application -> { // create a snapshot - return applicationSnapshotService.createApplicationSnapshot(application.getId(), null) - .thenReturn(application); - }).flatMap(application -> { // add a new page to the application + Mono<ApplicationPagesDTO> pagesBeforeSnapshot = applicationMono.flatMap(createdApp -> { + // add a page to the application PageDTO pageDTO = new PageDTO(); - pageDTO.setName("About"); - pageDTO.setApplicationId(application.getId()); - return applicationPageService.createPage(pageDTO) - .then(applicationSnapshotService.restoreSnapshot(application.getId(), null)) - .then(newPageService.findApplicationPages(application.getId(), null, null, ApplicationMode.EDIT)); + pageDTO.setName("Home"); + pageDTO.setApplicationId(createdApp.getId()); + return applicationPageService + .createPage(pageDTO) + .then(newPageService.findApplicationPages(createdApp.getId(), null, null, ApplicationMode.EDIT)); }); + Mono<ApplicationPagesDTO> pagesAfterSnapshot = applicationMono + .flatMap( + application -> { // create a snapshot + return applicationSnapshotService + .createApplicationSnapshot(application.getId(), null) + .thenReturn(application); + }) + .flatMap( + application -> { // add a new page to the application + PageDTO pageDTO = new PageDTO(); + pageDTO.setName("About"); + pageDTO.setApplicationId(application.getId()); + return applicationPageService + .createPage(pageDTO) + .then(applicationSnapshotService.restoreSnapshot(application.getId(), null)) + .then(newPageService.findApplicationPages( + application.getId(), null, null, ApplicationMode.EDIT)); + }); + // not using Mono.zip because we want pagesBeforeSnapshot to finish first - Mono<Tuple2<ApplicationPagesDTO, ApplicationPagesDTO>> tuple2Mono = pagesBeforeSnapshot - .flatMap(applicationPagesDTO -> pagesAfterSnapshot.zipWith(Mono.just(applicationPagesDTO))); + Mono<Tuple2<ApplicationPagesDTO, ApplicationPagesDTO>> tuple2Mono = pagesBeforeSnapshot.flatMap( + applicationPagesDTO -> pagesAfterSnapshot.zipWith(Mono.just(applicationPagesDTO))); StepVerifier.create(tuple2Mono) .assertNext(objects -> { ApplicationPagesDTO beforePages = objects.getT2(); ApplicationPagesDTO afterPages = objects.getT1(); - assertThat(beforePages.getPages().size()).isEqualTo(afterPages.getPages().size()); + assertThat(beforePages.getPages().size()) + .isEqualTo(afterPages.getPages().size()); }) .verifyComplete(); } @@ -236,22 +257,24 @@ public void restoreSnapshot_WhenSuccessfullyRestored_SnapshotDeleted() { Workspace workspace = new Workspace(); workspace.setName("Test workspace " + uniqueString); - Flux<ApplicationSnapshot> snapshotFlux = workspaceService.create(workspace) + Flux<ApplicationSnapshot> snapshotFlux = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application testApplication = new Application(); testApplication.setName("App before snapshot"); return applicationPageService.createApplication(testApplication, workspace.getId()); - }).flatMap(application -> { // create a snapshot - return applicationSnapshotService.createApplicationSnapshot(application.getId(), null) - .thenReturn(application); }) - .flatMapMany(application -> - applicationSnapshotService.restoreSnapshot(application.getId(), null) - .thenMany(applicationSnapshotRepository.findByApplicationId(application.getId())) - ); - - StepVerifier.create(snapshotFlux) - .verifyComplete(); + .flatMap( + application -> { // create a snapshot + return applicationSnapshotService + .createApplicationSnapshot(application.getId(), null) + .thenReturn(application); + }) + .flatMapMany(application -> applicationSnapshotService + .restoreSnapshot(application.getId(), null) + .thenMany(applicationSnapshotRepository.findByApplicationId(application.getId()))); + + StepVerifier.create(snapshotFlux).verifyComplete(); } @Test @@ -265,12 +288,12 @@ public void deleteSnapshot_WhenSnapshotExists_Deleted() { snapshot2.setApplicationId(testAppId); snapshot2.setChunkOrder(2); - Flux<ApplicationSnapshot> snapshotFlux = applicationSnapshotRepository.saveAll(List.of(snapshot1, snapshot2)) + Flux<ApplicationSnapshot> snapshotFlux = applicationSnapshotRepository + .saveAll(List.of(snapshot1, snapshot2)) .then(applicationSnapshotService.deleteSnapshot(testAppId, null)) .thenMany(applicationSnapshotRepository.findByApplicationId(testAppId)); - StepVerifier.create(snapshotFlux) - .verifyComplete(); + StepVerifier.create(snapshotFlux).verifyComplete(); } @WithUserDetails("api_user") @@ -280,7 +303,8 @@ public void getWithoutDataByApplicationId_WhenSnanshotNotFound_ReturnsEmptySnaps Workspace workspace = new Workspace(); workspace.setName("Test workspace " + uniqueString); - Mono<ApplicationSnapshot> applicationSnapshotMono = workspaceService.create(workspace) + Mono<ApplicationSnapshot> applicationSnapshotMono = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application testApplication = new Application(); testApplication.setName("Test app for snapshot"); @@ -297,4 +321,4 @@ public void getWithoutDataByApplicationId_WhenSnanshotNotFound_ReturnsEmptySnaps }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationTemplateServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationTemplateServiceTest.java index 8ba28cc42f9d..c6bc27d60d40 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationTemplateServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationTemplateServiceTest.java @@ -39,20 +39,28 @@ public class ApplicationTemplateServiceTest { private static final ObjectMapper objectMapper = new ObjectMapper(); private static MockWebServer mockCloudServices; ApplicationTemplateService applicationTemplateService; + @MockBean ApplicationPermission applicationPermission; + @MockBean private UserDataService userDataService; + @MockBean private CloudServicesConfig cloudServicesConfig; + @MockBean private ReleaseNotesService releaseNotesService; + @MockBean private ImportExportApplicationService importExportApplicationService; + @MockBean private AnalyticsService analyticsService; + @MockBean private ApplicationService applicationService; + @MockBean private ResponseUtils responseUtils; @@ -75,9 +83,14 @@ public void initialize() { Mockito.when(cloudServicesConfig.getBaseUrl()).thenReturn(baseUrl); applicationTemplateService = new ApplicationTemplateServiceImpl( - cloudServicesConfig, releaseNotesService, importExportApplicationService, analyticsService, - userDataService, applicationService, responseUtils, applicationPermission - ); + cloudServicesConfig, + releaseNotesService, + importExportApplicationService, + analyticsService, + userDataService, + applicationService, + responseUtils, + applicationPermission); } private ApplicationTemplate create(String id, String title) { @@ -94,10 +107,9 @@ public void getActiveTemplates_WhenRecentlyUsedExists_RecentOnesComesFirst() thr ApplicationTemplate templateThree = create("id-three", "Third template"); // mock the server to return the above three templates - mockCloudServices - .enqueue(new MockResponse() - .setBody(objectMapper.writeValueAsString(List.of(templateOne, templateTwo, templateThree))) - .addHeader("Content-Type", "application/json")); + mockCloudServices.enqueue(new MockResponse() + .setBody(objectMapper.writeValueAsString(List.of(templateOne, templateTwo, templateThree))) + .addHeader("Content-Type", "application/json")); // mock the user data to set second template as recently used UserData mockUserData = new UserData(); @@ -106,10 +118,12 @@ public void getActiveTemplates_WhenRecentlyUsedExists_RecentOnesComesFirst() thr Mono<List<ApplicationTemplate>> templateListMono = applicationTemplateService.getActiveTemplates(null); - StepVerifier.create(templateListMono).assertNext(applicationTemplates -> { - assertThat(applicationTemplates.size()).isEqualTo(3); - assertThat(applicationTemplates.get(0).getId()).isEqualTo("id-two"); // second one should come first - }).verifyComplete(); + StepVerifier.create(templateListMono) + .assertNext(applicationTemplates -> { + assertThat(applicationTemplates.size()).isEqualTo(3); + assertThat(applicationTemplates.get(0).getId()).isEqualTo("id-two"); // second one should come first + }) + .verifyComplete(); } @Test @@ -122,21 +136,22 @@ public void getRecentlyUsedTemplates_WhenNoRecentTemplate_ReturnsEmpty() { } @Test - public void getRecentlyUsedTemplates_WhenRecentTemplatesExist_ReturnsTemplates() throws InterruptedException, JsonProcessingException { + public void getRecentlyUsedTemplates_WhenRecentTemplatesExist_ReturnsTemplates() + throws InterruptedException, JsonProcessingException { // mock the user data to set recently used template ids UserData mockUserData = new UserData(); mockUserData.setRecentlyUsedTemplateIds(List.of("id-one", "id-two")); Mockito.when(userDataService.getForCurrentUser()).thenReturn(Mono.just(mockUserData)); // mock the server to return a template when it's called - mockCloudServices - .enqueue(new MockResponse() - .setBody(objectMapper.writeValueAsString(List.of(create("id-one", "First template")))) - .addHeader("Content-Type", "application/json")); + mockCloudServices.enqueue(new MockResponse() + .setBody(objectMapper.writeValueAsString(List.of(create("id-one", "First template")))) + .addHeader("Content-Type", "application/json")); // make sure we've received the response returned by the mockCloudServices StepVerifier.create(applicationTemplateService.getRecentlyUsedTemplates()) - .assertNext(applicationTemplates -> assertThat(applicationTemplates).hasSize(1)) + .assertNext( + applicationTemplates -> assertThat(applicationTemplates).hasSize(1)) .verifyComplete(); // verify that mockCloudServices was called with the query param id i.e. id=id-one&id=id-two @@ -164,10 +179,8 @@ public void get_WhenPageMetaDataExists_PageMetaDataParsedProperly() throws JsonP templates.put(templateObj); // mock the server to return a template when it's called - mockCloudServices - .enqueue(new MockResponse() - .setBody(templates.toString()) - .addHeader("Content-Type", "application/json")); + mockCloudServices.enqueue( + new MockResponse().setBody(templates.toString()).addHeader("Content-Type", "application/json")); // mock the user data to set recently used template ids UserData mockUserData = new UserData(); @@ -188,4 +201,4 @@ public void get_WhenPageMetaDataExists_PageMetaDataParsedProperly() throws JsonP }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CurlImporterServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CurlImporterServiceTest.java index 583ea3a9a64d..779ecdab4f26 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CurlImporterServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CurlImporterServiceTest.java @@ -130,7 +130,8 @@ private static void assertHeaders(ActionDTO action, Property... headers) { continue; } - // we keep removing the entries that have matched so that in the end we have zero entries in the headerStore. + // we keep removing the entries that have matched so that in the end we have zero entries in the + // headerStore. headerStorePropertyList.remove(listIndex); if (headerStorePropertyList.isEmpty()) { headerStore.remove(key); @@ -147,7 +148,7 @@ private static void assertHeaders(ActionDTO action, Property... headers) { } // if headerStore has keys then it would mean that there are more headers than expected; - assert headerStore.size() == 0; + assert headerStore.isEmpty(); // if all header matches then only it will reach here. } @@ -177,7 +178,8 @@ public void setup() { toCreate.setName("CurlImporterServiceTest"); if (workspaceId == null) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); } } @@ -193,52 +195,75 @@ public void lexerTests() { assertThat(curlImporterService.lex("curl -H X-Something:\\ something\\ else http://example.org/get")) .isEqualTo(List.of("curl", "-H", "X-Something: something else", "http://example.org/get")); - assertThat(curlImporterService.lex("curl -H \"X-Something: something \\\"quoted\\\" else\" http://example.org/get")) + assertThat(curlImporterService.lex( + "curl -H \"X-Something: something \\\"quoted\\\" else\" http://example.org/get")) .isEqualTo(List.of("curl", "-H", "X-Something: something \"quoted\" else", "http://example.org/get")); - assertThat(curlImporterService.lex("curl -H \"X-Something: something \\\\\\\"quoted\\\" else\" http://example.org/get")) + assertThat(curlImporterService.lex( + "curl -H \"X-Something: something \\\\\\\"quoted\\\" else\" http://example.org/get")) .isEqualTo(List.of("curl", "-H", "X-Something: something \\\"quoted\" else", "http://example.org/get")); // The following tests are meant for cases when any of the components have nested quotes within them - // In this example, the header argument is surrounded by single quotes, the value for it is surrounded by double quotes, + // In this example, the header argument is surrounded by single quotes, the value for it is surrounded by double + // quotes, // and the contents of the value has two single quotes - assertThat(curlImporterService.lex("curl -H 'X-Something: \"something '\\''quoted with nesting'\\'' else\"' http://example.org/get")) - .isEqualTo(List.of("curl", "-H", "X-Something: \"something 'quoted with nesting' else\"", "http://example.org/get")); - // In this example, the header argument is surrounded by single quotes, the value for it is surrounded by double quotes, + assertThat( + curlImporterService.lex( + "curl -H 'X-Something: \"something '\\''quoted with nesting'\\'' else\"' http://example.org/get")) + .isEqualTo(List.of( + "curl", + "-H", + "X-Something: \"something 'quoted with nesting' else\"", + "http://example.org/get")); + // In this example, the header argument is surrounded by single quotes, the value for it is surrounded by double + // quotes, // and the contents of the value has one single quote - assertThat(curlImporterService.lex("curl -H 'X-Something: \"something '\\''ed with nesting else\"' http://example.org/get")) - .isEqualTo(List.of("curl", "-H", "X-Something: \"something 'ed with nesting else\"", "http://example.org/get")); + assertThat(curlImporterService.lex( + "curl -H 'X-Something: \"something '\\''ed with nesting else\"' http://example.org/get")) + .isEqualTo(List.of( + "curl", "-H", "X-Something: \"something 'ed with nesting else\"", "http://example.org/get")); // In the following test, we're simulating a subshell. This subshell call is outside of quotes try { - curlImporterService.lex("curl -H 'X-Something: \"something '$(echo test)' quoted with nesting else\"' http://example.org/get"); + curlImporterService.lex( + "curl -H 'X-Something: \"something '$(echo test)' quoted with nesting else\"' http://example.org/get"); } catch (Exception e) { assertThat(e).isInstanceOf(AppsmithException.class); - assertThat(e.getMessage()).isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage("Please do not try to invoke a subshell in the cURL")); + assertThat(e.getMessage()) + .isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage( + "Please do not try to invoke a subshell in the cURL")); } try { - curlImporterService.lex("curl -H 'X-Something: \"something '`echo test`' quoted with nesting else\"' http://example.org/get"); + curlImporterService.lex( + "curl -H 'X-Something: \"something '`echo test`' quoted with nesting else\"' http://example.org/get"); } catch (Exception e) { assertThat(e).isInstanceOf(AppsmithException.class); - assertThat(e.getMessage()).isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage("Please do not try to invoke a subshell in the cURL")); + assertThat(e.getMessage()) + .isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage( + "Please do not try to invoke a subshell in the cURL")); } // In the following test, we're simulating a subshell. Subshells can be inside double-quoted strings as well try { - curlImporterService.lex("curl -H \"X-Something: 'something $(echo test) quoted with nesting else'\" http://example.org/get"); + curlImporterService.lex( + "curl -H \"X-Something: 'something $(echo test) quoted with nesting else'\" http://example.org/get"); } catch (Exception e) { assertThat(e).isInstanceOf(AppsmithException.class); - assertThat(e.getMessage()).isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage("Please do not try to invoke a subshell in the cURL")); + assertThat(e.getMessage()) + .isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage( + "Please do not try to invoke a subshell in the cURL")); } try { - curlImporterService.lex("curl -H \"X-Something: 'something `echo test` quoted with nesting else'\" http://example.org/get"); + curlImporterService.lex( + "curl -H \"X-Something: 'something `echo test` quoted with nesting else'\" http://example.org/get"); } catch (Exception e) { assertThat(e).isInstanceOf(AppsmithException.class); - assertThat(e.getMessage()).isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage("Please do not try to invoke a subshell in the cURL")); + assertThat(e.getMessage()) + .isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage( + "Please do not try to invoke a subshell in the cURL")); } } @Test public void lexComments() { - assertThat(curlImporterService.lex("curl some args # comment here")) - .isEqualTo(List.of("curl", "some", "args")); + assertThat(curlImporterService.lex("curl some args # comment here")).isEqualTo(List.of("curl", "some", "args")); assertThat(curlImporterService.lex("curl some args \\# comment here")) .isEqualTo(List.of("curl", "some", "args", "#", "comment", "here")); assertThat(curlImporterService.lex("curl some args '#' comment here")) @@ -261,17 +286,19 @@ public void testImportActionOnInvalidInput() { Application app = new Application(); app.setName("curlTest Incorrect Command"); - Application application = applicationPageService.createApplication(app, workspaceId).block(); + Application application = + applicationPageService.createApplication(app, workspaceId).block(); assert application != null; - PageDTO page = newPageService.findPageById(application.getPages().get(0).getId(), AclPermission.MANAGE_PAGES, false).block(); + PageDTO page = newPageService + .findPageById(application.getPages().get(0).getId(), AclPermission.MANAGE_PAGES, false) + .block(); assert page != null; Mono<ActionDTO> action = curlImporterService.importAction("'", page.getId(), "actionName", workspaceId, null); - StepVerifier - .create(action) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_CURL_COMMAND.getMessage())) + StepVerifier.create(action) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_CURL_COMMAND.getMessage())) .verify(); } @@ -283,17 +310,19 @@ public void testImportActionOnNullInput() { Application app = new Application(); app.setName("curlTest Incorrect Command"); - Application application = applicationPageService.createApplication(app, workspaceId).block(); + Application application = + applicationPageService.createApplication(app, workspaceId).block(); assert application != null; - PageDTO page = newPageService.findPageById(application.getPages().get(0).getId(), AclPermission.MANAGE_PAGES, false).block(); + PageDTO page = newPageService + .findPageById(application.getPages().get(0).getId(), AclPermission.MANAGE_PAGES, false) + .block(); assert page != null; Mono<ActionDTO> action = curlImporterService.importAction(null, page.getId(), "actionName", workspaceId, null); - StepVerifier - .create(action) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.EMPTY_CURL_INPUT_STATEMENT.getMessage())) + StepVerifier.create(action) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.EMPTY_CURL_INPUT_STATEMENT.getMessage())) .verify(); } @@ -305,17 +334,19 @@ public void testImportActionOnEmptyInput() { Application app = new Application(); app.setName("curlTest Incorrect Command"); - Application application = applicationPageService.createApplication(app, workspaceId).block(); + Application application = + applicationPageService.createApplication(app, workspaceId).block(); assert application != null; - PageDTO page = newPageService.findPageById(application.getPages().get(0).getId(), AclPermission.MANAGE_PAGES, false).block(); + PageDTO page = newPageService + .findPageById(application.getPages().get(0).getId(), AclPermission.MANAGE_PAGES, false) + .block(); assert page != null; Mono<ActionDTO> action = curlImporterService.importAction("", page.getId(), "actionName", workspaceId, null); - StepVerifier - .create(action) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.EMPTY_CURL_INPUT_STATEMENT.getMessage())) + StepVerifier.create(action) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.EMPTY_CURL_INPUT_STATEMENT.getMessage())) .verify(); } @@ -331,31 +362,36 @@ public void importValidCurlCommand() { Application app = new Application(); app.setName("curlTest App"); - Mono<Application> applicationMono = applicationPageService.createApplication(app, workspaceId) + Mono<Application> applicationMono = applicationPageService + .createApplication(app, workspaceId) .flatMap(application1 -> { String pageId = application1.getPages().get(0).getId(); - return newPageService.findById(pageId, AclPermission.MANAGE_PAGES) + return newPageService + .findById(pageId, AclPermission.MANAGE_PAGES) .flatMap(newPage -> { newPage.getDefaultResources().setBranchName("main"); return newPageService.update(pageId, newPage); }) .thenReturn(application1); - }).cache(); + }) + .cache(); Mono<NewPage> defaultPageMono = applicationMono - .flatMap(application -> newPageService.findById(application.getPages().get(0).getId(), AclPermission.MANAGE_PAGES)) + .flatMap(application -> + newPageService.findById(application.getPages().get(0).getId(), AclPermission.MANAGE_PAGES)) .cache(); - String command = "curl -X GET http://localhost:8080/api/v1/actions?name=something -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate' -H 'Authorization: Basic YXBpX3VzZXI6OHVBQDsmbUI6Y252Tn57Iw==' -H 'Cache-Control: no-cache' -H 'Connection: keep-alive' -H 'Content-Type: application/json' -H 'Cookie: SESSION=97c5def4-4f72-45aa-96fe-e8a9f5ade0b5,SESSION=97c5def4-4f72-45aa-96fe-e8a9f5ade0b5; SESSION=' -H 'Host: localhost:8080' -H 'Postman-Token: 16e4b6bc-2c7a-4ab1-a127-bca382dfc0f0,a6655daa-db07-4c5e-aca3-3fd505bd230d' -H 'User-Agent: PostmanRuntime/7.20.1' -H 'cache-control: no-cache' -d '{someJson}'"; + String command = + "curl -X GET http://localhost:8080/api/v1/actions?name=something -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate' -H 'Authorization: Basic YXBpX3VzZXI6OHVBQDsmbUI6Y252Tn57Iw==' -H 'Cache-Control: no-cache' -H 'Connection: keep-alive' -H 'Content-Type: application/json' -H 'Cookie: SESSION=97c5def4-4f72-45aa-96fe-e8a9f5ade0b5,SESSION=97c5def4-4f72-45aa-96fe-e8a9f5ade0b5; SESSION=' -H 'Host: localhost:8080' -H 'Postman-Token: 16e4b6bc-2c7a-4ab1-a127-bca382dfc0f0,a6655daa-db07-4c5e-aca3-3fd505bd230d' -H 'User-Agent: PostmanRuntime/7.20.1' -H 'cache-control: no-cache' -d '{someJson}'"; Mono<ActionDTO> resultMono = defaultPageMono - .flatMap(page -> curlImporterService.importAction(command, page.getId(), "actionName", workspaceId, "main")) + .flatMap(page -> + curlImporterService.importAction(command, page.getId(), "actionName", workspaceId, "main")) .cache(); Mono<NewAction> savedActionMono = resultMono.flatMap(actionDTO -> newActionService.getById(actionDTO.getId())); - StepVerifier - .create(Mono.zip(resultMono, defaultPageMono, savedActionMono)) + StepVerifier.create(Mono.zip(resultMono, defaultPageMono, savedActionMono)) .assertNext(tuple -> { ActionDTO action1 = tuple.getT1(); NewPage newPage = tuple.getT2(); @@ -363,51 +399,62 @@ public void importValidCurlCommand() { assertThat(action1).isNotNull(); assertThat(action1.getDatasource()).isNotNull(); - assertThat(action1.getDatasource().getDatasourceConfiguration()).isNotNull(); - assertThat(action1.getDatasource().getDatasourceConfiguration().getUrl()).isEqualTo("http://localhost:8080"); + assertThat(action1.getDatasource().getDatasourceConfiguration()) + .isNotNull(); + assertThat(action1.getDatasource() + .getDatasourceConfiguration() + .getUrl()) + .isEqualTo("http://localhost:8080"); assertThat(action1.getActionConfiguration().getPath()).isEqualTo("/api/v1/actions"); - assertThat(action1.getActionConfiguration().getHeaders().size()).isEqualTo(11); - assertThat(action1.getActionConfiguration().getQueryParameters().size()).isEqualTo(1); + assertThat(action1.getActionConfiguration().getHeaders().size()) + .isEqualTo(11); + assertThat(action1.getActionConfiguration() + .getQueryParameters() + .size()) + .isEqualTo(1); assertThat(action1.getActionConfiguration().getHttpMethod()).isEqualTo(HttpMethod.GET); assertThat(action1.getActionConfiguration().getBody()).isEqualTo("{someJson}"); assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); - assertThat(action1.getDefaultResources().getPageId()).isEqualTo(newPage.getDefaultResources().getPageId()); + assertThat(action1.getDefaultResources().getPageId()) + .isEqualTo(newPage.getDefaultResources().getPageId()); assertThat(newAction.getDefaultResources().getBranchName()).isNotEmpty(); - assertThat(newAction.getDefaultResources().getBranchName()).isEqualTo(newPage.getDefaultResources().getBranchName()); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(newPage.getDefaultResources().getApplicationId()); + assertThat(newAction.getDefaultResources().getBranchName()) + .isEqualTo(newPage.getDefaultResources().getBranchName()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(newPage.getDefaultResources().getApplicationId()); }) .verifyComplete(); - Application branchedApplication = new Application(); branchedApplication.setName("branched curl test app"); branchedApplication.setWorkspaceId(workspaceId); - branchedApplication = applicationPageService.createApplication(branchedApplication).block(); + branchedApplication = + applicationPageService.createApplication(branchedApplication).block(); String branchedPageId = branchedApplication.getPages().get(0).getId(); Mono<NewPage> branchedPageMono = defaultPageMono - .flatMap(defaultPage -> - newPageService.findById(branchedPageId, AclPermission.MANAGE_PAGES) - .flatMap(newPage -> { - newPage.setDefaultResources(defaultPage.getDefaultResources()); - newPage.getDefaultResources().setBranchName("testBranch"); - return newPageService.save(newPage); - }) - ) + .flatMap(defaultPage -> newPageService + .findById(branchedPageId, AclPermission.MANAGE_PAGES) + .flatMap(newPage -> { + newPage.setDefaultResources(defaultPage.getDefaultResources()); + newPage.getDefaultResources().setBranchName("testBranch"); + return newPageService.save(newPage); + })) .cache(); Mono<ActionDTO> branchedResultMono = branchedPageMono - .flatMap(page -> curlImporterService.importAction(command, page.getDefaultResources().getPageId(), "actionName", workspaceId, "testBranch")) + .flatMap(page -> curlImporterService.importAction( + command, page.getDefaultResources().getPageId(), "actionName", workspaceId, "testBranch")) .cache(); // As importAction updates the ids with the defaultIds before sending the response to client we have to again // fetch branched action - Mono<NewAction> branchedSavedActionMono = branchedResultMono - .flatMap(actionDTO -> newActionService.findByBranchNameAndDefaultActionId("testBranch", actionDTO.getId(), AclPermission.MANAGE_ACTIONS)); + Mono<NewAction> branchedSavedActionMono = + branchedResultMono.flatMap(actionDTO -> newActionService.findByBranchNameAndDefaultActionId( + "testBranch", actionDTO.getId(), AclPermission.MANAGE_ACTIONS)); - StepVerifier - .create(Mono.zip(branchedResultMono, branchedPageMono, branchedSavedActionMono)) + StepVerifier.create(Mono.zip(branchedResultMono, branchedPageMono, branchedSavedActionMono)) .assertNext(tuple -> { ActionDTO action1 = tuple.getT1(); NewPage newPage = tuple.getT2(); @@ -415,29 +462,39 @@ public void importValidCurlCommand() { assertThat(action1).isNotNull(); assertThat(action1.getDatasource()).isNotNull(); - assertThat(action1.getDatasource().getDatasourceConfiguration()).isNotNull(); - assertThat(action1.getDatasource().getDatasourceConfiguration().getUrl()).isEqualTo("http://localhost:8080"); + assertThat(action1.getDatasource().getDatasourceConfiguration()) + .isNotNull(); + assertThat(action1.getDatasource() + .getDatasourceConfiguration() + .getUrl()) + .isEqualTo("http://localhost:8080"); assertThat(action1.getActionConfiguration().getPath()).isEqualTo("/api/v1/actions"); - assertThat(action1.getActionConfiguration().getHeaders().size()).isEqualTo(11); - assertThat(action1.getActionConfiguration().getQueryParameters().size()).isEqualTo(1); + assertThat(action1.getActionConfiguration().getHeaders().size()) + .isEqualTo(11); + assertThat(action1.getActionConfiguration() + .getQueryParameters() + .size()) + .isEqualTo(1); assertThat(action1.getActionConfiguration().getHttpMethod()).isEqualTo(HttpMethod.GET); assertThat(action1.getActionConfiguration().getBody()).isEqualTo("{someJson}"); assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); - assertThat(action1.getDefaultResources().getPageId()).isEqualTo(newPage.getDefaultResources().getPageId()); + assertThat(action1.getDefaultResources().getPageId()) + .isEqualTo(newPage.getDefaultResources().getPageId()); assertThat(action1.getDefaultResources().getPageId()).isNotEqualTo(newPage.getId()); assertThat(newAction.getDefaultResources().getBranchName()).isNotEmpty(); assertThat(newAction.getDefaultResources().getBranchName()).isEqualTo("testBranch"); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(newPage.getDefaultResources().getApplicationId()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(newPage.getDefaultResources().getApplicationId()); }) .verifyComplete(); - } @Test public void urlInSingleQuotes() throws AppsmithException { - String command = "curl --location --request POST 'http://localhost:8080/scrap/api?slugifiedName=Freshdesk&ownerName=volodimir.kudriachenko'"; + String command = + "curl --location --request POST 'http://localhost:8080/scrap/api?slugifiedName=Freshdesk&ownerName=volodimir.kudriachenko'"; ActionDTO action = curlImporterService.curlToAction(command); assertThat(action).isNotNull(); @@ -473,9 +530,9 @@ public void missingMethod() throws AppsmithException { @Test public void multilineCommand() throws AppsmithException { - String command = "curl -d '{\"message\": \"The force is strong with this one...\"}' \\\n" + - " -H \"Content-Type: application/json\" \\\n" + - " \"http://piper.net\""; + String command = "curl -d '{\"message\": \"The force is strong with this one...\"}' \\\n" + + " -H \"Content-Type: application/json\" \\\n" + + " \"http://piper.net\""; ActionDTO action = curlImporterService.curlToAction(command); @@ -495,24 +552,21 @@ public void multilineCommand() throws AppsmithException { @Test public void testUrlEncodedData() throws AppsmithException { ActionDTO action = curlImporterService.curlToAction( - "curl --data-urlencode '=all of this exactly, but url encoded ' http://loc" - ); + "curl --data-urlencode '=all of this exactly, but url encoded ' http://loc"); assertMethod(action, HttpMethod.POST); assertUrl(action, "http://loc"); assertBody(action, "all of this exactly, but url encoded "); assertEmptyBodyFormData(action); action = curlImporterService.curlToAction( - "curl --data-urlencode 'spaced name=all of this exactly, but url encoded' http://loc" - ); + "curl --data-urlencode 'spaced name=all of this exactly, but url encoded' http://loc"); assertMethod(action, HttpMethod.POST); assertUrl(action, "http://loc"); assertBody(action, "spaced name=all of this exactly, but url encoded"); assertEmptyBodyFormData(action); action = curlImporterService.curlToAction( - "curl --data-urlencode 'awesome=details, all of this exactly, but url encoded' http://loc" - ); + "curl --data-urlencode 'awesome=details, all of this exactly, but url encoded' http://loc"); assertMethod(action, HttpMethod.POST); assertUrl(action, "http://loc"); assertBody(action, "awesome=details, all of this exactly, but url encoded"); @@ -522,219 +576,224 @@ public void testUrlEncodedData() throws AppsmithException { @Test public void chromeCurlCommands1() throws AppsmithException { ActionDTO action = curlImporterService.curlToAction( - "curl 'http://localhost:3000/applications/5ea054c531cc0f7a61af0cbe/pages/5ea054c531cc0f7a61af0cc0/edit/api' \\\n" + - " -H 'Connection: keep-alive' \\\n" + - " -H 'Cache-Control: max-age=0' \\\n" + - " -H 'Upgrade-Insecure-Requests: 1' \\\n" + - " -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36' \\\n" + - " -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \\\n" + - " -H 'Sec-Fetch-Site: same-origin' \\\n" + - " -H 'Sec-Fetch-Mode: navigate' \\\n" + - " -H 'Sec-Fetch-User: ?1' \\\n" + - " -H 'Sec-Fetch-Dest: document' \\\n" + - " -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \\\n" + - " -H 'Cookie: SESSION=1e3f32c2-cc72-4771-8ed5-40a9b15de0ef' \\\n" + - " --compressed ;\n" - ); + "curl 'http://localhost:3000/applications/5ea054c531cc0f7a61af0cbe/pages/5ea054c531cc0f7a61af0cc0/edit/api' \\\n" + + " -H 'Connection: keep-alive' \\\n" + + " -H 'Cache-Control: max-age=0' \\\n" + + " -H 'Upgrade-Insecure-Requests: 1' \\\n" + + " -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36' \\\n" + + " -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \\\n" + + " -H 'Sec-Fetch-Site: same-origin' \\\n" + + " -H 'Sec-Fetch-Mode: navigate' \\\n" + + " -H 'Sec-Fetch-User: ?1' \\\n" + + " -H 'Sec-Fetch-Dest: document' \\\n" + + " -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \\\n" + + " -H 'Cookie: SESSION=1e3f32c2-cc72-4771-8ed5-40a9b15de0ef' \\\n" + + " --compressed ;\n"); assertMethod(action, HttpMethod.GET); assertUrl(action, "http://localhost:3000"); assertPath(action, "/applications/5ea054c531cc0f7a61af0cbe/pages/5ea054c531cc0f7a61af0cc0/edit/api"); - assertHeaders(action, + assertHeaders( + action, new Property("Connection", "keep-alive"), new Property("Cache-Control", "max-age=0"), new Property("Upgrade-Insecure-Requests", "1"), - new Property("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"), - new Property("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"), + new Property( + "User-Agent", + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"), + new Property( + "Accept", + "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"), new Property("Sec-Fetch-Site", "same-origin"), new Property("Sec-Fetch-Mode", "navigate"), new Property("Sec-Fetch-User", "?1"), new Property("Sec-Fetch-Dest", "document"), new Property("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8"), - new Property("Cookie", "SESSION=1e3f32c2-cc72-4771-8ed5-40a9b15de0ef") - ); + new Property("Cookie", "SESSION=1e3f32c2-cc72-4771-8ed5-40a9b15de0ef")); action = curlImporterService.curlToAction( - "curl 'http://localhost:3000/static/js/bundle.js' \\\n" + - " -H 'Connection: keep-alive' \\\n" + - " -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36' \\\n" + - " -H 'If-None-Match: W/\"8bdb-LUN0UH41MBBa7I+k9MElog5H+1I\"' \\\n" + - " -H 'Accept: */*' \\\n" + - " -H 'Sec-Fetch-Site: same-origin' \\\n" + - " -H 'Sec-Fetch-Mode: no-cors' \\\n" + - " -H 'Sec-Fetch-Dest: script' \\\n" + - " -H 'Referer: http://localhost:3000/applications/5ea054c531cc0f7a61af0cbe/pages/5ea054c531cc0f7a61af0cc0/edit/api' \\\n" + - " -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \\\n" + - " -H 'Cookie: SESSION=1e3f32c2-cc72-4771-8ed5-40a9b15de0ef' \\\n" + - " --compressed ;\n" - ); + "curl 'http://localhost:3000/static/js/bundle.js' \\\n" + " -H 'Connection: keep-alive' \\\n" + + " -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36' \\\n" + + " -H 'If-None-Match: W/\"8bdb-LUN0UH41MBBa7I+k9MElog5H+1I\"' \\\n" + + " -H 'Accept: */*' \\\n" + + " -H 'Sec-Fetch-Site: same-origin' \\\n" + + " -H 'Sec-Fetch-Mode: no-cors' \\\n" + + " -H 'Sec-Fetch-Dest: script' \\\n" + + " -H 'Referer: http://localhost:3000/applications/5ea054c531cc0f7a61af0cbe/pages/5ea054c531cc0f7a61af0cc0/edit/api' \\\n" + + " -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \\\n" + + " -H 'Cookie: SESSION=1e3f32c2-cc72-4771-8ed5-40a9b15de0ef' \\\n" + + " --compressed ;\n"); assertMethod(action, HttpMethod.GET); assertUrl(action, "http://localhost:3000"); assertPath(action, "/static/js/bundle.js"); - assertHeaders(action, + assertHeaders( + action, new Property("Connection", "keep-alive"), - new Property("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"), + new Property( + "User-Agent", + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"), new Property("If-None-Match", "W/\"8bdb-LUN0UH41MBBa7I+k9MElog5H+1I\""), new Property("Accept", "*/*"), new Property("Sec-Fetch-Site", "same-origin"), new Property("Sec-Fetch-Mode", "no-cors"), new Property("Sec-Fetch-Dest", "script"), - new Property("Referer", "http://localhost:3000/applications/5ea054c531cc0f7a61af0cbe/pages/5ea054c531cc0f7a61af0cc0/edit/api"), + new Property( + "Referer", + "http://localhost:3000/applications/5ea054c531cc0f7a61af0cbe/pages/5ea054c531cc0f7a61af0cc0/edit/api"), new Property("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8"), - new Property("Cookie", "SESSION=1e3f32c2-cc72-4771-8ed5-40a9b15de0ef") - ); + new Property("Cookie", "SESSION=1e3f32c2-cc72-4771-8ed5-40a9b15de0ef")); } @Test public void firefoxCurlCommands1() throws AppsmithException { - final ActionDTO action = curlImporterService.curlToAction("curl 'http://localhost:8080/api/v1/actions?applicationId=5ea054c531cc0f7a61af0cbe' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0' -H 'Accept: application/json, text/plain, */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Origin: http://localhost:3000' -H 'DNT: 1' -H 'Connection: keep-alive' -H 'Referer: http://localhost:3000/' -H 'Cookie: SESSION=69b4b392-03b6-4e0a-a889-49ca4b8e267e'"); + final ActionDTO action = curlImporterService.curlToAction( + "curl 'http://localhost:8080/api/v1/actions?applicationId=5ea054c531cc0f7a61af0cbe' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0' -H 'Accept: application/json, text/plain, */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Origin: http://localhost:3000' -H 'DNT: 1' -H 'Connection: keep-alive' -H 'Referer: http://localhost:3000/' -H 'Cookie: SESSION=69b4b392-03b6-4e0a-a889-49ca4b8e267e'"); assertMethod(action, HttpMethod.GET); assertUrl(action, "http://localhost:8080"); assertPath(action, "/api/v1/actions"); assertQueryParams(action, new Property("applicationId", "5ea054c531cc0f7a61af0cbe")); - assertHeaders(action, - new Property("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0"), + assertHeaders( + action, + new Property( + "User-Agent", + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0"), new Property("Accept", "application/json, text/plain, */*"), new Property("Accept-Language", "en-US,en;q=0.5"), new Property("Origin", "http://localhost:3000"), new Property("DNT", "1"), new Property("Connection", "keep-alive"), new Property("Referer", "http://localhost:3000/"), - new Property("Cookie", "SESSION=69b4b392-03b6-4e0a-a889-49ca4b8e267e") - ); + new Property("Cookie", "SESSION=69b4b392-03b6-4e0a-a889-49ca4b8e267e")); } @Test public void postmanExportCommands1() throws AppsmithException { final ActionDTO action = curlImporterService.curlToAction( - "curl --location --request PUT 'https://release-api.appsmith.com/api/v1/users/5d81feb218e1c8217d20e13f' \\\n" + - "--header 'Content-Type: application/json' \\\n" + - "--header 'Authorization: Basic abcdefghijklmnop==' \\\n" + - "--header 'Content-Type: text/plain' \\\n" + - "--data-raw '{\n" + - "\t\"workspaceId\" : \"5d8c9e946599b93bd51a3400\"\n" + - "}'" - ); + "curl --location --request PUT 'https://release-api.appsmith.com/api/v1/users/5d81feb218e1c8217d20e13f' \\\n" + + "--header 'Content-Type: application/json' \\\n" + + "--header 'Authorization: Basic abcdefghijklmnop==' \\\n" + + "--header 'Content-Type: text/plain' \\\n" + + "--data-raw '{\n" + + "\t\"workspaceId\" : \"5d8c9e946599b93bd51a3400\"\n" + + "}'"); assertMethod(action, HttpMethod.PUT); assertUrl(action, "https://release-api.appsmith.com"); assertPath(action, "/api/v1/users/5d81feb218e1c8217d20e13f"); - assertHeaders(action, + assertHeaders( + action, new Property("Content-Type", "application/json"), new Property("Authorization", "Basic abcdefghijklmnop=="), - new Property("Content-Type", "text/plain") - ); - assertBody(action, "{\n" + - "\t\"workspaceId\" : \"5d8c9e946599b93bd51a3400\"\n" + - "}"); + new Property("Content-Type", "text/plain")); + assertBody(action, "{\n" + "\t\"workspaceId\" : \"5d8c9e946599b93bd51a3400\"\n" + "}"); } @Test public void postmanCreateDatasource() throws AppsmithException { final ActionDTO action = curlImporterService.curlToAction( - "curl --location --request POST 'https://release-api.appsmith.com/api/v1/datasources' \\\n" + - "--header 'Content-Type: application/json' \\\n" + - "--header 'Cookie: SESSION=61ee9df5-3cab-400c-831b-9533218d8f9f' \\\n" + - "--header 'Content-Type: text/plain' \\\n" + - "--data-raw '{\n" + - " \"name\": \"testPostgres\",\n" + - " \"datasourceConfiguration\": {\n" + - " \t\"url\" : \"jdbc:postgresql://appsmith-test-db.cgg2px8dsrli.ap-south-1.rds.amazonaws.com\",\n" + - " \"databaseName\": \"postgres\",\n" + - " \"authentication\" : {\n" + - " \t\"username\" : \"postgres\",\n" + - " \t\"password\" : \"qwerty1234\"\n" + - " }\n" + - " },\n" + - " \"pluginId\": \"5e54eb6a05f86f6b7ad1fb53\"\n" + - "}\t'" - ); + "curl --location --request POST 'https://release-api.appsmith.com/api/v1/datasources' \\\n" + + "--header 'Content-Type: application/json' \\\n" + + "--header 'Cookie: SESSION=61ee9df5-3cab-400c-831b-9533218d8f9f' \\\n" + + "--header 'Content-Type: text/plain' \\\n" + + "--data-raw '{\n" + + " \"name\": \"testPostgres\",\n" + + " \"datasourceConfiguration\": {\n" + + " \t\"url\" : \"jdbc:postgresql://appsmith-test-db.cgg2px8dsrli.ap-south-1.rds.amazonaws.com\",\n" + + " \"databaseName\": \"postgres\",\n" + + " \"authentication\" : {\n" + + " \t\"username\" : \"postgres\",\n" + + " \t\"password\" : \"qwerty1234\"\n" + + " }\n" + + " },\n" + + " \"pluginId\": \"5e54eb6a05f86f6b7ad1fb53\"\n" + + "}\t'"); assertMethod(action, HttpMethod.POST); assertUrl(action, "https://release-api.appsmith.com"); assertPath(action, "/api/v1/datasources"); - assertHeaders(action, + assertHeaders( + action, new Property("Content-Type", "application/json"), new Property("Cookie", "SESSION=61ee9df5-3cab-400c-831b-9533218d8f9f"), - new Property("Content-Type", "text/plain") - ); - assertBody(action, "{\n" + - " \"name\": \"testPostgres\",\n" + - " \"datasourceConfiguration\": {\n" + - " \t\"url\" : \"jdbc:postgresql://appsmith-test-db.cgg2px8dsrli.ap-south-1.rds.amazonaws.com\",\n" + - " \"databaseName\": \"postgres\",\n" + - " \"authentication\" : {\n" + - " \t\"username\" : \"postgres\",\n" + - " \t\"password\" : \"qwerty1234\"\n" + - " }\n" + - " },\n" + - " \"pluginId\": \"5e54eb6a05f86f6b7ad1fb53\"\n" + - "}\t"); + new Property("Content-Type", "text/plain")); + assertBody( + action, + "{\n" + " \"name\": \"testPostgres\",\n" + + " \"datasourceConfiguration\": {\n" + + " \t\"url\" : \"jdbc:postgresql://appsmith-test-db.cgg2px8dsrli.ap-south-1.rds.amazonaws.com\",\n" + + " \"databaseName\": \"postgres\",\n" + + " \"authentication\" : {\n" + + " \t\"username\" : \"postgres\",\n" + + " \t\"password\" : \"qwerty1234\"\n" + + " }\n" + + " },\n" + + " \"pluginId\": \"5e54eb6a05f86f6b7ad1fb53\"\n" + + "}\t"); } @Test public void postmanCreateProvider() throws AppsmithException { final ActionDTO action = curlImporterService.curlToAction( - "curl --location --request POST 'https://release-api.appsmith.com/api/v1/providers' \\\n" + - "--header 'Cookie: SESSION=61ee9df5-3cab-400c-831b-9533218d8f9f' \\\n" + - "--header 'Content-Type: application/json' \\\n" + - "--header 'Content-Type: application/json' \\\n" + - "--data-raw '{\n" + - " \"name\": \"Delta Video\",\n" + - " \"description\": \"This is a video\",\n" + - " \"url\": \"http://delta.com\",\n" + - " \"imageUrl\": \"http://delta-font.com\",\n" + - " \"documentationUrl\": \"http://delta-documentation.com\",\n" + - " \"credentialSteps\": \"Here goes the steps to create documentation in a long string\",\n" + - " \"categories\": [\n" + - " \"Video\"\n" + - " ],\n" + - " \"statistics\": {\n" + - " \"imports\": 1289,\n" + - " \"averageLatency\": 230,\n" + - " \"successRate\": 99.7\n" + - " },\n" + - " \"datasourceConfiguration\": {\n" + - " \"url\": \"http://google.com\",\n" + - " \"headers\": [\n" + - " {\n" + - " \"key\": \"header1\",\n" + - " \"value\": \"value1\"\n" + - " }\n" + - " ]\n" + - " }\n" + - "}'" - ); + "curl --location --request POST 'https://release-api.appsmith.com/api/v1/providers' \\\n" + + "--header 'Cookie: SESSION=61ee9df5-3cab-400c-831b-9533218d8f9f' \\\n" + + "--header 'Content-Type: application/json' \\\n" + + "--header 'Content-Type: application/json' \\\n" + + "--data-raw '{\n" + + " \"name\": \"Delta Video\",\n" + + " \"description\": \"This is a video\",\n" + + " \"url\": \"http://delta.com\",\n" + + " \"imageUrl\": \"http://delta-font.com\",\n" + + " \"documentationUrl\": \"http://delta-documentation.com\",\n" + + " \"credentialSteps\": \"Here goes the steps to create documentation in a long string\",\n" + + " \"categories\": [\n" + + " \"Video\"\n" + + " ],\n" + + " \"statistics\": {\n" + + " \"imports\": 1289,\n" + + " \"averageLatency\": 230,\n" + + " \"successRate\": 99.7\n" + + " },\n" + + " \"datasourceConfiguration\": {\n" + + " \"url\": \"http://google.com\",\n" + + " \"headers\": [\n" + + " {\n" + + " \"key\": \"header1\",\n" + + " \"value\": \"value1\"\n" + + " }\n" + + " ]\n" + + " }\n" + + "}'"); assertMethod(action, HttpMethod.POST); assertUrl(action, "https://release-api.appsmith.com"); assertPath(action, "/api/v1/providers"); - assertHeaders(action, + assertHeaders( + action, new Property("Cookie", "SESSION=61ee9df5-3cab-400c-831b-9533218d8f9f"), new Property("Content-Type", "application/json"), - new Property("Content-Type", "application/json") - ); - assertBody(action, "{\n" + - " \"name\": \"Delta Video\",\n" + - " \"description\": \"This is a video\",\n" + - " \"url\": \"http://delta.com\",\n" + - " \"imageUrl\": \"http://delta-font.com\",\n" + - " \"documentationUrl\": \"http://delta-documentation.com\",\n" + - " \"credentialSteps\": \"Here goes the steps to create documentation in a long string\",\n" + - " \"categories\": [\n" + - " \"Video\"\n" + - " ],\n" + - " \"statistics\": {\n" + - " \"imports\": 1289,\n" + - " \"averageLatency\": 230,\n" + - " \"successRate\": 99.7\n" + - " },\n" + - " \"datasourceConfiguration\": {\n" + - " \"url\": \"http://google.com\",\n" + - " \"headers\": [\n" + - " {\n" + - " \"key\": \"header1\",\n" + - " \"value\": \"value1\"\n" + - " }\n" + - " ]\n" + - " }\n" + - "}"); + new Property("Content-Type", "application/json")); + assertBody( + action, + "{\n" + " \"name\": \"Delta Video\",\n" + + " \"description\": \"This is a video\",\n" + + " \"url\": \"http://delta.com\",\n" + + " \"imageUrl\": \"http://delta-font.com\",\n" + + " \"documentationUrl\": \"http://delta-documentation.com\",\n" + + " \"credentialSteps\": \"Here goes the steps to create documentation in a long string\",\n" + + " \"categories\": [\n" + + " \"Video\"\n" + + " ],\n" + + " \"statistics\": {\n" + + " \"imports\": 1289,\n" + + " \"averageLatency\": 230,\n" + + " \"successRate\": 99.7\n" + + " },\n" + + " \"datasourceConfiguration\": {\n" + + " \"url\": \"http://google.com\",\n" + + " \"headers\": [\n" + + " {\n" + + " \"key\": \"header1\",\n" + + " \"value\": \"value1\"\n" + + " }\n" + + " ]\n" + + " }\n" + + "}"); } @Test @@ -786,10 +845,7 @@ public void parseCurlJsTestsPart2() throws AppsmithException { assertEmptyPath(action); assertHeaders(action, new Property("Content-Type", "application/x-www-form-urlencoded")); assertEmptyBody(action); - assertBodyFormData( - action, - new Property("foo", "bar") - ); + assertBodyFormData(action, new Property("foo", "bar")); action = curlImporterService.curlToAction("curl -d \"foo=bar\" -d bar=baz https://api.sloths.com"); assertMethod(action, HttpMethod.POST); @@ -797,40 +853,29 @@ public void parseCurlJsTestsPart2() throws AppsmithException { assertEmptyPath(action); assertHeaders(action, new Property("Content-Type", "application/x-www-form-urlencoded")); assertEmptyBody(action); - assertBodyFormData( - action, - new Property("foo", "bar"), - new Property("bar", "baz") - ); + assertBodyFormData(action, new Property("foo", "bar"), new Property("bar", "baz")); - action = curlImporterService.curlToAction("curl -H \"Accept: text/plain\" --header \"User-Agent: slothy\" https://api.sloths.com"); + action = curlImporterService.curlToAction( + "curl -H \"Accept: text/plain\" --header \"User-Agent: slothy\" https://api.sloths.com"); assertMethod(action, HttpMethod.GET); assertUrl(action, "https://api.sloths.com"); assertEmptyPath(action); - assertHeaders(action, - new Property("Accept", "text/plain"), - new Property("User-Agent", "slothy") - ); + assertHeaders(action, new Property("Accept", "text/plain"), new Property("User-Agent", "slothy")); assertEmptyBody(action); - action = curlImporterService.curlToAction("curl -H 'Accept: text/*' --header 'User-Agent: slothy' https://api.sloths.com"); + action = curlImporterService.curlToAction( + "curl -H 'Accept: text/*' --header 'User-Agent: slothy' https://api.sloths.com"); assertMethod(action, HttpMethod.GET); assertUrl(action, "https://api.sloths.com"); assertEmptyPath(action); - assertHeaders(action, - new Property("Accept", "text/*"), - new Property("User-Agent", "slothy") - ); + assertHeaders(action, new Property("Accept", "text/*"), new Property("User-Agent", "slothy")); assertEmptyBody(action); action = curlImporterService.curlToAction("curl -H 'Accept: text/*' -A slothy https://api.sloths.com"); assertMethod(action, HttpMethod.GET); assertUrl(action, "https://api.sloths.com"); assertEmptyPath(action); - assertHeaders(action, - new Property("Accept", "text/*"), - new Property("User-Agent", "slothy") - ); + assertHeaders(action, new Property("Accept", "text/*"), new Property("User-Agent", "slothy")); assertEmptyBody(action); action = curlImporterService.curlToAction("curl -b 'foo=bar' slothy https://api.sloths.com"); @@ -847,7 +892,8 @@ public void parseCurlJsTestsPart2() throws AppsmithException { assertHeaders(action, new Property("Set-Cookie", "foo=bar")); assertEmptyBody(action); - action = curlImporterService.curlToAction("curl --cookie 'species=sloth;type=galactic' slothy https://api.sloths.com"); + action = curlImporterService.curlToAction( + "curl --cookie 'species=sloth;type=galactic' slothy https://api.sloths.com"); assertMethod(action, HttpMethod.GET); assertUrl(action, "https://api.sloths.com"); assertEmptyPath(action); @@ -877,7 +923,8 @@ public void parseWithDashedUrlArgument() throws AppsmithException { @Test public void parseWithDashedUrlArgument2() throws AppsmithException { - ActionDTO action = curlImporterService.curlToAction("curl -X POST -d '{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}' --url http://dummy.restapiexample.com/api/v1/create"); + ActionDTO action = curlImporterService.curlToAction( + "curl -X POST -d '{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}' --url http://dummy.restapiexample.com/api/v1/create"); assertMethod(action, HttpMethod.POST); assertUrl(action, "http://dummy.restapiexample.com"); assertPath(action, "/api/v1/create"); @@ -888,7 +935,8 @@ public void parseWithDashedUrlArgument2() throws AppsmithException { @Test public void parseWithJson() throws AppsmithException { - ActionDTO action = curlImporterService.curlToAction("curl -X POST -H'Content-Type: application/json' -d '{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}' --url http://dummy.restapiexample.com/api/v1/create"); + ActionDTO action = curlImporterService.curlToAction( + "curl -X POST -H'Content-Type: application/json' -d '{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}' --url http://dummy.restapiexample.com/api/v1/create"); assertMethod(action, HttpMethod.POST); assertUrl(action, "http://dummy.restapiexample.com"); assertPath(action, "/api/v1/create"); @@ -898,7 +946,8 @@ public void parseWithJson() throws AppsmithException { @Test public void parseWithSpacedHeader() throws AppsmithException { - ActionDTO action = curlImporterService.curlToAction("curl -H \"Accept:application/json\" http://example.org/get"); + ActionDTO action = + curlImporterService.curlToAction("curl -H \"Accept:application/json\" http://example.org/get"); assertMethod(action, HttpMethod.GET); assertUrl(action, "http://example.org"); assertPath(action, "/get"); @@ -908,44 +957,40 @@ public void parseWithSpacedHeader() throws AppsmithException { @Test public void parseCurlCommand1() throws AppsmithException { - ActionDTO action = curlImporterService.curlToAction("curl -i -H \"Accept: application/json\" -H \"Content-Type: application/json\" -X POST -d '{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}' --url http://dummy.restapiexample.com/api/v1/create"); + ActionDTO action = curlImporterService.curlToAction( + "curl -i -H \"Accept: application/json\" -H \"Content-Type: application/json\" -X POST -d '{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}' --url http://dummy.restapiexample.com/api/v1/create"); assertMethod(action, HttpMethod.POST); assertUrl(action, "http://dummy.restapiexample.com"); assertPath(action, "/api/v1/create"); - assertHeaders(action, new Property("Accept", "application/json"), new Property("Content-Type", "application/json")); + assertHeaders( + action, new Property("Accept", "application/json"), new Property("Content-Type", "application/json")); assertBody(action, "{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}"); } @Test public void parseMultipleData() throws AppsmithException { - ActionDTO action = curlImporterService.curlToAction("curl https://api.stripe.com/v1/refunds -d payment_intent=pi_Aabcxyz01aDfoo -d amount=1000"); + ActionDTO action = curlImporterService.curlToAction( + "curl https://api.stripe.com/v1/refunds -d payment_intent=pi_Aabcxyz01aDfoo -d amount=1000"); assertMethod(action, HttpMethod.POST); assertUrl(action, "https://api.stripe.com"); assertPath(action, "/v1/refunds"); assertHeaders(action, new Property("Content-Type", "application/x-www-form-urlencoded")); assertEmptyBody(action); - assertBodyFormData( - action, - new Property("payment_intent", "pi_Aabcxyz01aDfoo"), - new Property("amount", "1000") - ); + assertBodyFormData(action, new Property("payment_intent", "pi_Aabcxyz01aDfoo"), new Property("amount", "1000")); } @Test public void parseMultiFormData() throws AppsmithException { // In the curl command, we test for a combination of --form and -F // Also some values are double-quoted while some aren't. This tests a permutation of all such fields - ActionDTO action = curlImporterService.curlToAction("curl --request POST 'http://example.org/post' -F 'somekey=value' --form 'anotherKey=\"anotherValue\"'"); + ActionDTO action = curlImporterService.curlToAction( + "curl --request POST 'http://example.org/post' -F 'somekey=value' --form 'anotherKey=\"anotherValue\"'"); assertMethod(action, HttpMethod.POST); assertUrl(action, "http://example.org"); assertPath(action, "/post"); assertHeaders(action, new Property("Content-Type", "multipart/form-data")); assertEmptyBody(action); - assertBodyFormData( - action, - new Property("somekey", "value"), - new Property("anotherKey", "anotherValue") - ); + assertBodyFormData(action, new Property("somekey", "value"), new Property("anotherKey", "anotherValue")); } @Test @@ -960,7 +1005,8 @@ public void dontEatBackslashesInSingleQuotes() throws AppsmithException { @Test public void importInvalidMethod() { - assertThatThrownBy(() -> curlImporterService.curlToAction("curl -X incorrect-charactèrs http://example.org/get")) + assertThatThrownBy( + () -> curlImporterService.curlToAction("curl -X incorrect-charactèrs http://example.org/get")) .isInstanceOf(AppsmithException.class) .matches(err -> ((AppsmithException) err).getError() == AppsmithError.INVALID_CURL_METHOD); } @@ -976,17 +1022,17 @@ public void importInvalidHeader() { public void importInvalidCurlCommand() { String command = "invalid curl command here"; - Mono<ActionDTO> actionMono = curlImporterService.importAction(command, "pageId", "actionName", workspaceId, null); + Mono<ActionDTO> actionMono = + curlImporterService.importAction(command, "pageId", "actionName", workspaceId, null); - StepVerifier - .create(actionMono) - .verifyError(); + StepVerifier.create(actionMono).verifyError(); } @Test public void checkActionConfigurationFormDataForApiContentKey() { final String API_CONTENT_TYPE = "apiContentType"; - String cURLCommand = "curl -X POST https://mockurl.com -H \"Content-Type: application/json\" -d '{\"productId\": 123456, \"quantity\": 100}'"; + String cURLCommand = + "curl -X POST https://mockurl.com -H \"Content-Type: application/json\" -d '{\"productId\": 123456, \"quantity\": 100}'"; String contentType = "application/json"; String name = "actionName"; @@ -999,7 +1045,5 @@ public void checkActionConfigurationFormDataForApiContentKey() { assert (!map.isEmpty()); assert (map.containsKey(API_CONTENT_TYPE)); assert (map.get(API_CONTENT_TYPE).equals(contentType)); - } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java index c36a32ee4c05..57470dc620d2 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java @@ -67,6 +67,7 @@ public class DatasourceContextServiceTest { @Autowired DatasourceService datasourceService; + @SpyBean DatasourceStorageService datasourceStorageService; @@ -95,7 +96,6 @@ public class DatasourceContextServiceTest { String workspaceId; - @BeforeEach @WithUserDetails(value = "api_user") public void setup() { @@ -104,13 +104,14 @@ public void setup() { toCreate.setName("DatasourceServiceTest"); if (!StringUtils.hasLength(workspaceId)) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } } - @Test @WithUserDetails(value = "api_user") public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnection() { @@ -120,7 +121,10 @@ public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnectio MockPluginExecutor mockPluginExecutor = new MockPluginExecutor(); MockPluginExecutor spyMockPluginExecutor = spy(mockPluginExecutor); /* Return two different connection objects if `datasourceCreate` method is called twice */ - doReturn(Mono.just("connection_1")).doReturn(Mono.just("connection_2")).when(spyMockPluginExecutor).datasourceCreate(any()); + doReturn(Mono.just("connection_1")) + .doReturn(Mono.just("connection_2")) + .when(spyMockPluginExecutor) + .datasourceCreate(any()); Mockito.when(pluginExecutorHelper.getPluginExecutor(any())).thenReturn(Mono.just(spyMockPluginExecutor)); DatasourceStorage datasourceStorage = new DatasourceStorage(); @@ -129,12 +133,13 @@ public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnectio datasourceStorage.setDatasourceConfiguration(new DatasourceConfiguration()); datasourceStorage.setWorkspaceId(workspaceId); - DatasourceContextIdentifier datasourceContextIdentifier = new DatasourceContextIdentifier(datasourceStorage.getDatasourceId(), null); + DatasourceContextIdentifier datasourceContextIdentifier = + new DatasourceContextIdentifier(datasourceStorage.getDatasourceId(), null); Object monitor = new Object(); // Create one instance of datasource connection - Mono<DatasourceContext<?>> dsContextMono1 = datasourceContextService.getCachedDatasourceContextMono(datasourceStorage, - spyMockPluginExecutor, monitor, datasourceContextIdentifier); + Mono<DatasourceContext<?>> dsContextMono1 = datasourceContextService.getCachedDatasourceContextMono( + datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier); Datasource datasource = new Datasource(); datasource.setId("id1"); @@ -144,8 +149,12 @@ public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnectio storages.put(defaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); - doReturn(Mono.just(datasource)).when(datasourceRepository).findById("id1", datasourcePermission.getDeletePermission()); - doReturn(Mono.just(datasource)).when(datasourceRepository).findById("id1", datasourcePermission.getExecutePermission()); + doReturn(Mono.just(datasource)) + .when(datasourceRepository) + .findById("id1", datasourcePermission.getDeletePermission()); + doReturn(Mono.just(datasource)) + .when(datasourceRepository) + .findById("id1", datasourcePermission.getExecutePermission()); doReturn(Mono.just(new Plugin())).when(pluginService).findById("mockPlugin"); doReturn(Mono.just(0L)).when(newActionRepository).countByDatasourceId("id1"); doReturn(Mono.just(datasource)).when(datasourceRepository).archiveById("id1"); @@ -153,9 +162,10 @@ public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnectio doReturn(Mono.just(datasourceStorage)).when(datasourceStorageService).archive(datasourceStorage); // Now delete the datasource and check if the cache retains the same instance of connection - Mono<DatasourceContext<?>> dsContextMono2 = datasourceService.archiveById("id1") - .flatMap(deleted -> datasourceContextService.getCachedDatasourceContextMono(datasourceStorage, - spyMockPluginExecutor, monitor, datasourceContextIdentifier)); + Mono<DatasourceContext<?>> dsContextMono2 = datasourceService + .archiveById("id1") + .flatMap(deleted -> datasourceContextService.getCachedDatasourceContextMono( + datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier)); StepVerifier.create(dsContextMono1) .assertNext(dsContext1 -> { @@ -173,15 +183,18 @@ public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnectio @Test @WithUserDetails(value = "api_user") public void checkDecryptionOfAuthenticationDTOTest() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("checkDecryptionOfAuthenticationDTOTest"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); String workspaceId = workspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); Datasource datasource = new Datasource(); @@ -214,37 +227,42 @@ public void checkDecryptionOfAuthenticationDTOTest() { .block(); assert createdDatasource != null; - Mono<DatasourceStorage> datasourceStorageMono = datasourceService.findById(createdDatasource.getId()) - .flatMap(datasource1 -> datasourceStorageService - .findByDatasourceAndEnvironmentId(datasource1, defaultEnvironmentId)); + Mono<DatasourceStorage> datasourceStorageMono = datasourceService + .findById(createdDatasource.getId()) + .flatMap(datasource1 -> + datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, defaultEnvironmentId)); - StepVerifier - .create(datasourceStorageMono) + StepVerifier.create(datasourceStorageMono) .assertNext(savedDatasource -> { - DBAuth authentication = (DBAuth) savedDatasource.getDatasourceConfiguration().getAuthentication(); + DBAuth authentication = (DBAuth) + savedDatasource.getDatasourceConfiguration().getAuthentication(); assertEquals(password, authentication.getPassword()); - DatasourceStorageDTO savedDatasourceStorageDTO = createdDatasource.getDatasourceStorages() - .get(defaultEnvironmentId); - DBAuth encryptedAuthentication = (DBAuth) savedDatasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); + DatasourceStorageDTO savedDatasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DBAuth encryptedAuthentication = (DBAuth) savedDatasourceStorageDTO + .getDatasourceConfiguration() + .getAuthentication(); assertEquals(password, encryptionService.decryptString(encryptedAuthentication.getPassword())); }) .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void checkDecryptionOfAuthenticationDTONullPassword() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("checkDecryptionOfAuthenticationDTONullPassword"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); String workspaceId = workspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); Datasource datasource = new Datasource(); @@ -269,19 +287,21 @@ public void checkDecryptionOfAuthenticationDTONullPassword() { .block(); assert createdDatasource != null; - Mono<DatasourceStorage> datasourceStorageMono = datasourceService.findById(createdDatasource.getId()) - .flatMap(datasource1 -> datasourceStorageService - .findByDatasourceAndEnvironmentId(datasource1, defaultEnvironmentId)); + Mono<DatasourceStorage> datasourceStorageMono = datasourceService + .findById(createdDatasource.getId()) + .flatMap(datasource1 -> + datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, defaultEnvironmentId)); - StepVerifier - .create(datasourceStorageMono) + StepVerifier.create(datasourceStorageMono) .assertNext(savedDatasource -> { - DBAuth authentication = (DBAuth) savedDatasource.getDatasourceConfiguration().getAuthentication(); + DBAuth authentication = (DBAuth) + savedDatasource.getDatasourceConfiguration().getAuthentication(); assertNull(authentication.getPassword()); - DatasourceStorageDTO datasourceStorageDTO = createdDatasource.getDatasourceStorages() - .get(defaultEnvironmentId); - DBAuth encryptedAuthentication = (DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); + DatasourceStorageDTO datasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DBAuth encryptedAuthentication = (DBAuth) + datasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); assertNull(encryptedAuthentication.getPassword()); }) .verifyComplete(); @@ -299,21 +319,27 @@ public void testCachedDatasourceCreate() { MockPluginExecutor mockPluginExecutor = new MockPluginExecutor(); MockPluginExecutor spyMockPluginExecutor = spy(mockPluginExecutor); /* Return two different connection objects if `datasourceCreate` method is called twice */ - doReturn(Mono.just("connection_1")).doReturn(Mono.just("connection_2")).when(spyMockPluginExecutor).datasourceCreate(any()); + doReturn(Mono.just("connection_1")) + .doReturn(Mono.just("connection_2")) + .when(spyMockPluginExecutor) + .datasourceCreate(any()); DatasourceStorage datasourceStorage = new DatasourceStorage(); datasourceStorage.setEnvironmentId(defaultEnvironmentId); datasourceStorage.setDatasourceId("id2"); datasourceStorage.setDatasourceConfiguration(new DatasourceConfiguration()); - DatasourceContextIdentifier datasourceContextIdentifier = new DatasourceContextIdentifier(datasourceStorage.getDatasourceId(), defaultEnvironmentId); + DatasourceContextIdentifier datasourceContextIdentifier = + new DatasourceContextIdentifier(datasourceStorage.getDatasourceId(), defaultEnvironmentId); Object monitor = new Object(); DatasourceContext<?> dsContext1 = (DatasourceContext<?>) datasourceContextService - .getCachedDatasourceContextMono(datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier) + .getCachedDatasourceContextMono( + datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier) .block(); DatasourceContext<?> dsContext2 = (DatasourceContext<?>) datasourceContextService - .getCachedDatasourceContextMono(datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier) + .getCachedDatasourceContextMono( + datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier) .block(); /* They can only be equal if the `datasourceCreate` method was called only once */ @@ -335,15 +361,18 @@ public void testDatasourceCreate_withUpdatableConnection_recreatesConnectionAlwa /* Return two different connection objects if `datasourceCreate` method is called twice */ doReturn(Mono.just((UpdatableConnection) auth -> new DBAuth())) .doReturn(Mono.just((UpdatableConnection) auth -> new BasicAuth())) - .when(spyMockPluginExecutor).datasourceCreate(any()); + .when(spyMockPluginExecutor) + .datasourceCreate(any()); User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("testDatasourceCreate_withUpdatableConnection_recreatesConnectionAlways"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); String workspaceId = workspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); Datasource datasource = new Datasource(); @@ -373,7 +402,8 @@ public void testDatasourceCreate_withUpdatableConnection_recreatesConnectionAlwa assert createdDatasource != null; - DatasourceStorageDTO datasourceStorageDTO = createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DatasourceStorageDTO datasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); assert datasourceStorageDTO != null; DatasourceStorage createdDatasourceStorage = new DatasourceStorage(datasourceStorageDTO); @@ -384,28 +414,22 @@ public void testDatasourceCreate_withUpdatableConnection_recreatesConnectionAlwa Object monitor = new Object(); final DatasourceContext<?> dsc1 = (DatasourceContext) datasourceContextService .getCachedDatasourceContextMono( - createdDatasourceStorage, - spyMockPluginExecutor, - monitor, - datasourceContextIdentifier) + createdDatasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier) .block(); assertNotNull(dsc1); assertTrue(dsc1.getConnection() instanceof UpdatableConnection); - assertTrue(((UpdatableConnection) dsc1.getConnection()) - .getAuthenticationDTO(new ApiKeyAuth()) instanceof DBAuth); - + assertTrue( + ((UpdatableConnection) dsc1.getConnection()).getAuthenticationDTO(new ApiKeyAuth()) instanceof DBAuth); final DatasourceContext<?> dsc2 = (DatasourceContext) datasourceContextService .getCachedDatasourceContextMono( - createdDatasourceStorage, - spyMockPluginExecutor, - monitor, - datasourceContextIdentifier) + createdDatasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier) .block(); assertNotNull(dsc2); assertTrue(dsc2.getConnection() instanceof UpdatableConnection); - assertTrue(((UpdatableConnection) dsc2.getConnection()) - .getAuthenticationDTO(new ApiKeyAuth()) instanceof BasicAuth); + assertTrue( + ((UpdatableConnection) dsc2.getConnection()).getAuthenticationDTO(new ApiKeyAuth()) + instanceof BasicAuth); } /** @@ -421,7 +445,9 @@ public void testDatasourceContextIsInvalid_whenCachedDatasourceContextMono_isInE MockPluginExecutor spyMockPluginExecutor = spy(mockPluginExecutor); // Introduce an error to fail the datasource context mono - doReturn(Mono.error(new RuntimeException("error"))).when(spyMockPluginExecutor).datasourceCreate(any()); + doReturn(Mono.error(new RuntimeException("error"))) + .when(spyMockPluginExecutor) + .datasourceCreate(any()); DatasourceStorage datasourceStorage = new DatasourceStorage(); datasourceStorage.setEnvironmentId(defaultEnvironmentId); @@ -434,13 +460,15 @@ public void testDatasourceContextIsInvalid_whenCachedDatasourceContextMono_isInE Object monitor = new Object(); Mono<DatasourceContext<?>> failedDatasourceContextMono = - datasourceContextService.getCachedDatasourceContextMono(datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier); + datasourceContextService.getCachedDatasourceContextMono( + datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier); StepVerifier.create(failedDatasourceContextMono) .expectError(RuntimeException.class) .verify(); - assertFalse(datasourceContextService.isValidDatasourceContextAvailable(datasourceStorage, datasourceContextIdentifier)); + assertFalse(datasourceContextService.isValidDatasourceContextAvailable( + datasourceStorage, datasourceContextIdentifier)); } /** @@ -460,7 +488,8 @@ public void testNewDatasourceContextCreate_whenCachedDatasourceContextMono_isInE // Introduce an error to fail the datasource context mono doReturn(Mono.error(new RuntimeException("error_connection"))) .doReturn(Mono.just("valid_connection")) - .when(spyMockPluginExecutor).datasourceCreate(any()); + .when(spyMockPluginExecutor) + .datasourceCreate(any()); DatasourceStorage datasourceStorage = new DatasourceStorage(); datasourceStorage.setEnvironmentId(defaultEnvironmentId); @@ -473,22 +502,23 @@ public void testNewDatasourceContextCreate_whenCachedDatasourceContextMono_isInE Object monitor = new Object(); Mono<DatasourceContext<?>> failedDatasourceContextMono = - datasourceContextService.getCachedDatasourceContextMono(datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier); + datasourceContextService.getCachedDatasourceContextMono( + datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier); StepVerifier.create(failedDatasourceContextMono) .expectError(RuntimeException.class) .verify(); - Mono<DatasourceContext<?>> validDatasourceContextMono = - datasourceContextService.getCachedDatasourceContextMono(datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier); + Mono<DatasourceContext<?>> validDatasourceContextMono = datasourceContextService.getCachedDatasourceContextMono( + datasourceStorage, spyMockPluginExecutor, monitor, datasourceContextIdentifier); StepVerifier.create(validDatasourceContextMono) - .assertNext(validDatasourceContext -> assertEquals(validDatasourceContext.getConnection(), "valid_connection")) + .assertNext(validDatasourceContext -> + assertEquals(validDatasourceContext.getConnection(), "valid_connection")) .verifyComplete(); assertNotEquals(failedDatasourceContextMono, validDatasourceContextMono); } - @Test @WithUserDetails(value = "api_user") public void verifyInitialiseDatasourceContextReturningRightIdentifier() { @@ -503,5 +533,4 @@ public void verifyInitialiseDatasourceContextReturningRightIdentifier() { assertThat(datasourceContextIdentifier.getDatasourceId()).isEqualTo(sampleDatasourceId); assertThat(datasourceContextIdentifier.getEnvironmentId()).isEqualTo(defaultEnvironmentId); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java index cc897f13ed04..806eb9279e29 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java @@ -78,6 +78,7 @@ public class DatasourceServiceTest { @Autowired DatasourceService datasourceService; + @SpyBean DatasourceStorageService datasourceStorageService; @@ -119,34 +120,40 @@ public void setup() { toCreate.setName("DatasourceServiceTest"); if (!StringUtils.hasLength(workspaceId)) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } } @Test @WithUserDetails(value = "api_user") public void datasourceDefaultNameCounterAsPerWorkspaceId() { - //Create new workspace + // Create new workspace Workspace workspace11 = new Workspace(); workspace11.setId("random-org-id-1"); workspace11.setName("Random Org 1"); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) - .thenReturn(Mono.just(new MockPluginExecutor())).thenReturn(Mono.just(new MockPluginExecutor())); + .thenReturn(Mono.just(new MockPluginExecutor())) + .thenReturn(Mono.just(new MockPluginExecutor())); - StepVerifier.create(workspaceService.create(workspace11) + StepVerifier.create(workspaceService + .create(workspace11) .zipWith(pluginService.findByPackageName("restapi-plugin")) .flatMap(tuple2 -> { Workspace workspace = tuple2.getT1(); Plugin plugin = tuple2.getT2(); - return workspaceService.getDefaultEnvironmentId(workspace.getId()) + return workspaceService + .getDefaultEnvironmentId(workspace.getId()) .flatMap(environmentId -> { Datasource datasource = new Datasource(); datasource.setWorkspaceId(workspace.getId()); datasource.setPluginId(plugin.getId()); - DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, environmentId); + DatasourceStorage datasourceStorage = + new DatasourceStorage(datasource, environmentId); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); storages.put(environmentId, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); @@ -162,16 +169,19 @@ public void datasourceDefaultNameCounterAsPerWorkspaceId() { .flatMap(tuple2 -> { Datasource datasource1 = tuple2.getT1(); final Workspace workspace2 = tuple2.getT2(); - return workspaceService.getDefaultEnvironmentId(workspace2.getId()) + return workspaceService + .getDefaultEnvironmentId(workspace2.getId()) .flatMap(environmentId -> { Datasource datasource2 = new Datasource(); datasource2.setWorkspaceId(workspace2.getId()); datasource2.setPluginId(datasource1.getPluginId()); - DatasourceStorage datasourceStorage = new DatasourceStorage(datasource2, environmentId); + DatasourceStorage datasourceStorage = + new DatasourceStorage(datasource2, environmentId); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); storages.put(environmentId, new DatasourceStorageDTO(datasourceStorage)); datasource2.setDatasourceStorages(storages); - return Mono.zip(Mono.just(tuple2.getT1()), datasourceService.create(datasource2)); + return Mono.zip( + Mono.just(tuple2.getT1()), datasourceService.create(datasource2)); }); })) .assertNext(datasource -> { @@ -194,10 +204,12 @@ public void createDatasourceWithNullPluginId() { Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-createDatasourceWithNullPluginId"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Datasource datasource = new Datasource(); datasource.setName("DS-with-null-pluginId"); @@ -207,10 +219,11 @@ public void createDatasourceWithNullPluginId() { storages.put(defaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); - StepVerifier - .create(datasourceService.create(datasource)) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PLUGIN_ID))) + StepVerifier.create(datasourceService.create(datasource)) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PLUGIN_ID))) .verify(); } @@ -225,8 +238,7 @@ public void testValidateDatasource_createDatasourceWithNullWorkspaceId() { storages.put(FieldName.UNUSED_ENVIRONMENT_ID, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); - StepVerifier - .create(datasourceService.validateDatasource(datasource)) + StepVerifier.create(datasourceService.validateDatasource(datasource)) .assertNext(datasource1 -> { assertThat(datasource1.getName()).isEqualTo(datasource.getName()); assertThat(datasource1.getIsValid()).isFalse(); @@ -252,26 +264,30 @@ public void createDatasourceWithId() { return datasourceService.create(datasource); }); - StepVerifier - .create(datasourceMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.DATASOURCE))) + StepVerifier.create(datasourceMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.DATASOURCE))) .verify(); } @Test @WithUserDetails(value = "api_user") public void createDatasourceNotInstalledPlugin() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-createDatasourceNotInstalledPlugin"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByName("Not Installed Plugin Name"); Datasource datasource = new Datasource(); @@ -292,15 +308,15 @@ public void createDatasourceNotInstalledPlugin() { }) .flatMap(datasourceService::create); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(datasource.getPluginId()); assertThat(createdDatasource.getName()).isEqualTo(datasource.getName()); assertThat(createdDatasource.getUserPermissions()).isNotEmpty(); assertThat(createdDatasource.getIsValid()).isFalse(); - assertThat(createdDatasource.getInvalids()).contains("Plugin " + datasource.getPluginId() + " not installed"); + assertThat(createdDatasource.getInvalids()) + .contains("Plugin " + datasource.getPluginId() + " not installed"); }) .verifyComplete(); } @@ -309,16 +325,19 @@ public void createDatasourceNotInstalledPlugin() { @WithUserDetails(value = "api_user") public void createDatasourceValid() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-createDatasourceValid"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -333,15 +352,18 @@ public void createDatasourceValid() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); Datasource datasource = new Datasource(); @@ -362,29 +384,39 @@ public void createDatasourceValid() { }) .flatMap(datasourceService::create); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getUserPermissions()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(datasource.getPluginId()); assertThat(createdDatasource.getName()).isEqualTo(datasource.getName()); - Policy manageDatasourcePolicy = Policy.builder().permission(MANAGE_DATASOURCES.getValue()) + Policy manageDatasourcePolicy = Policy.builder() + .permission(MANAGE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readDatasourcePolicy = Policy.builder().permission(READ_DATASOURCES.getValue()) + Policy readDatasourcePolicy = Policy.builder() + .permission(READ_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeDatasourcePolicy = Policy.builder().permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeDatasourcePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - Policy deleteDatasourcesPolicy = Policy.builder().permission(DELETE_DATASOURCES.getValue()) + Policy deleteDatasourcesPolicy = Policy.builder() + .permission(DELETE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); assertThat(createdDatasource.getPolicies()).isNotEmpty(); - assertThat(createdDatasource.getPolicies()).containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, - executeDatasourcePolicy, deleteDatasourcesPolicy)); + assertThat(createdDatasource.getPolicies()) + .containsAll(Set.of( + manageDatasourcePolicy, + readDatasourcePolicy, + executeDatasourcePolicy, + deleteDatasourcesPolicy)); Assertions.assertNull(createdDatasource.getIsMock()); Assertions.assertNull(createdDatasource.getIsTemplate()); @@ -395,16 +427,19 @@ public void createDatasourceValid() { @Test @WithUserDetails(value = "api_user") public void createAndUpdateDatasourceValidDB() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-createAndUpdateDatasourceValidDB"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Datasource datasource = new Datasource(); @@ -422,7 +457,8 @@ public void createAndUpdateDatasourceValidDB() { datasourceConfiguration.setConnection(connection); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); + storages.put( + defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); datasource.setDatasourceStorages(storages); Mono<Plugin> pluginMono = pluginService.findByName("Installed Plugin Name"); @@ -431,7 +467,8 @@ public void createAndUpdateDatasourceValidDB() { .map(plugin -> { datasource.setPluginId(plugin.getId()); return datasource; - }).flatMap(datasourceService::create) + }) + .flatMap(datasourceService::create) .flatMap(datasource1 -> { DatasourceConfiguration datasourceConfiguration1 = new DatasourceConfiguration(); Connection connection1 = new Connection(); @@ -441,28 +478,32 @@ public void createAndUpdateDatasourceValidDB() { connection1.setSsl(ssl); datasourceConfiguration1.setConnection(connection1); - DatasourceStorageDTO datasourceStorageDTO = new DatasourceStorageDTO(datasource1.getId(), defaultEnvironmentId, datasourceConfiguration1); - return datasourceService - .updateDatasourceStorage(datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); + DatasourceStorageDTO datasourceStorageDTO = new DatasourceStorageDTO( + datasource1.getId(), defaultEnvironmentId, datasourceConfiguration1); + return datasourceService.updateDatasourceStorage( + datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); }); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(datasource.getPluginId()); assertThat(createdDatasource.getName()).isEqualTo(datasource.getName()); assertThat(createdDatasource.getDatasourceStorages()).containsKey(defaultEnvironmentId); - assertThat(createdDatasource.getDatasourceStorages().get(defaultEnvironmentId) - .getDatasourceConfiguration().getConnection().getSsl().getKeyFile().getName()) + assertThat(createdDatasource + .getDatasourceStorages() + .get(defaultEnvironmentId) + .getDatasourceConfiguration() + .getConnection() + .getSsl() + .getKeyFile() + .getName()) .isEqualTo("ssl_key_file_id2"); assertThat(createdDatasource.getUserPermissions()).isNotEmpty(); - assertThat(createdDatasource.getUserPermissions()).containsAll( - Set.of( + assertThat(createdDatasource.getUserPermissions()) + .containsAll(Set.of( READ_DATASOURCES.getValue(), EXECUTE_DATASOURCES.getValue(), - MANAGE_DATASOURCES.getValue(), DELETE_DATASOURCES.getValue() - ) - ); + MANAGE_DATASOURCES.getValue(), DELETE_DATASOURCES.getValue())); }) .verifyComplete(); } @@ -470,14 +511,16 @@ public void createAndUpdateDatasourceValidDB() { @Test @WithUserDetails(value = "api_user") public void createAndUpdateDatasourceDifferentAuthentication() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-createAndUpdateDatasourceDifferentAuthentication"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); } @@ -528,24 +571,32 @@ public void createAndUpdateDatasourceDifferentAuthentication() { datasourceConfiguration1.setConnection(connection1); datasource1.setDatasourceConfiguration(datasourceConfiguration1); - DatasourceStorageDTO datasourceStorageDTO = - new DatasourceStorageDTO(datasource1.getId(), defaultEnvironmentId, datasourceConfiguration1); - return datasourceService - .updateDatasourceStorage(datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); + DatasourceStorageDTO datasourceStorageDTO = new DatasourceStorageDTO( + datasource1.getId(), defaultEnvironmentId, datasourceConfiguration1); + return datasourceService.updateDatasourceStorage( + datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); }); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(datasource.getPluginId()); assertThat(createdDatasource.getName()).isEqualTo(datasource.getName()); - assertThat(createdDatasource.getDatasourceStorages().get(defaultEnvironmentId)).isNotNull(); - DatasourceConfiguration datasourceConfiguration1 = - createdDatasource.getDatasourceStorages().get(defaultEnvironmentId).getDatasourceConfiguration(); - - assertThat(datasourceConfiguration1.getConnection().getSsl().getKeyFile().getName()).isEqualTo("ssl_key_file_id2"); - assertThat(datasourceConfiguration1.getAuthentication() instanceof OAuth2).isTrue(); + assertThat(createdDatasource.getDatasourceStorages().get(defaultEnvironmentId)) + .isNotNull(); + DatasourceConfiguration datasourceConfiguration1 = createdDatasource + .getDatasourceStorages() + .get(defaultEnvironmentId) + .getDatasourceConfiguration(); + + assertThat(datasourceConfiguration1 + .getConnection() + .getSsl() + .getKeyFile() + .getName()) + .isEqualTo("ssl_key_file_id2"); + assertThat(datasourceConfiguration1.getAuthentication() instanceof OAuth2) + .isTrue(); }) .verifyComplete(); } @@ -553,16 +604,19 @@ public void createAndUpdateDatasourceDifferentAuthentication() { @Test @WithUserDetails(value = "api_user") public void createNamelessDatasource() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-createNamelessDatasource"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -592,8 +646,7 @@ public void createNamelessDatasource() { }) .zipWhen(datasource -> datasourceService.create(datasource2)); - StepVerifier - .create(datasourcesMono) + StepVerifier.create(datasourcesMono) .assertNext(tuple2 -> { final Datasource ds1 = tuple2.getT1(); assertThat(ds1.getId()).isNotEmpty(); @@ -608,7 +661,6 @@ public void createNamelessDatasource() { .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void testDatasourceValid() { @@ -618,9 +670,11 @@ public void testDatasourceValid() { Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-testDatasourceValid"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -632,7 +686,8 @@ public void testDatasourceValid() { datasourceConfiguration.setUrl("http://test.com"); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); + storages.put( + defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); datasource.setDatasourceStorages(storages); Mono<Datasource> datasourceMono = pluginMono @@ -642,13 +697,14 @@ public void testDatasourceValid() { }) .flatMap(datasourceService::create); - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); - Mono<DatasourceTestResult> testResultMono = datasourceMono - .flatMap(datasource1 -> { - DatasourceStorageDTO datasourceStorageDTO = datasource1.getDatasourceStorages().get(defaultEnvironmentId); - return datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); - }); + Mono<DatasourceTestResult> testResultMono = datasourceMono.flatMap(datasource1 -> { + DatasourceStorageDTO datasourceStorageDTO = + datasource1.getDatasourceStorages().get(defaultEnvironmentId); + return datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); + }); StepVerifier.create(testResultMono) .assertNext(testResult -> { @@ -667,9 +723,11 @@ public void testDatasourceEmptyFields() { Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-testDatasourceEmptyFields"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -694,7 +752,8 @@ public void testDatasourceEmptyFields() { datasourceConfiguration.setAuthentication(auth); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); + storages.put( + defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); datasource.setDatasourceStorages(storages); Mono<Datasource> datasourceMono = pluginMono @@ -704,17 +763,17 @@ public void testDatasourceEmptyFields() { }) .flatMap(datasourceService::create); - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); - Mono<DatasourceTestResult> testResultMono = datasourceMono - .flatMap(datasource1 -> { - DatasourceStorageDTO datasourceStorageDTO = datasource1.getDatasourceStorages().get(defaultEnvironmentId); - ((DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication()).setPassword(null); - return datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); - }); + Mono<DatasourceTestResult> testResultMono = datasourceMono.flatMap(datasource1 -> { + DatasourceStorageDTO datasourceStorageDTO = + datasource1.getDatasourceStorages().get(defaultEnvironmentId); + ((DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication()).setPassword(null); + return datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); + }); - StepVerifier - .create(testResultMono) + StepVerifier.create(testResultMono) .assertNext(testResult -> { assertThat(testResult).isNotNull(); assertThat(testResult.getInvalids()).isEmpty(); @@ -725,16 +784,19 @@ public void testDatasourceEmptyFields() { @Test @WithUserDetails(value = "api_user") public void deleteDatasourceWithoutActions() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-deleteDatasourceWithoutActions"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -756,8 +818,7 @@ public void deleteDatasourceWithoutActions() { .flatMap(datasourceService::create) .flatMap(datasource1 -> datasourceService.archiveById(datasource1.getId())); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(datasource.getPluginId()); @@ -770,7 +831,8 @@ public void deleteDatasourceWithoutActions() { @Test @WithUserDetails(value = "api_user") public void deleteDatasourceWithActions() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); String name = "DatasourceServiceTest-deleteDatasourceWithActions"; @@ -778,15 +840,15 @@ public void deleteDatasourceWithActions() { Workspace toCreate = new Workspace(); toCreate.setName(name); - Workspace createdWorkspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace createdWorkspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); String workspaceId = createdWorkspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); - Mono<Datasource> datasourceMono = Mono - .zip( + Mono<Datasource> datasourceMono = Mono.zip( workspaceRepository.findByName(name, AclPermission.READ_WORKSPACES), - pluginService.findByPackageName("restapi-plugin") - ) + pluginService.findByPackageName("restapi-plugin")) .flatMap(objects -> { final Workspace workspace = objects.getT1(); final Plugin plugin = objects.getT2(); @@ -810,7 +872,8 @@ public void deleteDatasourceWithActions() { Mono.just(workspace), Mono.just(plugin), datasourceService.create(datasource), - applicationPageService.createApplication(application, workspace.getId()) + applicationPageService + .createApplication(application, workspace.getId()) .flatMap(application1 -> { final PageDTO page = new PageDTO(); page.setName("test page 1"); @@ -818,11 +881,9 @@ public void deleteDatasourceWithActions() { page.setPolicies(new HashSet<>(Set.of(Policy.builder() .permission(READ_PAGES.getValue()) .users(Set.of("api_user")) - .build() - ))); + .build()))); return applicationPageService.createPage(page); - }) - ); + })); }) .flatMap(objects -> { final Datasource datasource = objects.getT3(); @@ -838,34 +899,35 @@ public void deleteDatasourceWithActions() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - return layoutActionService.createSingleAction(action, Boolean.FALSE).thenReturn(datasource); + return layoutActionService + .createSingleAction(action, Boolean.FALSE) + .thenReturn(datasource); }) .flatMap(datasource -> datasourceService.archiveById(datasource.getId())); - StepVerifier - .create(datasourceMono) - .verifyErrorMessage(AppsmithError.DATASOURCE_HAS_ACTIONS.getMessage("1")); + StepVerifier.create(datasourceMono).verifyErrorMessage(AppsmithError.DATASOURCE_HAS_ACTIONS.getMessage("1")); } @Test @WithUserDetails(value = "api_user") public void deleteDatasourceWithDeletedActions() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); String name = "DatasourceServiceTest-deleteDatasourceWithDeletedActions"; User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName(name); - Workspace createdWorkspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace createdWorkspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); String workspaceId = createdWorkspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); - Mono<Datasource> datasourceMono = Mono - .zip( + Mono<Datasource> datasourceMono = Mono.zip( workspaceRepository.findByName(name, AclPermission.READ_WORKSPACES), - pluginService.findByPackageName("restapi-plugin") - ) + pluginService.findByPackageName("restapi-plugin")) .flatMap(objects -> { final Workspace workspace = objects.getT1(); final Plugin plugin = objects.getT2(); @@ -889,7 +951,8 @@ public void deleteDatasourceWithDeletedActions() { Mono.just(workspace), Mono.just(plugin), datasourceService.create(datasource), - applicationPageService.createApplication(application, workspace.getId()) + applicationPageService + .createApplication(application, workspace.getId()) .zipWhen(application1 -> { final PageDTO page = new PageDTO(); page.setName("test page 1"); @@ -897,11 +960,9 @@ public void deleteDatasourceWithDeletedActions() { page.setPolicies(new HashSet<>(Set.of(Policy.builder() .permission(READ_PAGES.getValue()) .users(Set.of("api_user")) - .build() - ))); + .build()))); return applicationPageService.createPage(page); - }) - ); + })); }) .flatMap(objects -> { final Datasource datasource = objects.getT3(); @@ -918,17 +979,18 @@ public void deleteDatasourceWithDeletedActions() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - return layoutActionService.createSingleAction(action, Boolean.FALSE) + return layoutActionService + .createSingleAction(action, Boolean.FALSE) .then(applicationPageService.deleteApplication(application.getId())) .thenReturn(datasource); }) .flatMap(datasource -> datasourceService.archiveById(datasource.getId())); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); - assertThat(createdDatasource.getName()).isEqualTo("test datasource name for deletion with deleted actions"); + assertThat(createdDatasource.getName()) + .isEqualTo("test datasource name for deletion with deleted actions"); assertThat(createdDatasource.getDeletedAt()).isNotNull(); }) .verifyComplete(); @@ -939,16 +1001,19 @@ public void deleteDatasourceWithDeletedActions() { public void checkEncryptionOfAuthenticationDTOTest() { // For this test, simply inserting a new datasource with authentication should immediately // set the authentication object as encrypted - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-checkEncryptionOfAuthenticationDTOTest"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -976,13 +1041,15 @@ public void checkEncryptionOfAuthenticationDTOTest() { }) .flatMap(datasourceService::create); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(savedDatasource -> { - DatasourceStorageDTO datasourceStorageDTO = savedDatasource.getDatasourceStorages().get(defaultEnvironmentId); - DBAuth authentication = (DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); + DatasourceStorageDTO datasourceStorageDTO = + savedDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DBAuth authentication = (DBAuth) + datasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); assertThat(authentication.getUsername()).isEqualTo(username); - assertThat(encryptionService.decryptString(authentication.getPassword())).isEqualTo(password); + assertThat(encryptionService.decryptString(authentication.getPassword())) + .isEqualTo(password); }) .verifyComplete(); } @@ -990,16 +1057,19 @@ public void checkEncryptionOfAuthenticationDTOTest() { @Test @WithUserDetails(value = "api_user") public void checkEncryptionOfAuthenticationDTONullPassword() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-checkEncryptionOfAuthenticationDTONullPassword"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -1023,12 +1093,13 @@ public void checkEncryptionOfAuthenticationDTONullPassword() { return datasource; }) .flatMap(datasourceService::create) - .flatMap(datasource1 -> datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, defaultEnvironmentId)); + .flatMap(datasource1 -> + datasourceStorageService.findByDatasourceAndEnvironmentId(datasource1, defaultEnvironmentId)); - StepVerifier - .create(datasourceStorageMono) + StepVerifier.create(datasourceStorageMono) .assertNext(savedDatasource -> { - DBAuth authentication = (DBAuth) savedDatasource.getDatasourceConfiguration().getAuthentication(); + DBAuth authentication = (DBAuth) + savedDatasource.getDatasourceConfiguration().getAuthentication(); assertThat(authentication.getUsername()).isNull(); assertThat(authentication.getPassword()).isNull(); }) @@ -1040,16 +1111,19 @@ public void checkEncryptionOfAuthenticationDTONullPassword() { public void checkEncryptionOfAuthenticationDTOAfterUpdate() { // Here, we're replacing an existing encrypted field with another // Encyption state would stay the same, that is, as true - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-checkEncryptionOfAuthenticationDTOAfterUpdate"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -1078,26 +1152,27 @@ public void checkEncryptionOfAuthenticationDTOAfterUpdate() { .flatMap(datasourceService::create) .block(); - Mono<Datasource> datasourceMono = Mono.just(createdDatasource) - .flatMap(original -> { - // Here we still need to send some object of authentication type to make sure that the entire object is not replaced by null - DBAuth partialAuthenticationDTO = new DBAuth(); - partialAuthenticationDTO.setUsername(username); - datasourceConfiguration.setAuthentication(partialAuthenticationDTO); - original.getDatasourceStorages().get(defaultEnvironmentId) - .setDatasourceConfiguration(datasourceConfiguration); - - DatasourceStorageDTO datasourceStorageDTO = - new DatasourceStorageDTO(original.getId(), defaultEnvironmentId, datasourceConfiguration); - return datasourceService - .updateDatasourceStorage(datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); - }); + Mono<Datasource> datasourceMono = Mono.just(createdDatasource).flatMap(original -> { + // Here we still need to send some object of authentication type to make sure that the entire object is not + // replaced by null + DBAuth partialAuthenticationDTO = new DBAuth(); + partialAuthenticationDTO.setUsername(username); + datasourceConfiguration.setAuthentication(partialAuthenticationDTO); + original.getDatasourceStorages() + .get(defaultEnvironmentId) + .setDatasourceConfiguration(datasourceConfiguration); + + DatasourceStorageDTO datasourceStorageDTO = + new DatasourceStorageDTO(original.getId(), defaultEnvironmentId, datasourceConfiguration); + return datasourceService.updateDatasourceStorage(datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); + }); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(updatedDatasource -> { - DatasourceStorageDTO datasourceStorageDTO = updatedDatasource.getDatasourceStorages().get(defaultEnvironmentId); - DBAuth authentication = (DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); + DatasourceStorageDTO datasourceStorageDTO = + updatedDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DBAuth authentication = (DBAuth) + datasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); assertThat(authentication.getUsername()).isEqualTo(username); assertThat(password).isEqualTo(encryptionService.decryptString(authentication.getPassword())); @@ -1109,17 +1184,21 @@ public void checkEncryptionOfAuthenticationDTOAfterUpdate() { @WithUserDetails(value = "api_user") public void checkEncryptionOfAuthenticationDTOAfterRemoval() { // Here is when authentication is removed from a datasource - // We want the entire authentication object to be discarded here to avoid reusing any sensitive data across types - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + // We want the entire authentication object to be discarded here to avoid reusing any sensitive data across + // types + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-checkEncryptionOfAuthenticationDTOAfterRemoval"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("postgres-plugin"); @@ -1145,23 +1224,23 @@ public void checkEncryptionOfAuthenticationDTOAfterRemoval() { datasource.setPluginId(plugin.getId()); return datasource; }) - .flatMap(datasourceService::create).block(); - - Mono<Datasource> datasourceMono = Mono.just(createdDatasource) - .flatMap(original -> { - Datasource datasource1 = new Datasource(); - // Here we abstain from sending an authentication object to remove the field from datasourceConfiguration - DatasourceConfiguration datasourceConfiguration2 = new DatasourceConfiguration(); - datasourceConfiguration2.setUrl("http://test.com"); - datasource1.setDatasourceConfiguration(datasourceConfiguration2); - datasource1.setName("New Name for update to test that encryption is now gone"); - return datasourceService.save(datasource1); - }); + .flatMap(datasourceService::create) + .block(); + + Mono<Datasource> datasourceMono = Mono.just(createdDatasource).flatMap(original -> { + Datasource datasource1 = new Datasource(); + // Here we abstain from sending an authentication object to remove the field from datasourceConfiguration + DatasourceConfiguration datasourceConfiguration2 = new DatasourceConfiguration(); + datasourceConfiguration2.setUrl("http://test.com"); + datasource1.setDatasourceConfiguration(datasourceConfiguration2); + datasource1.setName("New Name for update to test that encryption is now gone"); + return datasourceService.save(datasource1); + }); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(updatedDatasource -> { - assertThat(updatedDatasource.getDatasourceConfiguration().getAuthentication()).isNull(); + assertThat(updatedDatasource.getDatasourceConfiguration().getAuthentication()) + .isNull(); }) .verifyComplete(); } @@ -1169,15 +1248,18 @@ public void checkEncryptionOfAuthenticationDTOAfterRemoval() { @Test @WithUserDetails(value = "api_user") public void createDatasourceWithInvalidCharsInHost() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-createDatasourceWithInvalidCharsInHost"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); String workspaceId = workspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -1191,15 +1273,18 @@ public void createDatasourceWithInvalidCharsInHost() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); Mono<Plugin> pluginMono = pluginService.findByPackageName("postgres-plugin"); Datasource datasource = new Datasource(); @@ -1222,27 +1307,32 @@ public void createDatasourceWithInvalidCharsInHost() { }) .flatMap(datasourceService::create); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(datasource.getPluginId()); assertThat(createdDatasource.getName()).isEqualTo(datasource.getName()); assertThat(createdDatasource.getInvalids()).isEmpty(); - Policy manageDatasourcePolicy = Policy.builder().permission(MANAGE_DATASOURCES.getValue()) + Policy manageDatasourcePolicy = Policy.builder() + .permission(MANAGE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readDatasourcePolicy = Policy.builder().permission(READ_DATASOURCES.getValue()) + Policy readDatasourcePolicy = Policy.builder() + .permission(READ_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeDatasourcePolicy = Policy.builder().permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy executeDatasourcePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); assertThat(createdDatasource.getPolicies()).isNotEmpty(); - assertThat(createdDatasource.getPolicies()).containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); + assertThat(createdDatasource.getPolicies()) + .containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); }) .verifyComplete(); } @@ -1250,16 +1340,19 @@ public void createDatasourceWithInvalidCharsInHost() { @Test @WithUserDetails(value = "api_user") public void createDatasourceWithHostnameStartingWithSpace() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-createDatasourceWithHostnameStartingWithSpace"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); Datasource datasource = new Datasource(); @@ -1281,15 +1374,16 @@ public void createDatasourceWithHostnameStartingWithSpace() { }) .flatMap(datasourceService::create); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(datasource.getPluginId()); assertThat(createdDatasource.getName()).isEqualTo(datasource.getName()); - DatasourceStorageDTO datasourceStorageDTO = createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DatasourceStorageDTO datasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); assertThat(datasourceStorageDTO.getInvalids()).isEmpty(); - assertThat(datasourceStorageDTO.getDatasourceConfiguration().getEndpoints()).isEqualTo(List.of(new Endpoint("hostname", 5432L))); + assertThat(datasourceStorageDTO.getDatasourceConfiguration().getEndpoints()) + .isEqualTo(List.of(new Endpoint("hostname", 5432L))); }) .verifyComplete(); } @@ -1297,16 +1391,19 @@ public void createDatasourceWithHostnameStartingWithSpace() { @Test @WithUserDetails(value = "api_user") public void testHintMessageOnLocalhostUrlOnTestDatasourceEvent() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-testHintMessageOnLocalhostUrlOnTestDatasourceEvent"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -1320,7 +1417,8 @@ public void testHintMessageOnLocalhostUrlOnTestDatasourceEvent() { datasourceConfiguration.getEndpoints().add(endpoint); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); + storages.put( + defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); datasource.setDatasourceStorages(storages); Mono<Datasource> datasourceMono = pluginMono @@ -1330,13 +1428,14 @@ public void testHintMessageOnLocalhostUrlOnTestDatasourceEvent() { }) .flatMap(datasourceService::create); - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); - Mono<DatasourceTestResult> testResultMono = datasourceMono - .flatMap(datasource1 -> { - DatasourceStorageDTO datasourceStorageDTO = datasource1.getDatasourceStorages().get(defaultEnvironmentId); - return datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); - }); + Mono<DatasourceTestResult> testResultMono = datasourceMono.flatMap(datasource1 -> { + DatasourceStorageDTO datasourceStorageDTO = + datasource1.getDatasourceStorages().get(defaultEnvironmentId); + return datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); + }); StepVerifier.create(testResultMono) .assertNext(testResult -> { @@ -1344,14 +1443,12 @@ public void testHintMessageOnLocalhostUrlOnTestDatasourceEvent() { assertThat(testResult.getInvalids()).isEmpty(); assertThat(testResult.getMessages()).isNotEmpty(); - String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + - "inside a docker container or on the cloud. To enable access to your localhost you may use " + - "ngrok to expose your local endpoint to the internet. Please check out Appsmith's " + - "documentation to understand more."; - assertThat( - testResult.getMessages().stream() - .anyMatch(message -> expectedMessage.equals(message)) - ).isTrue(); + String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + + "inside a docker container or on the cloud. To enable access to your localhost you may use " + + "ngrok to expose your local endpoint to the internet. Please check out Appsmith's " + + "documentation to understand more."; + assertThat(testResult.getMessages().stream().anyMatch(message -> expectedMessage.equals(message))) + .isTrue(); }) .verifyComplete(); } @@ -1360,16 +1457,19 @@ public void testHintMessageOnLocalhostUrlOnTestDatasourceEvent() { @WithUserDetails(value = "api_user") public void testHintMessageOnLocalhostUrlOnCreateEventOnApiDatasource() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-testHintMessageOnLocalhostUrlOnCreateEventOnApiDatasource"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); Datasource datasource = new Datasource(); @@ -1390,17 +1490,16 @@ public void testHintMessageOnLocalhostUrlOnCreateEventOnApiDatasource() { }) .flatMap(datasourceService::create); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { - DatasourceStorageDTO datasourceStorageDTO = createdDatasource.getDatasourceStorages() - .get(defaultEnvironmentId); + DatasourceStorageDTO datasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); assertThat(datasourceStorageDTO.getMessages()).isNotEmpty(); - String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + - "inside a docker container or on the cloud. To enable access to your localhost you may " + - "use ngrok to expose your local endpoint to the internet. Please check out Appsmith's " + - "documentation to understand more."; + String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + + "inside a docker container or on the cloud. To enable access to your localhost you may " + + "use ngrok to expose your local endpoint to the internet. Please check out Appsmith's " + + "documentation to understand more."; assertThat(datasourceStorageDTO.getMessages()).containsExactly(expectedMessage); }) .verifyComplete(); @@ -1409,16 +1508,19 @@ public void testHintMessageOnLocalhostUrlOnCreateEventOnApiDatasource() { @Test @WithUserDetails(value = "api_user") public void testHintMessageOnLocalhostUrlOnUpdateEventOnApiDatasource() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-testHintMessageOnLocalhostUrlOnUpdateEventOnApiDatasource"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); @@ -1449,23 +1551,26 @@ public void testHintMessageOnLocalhostUrlOnUpdateEventOnApiDatasource() { Connection connection1 = new Connection(); datasourceConfiguration1.setConnection(connection1); datasourceConfiguration1.setUrl("http://localhost"); - datasource1.getDatasourceStorages().get(defaultEnvironmentId).setDatasourceConfiguration(datasourceConfiguration1); + datasource1 + .getDatasourceStorages() + .get(defaultEnvironmentId) + .setDatasourceConfiguration(datasourceConfiguration1); - DatasourceStorageDTO datasourceStorageDTO = - new DatasourceStorageDTO(datasource1.getId(), defaultEnvironmentId, datasourceConfiguration1); - return datasourceService - .updateDatasourceStorage(datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); + DatasourceStorageDTO datasourceStorageDTO = new DatasourceStorageDTO( + datasource1.getId(), defaultEnvironmentId, datasourceConfiguration1); + return datasourceService.updateDatasourceStorage( + datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); }); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(updatedDatasource -> { - DatasourceStorageDTO datasourceStorageDTO = updatedDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DatasourceStorageDTO datasourceStorageDTO = + updatedDatasource.getDatasourceStorages().get(defaultEnvironmentId); assertThat(datasourceStorageDTO.getMessages().size()).isNotZero(); - String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + - "inside a docker container or on the cloud. To enable access to your localhost you may " + - "use ngrok to expose your local endpoint to the internet. Please check out Appsmith's " + - "documentation to understand more."; + String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + + "inside a docker container or on the cloud. To enable access to your localhost you may " + + "use ngrok to expose your local endpoint to the internet. Please check out Appsmith's " + + "documentation to understand more."; assertThat(datasourceStorageDTO.getMessages()).containsExactly(expectedMessage); }) .verifyComplete(); @@ -1475,7 +1580,8 @@ public void testHintMessageOnLocalhostUrlOnUpdateEventOnApiDatasource() { @WithUserDetails(value = "api_user") public void testHintMessageOnLocalhostUrlOnCreateEventOnNonApiDatasource() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mono<Plugin> pluginMono = pluginService.findByName("Installed Plugin Name"); Datasource datasource = new Datasource(); @@ -1498,16 +1604,16 @@ public void testHintMessageOnLocalhostUrlOnCreateEventOnNonApiDatasource() { }) .flatMap(datasourceService::create); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { - DatasourceStorageDTO datasourceStorageDTO = createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DatasourceStorageDTO datasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); assertThat(datasourceStorageDTO.getMessages()).isNotEmpty(); - String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + - "inside a docker container or on the cloud. To enable access to your localhost you may " + - "use ngrok to expose your local endpoint to the internet. Please check out Appsmith's " + - "documentation to understand more."; + String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + + "inside a docker container or on the cloud. To enable access to your localhost you may " + + "use ngrok to expose your local endpoint to the internet. Please check out Appsmith's " + + "documentation to understand more."; assertThat(datasourceStorageDTO.getMessages()).containsExactly(expectedMessage); }) .verifyComplete(); @@ -1516,16 +1622,20 @@ public void testHintMessageOnLocalhostUrlOnCreateEventOnNonApiDatasource() { @Test @WithUserDetails(value = "api_user") public void testHintMessageOnLocalhostIPAddressOnUpdateEventOnNonApiDatasource() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); - toCreate.setName("DatasourceServiceTest-testHintMessageOnLocalhostIPAddressOnUpdateEventOnNonApiDatasource"); + toCreate.setName( + "DatasourceServiceTest-testHintMessageOnLocalhostIPAddressOnUpdateEventOnNonApiDatasource"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Datasource datasource = new Datasource(); @@ -1559,26 +1669,27 @@ public void testHintMessageOnLocalhostIPAddressOnUpdateEventOnNonApiDatasource() Endpoint endpoint = new Endpoint("http://127.0.0.1/xyz", 0L); datasourceConfiguration1.setEndpoints(new ArrayList<>()); datasourceConfiguration1.getEndpoints().add(endpoint); - datasource1.getDatasourceStorages().get(defaultEnvironmentId) + datasource1 + .getDatasourceStorages() + .get(defaultEnvironmentId) .setDatasourceConfiguration(datasourceConfiguration1); - DatasourceStorageDTO datasourceStorageDTO = - new DatasourceStorageDTO(datasource1.getId(), defaultEnvironmentId, datasourceConfiguration1); - return datasourceService - .updateDatasourceStorage(datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); + DatasourceStorageDTO datasourceStorageDTO = new DatasourceStorageDTO( + datasource1.getId(), defaultEnvironmentId, datasourceConfiguration1); + return datasourceService.updateDatasourceStorage( + datasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); }); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(updatedDatasource -> { - DatasourceStorageDTO datasourceStorageDTO = updatedDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DatasourceStorageDTO datasourceStorageDTO = + updatedDatasource.getDatasourceStorages().get(defaultEnvironmentId); assertThat(datasourceStorageDTO.getMessages().size()).isNotZero(); - String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + - "inside a docker container or on the cloud. To enable access to your localhost you may " + - "use ngrok to expose your local endpoint to the internet. Please check out " + - "Appsmith's documentation to understand more."; + String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + + "inside a docker container or on the cloud. To enable access to your localhost you may " + + "use ngrok to expose your local endpoint to the internet. Please check out " + + "Appsmith's documentation to understand more."; assertThat(datasourceStorageDTO.getMessages()).containsExactly(expectedMessage); - }) .verifyComplete(); } @@ -1587,16 +1698,19 @@ public void testHintMessageOnLocalhostIPAddressOnUpdateEventOnNonApiDatasource() @WithUserDetails(value = "api_user") public void testHintMessageNPE() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (!StringUtils.hasLength(workspaceId)) { User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest-testHintMessageNPE"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mono<Plugin> pluginMono = pluginService.findByPackageName("restapi-plugin"); Datasource datasource = new Datasource(); @@ -1611,8 +1725,8 @@ public void testHintMessageNPE() { datasourceConfiguration.getEndpoints().add(nullHost); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(defaultEnvironmentId, - new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); + storages.put( + defaultEnvironmentId, new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); datasource.setDatasourceStorages(storages); Mono<Datasource> datasourceMono = pluginMono @@ -1634,7 +1748,8 @@ public void testHintMessageNPE() { @Test @WithUserDetails(value = "api_user") public void get_WhenDatasourcesPresent_SortedAndIsRecentlyCreatedFlagSet() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Workspace toCreate = new Workspace(); toCreate.setName("DatasourceServiceTest : get_WhenDatasourcesPresent_SortedAndIsRecentlyCreatedFlagSet"); @@ -1646,20 +1761,21 @@ public void get_WhenDatasourcesPresent_SortedAndIsRecentlyCreatedFlagSet() { createDatasource("D", workspaceId), // should have isRecentlyCreated=false createDatasource("C", workspaceId), // should have isRecentlyCreated=true createDatasource("B", workspaceId), // should have isRecentlyCreated=true - createDatasource("A", workspaceId) // should have isRecentlyCreated=true - ); + createDatasource("A", workspaceId) // should have isRecentlyCreated=true + ); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add(fieldName(QDatasource.datasource.workspaceId), workspaceId); - Mono<List<Datasource>> listMono = datasourceService.getAllWithStorages(params).collectList(); + Mono<List<Datasource>> listMono = + datasourceService.getAllWithStorages(params).collectList(); StepVerifier.create(listMono) .assertNext(datasources -> { assertThat(datasources.size()).isEqualTo(4); - assertThat(datasources) - .allMatch(datasourceDTO -> Set.of("A", "B", "C", "D").contains(datasourceDTO.getName())); + assertThat(datasources).allMatch(datasourceDTO -> Set.of("A", "B", "C", "D") + .contains(datasourceDTO.getName())); datasources.stream().forEach(datasource -> { if (Set.of("A", "B", "C").contains(datasource.getName())) { @@ -1675,7 +1791,8 @@ public void get_WhenDatasourcesPresent_SortedAndIsRecentlyCreatedFlagSet() { private Datasource createDatasource(String name, String workspaceId) { Plugin plugin = pluginService.findByPackageName("restapi-plugin").block(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); Datasource datasource = new Datasource(); datasource.setPluginId(plugin.getId()); @@ -1707,15 +1824,15 @@ public void getErrorOnCreatingEmptyDatasource() { Datasource datasource = createDatasourceObject("testDs", workspaceId, "postgres-plugin"); Mono<Datasource> datasourceMono = datasourceService.create(datasource); - StepVerifier.create(datasourceMono) - .verifyErrorSatisfies(error -> { - assertThat(error).isInstanceOf(AppsmithException.class); - assertThat(((AppsmithException) error).getAppErrorCode()).isEqualTo(AppsmithErrorCode.INVALID_PARAMETER.getCode()); - }); + StepVerifier.create(datasourceMono).verifyErrorSatisfies(error -> { + assertThat(error).isInstanceOf(AppsmithException.class); + assertThat(((AppsmithException) error).getAppErrorCode()) + .isEqualTo(AppsmithErrorCode.INVALID_PARAMETER.getCode()); + }); } public DatasourceStorageDTO generateSampleDatasourceStorageDTO() { - DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); + DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); Endpoint endpoint = new Endpoint("https://sample.endpoint", 5432L); DBAuth dbAuth = new DBAuth(); dbAuth.setPassword("password"); @@ -1742,8 +1859,10 @@ public void verifyOnlyOneStorageIsSaved() { StepVerifier.create(datasourceMono) .assertNext(dbDatasource -> { assertThat(dbDatasource.getDatasourceStorages().size()).isEqualTo(1); - assertThat(dbDatasource.getDatasourceStorages().get(defaultEnvironmentId)).isNotNull(); - DatasourceStorageDTO datasourceStorageDTO = dbDatasource.getDatasourceStorages().get(defaultEnvironmentId); + assertThat(dbDatasource.getDatasourceStorages().get(defaultEnvironmentId)) + .isNotNull(); + DatasourceStorageDTO datasourceStorageDTO = + dbDatasource.getDatasourceStorages().get(defaultEnvironmentId); assertThat(datasourceStorageDTO.getDatasourceId()).isEqualTo(dbDatasource.getId()); assertThat(datasourceStorageDTO.getEnvironmentId()).isEqualTo(defaultEnvironmentId); }) @@ -1761,7 +1880,8 @@ public void verifyUpdateNameReturnsNullStorages() { Datasource createdDatasource = datasourceService.create(datasource).block(); createdDatasource.setName("renamedDs"); - Mono<Datasource> datasourceMono = datasourceService.updateDatasource(createdDatasource.getId(), createdDatasource, defaultEnvironmentId, Boolean.FALSE); + Mono<Datasource> datasourceMono = datasourceService.updateDatasource( + createdDatasource.getId(), createdDatasource, defaultEnvironmentId, Boolean.FALSE); StepVerifier.create(datasourceMono) .assertNext(dbDatasource -> { @@ -1786,13 +1906,14 @@ public void verifyUpdateDatasourceStorageWithoutDatasourceId() { sampleDatasourceStorageDTO.setWorkspaceId(createdDatasource.getWorkspaceId()); sampleDatasourceStorageDTO.setPluginId(createdDatasource.getPluginId()); - Mono<Datasource> datasourceMono = datasourceService.updateDatasourceStorage(sampleDatasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); + Mono<Datasource> datasourceMono = datasourceService.updateDatasourceStorage( + sampleDatasourceStorageDTO, defaultEnvironmentId, Boolean.FALSE); - StepVerifier.create(datasourceMono) - .verifyErrorSatisfies(error -> { - assertThat(error).isInstanceOf(AppsmithException.class); - assertThat(((AppsmithException) error).getAppErrorCode()).isEqualTo(AppsmithErrorCode.INVALID_PARAMETER.getCode()); - }); + StepVerifier.create(datasourceMono).verifyErrorSatisfies(error -> { + assertThat(error).isInstanceOf(AppsmithException.class); + assertThat(((AppsmithException) error).getAppErrorCode()) + .isEqualTo(AppsmithErrorCode.INVALID_PARAMETER.getCode()); + }); } @Test @@ -1803,22 +1924,32 @@ public void verifyTestDatasourceWithSavedDatasourceButNoDatasourceStorageSucceed datasource.getDatasourceStorages().put(defaultEnvironmentId, datasourceStorageDTO); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) - .thenReturn(Mono.just(new MockPluginExecutor())).thenReturn(Mono.just(new MockPluginExecutor())); + .thenReturn(Mono.just(new MockPluginExecutor())) + .thenReturn(Mono.just(new MockPluginExecutor())); DatasourceStorage datasourceStorage = new DatasourceStorage(datasourceStorageDTO); - Mockito.doReturn(Mono.just(datasourceStorage)).when(datasourceStorageService).create(Mockito.any()); + Mockito.doReturn(Mono.just(datasourceStorage)) + .when(datasourceStorageService) + .create(Mockito.any()); Datasource dbDatasource = datasourceService.create(datasource).block(); assertThat(dbDatasource.getId()).isNotNull(); assertThat(dbDatasource.getDatasourceStorages()).isNotNull(); - assertThat(dbDatasource.getDatasourceStorages().get(defaultEnvironmentId)).isNotNull(); - assertThat(dbDatasource.getDatasourceStorages().get(defaultEnvironmentId).getId()).isNull(); + assertThat(dbDatasource.getDatasourceStorages().get(defaultEnvironmentId)) + .isNotNull(); + assertThat(dbDatasource + .getDatasourceStorages() + .get(defaultEnvironmentId) + .getId()) + .isNull(); datasourceStorageDTO.setDatasourceId(dbDatasource.getId()); datasourceStorageDTO.setWorkspaceId(workspaceId); datasourceStorageDTO.setPluginId(dbDatasource.getPluginId()); - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); - Mono<DatasourceTestResult> testResultMono = datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); + Mono<DatasourceTestResult> testResultMono = + datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); StepVerifier.create(testResultMono) .assertNext(testResult -> { @@ -1837,8 +1968,10 @@ public void verifyTestDatasourceWithoutSavedDatasource() { datasourceStorageDTO.setWorkspaceId(workspaceId); datasourceStorageDTO.setPluginId(datasource.getPluginId()); - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); - Mono<DatasourceTestResult> testResultMono = datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); + Mono<DatasourceTestResult> testResultMono = + datasourceService.testDatasource(datasourceStorageDTO, defaultEnvironmentId); StepVerifier.create(testResultMono) .assertNext(testResult -> { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceStorageServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceStorageServiceTest.java index 03c82749aa83..cae503b8b389 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceStorageServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceStorageServiceTest.java @@ -31,20 +31,19 @@ public class DatasourceStorageServiceTest { @Autowired UserRepository userRepository; + @SpyBean WorkspaceService workspaceService; + @Autowired DatasourceStorageService datasourceStorageService; - @BeforeEach public void setup() { Mono<User> userMono = userRepository.findByEmail("api_user").cache(); - Workspace workspace = - userMono.flatMap(user -> workspaceService.createDefault(new Workspace(), user)) - .switchIfEmpty(Mono.error(new Exception("createDefault is returning empty!!"))) - .block(); - + Workspace workspace = userMono.flatMap(user -> workspaceService.createDefault(new Workspace(), user)) + .switchIfEmpty(Mono.error(new Exception("createDefault is returning empty!!"))) + .block(); } @Test @@ -62,13 +61,12 @@ public void verifyFindByDatasourceId() { DatasourceStorage datasourceStorageTwo = new DatasourceStorage(datasourceId, environmentIdTwo, datasourceConfiguration, null, null, null); - datasourceStorageService.save(datasourceStorageOne).block(); datasourceStorageService.save(datasourceStorageTwo).block(); - Flux<DatasourceStorage> datasourceStorageFlux = - datasourceStorageService.findStrictlyByDatasourceId(datasourceId) - .sort(Comparator.comparing(DatasourceStorage::getEnvironmentId)); + Flux<DatasourceStorage> datasourceStorageFlux = datasourceStorageService + .findStrictlyByDatasourceId(datasourceId) + .sort(Comparator.comparing(DatasourceStorage::getEnvironmentId)); StepVerifier.create(datasourceStorageFlux) .assertNext(datasourceStorage -> { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/FeatureFlagServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/FeatureFlagServiceTest.java index c790314fe3ae..f0a0e2e5d796 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/FeatureFlagServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/FeatureFlagServiceTest.java @@ -22,7 +22,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; - @ExtendWith(SpringExtension.class) @SpringBootTest @Slf4j @@ -91,7 +90,7 @@ public void testFeatureCheckForEmailStrategy() { } @Test - public void getFeatureFlags_withUserIdentifier_redisKeyExists(){ + public void getFeatureFlags_withUserIdentifier_redisKeyExists() { String userIdentifier = "testIdentifier"; Mono<CachedFlags> cachedFlagsMono = cacheableFeatureFlagHelper.fetchUserCachedFlags(userIdentifier); Mono<Boolean> hasKeyMono = reactiveRedisTemplate.hasKey("featureFlag:" + userIdentifier); @@ -103,7 +102,7 @@ public void getFeatureFlags_withUserIdentifier_redisKeyExists(){ } @Test - public void evictFeatureFlags_withUserIdentifier_redisKeyDoesNotExist(){ + public void evictFeatureFlags_withUserIdentifier_redisKeyDoesNotExist() { String userIdentifier = "testIdentifier"; Mono<Void> evictCache = cacheableFeatureFlagHelper.evictUserCachedFlags(userIdentifier); Mono<Boolean> hasKeyMono = reactiveRedisTemplate.hasKey("featureFlag:" + userIdentifier); @@ -125,5 +124,4 @@ FF4j ff4j() { return ff4j; } } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/GitServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/GitServiceTest.java index c04f8b6459c5..10e06dc71919 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/GitServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/GitServiceTest.java @@ -12,9 +12,9 @@ import com.appsmith.external.models.DatasourceStorageDTO; import com.appsmith.external.models.DefaultResources; import com.appsmith.external.models.JSValue; +import com.appsmith.external.models.PluginType; import com.appsmith.server.constants.FieldName; import com.appsmith.server.domains.ActionCollection; -import com.appsmith.external.models.PluginType; import com.appsmith.server.domains.Application; import com.appsmith.server.domains.ApplicationDetail; import com.appsmith.server.domains.ApplicationPage; @@ -62,9 +62,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; -import org.mockito.internal.stubbing.answers.AnswersWithDelay; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -112,51 +109,72 @@ public class GitServiceTest { private static final String DEFAULT_GIT_PROFILE = "default"; private static final String DEFAULT_BRANCH = "defaultBranchName"; - private final static String EMPTY_COMMIT_ERROR_MESSAGE = "On current branch nothing to commit, working tree clean"; - private final static String GIT_CONFIG_ERROR = "Unable to find the git configuration, please configure your application " + - "with git to use version control service"; + private static final String EMPTY_COMMIT_ERROR_MESSAGE = "On current branch nothing to commit, working tree clean"; + private static final String GIT_CONFIG_ERROR = + "Unable to find the git configuration, please configure your application " + + "with git to use version control service"; private static String workspaceId; private static String defaultEnvironmentId; private static Application gitConnectedApplication = new Application(); private static Boolean isSetupDone = false; private static final GitProfile testUserProfile = new GitProfile(); - private static final String filePath = "test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"; + private static final String filePath = + "test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"; + @Autowired GitService gitService; + @Autowired Gson gson; + @Autowired WorkspaceService workspaceService; + @Autowired WorkspaceRepository workspaceRepository; + @Autowired ApplicationPageService applicationPageService; + @Autowired ApplicationService applicationService; + @Autowired LayoutCollectionService layoutCollectionService; + @Autowired LayoutActionService layoutActionService; + @Autowired NewPageService newPageService; + @Autowired NewActionService newActionService; + @Autowired ActionCollectionService actionCollectionService; + @Autowired PluginRepository pluginRepository; + @Autowired DatasourceService datasourceService; + @Autowired UserService userService; + @MockBean GitExecutor gitExecutor; + @MockBean GitFileUtils gitFileUtils; + @MockBean GitCloudServicesUtils gitCloudServicesUtils; + @MockBean PluginExecutorHelper pluginExecutorHelper; + @Autowired private ThemeService themeService; @@ -170,18 +188,19 @@ public void setup() throws IOException, GitAPIException { toCreate.setName("Git Service Test"); if (!org.springframework.util.StringUtils.hasLength(workspaceId)) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = workspaceService + .create(toCreate, apiUser, Boolean.FALSE) + .block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } } - Mockito - .when(gitCloudServicesUtils.getPrivateRepoLimitForOrg(eq(workspaceId), Mockito.anyBoolean())) + Mockito.when(gitCloudServicesUtils.getPrivateRepoLimitForOrg(eq(workspaceId), Mockito.anyBoolean())) .thenReturn(Mono.just(-1)); - Mockito - .when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) .thenReturn(Mono.just(new MockPluginExecutor())); if (Boolean.TRUE.equals(isSetupDone)) { @@ -197,23 +216,19 @@ public void setup() throws IOException, GitAPIException { private Mono<ApplicationJson> createAppJson(String filePath) { FilePart filePart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read( - new ClassPathResource(filePath), - new DefaultDataBufferFactory(), - 4096) + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource(filePath), new DefaultDataBufferFactory(), 4096) .cache(); Mockito.when(filePart.content()).thenReturn(dataBufferFlux); Mockito.when(filePart.headers().getContentType()).thenReturn(MediaType.APPLICATION_JSON); - Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()) - .map(dataBuffer -> { - byte[] data = new byte[dataBuffer.readableByteCount()]; - dataBuffer.read(data); - DataBufferUtils.release(dataBuffer); - return new String(data); - }); + Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()).map(dataBuffer -> { + byte[] data = new byte[dataBuffer.readableByteCount()]; + dataBuffer.read(data); + DataBufferUtils.release(dataBuffer); + return new String(data); + }); return stringifiedFile .map(data -> { @@ -229,38 +244,46 @@ private GitConnectDTO getConnectRequest(String remoteUrl, GitProfile gitProfile) return gitConnectDTO; } - private Application createApplicationConnectedToGit(String name, String branchName) throws IOException, GitAPIException { + private Application createApplicationConnectedToGit(String name, String branchName) + throws IOException, GitAPIException { return createApplicationConnectedToGit(name, branchName, workspaceId); } - private Application createApplicationConnectedToGit(String name, String branchName, String workspaceId) throws IOException, GitAPIException { + private Application createApplicationConnectedToGit(String name, String branchName, String workspaceId) + throws IOException, GitAPIException { if (StringUtils.isEmpty(branchName)) { branchName = DEFAULT_BRANCH; } - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(branchName)); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("commit")); - Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())).thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); Mockito.when(gitExecutor.pushApplication( - Mockito.any(Path.class), - Mockito.any(), - Mockito.any(), - Mockito.any(), - Mockito.any()) - ) + Mockito.any(Path.class), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just("success")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("path"))); Application testApplication = new Application(); testApplication.setName(name); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); GitAuth gitAuth = new GitAuth(); @@ -279,7 +302,9 @@ private Application createApplicationConnectedToGit(String name, String branchNa String repoUrl = String.format("[email protected]:test/%s.git", name); GitConnectDTO gitConnectDTO = getConnectRequest(repoUrl, testUserProfile); - return gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl").block(); + return gitService + .connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl") + .block(); } @Test @@ -289,8 +314,7 @@ public void connectApplicationToGit_EmptyRemoteUrl_ThrowInvalidParameterExceptio GitConnectDTO gitConnectDTO = getConnectRequest(null, testUserProfile); Mono<Application> applicationMono = gitService.connectApplicationToGit("testID", gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage("Remote Url"))) .verify(); @@ -303,8 +327,7 @@ public void connectApplicationToGit_EmptyOriginHeader_ThrowInvalidParameterExcep GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); Mono<Application> applicationMono = gitService.connectApplicationToGit("testID", gitConnectDTO, null); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage("origin"))) .verify(); @@ -318,18 +341,20 @@ public void connectApplicationToGit_InvalidGitApplicationMetadata_ThrowInvalidGi testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); testApplication.setName("InvalidGitApplicationMetadata"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> { assertThat(throwable instanceof AppsmithException).isTrue(); assertThat(throwable.getMessage()) .contains(AppsmithError.INVALID_GIT_SSH_CONFIGURATION.getMessage("origin")); - assertThat(((AppsmithException) throwable).getReferenceDoc()).isNotEmpty(); + assertThat(((AppsmithException) throwable).getReferenceDoc()) + .isNotEmpty(); return true; }) .verify(); @@ -347,15 +372,18 @@ public void connectApplicationToGit_EmptyPrivateKey_ThrowInvalidGitConfiguration testApplication.setName("EmptyPrivateKey"); testApplication.setWorkspaceId(workspaceId); testApplication.setGitApplicationMetadata(gitApplicationMetadata); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().contains(AppsmithError.INVALID_GIT_SSH_CONFIGURATION.getMessage("origin"))) + && throwable + .getMessage() + .contains(AppsmithError.INVALID_GIT_SSH_CONFIGURATION.getMessage("origin"))) .verify(); } @@ -371,15 +399,18 @@ public void connectApplicationToGit_EmptyPublicKey_ThrowInvalidGitConfigurationE testApplication.setName("EmptyPublicKey"); testApplication.setWorkspaceId(workspaceId); testApplication.setGitApplicationMetadata(gitApplicationMetadata); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().contains(AppsmithError.INVALID_GIT_SSH_CONFIGURATION.getMessage("origin"))) + && throwable + .getMessage() + .contains(AppsmithError.INVALID_GIT_SSH_CONFIGURATION.getMessage("origin"))) .verify(); } @@ -396,18 +427,21 @@ public void connectApplicationToGit_InvalidRemoteUrl_ThrowInvalidRemoteUrl() thr testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("InvalidRemoteUrl"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(false)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(false)); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException) .verify(); } @@ -425,20 +459,22 @@ public void connectApplicationToGit_InvalidRemoteUrlHttp_ThrowInvalidRemoteUrl() testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("InvalidRemoteUrlHttp"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("https://github.com/test/testRepo.git", testUserProfile); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.error(new ClassCastException("TransportHttp"))); - Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))) - .thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().equals(AppsmithError.INVALID_GIT_SSH_URL.getMessage())) + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_GIT_SSH_URL.getMessage())) .verify(); } @@ -446,9 +482,11 @@ public void connectApplicationToGit_InvalidRemoteUrlHttp_ThrowInvalidRemoteUrl() @WithUserDetails(value = "api_user") public void connectApplicationToGit_InvalidFilePath_ThrowIOException() throws IOException { - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenThrow(new IOException("Error while accessing the file system")); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenThrow(new IOException("Error while accessing the file system")); Application testApplication = new Application(); GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); @@ -459,13 +497,14 @@ public void connectApplicationToGit_InvalidFilePath_ThrowIOException() throws IO testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("InvalidFilePath"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testy.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains("Error while accessing the file system")) .verify(); @@ -475,9 +514,11 @@ public void connectApplicationToGit_InvalidFilePath_ThrowIOException() throws IO @WithUserDetails(value = "api_user") public void connectApplicationToGit_ClonedRepoNotEmpty_Failure() throws IOException { - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(false)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(false)); Application testApplication = new Application(); GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); @@ -488,13 +529,14 @@ public void connectApplicationToGit_ClonedRepoNotEmpty_Failure() throws IOExcept testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("ValidTest TestApp"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testy.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains(AppsmithError.INVALID_GIT_REPO.getMessage())) .verify(); @@ -504,16 +546,16 @@ public void connectApplicationToGit_ClonedRepoNotEmpty_Failure() throws IOExcept @WithUserDetails(value = "api_user") public void connectApplicationToGit_cloneException_throwGitException() throws IOException { - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.error(new Exception("error message"))); - Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))) - .thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(gitConnectedApplication.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(gitConnectedApplication.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().equals(AppsmithError.GIT_GENERIC_ERROR.getMessage("error message"))) .verify(); @@ -523,19 +565,39 @@ public void connectApplicationToGit_cloneException_throwGitException() throws IO @WithUserDetails(value = "api_user") public void connectApplicationToGit_WithEmptyPublishedPages_CloneSuccess() throws IOException, GitAPIException { - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("commit")); - Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())).thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("success")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(Mono.just("commit")); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) + .thenReturn(Mono.just("commit")); + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); @@ -549,47 +611,72 @@ public void connectApplicationToGit_WithEmptyPublishedPages_CloneSuccess() throw testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("validData_WithEmptyPublishedPages"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application -> { GitApplicationMetadata gitApplicationMetadata1 = application.getGitApplicationMetadata(); assertThat(gitApplicationMetadata1.getRemoteUrl()).isEqualTo(gitConnectDTO.getRemoteUrl()); assertThat(gitApplicationMetadata1.getBranchName()).isEqualTo("defaultBranchName"); - assertThat(gitApplicationMetadata1.getGitAuth().getPrivateKey()).isNotNull(); - assertThat(gitApplicationMetadata1.getGitAuth().getPublicKey()).isNotNull(); - assertThat(gitApplicationMetadata1.getGitAuth().getGeneratedAt()).isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getPrivateKey()) + .isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getPublicKey()) + .isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getGeneratedAt()) + .isNotNull(); assertThat(gitApplicationMetadata1.getRepoName()).isEqualTo("testRepo"); - assertThat(gitApplicationMetadata1.getDefaultApplicationId()).isEqualTo(application.getId()); + assertThat(gitApplicationMetadata1.getDefaultApplicationId()) + .isEqualTo(application.getId()); }) .verifyComplete(); } @Test @WithUserDetails(value = "api_user") - public void connectApplicationToGit_WithoutGitProfileUsingDefaultProfile_CloneSuccess() throws IOException, GitAPIException { + public void connectApplicationToGit_WithoutGitProfileUsingDefaultProfile_CloneSuccess() + throws IOException, GitAPIException { - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("commit")); - Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())).thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("success")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(Mono.just("commit")); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) + .thenReturn(Mono.just("commit")); + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); - Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))) - .thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); GitProfile gitProfile = new GitProfile(); gitProfile.setAuthorName(null); @@ -604,13 +691,14 @@ public void connectApplicationToGit_WithoutGitProfileUsingDefaultProfile_CloneSu testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("emptyDefaultProfileConnectTest"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", gitProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application -> { GitApplicationMetadata gitApplicationMetadata1 = application.getGitApplicationMetadata(); assertThat(gitApplicationMetadata1.getRemoteUrl()).isEqualTo(gitConnectDTO.getRemoteUrl()); @@ -642,13 +730,14 @@ public void connectApplicationToGit_WithoutGitProfileUsingLocalProfile_ThrowAuth testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("localGitProfile"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", gitProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage("Author Name"))) .verify(); @@ -658,23 +747,42 @@ public void connectApplicationToGit_WithoutGitProfileUsingLocalProfile_ThrowAuth @WithUserDetails(value = "api_user") public void connectApplicationToGit_WithNonEmptyPublishedPages_CloneSuccess() throws IOException, GitAPIException { - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("commit")); - Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())).thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("success")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(Mono.just("commit")); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) + .thenReturn(Mono.just("commit")); + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); - Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))) - .thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); Application testApplication = new Application(); GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); @@ -687,7 +795,8 @@ public void connectApplicationToGit_WithNonEmptyPublishedPages_CloneSuccess() th testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("connectApplicationToGit_WithNonEmptyPublishedPages"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); PageDTO page = new PageDTO(); page.setName("New Page"); @@ -695,17 +804,20 @@ public void connectApplicationToGit_WithNonEmptyPublishedPages_CloneSuccess() th applicationPageService.createPage(page).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application -> { GitApplicationMetadata gitApplicationMetadata1 = application.getGitApplicationMetadata(); assertThat(gitApplicationMetadata1.getRemoteUrl()).isEqualTo(gitConnectDTO.getRemoteUrl()); assertThat(gitApplicationMetadata1.getBranchName()).isEqualTo("defaultBranchName"); - assertThat(gitApplicationMetadata1.getGitAuth().getPrivateKey()).isNotNull(); - assertThat(gitApplicationMetadata1.getGitAuth().getPublicKey()).isNotNull(); - assertThat(gitApplicationMetadata1.getGitAuth().getGeneratedAt()).isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getPrivateKey()) + .isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getPublicKey()) + .isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getGeneratedAt()) + .isNotNull(); assertThat(gitApplicationMetadata1.getRepoName()).isEqualTo("testRepo"); }) .verifyComplete(); @@ -716,20 +828,36 @@ public void connectApplicationToGit_WithNonEmptyPublishedPages_CloneSuccess() th public void connectApplicationToGit_moreThanThreePrivateRepos_throwException() throws IOException, GitAPIException { Workspace workspace = new Workspace(); workspace.setName("Limit Private Repo Test Workspace"); - String limitPrivateRepoTestWorkspaceId = workspaceService.create(workspace).map(Workspace::getId).block(); + String limitPrivateRepoTestWorkspaceId = + workspaceService.create(workspace).map(Workspace::getId).block(); GitService gitService1 = Mockito.spy(gitService); - Mockito.doReturn(Mono.just(Boolean.TRUE)).when(gitService1).isRepoLimitReached(Mockito.anyString(), Mockito.anyBoolean()); + Mockito.doReturn(Mono.just(Boolean.TRUE)) + .when(gitService1) + .isRepoLimitReached(Mockito.anyString(), Mockito.anyBoolean()); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("commit")); - Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())).thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("success")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); @@ -744,13 +872,14 @@ public void connectApplicationToGit_moreThanThreePrivateRepos_throwException() t testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("connectApplicationToGit_WithNonEmptyPublishedPages"); testApplication.setWorkspaceId(limitPrivateRepoTestWorkspaceId); - Application application = applicationPageService.createApplication(testApplication).block(); + Application application = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService1.connectApplicationToGit(application.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService1.connectApplicationToGit(application.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(error -> error instanceof AppsmithException && error.getMessage().equals(AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getMessage())) .verify(); @@ -758,27 +887,43 @@ public void connectApplicationToGit_moreThanThreePrivateRepos_throwException() t @Test @WithUserDetails(value = "api_user") - public void connectApplicationToGit_toggleAccessibilityToPublicForConnectedApp_connectSuccessful() throws IOException, GitAPIException { + public void connectApplicationToGit_toggleAccessibilityToPublicForConnectedApp_connectSuccessful() + throws IOException, GitAPIException { Workspace workspace = new Workspace(); workspace.setName("Toggle Accessibility To Public From Private Repo Test Workspace"); - String limitPrivateRepoTestWorkspaceId = workspaceService.create(workspace).map(Workspace::getId).block(); + String limitPrivateRepoTestWorkspaceId = + workspaceService.create(workspace).map(Workspace::getId).block(); - Mockito - .when(gitCloudServicesUtils.getPrivateRepoLimitForOrg(eq(limitPrivateRepoTestWorkspaceId), Mockito.anyBoolean())) + Mockito.when(gitCloudServicesUtils.getPrivateRepoLimitForOrg( + eq(limitPrivateRepoTestWorkspaceId), Mockito.anyBoolean())) .thenReturn(Mono.just(3)); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("commit")); - Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())).thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("success")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); - Application application1 = this.createApplicationConnectedToGit("private_repo_1", "master", limitPrivateRepoTestWorkspaceId); + Application application1 = + this.createApplicationConnectedToGit("private_repo_1", "master", limitPrivateRepoTestWorkspaceId); this.createApplicationConnectedToGit("private_repo_2", "master", limitPrivateRepoTestWorkspaceId); Application testApplication = new Application(); @@ -792,17 +937,18 @@ public void connectApplicationToGit_toggleAccessibilityToPublicForConnectedApp_c testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("connectApplicationToGit_WithNonEmptyPublishedPages"); testApplication.setWorkspaceId(limitPrivateRepoTestWorkspaceId); - Application application = applicationPageService.createApplication(testApplication).block(); + Application application = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "baseUrl"); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "baseUrl"); // Use any dummy url so as to get 2xx response application1.getGitApplicationMetadata().setBrowserSupportedRemoteUrl("https://www.google.com/"); applicationService.save(application1).block(); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(connectedApp -> { assertThat(connectedApp.getId()).isNotEmpty(); }) @@ -813,19 +959,39 @@ public void connectApplicationToGit_toggleAccessibilityToPublicForConnectedApp_c @WithUserDetails(value = "api_user") public void connectApplicationToGit_WithValidCustomGitDomain_CloneSuccess() throws IOException, GitAPIException { - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("commit")); - Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())).thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("success")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(Mono.just("commit")); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) + .thenReturn(Mono.just("commit")); + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); @@ -839,22 +1005,28 @@ public void connectApplicationToGit_WithValidCustomGitDomain_CloneSuccess() thro testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("connectApplicationToGit_WithValidCustomGitDomain_CloneSuccess"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); - GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:user/test/tests/testRepo.git", testUserProfile); - Mono<Application> applicationMono = gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); + GitConnectDTO gitConnectDTO = + getConnectRequest("[email protected]:user/test/tests/testRepo.git", testUserProfile); + Mono<Application> applicationMono = + gitService.connectApplicationToGit(application1.getId(), gitConnectDTO, "baseUrl"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application -> { GitApplicationMetadata gitApplicationMetadata1 = application.getGitApplicationMetadata(); assertThat(gitApplicationMetadata1.getRemoteUrl()).isEqualTo(gitConnectDTO.getRemoteUrl()); assertThat(gitApplicationMetadata1.getBranchName()).isEqualTo("defaultBranchName"); - assertThat(gitApplicationMetadata1.getGitAuth().getPrivateKey()).isNotNull(); - assertThat(gitApplicationMetadata1.getGitAuth().getPublicKey()).isNotNull(); - assertThat(gitApplicationMetadata1.getGitAuth().getGeneratedAt()).isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getPrivateKey()) + .isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getPublicKey()) + .isNotNull(); + assertThat(gitApplicationMetadata1.getGitAuth().getGeneratedAt()) + .isNotNull(); assertThat(gitApplicationMetadata1.getRepoName()).isEqualTo("testRepo"); - assertThat(gitApplicationMetadata1.getDefaultApplicationId()).isEqualTo(application.getId()); + assertThat(gitApplicationMetadata1.getDefaultApplicationId()) + .isEqualTo(application.getId()); }) .verifyComplete(); } @@ -873,15 +1045,15 @@ public void updateGitMetadata_EmptyData_Success() { testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("updateGitMetadata_EmptyData_Success"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitApplicationMetadata gitApplicationMetadata1 = null; Mono<Application> applicationMono = gitService.updateGitMetadata(application1.getId(), gitApplicationMetadata1); - StepVerifier - .create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().contains("Git metadata values cannot be null")) + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().contains("Git metadata values cannot be null")) .verify(); } @@ -899,17 +1071,18 @@ public void updateGitMetadata_validData_Success() { testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("updateGitMetadata_EmptyData_Success1"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitApplicationMetadata gitApplicationMetadata1 = application1.getGitApplicationMetadata(); gitApplicationMetadata1.setRemoteUrl("https://test/.git"); Mono<Application> applicationMono = gitService.updateGitMetadata(application1.getId(), gitApplicationMetadata1); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application -> { assertThat(application.getGitApplicationMetadata()).isNotNull(); - assertThat(application.getGitApplicationMetadata().getRemoteUrl()).isEqualTo("https://test/.git"); + assertThat(application.getGitApplicationMetadata().getRemoteUrl()) + .isEqualTo("https://test/.git"); }) .verifyComplete(); } @@ -926,10 +1099,16 @@ public void detachRemote_applicationWithActionAndActionCollection_Success() { remoteGitBranchDTO.setBranchName("origin/defaultBranch"); branchList.add(remoteGitBranchDTO); - Mockito.when(gitExecutor.listBranches(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), eq(false))) + Mockito.when(gitExecutor.listBranches( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + eq(false))) .thenReturn(Mono.just(branchList)); Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Application testApplication = new Application(); GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); @@ -948,18 +1127,18 @@ public void detachRemote_applicationWithActionAndActionCollection_Success() { testApplication.setName("detachRemote_validData"); testApplication.setWorkspaceId(workspaceId); - Mono<Application> applicationMono = applicationPageService.createApplication(testApplication) + Mono<Application> applicationMono = applicationPageService + .createApplication(testApplication) .flatMap(application -> { // Update the defaultIds for resources to mock merge action from other branch application.getPages().forEach(page -> page.setDefaultPageId(page.getId() + "randomId")); return Mono.zip( applicationService.save(application), pluginRepository.findByPackageName("installed-plugin"), - newPageService.findPageById(application.getPages().get(0).getId(), READ_PAGES, false) - ); + newPageService.findPageById( + application.getPages().get(0).getId(), READ_PAGES, false)); }) .flatMap(tuple -> { - Application application = tuple.getT1(); PageDTO testPage = tuple.getT3(); @@ -990,8 +1169,8 @@ public void detachRemote_applicationWithActionAndActionCollection_Success() { ObjectMapper objectMapper = new ObjectMapper(); JSONObject parentDsl = null; try { - parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + parentDsl = new JSONObject(objectMapper.readValue( + DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); } catch (JsonProcessingException e) { log.debug(String.valueOf(e)); } @@ -1027,22 +1206,30 @@ public void detachRemote_applicationWithActionAndActionCollection_Success() { actionCollectionDTO.setDefaultToBranchedActionIdsMap(Map.of("branchedId", "collectionId")); return Mono.zip( - layoutActionService.createSingleAction(action, Boolean.FALSE) - .then(layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout)), - layoutCollectionService.createCollection(actionCollectionDTO) - ) + layoutActionService + .createSingleAction(action, Boolean.FALSE) + .then(layoutActionService.updateLayout( + testPage.getId(), + testPage.getApplicationId(), + layout.getId(), + layout)), + layoutCollectionService.createCollection(actionCollectionDTO)) .map(tuple2 -> application); }); - Mono<Application> resultMono = applicationMono - .flatMap(application -> gitService.detachRemote(application.getId())); - - StepVerifier - .create(resultMono.zipWhen(application -> Mono.zip( - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findNewPagesByApplicationId(application.getId(), READ_PAGES).collectList() - ))) + Mono<Application> resultMono = + applicationMono.flatMap(application -> gitService.detachRemote(application.getId())); + + StepVerifier.create(resultMono.zipWhen(application -> Mono.zip( + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findNewPagesByApplicationId(application.getId(), READ_PAGES) + .collectList()))) .assertNext(tuple -> { Application application = tuple.getT1(); List<NewAction> actionList = tuple.getT2().getT1(); @@ -1050,63 +1237,75 @@ public void detachRemote_applicationWithActionAndActionCollection_Success() { List<NewPage> pageList = tuple.getT2().getT3(); assertThat(application.getGitApplicationMetadata()).isNull(); - application.getPages().forEach(page -> assertThat(page.getDefaultPageId()).isEqualTo(page.getId())); - application.getPublishedPages().forEach(page -> assertThat(page.getDefaultPageId()).isEqualTo(page.getId())); + application.getPages().forEach(page -> assertThat(page.getDefaultPageId()) + .isEqualTo(page.getId())); + application.getPublishedPages().forEach(page -> assertThat(page.getDefaultPageId()) + .isEqualTo(page.getId())); assertThat(pageList).isNotNull(); pageList.forEach(newPage -> { assertThat(newPage.getDefaultResources()).isNotNull(); assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); - assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); - assertThat(newPage.getDefaultResources().getBranchName()).isNullOrEmpty(); - - newPage.getUnpublishedPage() - .getLayouts() - .forEach(layout -> - layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { - dslActionDTOS.forEach(actionDTO -> { - Assertions.assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); - }); - }) - ); + assertThat(newPage.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); + assertThat(newPage.getDefaultResources().getBranchName()) + .isNullOrEmpty(); + + newPage.getUnpublishedPage().getLayouts().forEach(layout -> layout.getLayoutOnLoadActions() + .forEach(dslActionDTOS -> { + dslActionDTOS.forEach(actionDTO -> { + Assertions.assertThat(actionDTO.getId()) + .isEqualTo(actionDTO.getDefaultActionId()); + }); + })); }); assertThat(actionList).hasSize(2); actionList.forEach(newAction -> { assertThat(newAction.getDefaultResources()).isNotNull(); - assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); - assertThat(newAction.getDefaultResources().getBranchName()).isNullOrEmpty(); + assertThat(newAction.getDefaultResources().getActionId()) + .isEqualTo(newAction.getId()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); + assertThat(newAction.getDefaultResources().getBranchName()) + .isNullOrEmpty(); ActionDTO action = newAction.getUnpublishedAction(); assertThat(action.getDefaultResources()).isNotNull(); - assertThat(action.getDefaultResources().getPageId()).isEqualTo(application.getPages().get(0).getId()); + assertThat(action.getDefaultResources().getPageId()) + .isEqualTo(application.getPages().get(0).getId()); if (!StringUtils.isEmpty(action.getDefaultResources().getCollectionId())) { - assertThat(action.getDefaultResources().getCollectionId()).isEqualTo(action.getCollectionId()); + assertThat(action.getDefaultResources().getCollectionId()) + .isEqualTo(action.getCollectionId()); } }); assertThat(actionCollectionList).hasSize(1); actionCollectionList.forEach(actionCollection -> { assertThat(actionCollection.getDefaultResources()).isNotNull(); - assertThat(actionCollection.getDefaultResources().getCollectionId()).isEqualTo(actionCollection.getId()); - assertThat(actionCollection.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); - assertThat(actionCollection.getDefaultResources().getBranchName()).isNullOrEmpty(); + assertThat(actionCollection.getDefaultResources().getCollectionId()) + .isEqualTo(actionCollection.getId()); + assertThat(actionCollection.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); + assertThat(actionCollection.getDefaultResources().getBranchName()) + .isNullOrEmpty(); ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); assertThat(unpublishedCollection.getDefaultToBranchedActionIdsMap()) .hasSize(1); - unpublishedCollection.getDefaultToBranchedActionIdsMap().keySet() - .forEach(key -> - assertThat(key).isEqualTo(unpublishedCollection.getDefaultToBranchedActionIdsMap().get(key)) - ); + unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .keySet() + .forEach(key -> assertThat(key) + .isEqualTo(unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .get(key))); assertThat(unpublishedCollection.getDefaultResources()).isNotNull(); assertThat(unpublishedCollection.getDefaultResources().getPageId()) .isEqualTo(application.getPages().get(0).getId()); }); - }) .verifyComplete(); } @@ -1118,13 +1317,14 @@ public void detachRemote_EmptyGitData_NoChange() { testApplication.setGitApplicationMetadata(null); testApplication.setName("detachRemote_EmptyGitData"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); Mono<Application> applicationMono = gitService.detachRemote(application1.getId()); - StepVerifier - .create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException & throwable.getMessage().contains("Git configuration is invalid")) + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + & throwable.getMessage().contains("Git configuration is invalid")) .verify(); } @@ -1136,14 +1336,17 @@ public void listBranchForApplication_emptyGitMetadata_throwError() { testApplication.setGitApplicationMetadata(null); testApplication.setName("validData_WithNonEmptyPublishedPages"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); - Mono<List<GitBranchDTO>> listMono = gitService.listBranchForApplication(application1.getId(), false, "defaultBranch"); + Mono<List<GitBranchDTO>> listMono = + gitService.listBranchForApplication(application1.getId(), false, "defaultBranch"); - StepVerifier - .create(listMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR))) + StepVerifier.create(listMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR))) .verify(); } @@ -1151,7 +1354,8 @@ public void listBranchForApplication_emptyGitMetadata_throwError() { @WithUserDetails(value = "api_user") public void listBranchForApplication_applicationWithInvalidGitConfig_throwError() throws IOException { - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); @@ -1159,14 +1363,17 @@ public void listBranchForApplication_applicationWithInvalidGitConfig_throwError( testApplication.setGitApplicationMetadata(null); testApplication.setName("listBranchForApplication_GitFailure_ThrowError"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); - Mono<List<GitBranchDTO>> listMono = gitService.listBranchForApplication(application1.getId(), false, "defaultBranch"); + Mono<List<GitBranchDTO>> listMono = + gitService.listBranchForApplication(application1.getId(), false, "defaultBranch"); - StepVerifier - .create(listMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR))) + StepVerifier.create(listMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR))) .verify(); } @@ -1183,22 +1390,36 @@ public void listBranchForApplication_defaultBranchNotChangesInRemote_Success() t gitBranchDTO.setDefault(false); branchList.add(gitBranchDTO); - Mockito.when(gitExecutor.listBranches(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), eq(true))) + Mockito.when(gitExecutor.listBranches( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + eq(true))) .thenReturn(Mono.just(branchList)); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), eq(false), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + eq(false), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("status")); - Application application1 = createApplicationConnectedToGit("listBranchForApplication_pruneBranchNoChangesInRemote_Success", "defaultBranch"); + Application application1 = createApplicationConnectedToGit( + "listBranchForApplication_pruneBranchNoChangesInRemote_Success", "defaultBranch"); - Mono<List<GitBranchDTO>> listMono = gitService.listBranchForApplication(application1.getId(), true, "defaultBranch"); + Mono<List<GitBranchDTO>> listMono = + gitService.listBranchForApplication(application1.getId(), true, "defaultBranch"); - StepVerifier - .create(listMono) + StepVerifier.create(listMono) .assertNext(listBranch -> { assertThat(listBranch).isEqualTo(branchList); }) @@ -1207,7 +1428,8 @@ public void listBranchForApplication_defaultBranchNotChangesInRemote_Success() t @Test @WithUserDetails(value = "api_user") - public void listBranchForApplication_defaultBranchChangesInRemoteExistsInDB_Success() throws IOException, GitAPIException { + public void listBranchForApplication_defaultBranchChangesInRemoteExistsInDB_Success() + throws IOException, GitAPIException { List<GitBranchDTO> branchList = new ArrayList<>(); GitBranchDTO gitBranchDTO = new GitBranchDTO(); gitBranchDTO.setBranchName("defaultBranch"); @@ -1226,40 +1448,57 @@ public void listBranchForApplication_defaultBranchChangesInRemoteExistsInDB_Succ gitBranchDTO.setDefault(false); branchList.add(gitBranchDTO); - Mockito.when(gitExecutor.listBranches(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), eq(true))) + Mockito.when(gitExecutor.listBranches( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + eq(true))) .thenReturn(Mono.just(branchList)); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), eq(false), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + eq(false), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("status")); Mockito.when(gitExecutor.deleteBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Application application1 = createApplicationConnectedToGit("listBranchForApplication_pruneBranchWithBranchNotExistsInDB_Success", "defaultBranch"); + Application application1 = createApplicationConnectedToGit( + "listBranchForApplication_pruneBranchWithBranchNotExistsInDB_Success", "defaultBranch"); // Create branch - Application application2 = createApplicationConnectedToGit("listBranchForApplication_defaultBranchChangesInRemoteExistsInDB_Success", - "feature1"); + Application application2 = createApplicationConnectedToGit( + "listBranchForApplication_defaultBranchChangesInRemoteExistsInDB_Success", "feature1"); application2.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); applicationService.save(application2).block(); - Mono<Application> applicationUpdatedMono = gitService.listBranchForApplication(application1.getId(), true, "defaultBranch") + Mono<Application> applicationUpdatedMono = gitService + .listBranchForApplication(application1.getId(), true, "defaultBranch") .then(applicationService.findById(application1.getId())); - StepVerifier - .create(applicationUpdatedMono) + StepVerifier.create(applicationUpdatedMono) .assertNext(application -> { - assertThat(application.getGitApplicationMetadata().getDefaultBranchName()).isEqualTo("feature1"); - assertThat(application.getGitApplicationMetadata().getBranchName()).isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getDefaultBranchName()) + .isEqualTo("feature1"); + assertThat(application.getGitApplicationMetadata().getBranchName()) + .isEqualTo("defaultBranch"); }) .verifyComplete(); } @Test @WithUserDetails(value = "api_user") - public void listBranchForApplication_defaultBranchChangesInRemoteDoesNotExistsInDB_Success() throws IOException, GitAPIException { + public void listBranchForApplication_defaultBranchChangesInRemoteDoesNotExistsInDB_Success() + throws IOException, GitAPIException { List<GitBranchDTO> branchList = new ArrayList<>(); GitBranchDTO gitBranchDTO = new GitBranchDTO(); gitBranchDTO.setBranchName("defaultBranch"); @@ -1280,30 +1519,47 @@ public void listBranchForApplication_defaultBranchChangesInRemoteDoesNotExistsIn ApplicationJson applicationJson = createAppJson(filePath).block(); - Mockito.when(gitExecutor.listBranches(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), eq(true))) + Mockito.when(gitExecutor.listBranches( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + eq(true))) .thenReturn(Mono.just(branchList)); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), eq(false), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + eq(false), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("status")); Mockito.when(gitExecutor.checkoutRemoteBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just("feature1")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); - Application application1 = createApplicationConnectedToGit("listBranchForApplication_defaultBranchChangesInRemoteDoesNotExistsInDB_Success", "defaultBranch"); + Application application1 = createApplicationConnectedToGit( + "listBranchForApplication_defaultBranchChangesInRemoteDoesNotExistsInDB_Success", "defaultBranch"); - Mono<Application> applicationUpdatedMono = gitService.listBranchForApplication(application1.getId(), true, "defaultBranch") + Mono<Application> applicationUpdatedMono = gitService + .listBranchForApplication(application1.getId(), true, "defaultBranch") .then(applicationService.findById(application1.getId())); - StepVerifier - .create(applicationUpdatedMono) + StepVerifier.create(applicationUpdatedMono) .assertNext(application -> { - assertThat(application.getGitApplicationMetadata().getDefaultBranchName()).isEqualTo("feature1"); - assertThat(application.getGitApplicationMetadata().getBranchName()).isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getDefaultBranchName()) + .isEqualTo("feature1"); + assertThat(application.getGitApplicationMetadata().getBranchName()) + .isEqualTo("defaultBranch"); }) .verifyComplete(); @@ -1326,24 +1582,36 @@ public void pullChanges_upstreamChangesAvailable_pullSuccess() throws IOExceptio gitStatusDTO.setBehindCount(0); gitStatusDTO.setIsClean(true); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("path"))); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); Mockito.when(gitExecutor.pullApplication( - Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just(mergeStatusDTO)); Mockito.when(gitExecutor.getStatus(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(gitStatusDTO)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), eq(true), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + eq(true), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetched")); Mockito.when(gitExecutor.resetToLastCommit(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mono<GitPullDTO> applicationMono = gitService.pullApplication(application.getId(), application.getGitApplicationMetadata().getBranchName()); + Mono<GitPullDTO> applicationMono = gitService.pullApplication( + application.getId(), application.getGitApplicationMetadata().getBranchName()); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(gitPullDTO -> { assertThat(gitPullDTO.getMergeStatus().getStatus()).isEqualTo("2 commits pulled"); assertThat(gitPullDTO.getApplication()).isNotNull(); @@ -1360,20 +1628,26 @@ public void pullChanges_FileSystemAccessError_throwError() throws IOException, G mergeStatusDTO.setStatus("2 commits pulled"); mergeStatusDTO.setMergeAble(true); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenThrow(new IOException("Error accessing the file System")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(new ApplicationJson())); Mockito.when(gitExecutor.pullApplication( - Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just(mergeStatusDTO)); - Mono<GitPullDTO> applicationMono = gitService.pullApplication(application.getId(), application.getGitApplicationMetadata().getBranchName()); + Mono<GitPullDTO> applicationMono = gitService.pullApplication( + application.getId(), application.getGitApplicationMetadata().getBranchName()); - StepVerifier - .create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().contains("Error accessing the file System")) + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().contains("Error accessing the file System")) .verify(); } @@ -1388,26 +1662,38 @@ public void pullChanges_noUpstreamChanges_nothingToPullMessage() throws IOExcept mergeStatusDTO.setStatus("Nothing to fetch from remote. All changes are upto date."); mergeStatusDTO.setMergeAble(true); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.justOrEmpty(applicationJson)); - Mockito.when(gitExecutor.getStatus(Mockito.any(), Mockito.any())) - .thenReturn(Mono.just(new GitStatusDTO())); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.getStatus(Mockito.any(), Mockito.any())).thenReturn(Mono.just(new GitStatusDTO())); + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); Mockito.when(gitExecutor.pullApplication( - Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just(mergeStatusDTO)); Mockito.when(gitExecutor.resetToLastCommit(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mono<GitPullDTO> applicationMono = gitService.pullApplication(application.getId(), application.getGitApplicationMetadata().getBranchName()); + Mono<GitPullDTO> applicationMono = gitService.pullApplication( + application.getId(), application.getGitApplicationMetadata().getBranchName()); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(gitPullDTO -> { - assertThat(gitPullDTO.getMergeStatus().getStatus()).isEqualTo("Nothing to fetch from remote. All changes are upto date."); + assertThat(gitPullDTO.getMergeStatus().getStatus()) + .isEqualTo("Nothing to fetch from remote. All changes are upto date."); }) .verifyComplete(); } @@ -1434,23 +1720,29 @@ public void isBranchMergeable_nonConflictingChanges_canBeMerged() throws IOExcep gitStatusDTO.setAheadCount(0); gitStatusDTO.setBehindCount(0); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); Mockito.when(gitExecutor.isMergeBranch(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(mergeStatus)); - Mockito.when(gitExecutor.getStatus(Mockito.any(), Mockito.any())) - .thenReturn(Mono.just(gitStatusDTO)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.getStatus(Mockito.any(), Mockito.any())).thenReturn(Mono.just(gitStatusDTO)); + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); Mockito.when(gitExecutor.resetToLastCommit(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(Boolean.TRUE)); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); Mono<MergeStatusDTO> applicationMono = gitService.isBranchMergeable(application.getId(), gitMergeDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(s -> assertThat(s.isMergeAble()).isTrue()) .verifyComplete(); } @@ -1471,23 +1763,29 @@ public void isBranchMergeable_conflictingChanges_canNotBeMerged() throws IOExcep MergeStatusDTO mergeStatus = new MergeStatusDTO(); mergeStatus.setMergeAble(false); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); Mockito.when(gitExecutor.isMergeBranch(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(mergeStatus)); - Mockito.when(gitExecutor.getStatus(Mockito.any(), Mockito.any())) - .thenReturn(Mono.just(new GitStatusDTO())); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.getStatus(Mockito.any(), Mockito.any())).thenReturn(Mono.just(new GitStatusDTO())); + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); Mockito.when(gitExecutor.resetToLastCommit(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(Boolean.FALSE)); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); Mono<MergeStatusDTO> applicationMono = gitService.isBranchMergeable(application.getId(), gitMergeDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(s -> { assertThat(s.isMergeAble()).isFalse(); }) @@ -1498,7 +1796,8 @@ public void isBranchMergeable_conflictingChanges_canNotBeMerged() throws IOExcep @WithUserDetails(value = "api_user") public void isBranchMergeable_remoteAhead_remoteAheadErrorMessage() throws IOException, GitAPIException { - Application application1 = createApplicationConnectedToGit(gitConnectedApplication.getName(), "upstreamChangesBeforeMerge"); + Application application1 = + createApplicationConnectedToGit(gitConnectedApplication.getName(), "upstreamChangesBeforeMerge"); GitApplicationMetadata gitApplicationMetadata = application1.getGitApplicationMetadata(); gitApplicationMetadata.setDefaultApplicationId(gitConnectedApplication.getId()); application1.setGitApplicationMetadata(gitApplicationMetadata); @@ -1514,29 +1813,35 @@ public void isBranchMergeable_remoteAhead_remoteAheadErrorMessage() throws IOExc MergeStatusDTO mergeStatus = new MergeStatusDTO(); mergeStatus.setMergeAble(false); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("path"))); Mockito.when(gitExecutor.isMergeBranch(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(mergeStatus)); - Mockito.when(gitExecutor.getStatus(Mockito.any(), Mockito.any())) - .thenReturn(Mono.just(gitStatusDTO)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.getStatus(Mockito.any(), Mockito.any())).thenReturn(Mono.just(gitStatusDTO)); + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); Mockito.when(gitExecutor.resetToLastCommit(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(Boolean.FALSE)); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mono<MergeStatusDTO> applicationMono = gitService.isBranchMergeable(gitConnectedApplication.getId(), gitMergeDTO); + Mono<MergeStatusDTO> applicationMono = + gitService.isBranchMergeable(gitConnectedApplication.getId(), gitMergeDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(s -> { assertThat(s.isMergeAble()).isFalse(); assertThat(s.getMessage()).contains("Remote is ahead of local"); }) .verifyComplete(); - } @Test @@ -1547,13 +1852,13 @@ public void isBranchMergeable_checkMergingWithRemoteBranch_throwsUnsupportedOper gitMergeDTO.setSourceBranch("origin/branch2"); gitMergeDTO.setDestinationBranch("defaultBranch"); - Mono<MergeStatusDTO> applicationMono = gitService.isBranchMergeable(gitConnectedApplication.getId(), gitMergeDTO); + Mono<MergeStatusDTO> applicationMono = + gitService.isBranchMergeable(gitConnectedApplication.getId(), gitMergeDTO); - StepVerifier - .create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains("origin/branch2")) + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().contains("origin/branch2")) .verify(); - } @Test @@ -1570,23 +1875,34 @@ public void checkoutRemoteBranch_notPresentInLocal_newApplicationCreated() throw gitBranchDTO.setBranchName("origin/branchInLocal"); branchList.add(gitBranchDTO); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); Mockito.when(gitExecutor.checkoutRemoteBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just("testBranch")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); - Mockito.when(gitExecutor.listBranches(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.listBranches( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(branchList)); - Mono<Application> applicationMono = gitService.checkoutBranch(gitConnectedApplication.getId(), "origin/branchNotInLocal") - .flatMap(application1 -> applicationService.findByBranchNameAndDefaultApplicationId("branchNotInLocal", gitConnectedApplication.getId(), READ_APPLICATIONS)); + Mono<Application> applicationMono = gitService + .checkoutBranch(gitConnectedApplication.getId(), "origin/branchNotInLocal") + .flatMap(application1 -> applicationService.findByBranchNameAndDefaultApplicationId( + "branchNotInLocal", gitConnectedApplication.getId(), READ_APPLICATIONS)); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application1 -> { - assertThat(application1.getGitApplicationMetadata().getBranchName()).isEqualTo("branchNotInLocal"); - assertThat(application1.getGitApplicationMetadata().getDefaultApplicationId()).isEqualTo(gitConnectedApplication.getId()); + assertThat(application1.getGitApplicationMetadata().getBranchName()) + .isEqualTo("branchNotInLocal"); + assertThat(application1.getGitApplicationMetadata().getDefaultApplicationId()) + .isEqualTo(gitConnectedApplication.getId()); }) .verifyComplete(); } @@ -1603,17 +1919,27 @@ public void checkoutRemoteBranch_presentInLocal_throwError() { gitBranchDTO.setBranchName("origin/branchInLocal"); branchList.add(gitBranchDTO); - Mockito.when(gitExecutor.listBranches(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.listBranches( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(branchList)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); - Mono<Application> applicationMono = gitService.checkoutBranch(gitConnectedApplication.getId(), "origin/branchInLocal"); + Mono<Application> applicationMono = + gitService.checkoutBranch(gitConnectedApplication.getId(), "origin/branchInLocal"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().equals(AppsmithError.GIT_ACTION_FAILED.getMessage("checkout", "origin/branchInLocal already exists in local - branchInLocal"))) + && throwable + .getMessage() + .equals(AppsmithError.GIT_ACTION_FAILED.getMessage( + "checkout", "origin/branchInLocal already exists in local - branchInLocal"))) .verify(); } @@ -1623,10 +1949,11 @@ public void checkoutBranch_branchNotProvided_throwInvalidParameterError() { Mono<Application> applicationMono = gitService.checkoutBranch(gitConnectedApplication.getId(), null); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.BRANCH_NAME))) + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.BRANCH_NAME))) .verify(); } @@ -1638,15 +1965,22 @@ public void commitApplication_noChangesInLocal_emptyCommitMessage() throws GitAP commitDTO.setDoPush(false); commitDTO.setCommitMessage("empty commit"); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.error(new EmptyCommitException("nothing to commit"))); - Mono<String> commitMono = gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); + Mono<String> commitMono = + gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); - StepVerifier - .create(commitMono) + StepVerifier.create(commitMono) .assertNext(commitMsg -> { assertThat(commitMsg).contains(EMPTY_COMMIT_ERROR_MESSAGE); }) @@ -1669,32 +2003,37 @@ public void commitApplication_applicationNotConnectedToGit_throwInvalidGitConfig Mono<String> commitMono = gitService.commitApplication(commitDTO, application.getId(), DEFAULT_BRANCH); - StepVerifier - .create(commitMono) + StepVerifier.create(commitMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().equals( - AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR)) - ) + && throwable + .getMessage() + .equals(AppsmithError.INVALID_GIT_CONFIGURATION.getMessage(GIT_CONFIG_ERROR))) .verify(); } @Test @WithUserDetails(value = "api_user") - public void commitApplication_localRepoNotAvailable_throwRepoNotFoundException() throws GitAPIException, IOException { + public void commitApplication_localRepoNotAvailable_throwRepoNotFoundException() + throws GitAPIException, IOException { GitCommitDTO commitDTO = new GitCommitDTO(); commitDTO.setDoPush(false); commitDTO.setCommitMessage("empty commit"); - Mono<String> commitMono = gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); + Mono<String> commitMono = + gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) - .thenReturn(Mono.error(new RepositoryNotFoundException(AppsmithError.REPOSITORY_NOT_FOUND.getMessage()))); + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + .thenReturn( + Mono.error(new RepositoryNotFoundException(AppsmithError.REPOSITORY_NOT_FOUND.getMessage()))); - StepVerifier - .create(commitMono) + StepVerifier.create(commitMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().contains(AppsmithError.REPOSITORY_NOT_FOUND.getMessage(gitConnectedApplication.getId()))) + && throwable + .getMessage() + .contains( + AppsmithError.REPOSITORY_NOT_FOUND.getMessage(gitConnectedApplication.getId()))) .verify(); } @@ -1706,15 +2045,22 @@ public void commitApplication_commitChanges_success() throws GitAPIException, IO commitDTO.setDoPush(false); commitDTO.setCommitMessage("commit message"); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("sample response for commit")); - Mono<String> commitMono = gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); + Mono<String> commitMono = + gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); - StepVerifier - .create(commitMono) + StepVerifier.create(commitMono) .assertNext(commitMsg -> { assertThat(commitMsg).contains("sample response for commit"); }) @@ -1729,19 +2075,32 @@ public void commitAndPushApplication_commitAndPushChanges_success() throws GitAP commitDTO.setDoPush(true); commitDTO.setCommitMessage("commit message"); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("sample response for commit")); Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("pushed successfully")); - Mono<String> commitAndPushMono = gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); + Mono<String> commitAndPushMono = + gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); - StepVerifier - .create(commitAndPushMono.zipWhen(status -> applicationService.findByIdAndBranchName(gitConnectedApplication.getId(), DEFAULT_BRANCH))) + StepVerifier.create(commitAndPushMono.zipWhen(status -> + applicationService.findByIdAndBranchName(gitConnectedApplication.getId(), DEFAULT_BRANCH))) .assertNext(tuple -> { String commitMsg = tuple.getT1(); Application application = tuple.getT2(); @@ -1756,25 +2115,38 @@ public void commitAndPushApplication_commitAndPushChanges_success() throws GitAP @Test @WithUserDetails(value = "api_user") - public void commitAndPushApplication_noChangesToCommitWithLocalCommitsToPush_pushSuccess() throws GitAPIException, IOException { + public void commitAndPushApplication_noChangesToCommitWithLocalCommitsToPush_pushSuccess() + throws GitAPIException, IOException { GitCommitDTO commitDTO = new GitCommitDTO(); commitDTO.setDoPush(true); commitDTO.setCommitMessage("empty commit"); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.error(new EmptyCommitException("nothing to commit"))); Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("pushed successfully")); - Mono<String> commitAndPushMono = gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); + Mono<String> commitAndPushMono = + gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); - StepVerifier - .create(commitAndPushMono) + StepVerifier.create(commitAndPushMono) .assertNext(commitAndPushMsg -> { assertThat(commitAndPushMsg).contains(EMPTY_COMMIT_ERROR_MESSAGE); assertThat(commitAndPushMsg).contains("pushed successfully"); @@ -1787,11 +2159,15 @@ public void commitAndPushApplication_noChangesToCommitWithLocalCommitsToPush_pus */ @Test @WithUserDetails(value = "api_user") - public void commitApplication_pushFails_verifyAppNotPublished_throwUpstreamChangesFoundException() throws GitAPIException, IOException { + public void commitApplication_pushFails_verifyAppNotPublished_throwUpstreamChangesFoundException() + throws GitAPIException, IOException { // Create and fetch the application state before adding new page - Application testApplication = createApplicationConnectedToGit("gitConnectedPushFailApplication", DEFAULT_BRANCH); - Application preCommitApplication = applicationService.getApplicationByDefaultApplicationIdAndDefaultBranch(testApplication.getId()).block(); + Application testApplication = + createApplicationConnectedToGit("gitConnectedPushFailApplication", DEFAULT_BRANCH); + Application preCommitApplication = applicationService + .getApplicationByDefaultApplicationIdAndDefaultBranch(testApplication.getId()) + .block(); // Creating a new page to commit to git PageDTO testPage = new PageDTO(); @@ -1804,25 +2180,33 @@ public void commitApplication_pushFails_verifyAppNotPublished_throwUpstreamChang commitDTO.setCommitMessage("New page added"); Mono<String> commitMono = gitService.commitApplication(commitDTO, preCommitApplication.getId(), DEFAULT_BRANCH); - Mono<Application> committedApplicationMono = applicationService.getApplicationByDefaultApplicationIdAndDefaultBranch(preCommitApplication.getId()); + Mono<Application> committedApplicationMono = + applicationService.getApplicationByDefaultApplicationIdAndDefaultBranch(preCommitApplication.getId()); // Mocking a git push failure - Mockito.when(gitExecutor.pushApplication(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.error(new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES))); - StepVerifier - .create(commitMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals((new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "push", AppsmithError.GIT_UPSTREAM_CHANGES.getMessage())).getMessage())) + StepVerifier.create(commitMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals((new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "push", + AppsmithError.GIT_UPSTREAM_CHANGES.getMessage())) + .getMessage())) .verify(); - StepVerifier - .create(committedApplicationMono) + StepVerifier.create(committedApplicationMono) .assertNext(application -> { List<ApplicationPage> publishedPages = application.getPublishedPages(); - assertThat(application.getPublishedPages().size()).isEqualTo(preCommitApplication.getPublishedPages().size()); + assertThat(application.getPublishedPages().size()) + .isEqualTo(preCommitApplication.getPublishedPages().size()); publishedPages.forEach(publishedPage -> { - assertThat(publishedPage.getId().equals(createdPage.getId())).isFalse(); + assertThat(publishedPage.getId().equals(createdPage.getId())) + .isFalse(); }); }) .verifyComplete(); @@ -1832,8 +2216,11 @@ public void commitApplication_pushFails_verifyAppNotPublished_throwUpstreamChang @WithUserDetails(value = "api_user") public void commitApplication_protectedBranch_pushFails() throws GitAPIException, IOException { // Create and fetch the application state before adding new page - Application testApplication = createApplicationConnectedToGit("commitApplication_protectedBranch_pushFails", DEFAULT_BRANCH); - Application preCommitApplication = applicationService.getApplicationByDefaultApplicationIdAndDefaultBranch(testApplication.getId()).block(); + Application testApplication = + createApplicationConnectedToGit("commitApplication_protectedBranch_pushFails", DEFAULT_BRANCH); + Application preCommitApplication = applicationService + .getApplicationByDefaultApplicationIdAndDefaultBranch(testApplication.getId()) + .block(); // Creating a new page to commit to git PageDTO testPage = new PageDTO(); @@ -1847,15 +2234,21 @@ public void commitApplication_protectedBranch_pushFails() throws GitAPIException Mono<String> commitMono = gitService.commitApplication(commitDTO, preCommitApplication.getId(), DEFAULT_BRANCH); // Mocking a git push failure - Mockito.when(gitExecutor.pushApplication(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just("REJECTED_OTHERREASON, pre-receive hook declined")); Mockito.when(gitExecutor.resetHard(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - StepVerifier - .create(commitMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().contains((new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "push", "Unable to push changes as pre-receive hook declined. Please make sure that you don't have any rules enabled on the branch ")).getMessage())) + StepVerifier.create(commitMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .contains((new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "push", + "Unable to push changes as pre-receive hook declined. Please make sure that you don't have any rules enabled on the branch ")) + .getMessage())) .verify(); } @@ -1866,13 +2259,16 @@ public void createBranch_branchWithOriginPrefix_throwUnsupportedException() { GitBranchDTO createGitBranchDTO = new GitBranchDTO(); createGitBranchDTO.setBranchName("origin/createNewBranch"); - Mono<Application> createBranchMono = gitService - .createBranch(gitConnectedApplication.getId(), createGitBranchDTO, gitConnectedApplication.getGitApplicationMetadata().getBranchName()); + Mono<Application> createBranchMono = gitService.createBranch( + gitConnectedApplication.getId(), + createGitBranchDTO, + gitConnectedApplication.getGitApplicationMetadata().getBranchName()); - StepVerifier - .create(createBranchMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage() - .contains(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.BRANCH_NAME))) + StepVerifier.create(createBranchMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .contains(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.BRANCH_NAME))) .verify(); } @@ -1890,17 +2286,28 @@ public void createBranch_duplicateNameBranchPresentInRemote_throwDuplicateKeyExc Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); - Mockito.when(gitExecutor.listBranches(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.listBranches( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(branchList)); - Mono<Application> createBranchMono = gitService - .createBranch(gitConnectedApplication.getId(), createGitBranchDTO, gitConnectedApplication.getGitApplicationMetadata().getBranchName()); + Mono<Application> createBranchMono = gitService.createBranch( + gitConnectedApplication.getId(), + createGitBranchDTO, + gitConnectedApplication.getGitApplicationMetadata().getBranchName()); - StepVerifier - .create(createBranchMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage() - .contains(AppsmithError.DUPLICATE_KEY_USER_ERROR.getMessage("remotes/origin/" + createGitBranchDTO.getBranchName(), FieldName.BRANCH_NAME))) + StepVerifier.create(createBranchMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .contains(AppsmithError.DUPLICATE_KEY_USER_ERROR.getMessage( + "remotes/origin/" + createGitBranchDTO.getBranchName(), FieldName.BRANCH_NAME))) .verify(); } @@ -1915,24 +2322,45 @@ public void createBranch_validCreateBranchRequest_newApplicationCreated() throws Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); - Mockito.when(gitExecutor.listBranches(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.listBranches( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(new ArrayList<>())); Mockito.when(gitExecutor.createAndCheckoutToBranch(Mockito.any(), Mockito.any())) .thenReturn(Mono.just(createGitBranchDTO.getBranchName())); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("System generated commit")); Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("pushed successfully")); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(DEFAULT_BRANCH)); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); @@ -1946,15 +2374,14 @@ public void createBranch_validCreateBranchRequest_newApplicationCreated() throws testApplication.setName("validAppWithActionAndActionCollection"); testApplication.setWorkspaceId(workspaceId); - Mono<Application> createBranchMono = applicationPageService.createApplication(testApplication) - .flatMap(application -> - Mono.zip( - Mono.just(application), - pluginRepository.findByPackageName("installed-plugin"), - newPageService.findPageById(application.getPages().get(0).getId(), READ_PAGES, false)) - ) + Mono<Application> createBranchMono = applicationPageService + .createApplication(testApplication) + .flatMap(application -> Mono.zip( + Mono.just(application), + pluginRepository.findByPackageName("installed-plugin"), + newPageService.findPageById( + application.getPages().get(0).getId(), READ_PAGES, false))) .flatMap(tuple -> { - Application application = tuple.getT1(); PageDTO testPage = tuple.getT3(); @@ -1977,8 +2404,8 @@ public void createBranch_validCreateBranchRequest_newApplicationCreated() throws ObjectMapper objectMapper = new ObjectMapper(); JSONObject parentDsl = null; try { - parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + parentDsl = new JSONObject(objectMapper.readValue( + DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); } catch (JsonProcessingException e) { log.debug(String.valueOf(e)); } @@ -2012,25 +2439,36 @@ public void createBranch_validCreateBranchRequest_newApplicationCreated() throws actionCollectionDTO.setPluginType(PluginType.JS); return Mono.zip( - layoutActionService.createSingleActionWithBranch(action, null) - .then(layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout)), - layoutCollectionService.createCollection(actionCollectionDTO, null) - ) + layoutActionService + .createSingleActionWithBranch(action, null) + .then(layoutActionService.updateLayout( + testPage.getId(), + testPage.getApplicationId(), + layout.getId(), + layout)), + layoutCollectionService.createCollection(actionCollectionDTO, null)) .then(gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")); }) - .flatMap(application -> - gitService - .createBranch(application.getId(), createGitBranchDTO, application.getGitApplicationMetadata().getBranchName()) - .then(applicationService.findByBranchNameAndDefaultApplicationId(createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS)) - ); - - StepVerifier - .create(createBranchMono.zipWhen(application -> Mono.zip( - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findNewPagesByApplicationId(application.getId(), READ_PAGES).collectList(), - applicationService.findById(application.getGitApplicationMetadata().getDefaultApplicationId()) - ))) + .flatMap(application -> gitService + .createBranch( + application.getId(), + createGitBranchDTO, + application.getGitApplicationMetadata().getBranchName()) + .then(applicationService.findByBranchNameAndDefaultApplicationId( + createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS))); + + StepVerifier.create(createBranchMono.zipWhen(application -> Mono.zip( + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findNewPagesByApplicationId(application.getId(), READ_PAGES) + .collectList(), + applicationService.findById( + application.getGitApplicationMetadata().getDefaultApplicationId())))) .assertNext(tuple -> { Application application = tuple.getT1(); List<NewAction> actionList = tuple.getT2().getT1(); @@ -2050,56 +2488,67 @@ public void createBranch_validCreateBranchRequest_newApplicationCreated() throws assertThat(gitData.getGitAuth()).isNull(); assertThat(gitData.getIsRepoPrivate()).isNull(); - application.getPages().forEach(page -> assertThat(page.getDefaultPageId()).isNotEqualTo(page.getId())); - application.getPublishedPages().forEach(page -> assertThat(page.getDefaultPageId()).isNotEqualTo(page.getId())); + application.getPages().forEach(page -> assertThat(page.getDefaultPageId()) + .isNotEqualTo(page.getId())); + application.getPublishedPages().forEach(page -> assertThat(page.getDefaultPageId()) + .isNotEqualTo(page.getId())); assertThat(pageList).isNotNull(); pageList.forEach(newPage -> { assertThat(newPage.getDefaultResources()).isNotNull(); assertThat(newPage.getDefaultResources().getPageId()).isNotEqualTo(newPage.getId()); - assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(parentApplication.getId()); - assertThat(newPage.getDefaultResources().getBranchName()).isEqualTo(createGitBranchDTO.getBranchName()); + assertThat(newPage.getDefaultResources().getApplicationId()) + .isEqualTo(parentApplication.getId()); + assertThat(newPage.getDefaultResources().getBranchName()) + .isEqualTo(createGitBranchDTO.getBranchName()); - newPage.getUnpublishedPage() - .getLayouts() - .stream() + newPage.getUnpublishedPage().getLayouts().stream() .filter(layout -> !CollectionUtils.isNullOrEmpty(layout.getLayoutOnLoadActions())) - .forEach(layout -> - layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { + .forEach(layout -> layout.getLayoutOnLoadActions() + .forEach(dslActionDTOS -> { dslActionDTOS.forEach(actionDTO -> { - Assertions.assertThat(actionDTO.getId()).isNotEqualTo(actionDTO.getDefaultActionId()); + Assertions.assertThat(actionDTO.getId()) + .isNotEqualTo(actionDTO.getDefaultActionId()); }); - }) - ); + })); }); assertThat(actionList).hasSize(2); actionList.forEach(newAction -> { assertThat(newAction.getDefaultResources()).isNotNull(); - assertThat(newAction.getDefaultResources().getActionId()).isNotEqualTo(newAction.getId()); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(parentApplication.getId()); - assertThat(newAction.getDefaultResources().getBranchName()).isEqualTo(createGitBranchDTO.getBranchName()); + assertThat(newAction.getDefaultResources().getActionId()) + .isNotEqualTo(newAction.getId()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(parentApplication.getId()); + assertThat(newAction.getDefaultResources().getBranchName()) + .isEqualTo(createGitBranchDTO.getBranchName()); ActionDTO action = newAction.getUnpublishedAction(); assertThat(action.getDefaultResources()).isNotNull(); - assertThat(action.getDefaultResources().getPageId()).isEqualTo(parentApplication.getPages().get(0).getId()); + assertThat(action.getDefaultResources().getPageId()) + .isEqualTo(parentApplication.getPages().get(0).getId()); if (!StringUtils.isEmpty(action.getDefaultResources().getCollectionId())) { - assertThat(action.getDefaultResources().getCollectionId()).isNotEqualTo(action.getCollectionId()); + assertThat(action.getDefaultResources().getCollectionId()) + .isNotEqualTo(action.getCollectionId()); } }); assertThat(actionCollectionList).hasSize(1); actionCollectionList.forEach(actionCollection -> { assertThat(actionCollection.getDefaultResources()).isNotNull(); - assertThat(actionCollection.getDefaultResources().getCollectionId()).isNotEqualTo(actionCollection.getId()); - assertThat(actionCollection.getDefaultResources().getApplicationId()).isEqualTo(parentApplication.getId()); - assertThat(actionCollection.getDefaultResources().getBranchName()).isEqualTo(createGitBranchDTO.getBranchName()); + assertThat(actionCollection.getDefaultResources().getCollectionId()) + .isNotEqualTo(actionCollection.getId()); + assertThat(actionCollection.getDefaultResources().getApplicationId()) + .isEqualTo(parentApplication.getId()); + assertThat(actionCollection.getDefaultResources().getBranchName()) + .isEqualTo(createGitBranchDTO.getBranchName()); ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); assertThat(unpublishedCollection.getDefaultToBranchedActionIdsMap()) .hasSize(1); - unpublishedCollection.getDefaultToBranchedActionIdsMap().forEach((key, value) -> assertThat(key).isNotEqualTo(value)); + unpublishedCollection.getDefaultToBranchedActionIdsMap().forEach((key, value) -> assertThat(key) + .isNotEqualTo(value)); assertThat(unpublishedCollection.getDefaultResources()).isNotNull(); assertThat(unpublishedCollection.getDefaultResources().getPageId()) @@ -2111,7 +2560,8 @@ public void createBranch_validCreateBranchRequest_newApplicationCreated() throws @Test @WithUserDetails(value = "api_user") - public void createBranch_SrcHasCustomTheme_newApplicationCreatedWithThemesCopied() throws GitAPIException, IOException { + public void createBranch_SrcHasCustomTheme_newApplicationCreatedWithThemesCopied() + throws GitAPIException, IOException { GitBranchDTO createGitBranchDTO = new GitBranchDTO(); createGitBranchDTO.setBranchName("valid_branch"); @@ -2119,24 +2569,45 @@ public void createBranch_SrcHasCustomTheme_newApplicationCreatedWithThemesCopied Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); - Mockito.when(gitExecutor.listBranches(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.listBranches( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(new ArrayList<>())); Mockito.when(gitExecutor.createAndCheckoutToBranch(Mockito.any(), Mockito.any())) .thenReturn(Mono.just(createGitBranchDTO.getBranchName())); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("System generated commit")); Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("pushed successfully")); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(DEFAULT_BRANCH)); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); @@ -2150,35 +2621,36 @@ public void createBranch_SrcHasCustomTheme_newApplicationCreatedWithThemesCopied testApplication.setName("Test App" + UUID.randomUUID()); testApplication.setWorkspaceId(workspaceId); - Mono<Tuple2<Application, Application>> createBranchMono = applicationPageService.createApplication(testApplication) - .flatMap(application -> - Mono.zip( - Mono.just(application), - pluginRepository.findByPackageName("installed-plugin"), - newPageService.findPageById(application.getPages().get(0).getId(), READ_PAGES, false)) - ) + Mono<Tuple2<Application, Application>> createBranchMono = applicationPageService + .createApplication(testApplication) + .flatMap(application -> Mono.zip( + Mono.just(application), + pluginRepository.findByPackageName("installed-plugin"), + newPageService.findPageById( + application.getPages().get(0).getId(), READ_PAGES, false))) .flatMap(tuple -> { Application application = tuple.getT1(); // customize the theme for this application - return themeService.getSystemTheme(Theme.DEFAULT_THEME_NAME).flatMap(theme -> { - theme.setId(null); - theme.setName("Custom theme"); - return themeService.updateTheme(application.getId(), null, theme); - }).then( - gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin") - ); + return themeService + .getSystemTheme(Theme.DEFAULT_THEME_NAME) + .flatMap(theme -> { + theme.setId(null); + theme.setName("Custom theme"); + return themeService.updateTheme(application.getId(), null, theme); + }) + .then(gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")); }) - .flatMap(application -> - gitService - .createBranch(application.getId(), createGitBranchDTO, application.getGitApplicationMetadata().getBranchName()) - .then(applicationService.findByBranchNameAndDefaultApplicationId(createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS)) - ) - .zipWhen(application -> - applicationService.findById(application.getGitApplicationMetadata().getDefaultApplicationId()) - ); - - StepVerifier - .create(createBranchMono) + .flatMap(application -> gitService + .createBranch( + application.getId(), + createGitBranchDTO, + application.getGitApplicationMetadata().getBranchName()) + .then(applicationService.findByBranchNameAndDefaultApplicationId( + createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS))) + .zipWhen(application -> applicationService.findById( + application.getGitApplicationMetadata().getDefaultApplicationId())); + + StepVerifier.create(createBranchMono) .assertNext(tuple -> { Application srcApp = tuple.getT1(); Application branchedApp = tuple.getT2(); @@ -2191,32 +2663,53 @@ public void createBranch_SrcHasCustomTheme_newApplicationCreatedWithThemesCopied private void mockitoSetUp(GitBranchDTO createGitBranchDTO) throws GitAPIException, IOException { Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); - Mockito.when(gitExecutor.listBranches(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.listBranches( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(new ArrayList<>())); Mockito.when(gitExecutor.createAndCheckoutToBranch(Mockito.any(), Mockito.any())) .thenReturn(Mono.just(createGitBranchDTO.getBranchName())); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("System generated commit")); Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("pushed successfully")); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(DEFAULT_BRANCH)); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); - } @Test @WithUserDetails(value = "api_user") - public void createBranch_BranchHasCustomNavigationSettings_SrcBranchRemainsUnchanged() throws GitAPIException, IOException { + public void createBranch_BranchHasCustomNavigationSettings_SrcBranchRemainsUnchanged() + throws GitAPIException, IOException { GitBranchDTO createGitBranchDTO = new GitBranchDTO(); createGitBranchDTO.setBranchName("valid_branch"); @@ -2233,42 +2726,40 @@ public void createBranch_BranchHasCustomNavigationSettings_SrcBranchRemainsUncha testApplication.setName("Test App" + UUID.randomUUID()); testApplication.setWorkspaceId(workspaceId); - Mono<Tuple2<Application, Application>> createBranchMono = applicationPageService.createApplication(testApplication) - .flatMap(application -> gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")) - .flatMap(application -> gitService.createBranch( - application.getId(), createGitBranchDTO, application.getGitApplicationMetadata().getBranchName()) - .then(applicationService.findByBranchNameAndDefaultApplicationId( - createGitBranchDTO.getBranchName(), + Mono<Tuple2<Application, Application>> createBranchMono = applicationPageService + .createApplication(testApplication) + .flatMap( + application -> gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")) + .flatMap(application -> gitService + .createBranch( application.getId(), - READ_APPLICATIONS - )) - - - ) + createGitBranchDTO, + application.getGitApplicationMetadata().getBranchName()) + .then(applicationService.findByBranchNameAndDefaultApplicationId( + createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS))) .flatMap(branchedApplication -> { - Application.NavigationSetting appNavigationSetting = new Application.NavigationSetting(); appNavigationSetting.setOrientation("top"); branchedApplication.setUnpublishedApplicationDetail(new ApplicationDetail()); branchedApplication.getUnpublishedApplicationDetail().setNavigationSetting(appNavigationSetting); return Mono.just(branchedApplication); }) - .flatMap(branchedApplication -> - applicationService.update( - branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(), - branchedApplication, branchedApplication.getGitApplicationMetadata().getBranchName() - ) - ) - .zipWhen(application -> - applicationService.findById(application.getGitApplicationMetadata().getDefaultApplicationId()) - ); - - StepVerifier - .create(createBranchMono) + .flatMap(branchedApplication -> applicationService.update( + branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(), + branchedApplication, + branchedApplication.getGitApplicationMetadata().getBranchName())) + .zipWhen(application -> applicationService.findById( + application.getGitApplicationMetadata().getDefaultApplicationId())); + + StepVerifier.create(createBranchMono) .assertNext(tuple -> { Application branchedApp = tuple.getT1(); Application srcApp = tuple.getT2(); - assertThat(branchedApp.getUnpublishedApplicationDetail().getNavigationSetting().getOrientation()).isEqualTo("top"); + assertThat(branchedApp + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getOrientation()) + .isEqualTo("top"); assertThat(srcApp.getUnpublishedApplicationDetail()).isNull(); }) .verifyComplete(); @@ -2276,8 +2767,11 @@ public void createBranch_BranchHasCustomNavigationSettings_SrcBranchRemainsUncha private FilePart createMockFilePart() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), new DefaultDataBufferFactory(), 4096).cache(); + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), + new DefaultDataBufferFactory(), + 4096) + .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); return filepart; @@ -2302,33 +2796,44 @@ public void createBranch_BranchUploadLogo_SrcBranchRemainsUnchanged() throws Git testApplication.setName("Test App" + UUID.randomUUID()); testApplication.setWorkspaceId(workspaceId); - Mono<Tuple2<Application, Application>> createBranchMono = applicationPageService.createApplication(testApplication) - .flatMap(application -> gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")) - .flatMap(application -> gitService.createBranch( - application.getId(), createGitBranchDTO, application.getGitApplicationMetadata().getBranchName()) - .then(applicationService.findByBranchNameAndDefaultApplicationId( - createGitBranchDTO.getBranchName(), + Mono<Tuple2<Application, Application>> createBranchMono = applicationPageService + .createApplication(testApplication) + .flatMap( + application -> gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")) + .flatMap(application -> gitService + .createBranch( application.getId(), - READ_APPLICATIONS - )) - ) + createGitBranchDTO, + application.getGitApplicationMetadata().getBranchName()) + .then(applicationService.findByBranchNameAndDefaultApplicationId( + createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS))) .flatMap(branchedApplication -> { - FilePart filepart = createMockFilePart(); - return applicationService.saveAppNavigationLogo(branchedApplication.getGitApplicationMetadata().getBranchName(), branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(), filepart).cache(); - + return applicationService + .saveAppNavigationLogo( + branchedApplication + .getGitApplicationMetadata() + .getBranchName(), + branchedApplication + .getGitApplicationMetadata() + .getDefaultApplicationId(), + filepart) + .cache(); }) - .zipWhen(application -> - applicationService.findById(application.getGitApplicationMetadata().getDefaultApplicationId()) - ); + .zipWhen(application -> applicationService.findById( + application.getGitApplicationMetadata().getDefaultApplicationId())); - StepVerifier - .create(createBranchMono) + StepVerifier.create(createBranchMono) .assertNext(tuple -> { Application branchedApp = tuple.getT1(); Application srcApp = tuple.getT2(); - assertThat(branchedApp.getUnpublishedApplicationDetail().getNavigationSetting()).isNotNull(); - assertThat(branchedApp.getUnpublishedApplicationDetail().getNavigationSetting().getLogoAssetId()).isNotNull(); + assertThat(branchedApp.getUnpublishedApplicationDetail().getNavigationSetting()) + .isNotNull(); + assertThat(branchedApp + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getLogoAssetId()) + .isNotNull(); assertThat(srcApp.getUnpublishedApplicationDetail()).isNull(); }) .verifyComplete(); @@ -2353,48 +2858,78 @@ public void createBranch_BranchDeleteLogo_SrcLogoRemainsUnchanged() throws GitAP testApplication.setName("Test App" + UUID.randomUUID()); testApplication.setWorkspaceId(workspaceId); - Mono<Tuple2<Application, Application>> createBranchMono = applicationPageService.createApplication(testApplication) - .flatMap(application -> gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")) - .flatMap(application -> - Mono.zip(gitService - .createBranch(application.getId(), createGitBranchDTO, application.getGitApplicationMetadata().getBranchName()) - .then(applicationService.findByBranchNameAndDefaultApplicationId(createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS)), - Mono.just(application)) - - ) + Mono<Tuple2<Application, Application>> createBranchMono = applicationPageService + .createApplication(testApplication) + .flatMap( + application -> gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")) + .flatMap(application -> Mono.zip( + gitService + .createBranch( + application.getId(), + createGitBranchDTO, + application.getGitApplicationMetadata().getBranchName()) + .then(applicationService.findByBranchNameAndDefaultApplicationId( + createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS)), + Mono.just(application))) .flatMap(applicationTuple -> { Application branchedApplication = applicationTuple.getT1(); Application application = applicationTuple.getT2(); - String srcBranchName = application.getGitApplicationMetadata().getBranchName(); - String otherBranchName = branchedApplication.getGitApplicationMetadata().getBranchName(); - String defaultApplicationId = branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(); + String srcBranchName = + application.getGitApplicationMetadata().getBranchName(); + String otherBranchName = + branchedApplication.getGitApplicationMetadata().getBranchName(); + String defaultApplicationId = + branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(); FilePart filepart = createMockFilePart(); return Mono.zip( - applicationService.saveAppNavigationLogo(otherBranchName, defaultApplicationId, filepart).cache(), - applicationService.saveAppNavigationLogo(srcBranchName, defaultApplicationId, filepart).cache() - ); + applicationService + .saveAppNavigationLogo(otherBranchName, defaultApplicationId, filepart) + .cache(), + applicationService + .saveAppNavigationLogo(srcBranchName, defaultApplicationId, filepart) + .cache()); }) .flatMap(appTuple -> { Application branchedApplication = appTuple.getT1(); Application application = appTuple.getT2(); - return applicationService.deleteAppNavigationLogo(branchedApplication.getGitApplicationMetadata().getBranchName(), branchedApplication.getGitApplicationMetadata().getDefaultApplicationId()) - .then(applicationService.findByIdAndBranchName(branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(), branchedApplication.getGitApplicationMetadata().getBranchName())); + return applicationService + .deleteAppNavigationLogo( + branchedApplication + .getGitApplicationMetadata() + .getBranchName(), + branchedApplication + .getGitApplicationMetadata() + .getDefaultApplicationId()) + .then(applicationService.findByIdAndBranchName( + branchedApplication + .getGitApplicationMetadata() + .getDefaultApplicationId(), + branchedApplication + .getGitApplicationMetadata() + .getBranchName())); }) - .zipWhen(application -> - applicationService.findById(application.getGitApplicationMetadata().getDefaultApplicationId()) - ); + .zipWhen(application -> applicationService.findById( + application.getGitApplicationMetadata().getDefaultApplicationId())); - StepVerifier - .create(createBranchMono) + StepVerifier.create(createBranchMono) .assertNext(tuple -> { Application branchedApp = tuple.getT1(); Application srcApp = tuple.getT2(); - assertThat(branchedApp.getUnpublishedApplicationDetail().getNavigationSetting()).isNotNull(); - assertThat(branchedApp.getUnpublishedApplicationDetail().getNavigationSetting().getLogoAssetId()).isNull(); - assertThat(srcApp.getUnpublishedApplicationDetail().getNavigationSetting()).isNotNull(); - assertThat(srcApp.getUnpublishedApplicationDetail().getNavigationSetting().getLogoAssetId()).isNotNull(); + assertThat(branchedApp.getUnpublishedApplicationDetail().getNavigationSetting()) + .isNotNull(); + assertThat(branchedApp + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getLogoAssetId()) + .isNull(); + assertThat(srcApp.getUnpublishedApplicationDetail().getNavigationSetting()) + .isNotNull(); + assertThat(srcApp.getUnpublishedApplicationDetail() + .getNavigationSetting() + .getLogoAssetId()) + .isNotNull(); }) .verifyComplete(); } @@ -2418,21 +2953,28 @@ public void createBranch_BranchSetPageIcon_SrcBranchPageIconRemainsNull() throws testApplication.setName("Test App" + UUID.randomUUID()); testApplication.setWorkspaceId(workspaceId); - Mono<Tuple2<PageDTO, PageDTO>> createBranchMono = applicationPageService.createApplication(testApplication) - .flatMap(application -> gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")) - .flatMap(application -> - Mono.zip(gitService - .createBranch(application.getId(), createGitBranchDTO, application.getGitApplicationMetadata().getBranchName()) - .then(applicationService.findByBranchNameAndDefaultApplicationId(createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS)), - Mono.just(application)) - - ) + Mono<Tuple2<PageDTO, PageDTO>> createBranchMono = applicationPageService + .createApplication(testApplication) + .flatMap( + application -> gitService.connectApplicationToGit(application.getId(), gitConnectDTO, "origin")) + .flatMap(application -> Mono.zip( + gitService + .createBranch( + application.getId(), + createGitBranchDTO, + application.getGitApplicationMetadata().getBranchName()) + .then(applicationService.findByBranchNameAndDefaultApplicationId( + createGitBranchDTO.getBranchName(), application.getId(), READ_APPLICATIONS)), + Mono.just(application))) .flatMap(applicationTuple -> { Application branchedApplication = applicationTuple.getT1(); Application application = applicationTuple.getT2(); - String srcBranchName = application.getGitApplicationMetadata().getBranchName(); - String otherBranchName = branchedApplication.getGitApplicationMetadata().getBranchName(); - String defaultApplicationId = branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(); + String srcBranchName = + application.getGitApplicationMetadata().getBranchName(); + String otherBranchName = + branchedApplication.getGitApplicationMetadata().getBranchName(); + String defaultApplicationId = + branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(); PageDTO newSrcPage = new PageDTO(); newSrcPage.setName("newSrcPage"); @@ -2445,12 +2987,10 @@ public void createBranch_BranchSetPageIcon_SrcBranchPageIconRemainsNull() throws return Mono.zip( applicationPageService.createPageWithBranchName(newBranchPage, otherBranchName), - applicationPageService.createPageWithBranchName(newSrcPage, srcBranchName) - ); + applicationPageService.createPageWithBranchName(newSrcPage, srcBranchName)); }); - StepVerifier - .create(createBranchMono) + StepVerifier.create(createBranchMono) .assertNext(tuple -> { PageDTO branchedPage = tuple.getT1(); PageDTO srcPage = tuple.getT2(); @@ -2458,7 +2998,6 @@ public void createBranch_BranchSetPageIcon_SrcBranchPageIconRemainsNull() throws assertThat(srcPage.getIcon()).isNull(); assertThat(branchedPage.getName()).isEqualTo("newBranchPage"); assertThat(branchedPage.getIcon()).isEqualTo("flight"); - }) .verifyComplete(); } @@ -2467,15 +3006,28 @@ public void createBranch_BranchSetPageIcon_SrcBranchPageIconRemainsNull() throws @WithUserDetails(value = "api_user") public void connectApplicationToGit_cancelledMidway_cloneSuccess() throws IOException { - Mockito.when(gitExecutor.cloneApplication(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranchName")); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("commit")); - Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())).thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), - Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("success")); - Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))).thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(Mockito.any(Path.class))) + .thenReturn(Mono.just(true)); Mockito.when(gitFileUtils.initializeReadme(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("textPath"))); @@ -2490,7 +3042,8 @@ public void connectApplicationToGit_cancelledMidway_cloneSuccess() throws IOExce testApplication.setGitApplicationMetadata(gitApplicationMetadata); testApplication.setName("validData"); testApplication.setWorkspaceId(workspaceId); - Application application1 = applicationPageService.createApplication(testApplication).block(); + Application application1 = + applicationPageService.createApplication(testApplication).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); @@ -2500,22 +3053,21 @@ public void connectApplicationToGit_cancelledMidway_cloneSuccess() throws IOExce .subscribe(); // Wait for git clone to complete - Mono<Application> gitConnectedAppFromDbMono = Mono.just(application1) - .flatMap(application -> { - try { - // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone - // completes - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return applicationService.getById(application.getId()); - }); + Mono<Application> gitConnectedAppFromDbMono = Mono.just(application1).flatMap(application -> { + try { + // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone + // completes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationService.getById(application.getId()); + }); - StepVerifier - .create(gitConnectedAppFromDbMono) + StepVerifier.create(gitConnectedAppFromDbMono) .assertNext(application -> { - assertThat(application.getGitApplicationMetadata().getDefaultApplicationId()).isEqualTo(application.getId()); + assertThat(application.getGitApplicationMetadata().getDefaultApplicationId()) + .isEqualTo(application.getId()); }) .verifyComplete(); } @@ -2533,13 +3085,25 @@ public void commitAndPushApplication_cancelledMidway_pushSuccess() throws GitAPI page.setName("commit_sink_page"); applicationPageService.createPage(page).block(); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("committed successfully")); Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("pushed successfully")); gitService @@ -2548,20 +3112,18 @@ public void commitAndPushApplication_cancelledMidway_pushSuccess() throws GitAPI .subscribe(); // Wait for git commit to complete - Mono<Application> appFromDbMono = Mono.just(gitConnectedApplication) - .flatMap(application -> { - try { - // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone - // completes - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return applicationService.getById(application.getId()); - }); + Mono<Application> appFromDbMono = Mono.just(gitConnectedApplication).flatMap(application -> { + try { + // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone + // completes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationService.getById(application.getId()); + }); - StepVerifier - .create(appFromDbMono) + StepVerifier.create(appFromDbMono) .assertNext(application -> { assertThat(application.getPages()).isEqualTo(application.getPublishedPages()); }) @@ -2577,44 +3139,64 @@ public void createBranch_cancelledMidway_newApplicationCreated() throws GitAPIEx Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetchResult")); - Mockito.when(gitExecutor.listBranches(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(gitExecutor.listBranches( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(new ArrayList<>())); Mockito.when(gitExecutor.createAndCheckoutToBranch(Mockito.any(), Mockito.any())) .thenReturn(Mono.just(createGitBranchDTO.getBranchName())); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("System generated commit")); Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("pushed successfully")); - Application application1 = createApplicationConnectedToGit("createBranch_cancelledMidway_newApplicationCreated", "master"); + Application application1 = + createApplicationConnectedToGit("createBranch_cancelledMidway_newApplicationCreated", "master"); gitService - .createBranch(application1.getId(), createGitBranchDTO, application1.getGitApplicationMetadata().getBranchName()) + .createBranch( + application1.getId(), + createGitBranchDTO, + application1.getGitApplicationMetadata().getBranchName()) .timeout(Duration.ofMillis(10)) .subscribe(); - Mono<Application> branchedAppMono = Mono.just(application1) - .flatMap(application -> { - try { - // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone - // completes - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return applicationService - .findByBranchNameAndDefaultApplicationId(createGitBranchDTO.getBranchName(), application.getId(), MANAGE_APPLICATIONS); - }); + Mono<Application> branchedAppMono = Mono.just(application1).flatMap(application -> { + try { + // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone + // completes + Thread.sleep(10000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationService.findByBranchNameAndDefaultApplicationId( + createGitBranchDTO.getBranchName(), application.getId(), MANAGE_APPLICATIONS); + }); - StepVerifier - .create(branchedAppMono) + StepVerifier.create(branchedAppMono) .assertNext(application -> { - GitApplicationMetadata gitData = application.getGitApplicationMetadata(); assertThat(application).isNotNull(); assertThat(application.getId()).isNotEqualTo(gitData.getDefaultApplicationId()); @@ -2627,8 +3209,10 @@ public void createBranch_cancelledMidway_newApplicationCreated() throws GitAPIEx assertThat(gitData.getGitAuth()).isNull(); assertThat(gitData.getIsRepoPrivate()).isNull(); - application.getPages().forEach(page -> assertThat(page.getDefaultPageId()).isNotEqualTo(page.getId())); - application.getPublishedPages().forEach(page -> assertThat(page.getDefaultPageId()).isNotEqualTo(page.getId())); + application.getPages().forEach(page -> assertThat(page.getDefaultPageId()) + .isNotEqualTo(page.getId())); + application.getPublishedPages().forEach(page -> assertThat(page.getDefaultPageId()) + .isNotEqualTo(page.getId())); }) .verifyComplete(); } @@ -2638,8 +3222,7 @@ public void createBranch_cancelledMidway_newApplicationCreated() throws GitAPIEx public void generateSSHKeyDefaultType_DataNotExistsInCollection_Success() { Mono<GitAuth> publicKey = gitService.generateSSHKey(null); - StepVerifier - .create(publicKey) + StepVerifier.create(publicKey) .assertNext(s -> { assertThat(s).isNotNull(); assertThat(s.getPublicKey()).contains("appsmith"); @@ -2653,8 +3236,7 @@ public void generateSSHKeyDefaultType_DataNotExistsInCollection_Success() { public void generateSSHKeyRSAType_DataNotExistsInCollection_Success() { Mono<GitAuth> publicKey = gitService.generateSSHKey("RSA"); - StepVerifier - .create(publicKey) + StepVerifier.create(publicKey) .assertNext(s -> { assertThat(s).isNotNull(); assertThat(s.getPublicKey()).contains("appsmith"); @@ -2670,8 +3252,7 @@ public void generateSSHKeyDefaultType_KeyExistsInCollection_Success() { Mono<GitAuth> newKey = gitService.generateSSHKey(null); - StepVerifier - .create(newKey) + StepVerifier.create(newKey) .assertNext(s -> { assertThat(s).isNotNull(); assertThat(s.getPublicKey()).contains("appsmith"); @@ -2689,8 +3270,7 @@ public void generateSSHKeyRSA_KeyExistsInCollection_Success() { Mono<GitAuth> newKey = gitService.generateSSHKey("RSA"); - StepVerifier - .create(newKey) + StepVerifier.create(newKey) .assertNext(s -> { assertThat(s).isNotNull(); assertThat(s.getPublicKey()).contains("appsmith"); @@ -2707,8 +3287,7 @@ public void importApplicationFromGit_InvalidRemoteUrl_ThrowError() { GitConnectDTO gitConnectDTO = getConnectRequest(null, testUserProfile); Mono<ApplicationImportDTO> applicationMono = gitService.importApplicationFromGit("testID", gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage("Remote Url"))) .verify(); @@ -2720,10 +3299,11 @@ public void importApplicationFromGit_emptyWorkspaceId_ThrowError() { GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); Mono<ApplicationImportDTO> applicationMono = gitService.importApplicationFromGit(null, gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage("Invalid workspace id"))) + && throwable + .getMessage() + .contains(AppsmithError.INVALID_PARAMETER.getMessage("Invalid workspace id"))) .verify(); } @@ -2733,14 +3313,18 @@ public void importApplicationFromGit_privateRepoLimitReached_ThrowApplicationLim GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testRepo.git", testUserProfile); gitService.generateSSHKey(null).block(); GitService gitService1 = Mockito.spy(gitService); - Mockito.doReturn(Mono.just(Boolean.TRUE)).when(gitService1).isRepoLimitReached(Mockito.anyString(), Mockito.anyBoolean()); + Mockito.doReturn(Mono.just(Boolean.TRUE)) + .when(gitService1) + .isRepoLimitReached(Mockito.anyString(), Mockito.anyBoolean()); Mono<ApplicationImportDTO> applicationMono = gitService1.importApplicationFromGit(workspaceId, gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().contains(AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getMessage(AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getMessage()))) + && throwable + .getMessage() + .contains(AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getMessage( + AppsmithError.GIT_APPLICATION_LIMIT_ERROR.getMessage()))) .verify(); } @@ -2754,17 +3338,17 @@ public void importApplicationFromGit_emptyRepo_ThrowError() { applicationJson.setExportedApplication(null); applicationJson.setDatasourceList(new ArrayList<>()); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); - Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))) - .thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); Mono<ApplicationImportDTO> applicationMono = gitService.importApplicationFromGit(workspaceId, gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains("Cannot import app from an empty repo")) .verify(); @@ -2780,25 +3364,33 @@ public void importApplicationFromGit_validRequest_Success() { applicationJson.getExportedApplication().setName("testRepo"); applicationJson.setDatasourceList(new ArrayList<>()); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); Mono<ApplicationImportDTO> applicationMono = gitService.importApplicationFromGit(workspaceId, gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(applicationImportDTO -> { Application application = applicationImportDTO.getApplication(); assertThat(application.getName()).isEqualTo("testRepo"); assertThat(application.getGitApplicationMetadata()).isNotNull(); - assertThat(application.getGitApplicationMetadata().getBranchName()).isEqualTo("defaultBranch"); - assertThat(application.getGitApplicationMetadata().getDefaultBranchName()).isEqualTo("defaultBranch"); - assertThat(application.getGitApplicationMetadata().getRemoteUrl()).isEqualTo("[email protected]:test/testRepo.git"); - assertThat(application.getGitApplicationMetadata().getIsRepoPrivate()).isEqualTo(true); - assertThat(application.getGitApplicationMetadata().getGitAuth().getPublicKey()).isEqualTo(gitAuth.getPublicKey()); - + assertThat(application.getGitApplicationMetadata().getBranchName()) + .isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getDefaultBranchName()) + .isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getRemoteUrl()) + .isEqualTo("[email protected]:test/testRepo.git"); + assertThat(application.getGitApplicationMetadata().getIsRepoPrivate()) + .isEqualTo(true); + assertThat(application + .getGitApplicationMetadata() + .getGitAuth() + .getPublicKey()) + .isEqualTo(gitAuth.getPublicKey()); }) .verifyComplete(); } @@ -2818,25 +3410,33 @@ public void importApplicationFromGit_validRequestWithDuplicateApplicationName_Su testApplication.setWorkspaceId(workspaceId); applicationPageService.createApplication(testApplication).block(); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); Mono<ApplicationImportDTO> applicationMono = gitService.importApplicationFromGit(workspaceId, gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(applicationImportDTO -> { Application application = applicationImportDTO.getApplication(); assertThat(application.getName()).isEqualTo("testGitRepo (1)"); assertThat(application.getGitApplicationMetadata()).isNotNull(); - assertThat(application.getGitApplicationMetadata().getBranchName()).isEqualTo("defaultBranch"); - assertThat(application.getGitApplicationMetadata().getDefaultBranchName()).isEqualTo("defaultBranch"); - assertThat(application.getGitApplicationMetadata().getRemoteUrl()).isEqualTo("[email protected]:test/testGitRepo.git"); - assertThat(application.getGitApplicationMetadata().getIsRepoPrivate()).isEqualTo(true); - assertThat(application.getGitApplicationMetadata().getGitAuth().getPublicKey()).isEqualTo(gitAuth.getPublicKey()); - + assertThat(application.getGitApplicationMetadata().getBranchName()) + .isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getDefaultBranchName()) + .isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getRemoteUrl()) + .isEqualTo("[email protected]:test/testGitRepo.git"); + assertThat(application.getGitApplicationMetadata().getIsRepoPrivate()) + .isEqualTo(true); + assertThat(application + .getGitApplicationMetadata() + .getGitAuth() + .getPublicKey()) + .isEqualTo(gitAuth.getPublicKey()); }) .verifyComplete(); } @@ -2846,10 +3446,10 @@ public void importApplicationFromGit_validRequestWithDuplicateApplicationName_Su public void importApplicationFromGit_validRequestWithDuplicateDatasourceOfSameType_Success() { Workspace workspace = new Workspace(); workspace.setName("gitImportOrg"); - final String testWorkspaceId = workspaceService.create(workspace) - .map(Workspace::getId) - .block(); - String environmentId = workspaceService.getDefaultEnvironmentId(testWorkspaceId).block(); + final String testWorkspaceId = + workspaceService.create(workspace).map(Workspace::getId).block(); + String environmentId = + workspaceService.getDefaultEnvironmentId(testWorkspaceId).block(); GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testGitImportRepo.git", testUserProfile); GitAuth gitAuth = gitService.generateSSHKey(null).block(); @@ -2858,7 +3458,8 @@ public void importApplicationFromGit_validRequestWithDuplicateDatasourceOfSameTy applicationJson.getExportedApplication().setName("testGitImportRepo"); applicationJson.getDatasourceList().get(0).setName("db-auth-testGitImportRepo"); - String pluginId = pluginRepository.findByPackageName("mongo-plugin").block().getId(); + String pluginId = + pluginRepository.findByPackageName("mongo-plugin").block().getId(); Datasource datasource = new Datasource(); datasource.setName("db-auth-testGitImportRepo"); datasource.setPluginId(pluginId); @@ -2870,26 +3471,34 @@ public void importApplicationFromGit_validRequestWithDuplicateDatasourceOfSameTy datasourceService.create(datasource).block(); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); Mono<ApplicationImportDTO> applicationMono = gitService.importApplicationFromGit(workspaceId, gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(applicationImportDTO -> { Application application = applicationImportDTO.getApplication(); assertThat(application.getName()).isEqualTo("testGitImportRepo"); assertThat(application.getGitApplicationMetadata()).isNotNull(); - assertThat(application.getGitApplicationMetadata().getBranchName()).isEqualTo("defaultBranch"); - assertThat(application.getGitApplicationMetadata().getDefaultBranchName()).isEqualTo("defaultBranch"); - assertThat(application.getGitApplicationMetadata().getRemoteUrl()).isEqualTo("[email protected]:test/testGitImportRepo.git"); - assertThat(application.getGitApplicationMetadata().getIsRepoPrivate()).isEqualTo(true); - assertThat(application.getGitApplicationMetadata().getGitAuth().getPublicKey()).isEqualTo(gitAuth.getPublicKey()); - + assertThat(application.getGitApplicationMetadata().getBranchName()) + .isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getDefaultBranchName()) + .isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getRemoteUrl()) + .isEqualTo("[email protected]:test/testGitImportRepo.git"); + assertThat(application.getGitApplicationMetadata().getIsRepoPrivate()) + .isEqualTo(true); + assertThat(application + .getGitApplicationMetadata() + .getGitAuth() + .getPublicKey()) + .isEqualTo(gitAuth.getPublicKey()); }) .verifyComplete(); } @@ -2899,19 +3508,21 @@ public void importApplicationFromGit_validRequestWithDuplicateDatasourceOfSameTy public void importApplicationFromGit_validRequestWithDuplicateDatasourceOfSameTypeCancelledMidway_Success() { Workspace workspace = new Workspace(); workspace.setName("gitImportOrgCancelledMidway"); - final String testWorkspaceId = workspaceService.create(workspace) - .map(Workspace::getId) - .block(); - String environmentId = workspaceService.getDefaultEnvironmentId(testWorkspaceId).block(); + final String testWorkspaceId = + workspaceService.create(workspace).map(Workspace::getId).block(); + String environmentId = + workspaceService.getDefaultEnvironmentId(testWorkspaceId).block(); - GitConnectDTO gitConnectDTO = getConnectRequest("[email protected]:test/testGitImportRepoCancelledMidway.git", testUserProfile); + GitConnectDTO gitConnectDTO = + getConnectRequest("[email protected]:test/testGitImportRepoCancelledMidway.git", testUserProfile); GitAuth gitAuth = gitService.generateSSHKey(null).block(); ApplicationJson applicationJson = createAppJson(filePath).block(); applicationJson.getExportedApplication().setName(null); applicationJson.getDatasourceList().get(0).setName("db-auth-testGitImportRepo"); - String pluginId = pluginRepository.findByPackageName("mongo-plugin").block().getId(); + String pluginId = + pluginRepository.findByPackageName("mongo-plugin").block().getId(); Datasource datasource = new Datasource(); datasource.setName("db-auth-testGitImportRepo"); datasource.setPluginId(pluginId); @@ -2920,48 +3531,56 @@ public void importApplicationFromGit_validRequestWithDuplicateDatasourceOfSameTy HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); storages.put(environmentId, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); - + datasourceService.create(datasource).block(); - Mockito - .when(gitCloudServicesUtils.getPrivateRepoLimitForOrg(eq(testWorkspaceId), Mockito.anyBoolean())) + Mockito.when(gitCloudServicesUtils.getPrivateRepoLimitForOrg(eq(testWorkspaceId), Mockito.anyBoolean())) .thenReturn(Mono.just(3)); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); - gitService.importApplicationFromGit(testWorkspaceId, gitConnectDTO) + gitService + .importApplicationFromGit(testWorkspaceId, gitConnectDTO) .timeout(Duration.ofMillis(10)) .subscribe(); // Wait for git clone to complete - Mono<Application> gitConnectedAppFromDbMono = Mono.just(testWorkspaceId) - .flatMap(ignore -> { - try { - // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone - // completes - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return applicationService.findByWorkspaceId(testWorkspaceId, READ_APPLICATIONS) - .filter(application1 -> "testGitImportRepoCancelledMidway".equals(application1.getName())) - .next(); - }); + Mono<Application> gitConnectedAppFromDbMono = Mono.just(testWorkspaceId).flatMap(ignore -> { + try { + // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone + // completes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationService + .findByWorkspaceId(testWorkspaceId, READ_APPLICATIONS) + .filter(application1 -> "testGitImportRepoCancelledMidway".equals(application1.getName())) + .next(); + }); - StepVerifier - .create(gitConnectedAppFromDbMono) + StepVerifier.create(gitConnectedAppFromDbMono) .assertNext(application -> { assertThat(application.getName()).isEqualTo("testGitImportRepoCancelledMidway"); assertThat(application.getGitApplicationMetadata()).isNotNull(); - assertThat(application.getGitApplicationMetadata().getBranchName()).isEqualTo("defaultBranch"); - assertThat(application.getGitApplicationMetadata().getDefaultBranchName()).isEqualTo("defaultBranch"); - assertThat(application.getGitApplicationMetadata().getRemoteUrl()).isEqualTo("[email protected]:test/testGitImportRepoCancelledMidway.git"); - assertThat(application.getGitApplicationMetadata().getIsRepoPrivate()).isEqualTo(true); - assertThat(application.getGitApplicationMetadata().getGitAuth().getPublicKey()).isEqualTo(gitAuth.getPublicKey()); - + assertThat(application.getGitApplicationMetadata().getBranchName()) + .isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getDefaultBranchName()) + .isEqualTo("defaultBranch"); + assertThat(application.getGitApplicationMetadata().getRemoteUrl()) + .isEqualTo("[email protected]:test/testGitImportRepoCancelledMidway.git"); + assertThat(application.getGitApplicationMetadata().getIsRepoPrivate()) + .isEqualTo(true); + assertThat(application + .getGitApplicationMetadata() + .getGitAuth() + .getPublicKey()) + .isEqualTo(gitAuth.getPublicKey()); }) .verifyComplete(); } @@ -2975,7 +3594,8 @@ public void importApplicationFromGit_validRequestWithDuplicateDatasourceOfDiffer applicationJson.getExportedApplication().setName("testGitImportRepo1"); applicationJson.getDatasourceList().get(0).setName("db-auth-1"); - String pluginId = pluginRepository.findByPackageName("postgres-plugin").block().getId(); + String pluginId = + pluginRepository.findByPackageName("postgres-plugin").block().getId(); Datasource datasource = new Datasource(); datasource.setName("db-auth-1"); datasource.setPluginId(pluginId); @@ -2987,17 +3607,17 @@ public void importApplicationFromGit_validRequestWithDuplicateDatasourceOfDiffer datasourceService.create(datasource).block(); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); - Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))) - .thenReturn(Mono.just(true)); + Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); Mono<ApplicationImportDTO> applicationMono = gitService.importApplicationFromGit(workspaceId, gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains("Datasource already exists with the same name")) .verify(); @@ -3011,16 +3631,17 @@ public void importApplicationFromGit_validRequestWithEmptyRepo_ThrowError() { ApplicationJson applicationJson = new ApplicationJson(); - Mockito.when(gitExecutor.cloneApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.cloneApplication( + Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just("defaultBranch")); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); Mockito.when(gitFileUtils.deleteLocalRepo(Mockito.any(Path.class))).thenReturn(Mono.just(true)); Mono<ApplicationImportDTO> applicationMono = gitService.importApplicationFromGit(workspaceId, gitConnectDTO); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains("Cannot import app from an empty repo")) .verify(); @@ -3039,13 +3660,11 @@ public void deleteBranch_staleBranchNotInDB_Success() throws IOException, GitAPI Mono<Application> applicationMono = gitService.deleteBranch(application.getId(), "test"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application1 -> { assertThat(application1.getId()).isEqualTo(application.getId()); }) .verifyComplete(); - } @Test @@ -3059,8 +3678,7 @@ public void deleteBranch_existsInDB_Success() throws IOException, GitAPIExceptio Mono<Application> applicationMono = gitService.deleteBranch(application.getId(), "master"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application1 -> { assertThat(application1.getId()).isEqualTo(application.getId()); assertThat(application1.getDeleted()).isFalse(); @@ -3071,7 +3689,8 @@ public void deleteBranch_existsInDB_Success() throws IOException, GitAPIExceptio @Test @WithUserDetails(value = "api_user") public void deleteBranch_branchDoesNotExist_ThrowError() throws IOException, GitAPIException { - Application application = createApplicationConnectedToGit("deleteBranch_branchDoesNotExist_ThrowError", "master"); + Application application = + createApplicationConnectedToGit("deleteBranch_branchDoesNotExist_ThrowError", "master"); application.getGitApplicationMetadata().setDefaultBranchName("test"); applicationService.save(application).block(); Mockito.when(gitExecutor.deleteBranch(Mockito.any(Path.class), Mockito.anyString())) @@ -3079,10 +3698,9 @@ public void deleteBranch_branchDoesNotExist_ThrowError() throws IOException, Git Mono<Application> applicationMono = gitService.deleteBranch(application.getId(), "master"); - StepVerifier - .create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().contains("delete branch. Branch does not exists in the repo")) + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().contains("delete branch. Branch does not exists in the repo")) .verify(); } @@ -3097,17 +3715,17 @@ public void deleteBranch_defaultBranch_ThrowError() throws IOException, GitAPIEx Mono<Application> applicationMono = gitService.deleteBranch(application.getId(), "master"); - StepVerifier - .create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().contains("Cannot delete default branch")) + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().contains("Cannot delete default branch")) .verify(); } @Test @WithUserDetails(value = "api_user") public void deleteBranch_defaultBranchUpdated_Success() throws IOException, GitAPIException { - Application application = createApplicationConnectedToGit("deleteBranch_defaultBranchUpdated_Success1", "master"); + Application application = + createApplicationConnectedToGit("deleteBranch_defaultBranchUpdated_Success1", "master"); application.getGitApplicationMetadata().setDefaultBranchName("f1"); applicationService.save(application).block(); @@ -3121,8 +3739,7 @@ public void deleteBranch_defaultBranchUpdated_Success() throws IOException, GitA Mono<Application> applicationMono = gitService.deleteBranch(application.getId(), "master"); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application1 -> { assertThat(application1.getDeleted()).isEqualTo(Boolean.FALSE); assertThat(application1.getName()).isEqualTo("deleteBranch_defaultBranchUpdated_Success1"); @@ -3145,23 +3762,24 @@ public void discardChanges_upstreamChangesAvailable_discardSuccess() throws IOEx ApplicationJson applicationJson = createAppJson(filePath).block(); applicationJson.getExportedApplication().setName("discardChangesAvailable"); - GitStatusDTO gitStatusDTO = new GitStatusDTO(); gitStatusDTO.setAheadCount(2); gitStatusDTO.setBehindCount(0); gitStatusDTO.setIsClean(true); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("path"))); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); Mockito.when(gitExecutor.rebaseBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mono<Application> applicationMono = gitService.discardChanges(application.getId(), application.getGitApplicationMetadata().getBranchName()); + Mono<Application> applicationMono = gitService.discardChanges( + application.getId(), application.getGitApplicationMetadata().getBranchName()); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application1 -> { assertThat(application1.getPages()).isNotEqualTo(application.getPages()); }) @@ -3171,7 +3789,8 @@ public void discardChanges_upstreamChangesAvailable_discardSuccess() throws IOEx @Test @WithUserDetails(value = "api_user") public void discardChanges_cancelledMidway_discardSuccess() throws IOException, GitAPIException { - Application application = createApplicationConnectedToGit("discard-changes-midway", "discard-change-midway-branch"); + Application application = + createApplicationConnectedToGit("discard-changes-midway", "discard-change-midway-branch"); MergeStatusDTO mergeStatusDTO = new MergeStatusDTO(); mergeStatusDTO.setStatus("Nothing to fetch from remote. All changes are upto date."); mergeStatusDTO.setMergeAble(true); @@ -3179,44 +3798,55 @@ public void discardChanges_cancelledMidway_discardSuccess() throws IOException, ApplicationJson applicationJson = createAppJson(filePath).block(); applicationJson.getExportedApplication().setName("discard-changes-midway"); - GitStatusDTO gitStatusDTO = new GitStatusDTO(); gitStatusDTO.setAheadCount(0); gitStatusDTO.setBehindCount(0); gitStatusDTO.setIsClean(true); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get("path"))); - Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitFileUtils.reconstructApplicationJsonFromGitRepo( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Mono.just(applicationJson)); Mockito.when(gitExecutor.pullApplication( - Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just(mergeStatusDTO)); Mockito.when(gitExecutor.getStatus(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(gitStatusDTO)); - Mockito.when(gitExecutor.fetchRemote(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), eq(true), Mockito.anyString(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.fetchRemote( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + eq(true), + Mockito.anyString(), + Mockito.anyBoolean())) .thenReturn(Mono.just("fetched")); gitService - .discardChanges(application.getId(), application.getGitApplicationMetadata().getBranchName()) + .discardChanges( + application.getId(), + application.getGitApplicationMetadata().getBranchName()) .timeout(Duration.ofNanos(100)) .subscribe(); // Wait for git clone to complete - Mono<Application> applicationFromDbMono = Mono.just(application) - .flatMap(application1 -> { - try { - // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone - // completes - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return applicationService.getById(application1.getId()); - }); + Mono<Application> applicationFromDbMono = Mono.just(application).flatMap(application1 -> { + try { + // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone + // completes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationService.getById(application1.getId()); + }); - StepVerifier - .create(applicationFromDbMono) + StepVerifier.create(applicationFromDbMono) .assertNext(application1 -> { assertThat(application1).isNotEqualTo(application); }) @@ -3228,11 +3858,13 @@ public void discardChanges_cancelledMidway_discardSuccess() throws IOException, public void deleteBranch_cancelledMidway_success() throws GitAPIException, IOException { final String DEFAULT_BRANCH = "master", TO_BE_DELETED_BRANCH = "deleteBranch"; - Application application = createApplicationConnectedToGit("deleteBranch_defaultBranchUpdated_Success", DEFAULT_BRANCH); + Application application = + createApplicationConnectedToGit("deleteBranch_defaultBranchUpdated_Success", DEFAULT_BRANCH); application.getGitApplicationMetadata().setDefaultBranchName(DEFAULT_BRANCH); applicationService.save(application).block(); - Application branchApp = createApplicationConnectedToGit("deleteBranch_defaultBranchUpdated_Success2", TO_BE_DELETED_BRANCH); + Application branchApp = + createApplicationConnectedToGit("deleteBranch_defaultBranchUpdated_Success2", TO_BE_DELETED_BRANCH); branchApp.getGitApplicationMetadata().setDefaultBranchName(DEFAULT_BRANCH); branchApp.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); applicationService.save(branchApp).block(); @@ -3255,15 +3887,16 @@ public void deleteBranch_cancelledMidway_success() throws GitAPIException, IOExc } catch (InterruptedException e) { e.printStackTrace(); } - return applicationService.findAllApplicationsByDefaultApplicationId(DBApplication.getId(), MANAGE_APPLICATIONS); + return applicationService.findAllApplicationsByDefaultApplicationId( + DBApplication.getId(), MANAGE_APPLICATIONS); }) .collectList(); - StepVerifier - .create(applicationsFromDbMono) + StepVerifier.create(applicationsFromDbMono) .assertNext(applicationList -> { Set<String> branchNames = new HashSet<>(); - applicationList.forEach(application1 -> branchNames.add(application1.getGitApplicationMetadata().getBranchName())); + applicationList.forEach(application1 -> branchNames.add( + application1.getGitApplicationMetadata().getBranchName())); assertThat(branchNames).doesNotContain(TO_BE_DELETED_BRANCH); }) .verifyComplete(); @@ -3281,23 +3914,36 @@ public void commitAndPushApplication_WithMultipleUsers_success() throws GitAPIEx page.setName("commit_WithMultipleUsers_page"); applicationPageService.createPage(page).block(); - Mockito.when(gitFileUtils.saveApplicationToLocalRepo(Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) + Mockito.when(gitFileUtils.saveApplicationToLocalRepo( + Mockito.any(Path.class), Mockito.any(ApplicationJson.class), Mockito.anyString())) .thenReturn(Mono.just(Paths.get(""))); - Mockito.when(gitExecutor.commitApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean())) + Mockito.when(gitExecutor.commitApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean())) .thenReturn(Mono.just("committed successfully")); Mockito.when(gitExecutor.checkoutToBranch(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mockito.when(gitExecutor.pushApplication(Mockito.any(Path.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(gitExecutor.pushApplication( + Mockito.any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) .thenReturn(Mono.just("pushed successfully")); // First request for commit operation - Mono<String> commitMonoReq1 = gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); + Mono<String> commitMonoReq1 = + gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); // Second request for commit operation - Mono<String> commitMonoReq2 = gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); + Mono<String> commitMonoReq2 = + gitService.commitApplication(commitDTO, gitConnectedApplication.getId(), DEFAULT_BRANCH); // Both the request to execute completely without the file lock error from jgit. - StepVerifier - .create(Mono.zip(commitMonoReq1, commitMonoReq2)) + StepVerifier.create(Mono.zip(commitMonoReq1, commitMonoReq2)) .assertNext(tuple -> { assertThat(tuple.getT1()).contains("committed successfully"); assertThat(tuple.getT2()).contains("committed successfully"); @@ -3311,7 +3957,8 @@ public void getGitConnectedApps_privateRepositories_Success() throws GitAPIExcep Workspace workspace = new Workspace(); workspace.setName("Limit Private Repo Test Workspace"); - String localWorkspaceId = workspaceService.create(workspace).map(Workspace::getId).block(); + String localWorkspaceId = + workspaceService.create(workspace).map(Workspace::getId).block(); Mockito.when(gitCloudServicesUtils.getPrivateRepoLimitForOrg(eq(localWorkspaceId), Mockito.anyBoolean())) .thenReturn(Mono.just(-1)); @@ -3320,8 +3967,7 @@ public void getGitConnectedApps_privateRepositories_Success() throws GitAPIExcep createApplicationConnectedToGit("private_repo_2", "master", localWorkspaceId); createApplicationConnectedToGit("private_repo_3", "master", localWorkspaceId); - StepVerifier - .create(gitService.getApplicationCountWithPrivateRepo(localWorkspaceId)) + StepVerifier.create(gitService.getApplicationCountWithPrivateRepo(localWorkspaceId)) .assertNext(limit -> assertThat(limit).isEqualTo(3)) .verifyComplete(); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutActionServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutActionServiceTest.java index 17303498b082..9eb944e2353f 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutActionServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutActionServiceTest.java @@ -151,14 +151,17 @@ public void setup() { Workspace toCreate = new Workspace(); toCreate.setName("LayoutActionServiceTest"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); if (testApp == null && testPage == null) { - //Create application and page which will be used by the tests to create actions for. + // Create application and page which will be used by the tests to create actions for. Application application = new Application(); application.setName(UUID.randomUUID().toString()); - testApp = applicationPageService.createApplication(application, workspace.getId()).block(); + testApp = applicationPageService + .createApplication(application, workspace.getId()) + .block(); final String pageId = testApp.getPages().get(0).getId(); @@ -168,8 +171,8 @@ public void setup() { JSONObject dsl = new JSONObject(); dsl.put("widgetName", "firstWidget"); JSONArray temp = new JSONArray(); - temp.addAll(List.of(new JSONObject(Map.of("key", "testField")), - new JSONObject(Map.of("key", "testField2")))); + temp.addAll( + List.of(new JSONObject(Map.of("key", "testField")), new JSONObject(Map.of("key", "testField2")))); dsl.put("dynamicBindingPathList", temp); dsl.put("testField", "{{ query1.data }}"); dsl.put("testField2", "{{jsObject.jsFunction.data}}"); @@ -191,7 +194,9 @@ public void setup() { layout.setDsl(dsl); layout.setPublishedDsl(dsl); - layoutActionService.updateLayout(pageId, testApp.getId(), layout.getId(), layout).block(); + layoutActionService + .updateLayout(pageId, testApp.getId(), layout.getId(), layout) + .block(); testPage = newPageService.findPageById(pageId, READ_PAGES, false).block(); } @@ -202,17 +207,23 @@ public void setup() { GitApplicationMetadata gitData = new GitApplicationMetadata(); gitData.setBranchName("actionServiceTest"); newApp.setGitApplicationMetadata(gitData); - gitConnectedApp = applicationPageService.createApplication(newApp, workspaceId) + gitConnectedApp = applicationPageService + .createApplication(newApp, workspaceId) .flatMap(application -> { application.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); - return applicationService.save(application) - .zipWhen(application1 -> importExportApplicationService.exportApplicationById(application1.getId(), gitData.getBranchName())); + return applicationService + .save(application) + .zipWhen(application1 -> importExportApplicationService.exportApplicationById( + application1.getId(), gitData.getBranchName())); }) // Assign the branchName to all the resources connected to the application - .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) + .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) .block(); - gitConnectedPage = newPageService.findPageById(gitConnectedApp.getPages().get(0).getId(), READ_PAGES, false).block(); + gitConnectedPage = newPageService + .findPageById(gitConnectedApp.getPages().get(0).getId(), READ_PAGES, false) + .block(); branchName = gitConnectedApp.getGitApplicationMetadata().getBranchName(); } @@ -221,13 +232,15 @@ public void setup() { datasource = new Datasource(); datasource.setName("Default Database"); datasource.setWorkspaceId(workspaceId); - installed_plugin = pluginRepository.findByPackageName("installed-plugin").block(); + installed_plugin = + pluginRepository.findByPackageName("installed-plugin").block(); datasource.setPluginId(installed_plugin.getId()); jsDatasource = new Datasource(); jsDatasource.setName("Default JS Database"); jsDatasource.setWorkspaceId(workspaceId); - installedJsPlugin = pluginRepository.findByPackageName("installed-js-plugin").block(); + installedJsPlugin = + pluginRepository.findByPackageName("installed-js-plugin").block(); assert installedJsPlugin != null; jsDatasource.setPluginId(installedJsPlugin.getId()); } @@ -243,7 +256,8 @@ public void cleanup() { @Test @WithUserDetails(value = "api_user") public void deleteUnpublishedAction_WhenActionDeleted_OnPageLoadActionsIsEmpty() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("query1"); @@ -267,19 +281,24 @@ public void deleteUnpublishedAction_WhenActionDeleted_OnPageLoadActionsIsEmpty() updates.setDatasource(datasource); // Save updated configuration and re-compute on page load actions. - return layoutActionService.updateSingleAction(savedAction.getId(), updates) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); + return layoutActionService + .updateSingleAction(savedAction.getId(), updates) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); }) - .flatMap(savedAction -> layoutActionService.deleteUnpublishedAction(savedAction.getId())) // Delete action - .flatMap(savedAction -> newPageService.findPageById(testPage.getId(), READ_PAGES, false)); // Get page info + .flatMap(savedAction -> + layoutActionService.deleteUnpublishedAction(savedAction.getId())) // Delete action + .flatMap(savedAction -> + newPageService.findPageById(testPage.getId(), READ_PAGES, false)); // Get page info - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(page -> { assertThat(page.getLayouts()).hasSize(1); // Verify that no action is marked to run on page load. - assertThat(page.getLayouts().get(0).getLayoutOnLoadActions()).hasSize(0); + assertThat(page.getLayouts().get(0).getLayoutOnLoadActions()) + .hasSize(0); }) .verifyComplete(); } @@ -287,7 +306,8 @@ public void deleteUnpublishedAction_WhenActionDeleted_OnPageLoadActionsIsEmpty() @Test @WithUserDetails(value = "api_user") public void updateActionUpdatesLayout() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("query1"); @@ -330,8 +350,11 @@ public void updateActionUpdatesLayout() { updates.setPolicies(null); updates.setUserPermissions(null); updates.setDatasource(datasource); - return layoutActionService.updateSingleAction(savedAction.getId(), updates) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); + return layoutActionService + .updateSingleAction(savedAction.getId(), updates) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); }) .flatMap(savedAction -> layoutActionService.createSingleAction(unreferencedAction, Boolean.FALSE)) .flatMap(savedAction -> { @@ -340,8 +363,11 @@ public void updateActionUpdatesLayout() { updates.setPolicies(null); updates.setUserPermissions(null); updates.setDatasource(datasource); - return layoutActionService.updateSingleAction(savedAction.getId(), updates) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); + return layoutActionService + .updateSingleAction(savedAction.getId(), updates) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); }) .flatMap(savedAction -> layoutActionService.createSingleAction(action3, Boolean.FALSE)) .flatMap(savedAction -> { @@ -352,23 +378,30 @@ public void updateActionUpdatesLayout() { updates.setPolicies(null); updates.setUserPermissions(null); updates.setDatasource(d2); - return layoutActionService.updateSingleAction(savedAction.getId(), updates) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); + return layoutActionService + .updateSingleAction(savedAction.getId(), updates) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); }) // fetch the unpublished page .flatMap(savedAction -> newPageService.findPageById(testPage.getId(), READ_PAGES, false)); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(page -> { assertThat(page.getLayouts()).hasSize(1); - assertThat(page.getLayouts().get(0).getLayoutOnLoadActions()).hasSize(2); - Set<DslActionDTO> dslActionDTOS1 = page.getLayouts().get(0).getLayoutOnLoadActions().get(0); + assertThat(page.getLayouts().get(0).getLayoutOnLoadActions()) + .hasSize(2); + Set<DslActionDTO> dslActionDTOS1 = + page.getLayouts().get(0).getLayoutOnLoadActions().get(0); assertThat(dslActionDTOS1).hasSize(1); - assertThat(dslActionDTOS1.stream().map(dto -> dto.getName()).collect(Collectors.toSet())).containsAll(Set.of("jsObject.jsFunction")); - Set<DslActionDTO> dslActionDTOS2 = page.getLayouts().get(0).getLayoutOnLoadActions().get(1); + assertThat(dslActionDTOS1.stream().map(dto -> dto.getName()).collect(Collectors.toSet())) + .containsAll(Set.of("jsObject.jsFunction")); + Set<DslActionDTO> dslActionDTOS2 = + page.getLayouts().get(0).getLayoutOnLoadActions().get(1); assertThat(dslActionDTOS2).hasSize(1); - assertThat(dslActionDTOS2.stream().map(dto -> dto.getName()).collect(Collectors.toSet())).containsAll(Set.of("query1")); + assertThat(dslActionDTOS2.stream().map(dto -> dto.getName()).collect(Collectors.toSet())) + .containsAll(Set.of("query1")); }) .verifyComplete(); } @@ -376,7 +409,8 @@ public void updateActionUpdatesLayout() { @Test @WithUserDetails(value = "api_user") public void updateLayout_WhenOnLoadChanged_ActionExecuted() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action1 = new ActionDTO(); action1.setName("firstAction"); @@ -404,14 +438,21 @@ public void updateLayout_WhenOnLoadChanged_ActionExecuted() { Layout layout = testPage.getLayouts().get(0); layout.setDsl(dsl); - ActionDTO createdAction1 = layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); - ActionDTO createdAction2 = layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); + ActionDTO createdAction1 = + layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); + ActionDTO createdAction2 = + layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); - Mono<LayoutDTO> updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); + Mono<LayoutDTO> updateLayoutMono = + layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); StepVerifier.create(updateLayoutMono) .assertNext(updatedLayout -> { - DslActionDTO actionDTO = updatedLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO = updatedLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO.getName()).isEqualTo("firstAction"); List<LayoutActionUpdateDTO> actionUpdates = updatedLayout.getActionUpdates(); @@ -421,11 +462,13 @@ public void updateLayout_WhenOnLoadChanged_ActionExecuted() { }) .verifyComplete(); - StepVerifier.create(newActionService.findById(createdAction1.getId())) - .assertNext(newAction -> assertThat(newAction.getUnpublishedAction().getExecuteOnLoad()).isTrue()); + StepVerifier.create(newActionService.findById(createdAction1.getId())).assertNext(newAction -> assertThat( + newAction.getUnpublishedAction().getExecuteOnLoad()) + .isTrue()); - StepVerifier.create(newActionService.findById(createdAction2.getId())) - .assertNext(newAction -> assertThat(newAction.getUnpublishedAction().getExecuteOnLoad()).isFalse()); + StepVerifier.create(newActionService.findById(createdAction2.getId())).assertNext(newAction -> assertThat( + newAction.getUnpublishedAction().getExecuteOnLoad()) + .isFalse()); dsl = new JSONObject(); dsl.put("widgetName", "firstWidget"); @@ -436,41 +479,52 @@ public void updateLayout_WhenOnLoadChanged_ActionExecuted() { layout.setDsl(dsl); - updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); + updateLayoutMono = + layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); StepVerifier.create(updateLayoutMono) .assertNext(updatedLayout -> { log.debug("{}", updatedLayout.getMessages()); - DslActionDTO actionDTO = updatedLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO = updatedLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO.getName()).isEqualTo("secondAction"); List<LayoutActionUpdateDTO> actionUpdates = updatedLayout.getActionUpdates(); assertThat(actionUpdates.size()).isEqualTo(2); - Optional<LayoutActionUpdateDTO> firstActionUpdateOptional = actionUpdates.stream().filter(actionUpdate -> actionUpdate.getName().equals("firstAction")).findFirst(); + Optional<LayoutActionUpdateDTO> firstActionUpdateOptional = actionUpdates.stream() + .filter(actionUpdate -> actionUpdate.getName().equals("firstAction")) + .findFirst(); LayoutActionUpdateDTO firstActionUpdate = firstActionUpdateOptional.get(); assertThat(firstActionUpdate).isNotNull(); assertThat(firstActionUpdate.getExecuteOnLoad()).isFalse(); - Optional<LayoutActionUpdateDTO> secondActionUpdateOptional = actionUpdates.stream().filter(actionUpdate -> actionUpdate.getName().equals("secondAction")).findFirst(); + Optional<LayoutActionUpdateDTO> secondActionUpdateOptional = actionUpdates.stream() + .filter(actionUpdate -> actionUpdate.getName().equals("secondAction")) + .findFirst(); LayoutActionUpdateDTO secondActionUpdate = secondActionUpdateOptional.get(); assertThat(secondActionUpdate).isNotNull(); assertThat(secondActionUpdate.getExecuteOnLoad()).isTrue(); }) .verifyComplete(); - StepVerifier.create(newActionService.findById(createdAction1.getId())) - .assertNext(newAction -> assertThat(newAction.getUnpublishedAction().getExecuteOnLoad()).isFalse()); - - StepVerifier.create(newActionService.findById(createdAction2.getId())) - .assertNext(newAction -> assertThat(newAction.getUnpublishedAction().getExecuteOnLoad()).isTrue()); + StepVerifier.create(newActionService.findById(createdAction1.getId())).assertNext(newAction -> assertThat( + newAction.getUnpublishedAction().getExecuteOnLoad()) + .isFalse()); + StepVerifier.create(newActionService.findById(createdAction2.getId())).assertNext(newAction -> assertThat( + newAction.getUnpublishedAction().getExecuteOnLoad()) + .isTrue()); } @Test @WithUserDetails(value = "api_user") public void testHintMessageOnLocalhostUrlOnUpdateActionEvent() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("query1"); @@ -494,22 +548,25 @@ public void testHintMessageOnLocalhostUrlOnUpdateActionEvent() { ds.getDatasourceConfiguration().setUrl("http://localhost"); ds.setPluginId(datasource.getPluginId()); updates.setDatasource(ds); - return layoutActionService.updateSingleAction(savedAction.getId(), updates) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); + return layoutActionService + .updateSingleAction(savedAction.getId(), updates) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); }); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(resultAction -> { - assertThat(resultAction.getDatasource().getMessages().size()).isNotZero(); + assertThat(resultAction.getDatasource().getMessages().size()) + .isNotZero(); - String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + - "inside a docker container or on the cloud. To enable access to your localhost you may " + - "use ngrok to expose your local endpoint to the internet. Please check out " + - "Appsmith's documentation to understand more."; + String expectedMessage = "You may not be able to access your localhost if Appsmith is running " + + "inside a docker container or on the cloud. To enable access to your localhost you may " + + "use ngrok to expose your local endpoint to the internet. Please check out " + + "Appsmith's documentation to understand more."; assertThat(resultAction.getDatasource().getMessages().stream() - .anyMatch(message -> expectedMessage.equals(message)) - ).isTrue(); + .anyMatch(message -> expectedMessage.equals(message))) + .isTrue(); }) .verifyComplete(); } @@ -517,7 +574,8 @@ public void testHintMessageOnLocalhostUrlOnUpdateActionEvent() { @Test @WithUserDetails(value = "api_user") public void tableWidgetKeyEscape() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); JSONObject dsl = new JSONObject(); dsl.put("widgetName", "Table1"); @@ -530,21 +588,26 @@ public void tableWidgetKeyEscape() { Layout layout = testPage.getLayouts().get(0); layout.setDsl(dsl); - Mono<LayoutDTO> updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout).cache(); + Mono<LayoutDTO> updateLayoutMono = layoutActionService + .updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout) + .cache(); - Mono<PageDTO> pageFromRepoMono = updateLayoutMono.then(newPageService.findPageById(testPage.getId(), READ_PAGES, false)); + Mono<PageDTO> pageFromRepoMono = + updateLayoutMono.then(newPageService.findPageById(testPage.getId(), READ_PAGES, false)); - StepVerifier - .create(Mono.zip(updateLayoutMono, pageFromRepoMono)) + StepVerifier.create(Mono.zip(updateLayoutMono, pageFromRepoMono)) .assertNext(tuple -> { LayoutDTO updatedLayout = tuple.getT1(); PageDTO pageFromRepo = tuple.getT2(); Map primaryColumns1 = (Map) updatedLayout.getDsl().get("primaryColumns"); - assertThat(primaryColumns1.keySet()).containsAll(Set.of(FieldName.MONGO_UNESCAPED_ID, FieldName.MONGO_UNESCAPED_CLASS)); + assertThat(primaryColumns1.keySet()) + .containsAll(Set.of(FieldName.MONGO_UNESCAPED_ID, FieldName.MONGO_UNESCAPED_CLASS)); - Map primaryColumns2 = (Map) pageFromRepo.getLayouts().get(0).getDsl().get("primaryColumns"); - assertThat(primaryColumns2.keySet()).containsAll(Set.of(FieldName.MONGO_ESCAPE_ID, FieldName.MONGO_ESCAPE_CLASS)); + Map primaryColumns2 = + (Map) pageFromRepo.getLayouts().get(0).getDsl().get("primaryColumns"); + assertThat(primaryColumns2.keySet()) + .containsAll(Set.of(FieldName.MONGO_ESCAPE_ID, FieldName.MONGO_ESCAPE_CLASS)); }) .verifyComplete(); } @@ -560,17 +623,17 @@ public void testIsNameAllowed_withRepeatedActionCollectionName_throwsError() { Mockito.when(actionCollectionService.getActionCollectionsByViewMode(Mockito.any(), Mockito.anyBoolean())) .thenReturn(Flux.just(mockActionCollectionDTO)); - Mono<Boolean> nameAllowedMono = layoutActionService.isNameAllowed(testPage.getId(), testPage.getLayouts().get(0).getId(), "testCollection"); + Mono<Boolean> nameAllowedMono = layoutActionService.isNameAllowed( + testPage.getId(), testPage.getLayouts().get(0).getId(), "testCollection"); - StepVerifier.create(nameAllowedMono) - .assertNext(Assertions::assertFalse) - .verifyComplete(); + StepVerifier.create(nameAllowedMono).assertNext(Assertions::assertFalse).verifyComplete(); } @Test @WithUserDetails(value = "api_user") public void duplicateActionNameCreation() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); String name = "query1"; @@ -592,10 +655,11 @@ public void duplicateActionNameCreation() { Mono<ActionDTO> duplicateActionMono = layoutActionService.createSingleAction(duplicateAction, Boolean.FALSE); - StepVerifier - .create(duplicateActionMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.DUPLICATE_KEY_USER_ERROR.getMessage(name, FieldName.NAME))) + StepVerifier.create(duplicateActionMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.DUPLICATE_KEY_USER_ERROR.getMessage(name, FieldName.NAME))) .verify(); } @@ -603,7 +667,8 @@ public void duplicateActionNameCreation() { @Test @WithUserDetails(value = "api_user") public void OnLoadActionsWhenActionDependentOnActionViaWidget() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); /* * The left entity depends on the entity on the right @@ -639,8 +704,8 @@ public void OnLoadActionsWhenActionDependentOnActionViaWidget() { action2.setDynamicBindingPathList(List.of(new Property("body", null))); action2.setDatasource(datasource); - JSONObject parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + JSONObject parentDsl = new JSONObject( + objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); ArrayList children = (ArrayList) parentDsl.get("children"); @@ -673,32 +738,41 @@ public void OnLoadActionsWhenActionDependentOnActionViaWidget() { Layout layout = testPage.getLayouts().get(0); layout.setDsl(parentDsl); - ActionDTO createdAction1 = layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); - ActionDTO createdAction2 = layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); + ActionDTO createdAction1 = + layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); + ActionDTO createdAction2 = + layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); - Mono<LayoutDTO> updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); + Mono<LayoutDTO> updateLayoutMono = + layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); StepVerifier.create(updateLayoutMono) .assertNext(updatedLayout -> { - assertThat(updatedLayout.getLayoutOnLoadActions().size()).isEqualTo(2); // Assert that both the actions don't belong to the same set. They should be run iteratively. - DslActionDTO actionDTO = updatedLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO = updatedLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO.getName()).isEqualTo("firstAction"); - actionDTO = updatedLayout.getLayoutOnLoadActions().get(1).iterator().next(); + actionDTO = updatedLayout + .getLayoutOnLoadActions() + .get(1) + .iterator() + .next(); assertThat(actionDTO.getName()).isEqualTo("secondAction"); - }) .verifyComplete(); - } @Test @WithUserDetails(value = "api_user") public void simpleOnPageLoadActionCreationTest() throws JsonProcessingException { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); // This action should be tagged as on page load since it is used by firstWidget ActionDTO action1 = new ActionDTO(); @@ -709,7 +783,8 @@ public void simpleOnPageLoadActionCreationTest() throws JsonProcessingException action1.setActionConfiguration(actionConfiguration1); action1.setDatasource(datasource); - // Gen action which does not get used anywhere but depends implicitly on first action and has been set to run on load + // Gen action which does not get used anywhere but depends implicitly on first action and has been set to run on + // load ActionDTO action2 = new ActionDTO(); action2.setName("secondAction"); action2.setPageId(testPage.getId()); @@ -733,8 +808,8 @@ public void simpleOnPageLoadActionCreationTest() throws JsonProcessingException action3.setDynamicBindingPathList(List.of(new Property("body", null))); action3.setDatasource(datasource); - JSONObject parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + JSONObject parentDsl = new JSONObject( + objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); ArrayList children = (ArrayList) parentDsl.get("children"); @@ -751,8 +826,10 @@ public void simpleOnPageLoadActionCreationTest() throws JsonProcessingException Layout layout = testPage.getLayouts().get(0); layout.setDsl(parentDsl); - ActionDTO createdAction1 = layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); - ActionDTO createdAction2 = layoutActionService.createSingleAction(action2, Boolean.FALSE) + ActionDTO createdAction1 = + layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); + ActionDTO createdAction2 = layoutActionService + .createSingleAction(action2, Boolean.FALSE) .flatMap(savedAction -> { ActionDTO updates = new ActionDTO(); @@ -760,10 +837,15 @@ public void simpleOnPageLoadActionCreationTest() throws JsonProcessingException updates.setExecuteOnLoad(true); // Save updated configuration and re-compute on page load actions. - return layoutActionService.updateSingleAction(savedAction.getId(), updates) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); - }).block(); - ActionDTO createdAction3 = layoutActionService.createSingleAction(action3, Boolean.FALSE) + return layoutActionService + .updateSingleAction(savedAction.getId(), updates) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); + }) + .block(); + ActionDTO createdAction3 = layoutActionService + .createSingleAction(action3, Boolean.FALSE) .flatMap(savedAction -> { ActionDTO updates = new ActionDTO(); @@ -771,33 +853,42 @@ public void simpleOnPageLoadActionCreationTest() throws JsonProcessingException updates.setExecuteOnLoad(true); // Save updated configuration and re-compute on page load actions. - return layoutActionService.updateSingleAction(savedAction.getId(), updates) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); - }).block(); + return layoutActionService + .updateSingleAction(savedAction.getId(), updates) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); + }) + .block(); - Mono<LayoutDTO> updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); + Mono<LayoutDTO> updateLayoutMono = + layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); StepVerifier.create(updateLayoutMono) .assertNext(updatedLayout -> { - assertThat(updatedLayout.getLayoutOnLoadActions().size()).isEqualTo(2); // Assert that all three the actions dont belong to the same set - final Set<DslActionDTO> firstSet = updatedLayout.getLayoutOnLoadActions().get(0); - assertThat(firstSet).allMatch(actionDTO -> Set.of("firstAction", "thirdAction").contains(actionDTO.getName())); - final DslActionDTO secondSetAction = updatedLayout.getLayoutOnLoadActions().get(1).iterator().next(); + final Set<DslActionDTO> firstSet = + updatedLayout.getLayoutOnLoadActions().get(0); + assertThat(firstSet).allMatch(actionDTO -> Set.of("firstAction", "thirdAction") + .contains(actionDTO.getName())); + final DslActionDTO secondSetAction = updatedLayout + .getLayoutOnLoadActions() + .get(1) + .iterator() + .next(); assertThat(secondSetAction.getName()).isEqualTo("secondAction"); - }) .verifyComplete(); - } @SneakyThrows @Test @WithUserDetails(value = "api_user") public void OnLoadActionsWhenActionDependentOnWidgetButNotPageLoadCandidate() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); /* * The left entity depends on the entity on the right @@ -832,8 +923,8 @@ public void OnLoadActionsWhenActionDependentOnWidgetButNotPageLoadCandidate() { action2.setDynamicBindingPathList(List.of(new Property("body", null))); action2.setDatasource(datasource); - JSONObject parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + JSONObject parentDsl = new JSONObject( + objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); ArrayList children = (ArrayList) parentDsl.get("children"); @@ -858,30 +949,34 @@ public void OnLoadActionsWhenActionDependentOnWidgetButNotPageLoadCandidate() { Layout layout = testPage.getLayouts().get(0); layout.setDsl(parentDsl); - ActionDTO createdAction1 = layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); - ActionDTO createdAction2 = layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); + ActionDTO createdAction1 = + layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); + ActionDTO createdAction2 = + layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); - Mono<LayoutDTO> updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); + Mono<LayoutDTO> updateLayoutMono = + layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); StepVerifier.create(updateLayoutMono) .assertNext(updatedLayout -> { - assertThat(updatedLayout.getLayoutOnLoadActions().size()).isEqualTo(1); - DslActionDTO actionDTO = updatedLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO = updatedLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO.getName()).isEqualTo("firstAction"); - }) .verifyComplete(); - } @SneakyThrows(JsonProcessingException.class) @Test @WithUserDetails(value = "api_user") public void updateLayout_withSelfReferencingWidget_updatesLayout() { - JSONObject parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + JSONObject parentDsl = new JSONObject( + objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); ArrayList children = (ArrayList) parentDsl.get("children"); @@ -898,13 +993,14 @@ public void updateLayout_withSelfReferencingWidget_updatesLayout() { Layout layout = testPage.getLayouts().get(0); layout.setDsl(parentDsl); - - Mono<LayoutDTO> updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); + Mono<LayoutDTO> updateLayoutMono = + layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); StepVerifier.create(updateLayoutMono) .assertNext(layoutDTO -> { final JSONObject dsl = layoutDTO.getDsl(); - final Object fieldValue = ((JSONObject) ((ArrayList) dsl.get("children")).get(0)).getAsString("testField"); + final Object fieldValue = + ((JSONObject) ((ArrayList) dsl.get("children")).get(0)).getAsString("testField"); // Make sure the DSL got updated assertEquals("{{ firstWidget.testField }}", fieldValue); }) @@ -927,7 +1023,8 @@ public void updateMultipleLayouts_MultipleLayouts_LayoutsUpdated() { Layout layout = page.getLayouts().get(0); layout.setDsl(createTestDslWithTestWidget("Layout" + (i + 1))); - UpdateMultiplePageLayoutDTO.UpdatePageLayoutDTO pageLayoutDTO = new UpdateMultiplePageLayoutDTO.UpdatePageLayoutDTO(); + UpdateMultiplePageLayoutDTO.UpdatePageLayoutDTO pageLayoutDTO = + new UpdateMultiplePageLayoutDTO.UpdatePageLayoutDTO(); pageLayoutDTO.setPageId(page.getId()); pageLayoutDTO.setLayoutId(layout.getId()); pageLayoutDTO.setLayout(layout); @@ -935,10 +1032,10 @@ public void updateMultipleLayouts_MultipleLayouts_LayoutsUpdated() { } Mono<Tuple2<PageDTO, PageDTO>> pagesMono = Mono.zip( newPageService.findPageById(testPage.getId(), READ_PAGES, false), - newPageService.findPageById(secondPage.getId(), READ_PAGES, false) - ); + newPageService.findPageById(secondPage.getId(), READ_PAGES, false)); - Mono<Tuple2<PageDTO, PageDTO>> updateAndGetPagesMono = layoutActionService.updateMultipleLayouts(testApp.getId(), null, multiplePageLayoutDTO) + Mono<Tuple2<PageDTO, PageDTO>> updateAndGetPagesMono = layoutActionService + .updateMultipleLayouts(testApp.getId(), null, multiplePageLayoutDTO) .then(pagesMono); StepVerifier.create(updateAndGetPagesMono) @@ -954,12 +1051,10 @@ public void updateMultipleLayouts_MultipleLayouts_LayoutsUpdated() { LinkedHashMap<String, String> widget1 = childArray1.get(0); LinkedHashMap<String, String> widget2 = childArray2.get(0); - List<String> widgetNames = List.of( - widget1.get("widgetName"), - widget2.get("widgetName") - ); + List<String> widgetNames = List.of(widget1.get("widgetName"), widget2.get("widgetName")); assertThat(widgetNames).contains("Layout1", "Layout2"); - }).verifyComplete(); + }) + .verifyComplete(); } /** @@ -974,7 +1069,8 @@ public void updateMultipleLayouts_MultipleLayouts_LayoutsUpdated() { @Test @WithUserDetails(value = "api_user") public void testExecuteOnPageLoadOrderWhenAllActionsAreOnlyExplicitlySetToExecute() throws JsonProcessingException { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); // Configure action1 ActionDTO action1 = new ActionDTO(); @@ -998,12 +1094,13 @@ public void testExecuteOnPageLoadOrderWhenAllActionsAreOnlyExplicitlySetToExecut action2.setExecuteOnLoad(true); action2.setDatasource(datasource); - JSONObject parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + JSONObject parentDsl = new JSONObject( + objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); Layout layout = testPage.getLayouts().get(0); layout.setDsl(parentDsl); - ActionDTO createdAction1 = layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); // create action1 + ActionDTO createdAction1 = + layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); // create action1 assertNotNull(createdAction1); createdAction1.setExecuteOnLoad(true); // this can only be set to true post action creation. NewAction newAction1 = new NewAction(); @@ -1012,7 +1109,8 @@ public void testExecuteOnPageLoadOrderWhenAllActionsAreOnlyExplicitlySetToExecut newAction1.setPluginId(installed_plugin.getId()); newAction1.setPluginType(installed_plugin.getType()); - ActionDTO createdAction2 = layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); // create action2 + ActionDTO createdAction2 = + layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); // create action2 assertNotNull(createdAction1); createdAction2.setExecuteOnLoad(true); // this can only be set to true post action creation. NewAction newAction2 = new NewAction(); @@ -1025,22 +1123,30 @@ public void testExecuteOnPageLoadOrderWhenAllActionsAreOnlyExplicitlySetToExecut newActionArray[0] = newAction1; newActionArray[1] = newAction2; Flux<NewAction> newActionFlux = Flux.fromArray(newActionArray); - Mockito.when(newActionService.findUnpublishedOnLoadActionsExplicitSetByUserInPage(Mockito.any())).thenReturn(newActionFlux); + Mockito.when(newActionService.findUnpublishedOnLoadActionsExplicitSetByUserInPage(Mockito.any())) + .thenReturn(newActionFlux); - Mono<LayoutDTO> updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); + Mono<LayoutDTO> updateLayoutMono = + layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); StepVerifier.create(updateLayoutMono) .assertNext(updatedLayout -> { - assertThat(updatedLayout.getLayoutOnLoadActions().size()).isEqualTo(2); // Assert that both the actions don't belong to the same set. They should be run iteratively. - DslActionDTO actionDTO1 = updatedLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO1 = updatedLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO1.getName()).isEqualTo("firstAction"); - DslActionDTO actionDTO2 = updatedLayout.getLayoutOnLoadActions().get(1).iterator().next(); + DslActionDTO actionDTO2 = updatedLayout + .getLayoutOnLoadActions() + .get(1) + .iterator() + .next(); assertThat(actionDTO2.getName()).isEqualTo("secondAction"); - }) .verifyComplete(); } @@ -1054,7 +1160,8 @@ public void testExecuteOnPageLoadOrderWhenAllActionsAreOnlyExplicitlySetToExecut @Test @WithUserDetails(value = "api_user") public void updateLayout_WhenPageLoadActionSetBothWaysExplicitlyAndImplicitlyViaWidget_ActionsSaved() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action1 = new ActionDTO(); action1.setName("firstAction"); @@ -1074,7 +1181,8 @@ public void updateLayout_WhenPageLoadActionSetBothWaysExplicitlyAndImplicitlyVia Layout layout = testPage.getLayouts().get(0); layout.setDsl(dsl); - ActionDTO createdAction1 = layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); + ActionDTO createdAction1 = + layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); assertNotNull(createdAction1); createdAction1.setExecuteOnLoad(true); // this can only be set to true post action creation. createdAction1.setUserSetOnLoad(true); @@ -1087,16 +1195,22 @@ public void updateLayout_WhenPageLoadActionSetBothWaysExplicitlyAndImplicitlyVia NewAction[] newActionArray = new NewAction[1]; newActionArray[0] = newAction1; Flux<NewAction> newActionFlux = Flux.fromArray(newActionArray); - Mockito.when(newActionService.findUnpublishedOnLoadActionsExplicitSetByUserInPage(Mockito.any())).thenReturn(newActionFlux); + Mockito.when(newActionService.findUnpublishedOnLoadActionsExplicitSetByUserInPage(Mockito.any())) + .thenReturn(newActionFlux); - Mono<LayoutDTO> updateLayoutMono = layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); + Mono<LayoutDTO> updateLayoutMono = + layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout); StepVerifier.create(updateLayoutMono) .assertNext(updatedLayout -> { assertThat(updatedLayout.getLayoutOnLoadActions().size()).isEqualTo(1); // Assert that both the actions don't belong to the same set. They should be run iteratively. - DslActionDTO actionDTO1 = updatedLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO1 = updatedLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO1.getName()).isEqualTo("firstAction"); }) .verifyComplete(); @@ -1106,7 +1220,8 @@ public void updateLayout_WhenPageLoadActionSetBothWaysExplicitlyAndImplicitlyVia @WithUserDetails(value = "api_user") public void introduceCyclicDependencyAndRemoveLater() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); // creating new action based on which we will introduce cyclic dependency ActionDTO actionDTO = new ActionDTO(); @@ -1118,7 +1233,8 @@ public void introduceCyclicDependencyAndRemoveLater() { actionDTO.setDatasource(datasource); actionDTO.setExecuteOnLoad(true); - ActionDTO createdAction = layoutActionService.createSingleAction(actionDTO, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(actionDTO, Boolean.FALSE).block(); // retrieving layout from test page; Layout layout = testPage.getLayouts().get(0); @@ -1129,12 +1245,13 @@ public void introduceCyclicDependencyAndRemoveLater() { JSONArray temp = new JSONArray(); temp.add(new JSONObject(Map.of("key", "defaultText"))); dsl.put("dynamicBindingPathList", temp); - dsl.put("defaultText", "{{\n" + - "(function(){\n" + - "\tlet inputWidget = \"abc\";\n" + - "\treturn actionName.data;\n" + - "})()\n" + - "}}"); + dsl.put( + "defaultText", + "{{\n" + "(function(){\n" + + "\tlet inputWidget = \"abc\";\n" + + "\treturn actionName.data;\n" + + "})()\n" + + "}}"); final JSONObject innerObjectReference = new JSONObject(); innerObjectReference.put("k", "{{\tactionName.data[0].inputWidget}}"); @@ -1151,13 +1268,17 @@ public void introduceCyclicDependencyAndRemoveLater() { mainDsl.put("children", objects); layout.setDsl(mainDsl); - LayoutDTO firstLayout = layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + LayoutDTO firstLayout = layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); - // by default there should be no error in the layout, hence no error should be sent to ActionDTO/ errorReports will be null + // by default there should be no error in the layout, hence no error should be sent to ActionDTO/ errorReports + // will be null assertNotNull(createdAction); assertNull(createdAction.getErrorReports()); - // since the dependency has been introduced calling updateLayout will return a LayoutDTO with a populated layoutOnLoadActionErrors + // since the dependency has been introduced calling updateLayout will return a LayoutDTO with a populated + // layoutOnLoadActionErrors assertNotNull(firstLayout); assertEquals(1, firstLayout.getLayoutOnLoadActionErrors().size()); @@ -1170,19 +1291,21 @@ public void introduceCyclicDependencyAndRemoveLater() { refactorActionNameDTO.setActionId(createdAction.getId()); Mono<LayoutDTO> layoutDTOMono = refactoringSolution.refactorActionName(refactorActionNameDTO); - StepVerifier.create(layoutDTOMono.map(layoutDTO -> layoutDTO.getLayoutOnLoadActionErrors().size())) + StepVerifier.create(layoutDTOMono.map( + layoutDTO -> layoutDTO.getLayoutOnLoadActionErrors().size())) .expectNext(1) .verifyComplete(); // updateAction to see if the error persists actionDTO.setName("finalActionName"); - Mono<ActionDTO> actionDTOMono = layoutActionService.updateSingleActionWithBranchName(createdAction.getId(), actionDTO, null); + Mono<ActionDTO> actionDTOMono = + layoutActionService.updateSingleActionWithBranchName(createdAction.getId(), actionDTO, null); - StepVerifier.create(actionDTOMono.map(actionDTO1 -> actionDTO1.getErrorReports().size())) + StepVerifier.create(actionDTOMono.map( + actionDTO1 -> actionDTO1.getErrorReports().size())) .expectNext(1) .verifyComplete(); - JSONObject newDsl = new JSONObject(); newDsl.put("widgetName", "newInputWidget"); newDsl.put("innerArrayReference", innerArrayReference); @@ -1194,11 +1317,12 @@ public void introduceCyclicDependencyAndRemoveLater() { layout.setDsl(mainDsl); - LayoutDTO changedLayoutDTO = layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + LayoutDTO changedLayoutDTO = layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); assertNotNull(changedLayoutDTO); assertNotNull(changedLayoutDTO.getLayoutOnLoadActionErrors()); assertEquals(0, changedLayoutDTO.getLayoutOnLoadActionErrors().size()); - } @Test @@ -1216,8 +1340,9 @@ public void jsActionWithoutCollectionIdShouldBeIgnoredDuringNameChecking() { secondAction.setFullyQualifiedName("testCollection.bar"); secondAction.setCollectionId(null); - - Mockito.doReturn(Flux.just(firstAction, secondAction)).when(newActionService).getUnpublishedActions(Mockito.any()); + Mockito.doReturn(Flux.just(firstAction, secondAction)) + .when(newActionService) + .getUnpublishedActions(Mockito.any()); ActionCollectionDTO mockActionCollectionDTO = new ActionCollectionDTO(); mockActionCollectionDTO.setName("testCollection"); @@ -1226,11 +1351,10 @@ public void jsActionWithoutCollectionIdShouldBeIgnoredDuringNameChecking() { Mockito.when(actionCollectionService.getActionCollectionsByViewMode(Mockito.any(), Mockito.anyBoolean())) .thenReturn(Flux.just(mockActionCollectionDTO)); - Mono<Boolean> nameAllowedMono = layoutActionService.isNameAllowed(testPage.getId(), testPage.getLayouts().get(0).getId(), "testCollection.bar"); + Mono<Boolean> nameAllowedMono = layoutActionService.isNameAllowed( + testPage.getId(), testPage.getLayouts().get(0).getId(), "testCollection.bar"); - StepVerifier.create(nameAllowedMono) - .assertNext(Assertions::assertTrue) - .verifyComplete(); + StepVerifier.create(nameAllowedMono).assertNext(Assertions::assertTrue).verifyComplete(); } /** @@ -1239,8 +1363,8 @@ public void jsActionWithoutCollectionIdShouldBeIgnoredDuringNameChecking() { * @return JSONObject of the DSL */ private JSONObject createTestDslWithTestWidget(String testWidgetName) throws JsonProcessingException { - JSONObject parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + JSONObject parentDsl = new JSONObject( + objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); JSONObject firstWidget = new JSONObject(); firstWidget.put("widgetName", testWidgetName); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java index 46f5cc2e49bc..1dd2ccec8aca 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java @@ -105,14 +105,17 @@ public void setup() { Workspace toCreate = new Workspace(); toCreate.setName("LayoutServiceTest"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); datasource = new Datasource(); datasource.setName("Default Database"); datasource.setWorkspaceId(workspaceId); - Plugin installedPlugin = pluginRepository.findByPackageName("installed-plugin").block(); - installedJsPlugin = pluginRepository.findByPackageName("installed-js-plugin").block(); + Plugin installedPlugin = + pluginRepository.findByPackageName("installed-plugin").block(); + installedJsPlugin = + pluginRepository.findByPackageName("installed-js-plugin").block(); datasource.setPluginId(installedPlugin.getId()); } @@ -125,10 +128,9 @@ private void purgeAllPages() { public void createLayoutWithNullPageId() { Layout layout = new Layout(); Mono<Layout> layoutMono = layoutService.createLayout(null, layout); - StepVerifier - .create(layoutMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PAGE_ID))) + StepVerifier.create(layoutMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PAGE_ID))) .verify(); } @@ -138,10 +140,9 @@ public void createLayoutWithInvalidPageID() { Layout layout = new Layout(); String pageId = "Some random ID which can never be a page's ID"; Mono<Layout> layoutMono = layoutService.createLayout(pageId, layout); - StepVerifier - .create(layoutMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PAGE_ID))) + StepVerifier.create(layoutMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PAGE_ID))) .verify(); } @@ -168,11 +169,9 @@ public void createValidLayout() { obj.put("key1", "value1"); testLayout.setDsl(obj); - Mono<Layout> layoutMono = pageMono - .flatMap(page -> layoutService.createLayout(page.getId(), testLayout)); + Mono<Layout> layoutMono = pageMono.flatMap(page -> layoutService.createLayout(page.getId(), testLayout)); - StepVerifier - .create(layoutMono) + StepVerifier.create(layoutMono) .assertNext(layout -> { assertThat(layout).isNotNull(); assertThat(layout.getId()).isNotNull(); @@ -184,7 +183,8 @@ public void createValidLayout() { private Mono<PageDTO> createPage(Application app, PageDTO page) { return newPageService .findByNameAndViewMode(page.getName(), AclPermission.READ_PAGES, false) - .switchIfEmpty(applicationPageService.createApplication(app, workspaceId) + .switchIfEmpty(applicationPageService + .createApplication(app, workspaceId) .map(application -> { page.setApplicationId(application.getId()); return page; @@ -212,15 +212,19 @@ public void updateLayoutInvalidPageId() { app.setName("newApplication-updateLayoutInvalidPageId-Test"); PageDTO page = createPage(app, testPage).block(); - Layout startLayout = layoutService.createLayout(page.getId(), testLayout).block(); + Layout startLayout = + layoutService.createLayout(page.getId(), testLayout).block(); - Mono<LayoutDTO> updatedLayoutMono = layoutActionService.updateLayout("random-impossible-id-page", page.getApplicationId(), startLayout.getId(), updateLayout); + Mono<LayoutDTO> updatedLayoutMono = layoutActionService.updateLayout( + "random-impossible-id-page", page.getApplicationId(), startLayout.getId(), updateLayout); - StepVerifier - .create(updatedLayoutMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.ACL_NO_RESOURCE_FOUND - .getMessage(FieldName.PAGE_ID + " or " + FieldName.LAYOUT_ID, "random-impossible-id-page" + ", " + startLayout.getId()))) + StepVerifier.create(updatedLayoutMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.ACL_NO_RESOURCE_FOUND.getMessage( + FieldName.PAGE_ID + " or " + FieldName.LAYOUT_ID, + "random-impossible-id-page" + ", " + startLayout.getId()))) .verify(); } @@ -244,15 +248,18 @@ public void updateLayoutInvalidAppId() { app.setName("newApplication-updateLayoutInvalidPageId-Test"); PageDTO page = createPage(app, testPage).block(); - Layout startLayout = layoutService.createLayout(page.getId(), testLayout).block(); + Layout startLayout = + layoutService.createLayout(page.getId(), testLayout).block(); - Mono<LayoutDTO> updatedLayoutMono = layoutActionService.updateLayout(page.getId(), "random-impossible-id-app", startLayout.getId(), updateLayout); + Mono<LayoutDTO> updatedLayoutMono = layoutActionService.updateLayout( + page.getId(), "random-impossible-id-app", startLayout.getId(), updateLayout); - StepVerifier - .create(updatedLayoutMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.ACL_NO_RESOURCE_FOUND - .getMessage(FieldName.APPLICATION_ID, "random-impossible-id-app"))) + StepVerifier.create(updatedLayoutMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.ACL_NO_RESOURCE_FOUND.getMessage( + FieldName.APPLICATION_ID, "random-impossible-id-app"))) .verify(); } @@ -279,16 +286,15 @@ public void updateLayoutValidPageId() { Mono<Layout> startLayoutMono = pageMono.flatMap(page -> layoutService.createLayout(page.getId(), testLayout)); - Mono<LayoutDTO> updatedLayoutMono = Mono.zip(pageMono, startLayoutMono) - .flatMap(tuple -> { - PageDTO page = tuple.getT1(); - Layout startLayout = tuple.getT2(); - startLayout.setDsl(obj1); - return layoutActionService.updateLayout(page.getId(), page.getApplicationId(), startLayout.getId(), startLayout); - }); + Mono<LayoutDTO> updatedLayoutMono = Mono.zip(pageMono, startLayoutMono).flatMap(tuple -> { + PageDTO page = tuple.getT1(); + Layout startLayout = tuple.getT2(); + startLayout.setDsl(obj1); + return layoutActionService.updateLayout( + page.getId(), page.getApplicationId(), startLayout.getId(), startLayout); + }); - StepVerifier - .create(updatedLayoutMono) + StepVerifier.create(updatedLayoutMono) .assertNext(layout -> { assertThat(layout).isNotNull(); assertThat(layout.getId()).isNotNull(); @@ -299,8 +305,7 @@ public void updateLayoutValidPageId() { private Mono<LayoutDTO> createComplexAppForExecuteOnLoad(Mono<PageDTO> pageMono) { - Mono<LayoutDTO> testMono = pageMono - .flatMap(page1 -> { + Mono<LayoutDTO> testMono = pageMono.flatMap(page1 -> { List<Mono<ActionDTO>> monos = new ArrayList<>(); // Create a GET API Action @@ -335,8 +340,9 @@ private Mono<LayoutDTO> createComplexAppForExecuteOnLoad(Mono<PageDTO> pageMono) action.setName("aPostActionWithAutoExec"); action.setActionConfiguration(new ActionConfiguration()); action.getActionConfiguration().setHttpMethod(HttpMethod.POST); - action.getActionConfiguration().setBody( - "this won't be auto-executed: {{aPostSecondaryAction.data}}, but this one will be: {{aPostTertiaryAction.data}}."); + action.getActionConfiguration() + .setBody( + "this won't be auto-executed: {{aPostSecondaryAction.data}}, but this one will be: {{aPostTertiaryAction.data}}."); action.setPageId(page1.getId()); action.setDatasource(datasource); action.setDynamicBindingPathList(List.of(new Property("body", null))); @@ -522,9 +528,7 @@ private Mono<LayoutDTO> createComplexAppForExecuteOnLoad(Mono<PageDTO> pageMono) .zipWhen(page1 -> { Layout layout = new Layout(); - JSONObject obj = new JSONObject(Map.of( - "key", "value" - )); + JSONObject obj = new JSONObject(Map.of("key", "value")); layout.setDsl(obj); return layoutService.createLayout(page1.getId(), layout); @@ -540,32 +544,31 @@ private Mono<LayoutDTO> createComplexAppForExecuteOnLoad(Mono<PageDTO> pageMono) "key", "value-updated", "another", "Hello people of the {{input1.text}} planet!", "dynamicGet", "some dynamic {{\"anIgnoredAction.data:\" + aGetAction.data}}", - "dynamicPost", "some dynamic {{\n" + - "(function(ignoredAction1){\n" + - "\tlet a = ignoredAction1.data\n" + - "\tlet ignoredAction2 = { data: \"nothing\" }\n" + - "\tlet b = ignoredAction2.data\n" + - "\tlet c = \"ignoredAction3.data\"\n" + - "\t// ignoredAction4.data\n" + - "\treturn aPostAction.data\n" + - "})(anotherPostAction.data)}}", + "dynamicPost", + "some dynamic {{\n" + "(function(ignoredAction1){\n" + + "\tlet a = ignoredAction1.data\n" + + "\tlet ignoredAction2 = { data: \"nothing\" }\n" + + "\tlet b = ignoredAction2.data\n" + + "\tlet c = \"ignoredAction3.data\"\n" + + "\t// ignoredAction4.data\n" + + "\treturn aPostAction.data\n" + + "})(anotherPostAction.data)}}", "dynamicPostWithAutoExec", "some dynamic {{aPostActionWithAutoExec.data}}", - "dynamicDelete", "some dynamic {{aDeleteAction.data}}" - )); + "dynamicDelete", "some dynamic {{aDeleteAction.data}}")); obj.putAll(Map.of( "collection1Key", "some dynamic {{Collection.anAsyncCollectionActionWithoutCall.data}}", "collection2Key", "some dynamic {{Collection.aSyncCollectionActionWithoutCall.data}}", "collection3Key", "some dynamic {{Collection.anAsyncCollectionActionWithCall()}}", - // only add sync function call dependencies in the dependency tree. sync call would be done during eval. - "collection4Key", "some dynamic {{Collection.aSyncCollectionActionWithCall()}}" - )); + // only add sync function call dependencies in the dependency tree. sync call would be done + // during eval. + "collection4Key", "some dynamic {{Collection.aSyncCollectionActionWithCall()}}")); obj.put("dynamicDB", new JSONObject(Map.of("test", "child path {{aDBAction.data[0].irrelevant}}"))); obj.put("dynamicDB2", List.of("{{ anotherDBAction.data.optional }}")); - obj.put("tableWidget", new JSONObject( - Map.of("test", - List.of( - Map.of("content", - Map.of("child", "{{aTableAction.data.child}}")))))); + obj.put( + "tableWidget", + new JSONObject(Map.of( + "test", + List.of(Map.of("content", Map.of("child", "{{aTableAction.data.child}}")))))); JSONArray dynamicBindingsPathList = new JSONArray(); dynamicBindingsPathList.addAll(List.of( new JSONObject(Map.of("key", "dynamicGet")), @@ -577,15 +580,13 @@ private Mono<LayoutDTO> createComplexAppForExecuteOnLoad(Mono<PageDTO> pageMono) new JSONObject(Map.of("key", "collection1Key")), new JSONObject(Map.of("key", "collection2Key")), new JSONObject(Map.of("key", "collection3Key")), - new JSONObject(Map.of("key", "collection4Key")) - )); - + new JSONObject(Map.of("key", "collection4Key")))); obj.put("dynamicBindingPathList", dynamicBindingsPathList); newLayout.setDsl(obj); - return layoutActionService.updateLayout(page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); - + return layoutActionService.updateLayout( + page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); }); return testMono; @@ -593,8 +594,7 @@ private Mono<LayoutDTO> createComplexAppForExecuteOnLoad(Mono<PageDTO> pageMono) private Mono<LayoutDTO> createAppWithAllTypesOfReferencesForExecuteOnLoad(Mono<PageDTO> pageMono) { - Mono<LayoutDTO> testMono = pageMono - .flatMap(page1 -> { + Mono<LayoutDTO> testMono = pageMono.flatMap(page1 -> { List<Mono<ActionDTO>> monos = new ArrayList<>(); // Create a GET API Action for : aGetAction.data @@ -758,9 +758,7 @@ private Mono<LayoutDTO> createAppWithAllTypesOfReferencesForExecuteOnLoad(Mono<P .zipWhen(page1 -> { Layout layout = new Layout(); - JSONObject obj = new JSONObject(Map.of( - "key", "value" - )); + JSONObject obj = new JSONObject(Map.of("key", "value")); layout.setDsl(obj); return layoutService.createLayout(page1.getId(), layout); @@ -779,12 +777,10 @@ private Mono<LayoutDTO> createAppWithAllTypesOfReferencesForExecuteOnLoad(Mono<P "k4", "{{ Collection.anAsyncCollectionActionWithoutCall.data }}", "k5", "{{ Collection.aSyncCollectionActionWithoutCall.data }}", "k6", "{{ Collection.anAsyncCollectionActionWithCall() }}", - "k7", "{{ Collection.aSyncCollectionActionWithCall() }}" - )); + "k7", "{{ Collection.aSyncCollectionActionWithCall() }}")); obj.putAll(Map.of( "k8", "{{ Collection.data() }}", - "k9", "{{ Collection2.data() }}" - )); + "k9", "{{ Collection2.data() }}")); JSONArray dynamicBindingsPathList = new JSONArray(); dynamicBindingsPathList.addAll(List.of( new JSONObject(Map.of("key", "k1")), @@ -795,14 +791,13 @@ private Mono<LayoutDTO> createAppWithAllTypesOfReferencesForExecuteOnLoad(Mono<P new JSONObject(Map.of("key", "k6")), new JSONObject(Map.of("key", "k7")), new JSONObject(Map.of("key", "k8")), - new JSONObject(Map.of("key", "k9")) - )); + new JSONObject(Map.of("key", "k9")))); obj.put("dynamicBindingPathList", dynamicBindingsPathList); newLayout.setDsl(obj); - return layoutActionService.updateLayout(page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); - + return layoutActionService.updateLayout( + page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); }); return testMono; @@ -811,7 +806,8 @@ private Mono<LayoutDTO> createAppWithAllTypesOfReferencesForExecuteOnLoad(Mono<P @Test @WithUserDetails(value = "api_user") public void getActionsExecuteOnLoadWithAstLogic_withAllTypesOfActionReferences() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); PageDTO testPage = new PageDTO(); testPage.setName("ActionsExecuteOnLoad Test Page1 Universal"); @@ -823,62 +819,79 @@ public void getActionsExecuteOnLoadWithAstLogic_withAllTypesOfActionReferences() Mono<LayoutDTO> testMono = createAppWithAllTypesOfReferencesForExecuteOnLoad(pageMono); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("aGetAction.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("aGetAction.data", new HashSet<>(Set.of("aGetAction.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("aPostAction.data.users.name"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("aPostAction.data.users.name", new HashSet<>(Set.of("aPostAction.data.users.name"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("anotherPostAction.run()"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("anotherPostAction.run()", new HashSet<>(Set.of("anotherPostAction.run"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.anAsyncCollectionActionWithoutCall.data"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("Collection.anAsyncCollectionActionWithoutCall.data", new HashSet<>(Set.of("Collection.anAsyncCollectionActionWithoutCall.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.aSyncCollectionActionWithoutCall.data"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("Collection.aSyncCollectionActionWithoutCall.data", new HashSet<>(Set.of("Collection.aSyncCollectionActionWithoutCall.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.anAsyncCollectionActionWithCall()"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("Collection.anAsyncCollectionActionWithCall()", new HashSet<>(Set.of("Collection.anAsyncCollectionActionWithCall"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.aSyncCollectionActionWithCall()"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("Collection.aSyncCollectionActionWithCall()", new HashSet<>(Set.of("Collection.aSyncCollectionActionWithCall"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.data()"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("aPostAction.data.users.name"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "aPostAction.data.users.name", new HashSet<>(Set.of("aPostAction.data.users.name"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("anotherPostAction.run()"), EVALUATION_VERSION)) + .thenReturn(Flux.just( + Tuples.of("anotherPostAction.run()", new HashSet<>(Set.of("anotherPostAction.run"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.anAsyncCollectionActionWithoutCall.data"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "Collection.anAsyncCollectionActionWithoutCall.data", + new HashSet<>(Set.of("Collection.anAsyncCollectionActionWithoutCall.data"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.aSyncCollectionActionWithoutCall.data"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "Collection.aSyncCollectionActionWithoutCall.data", + new HashSet<>(Set.of("Collection.aSyncCollectionActionWithoutCall.data"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.anAsyncCollectionActionWithCall()"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "Collection.anAsyncCollectionActionWithCall()", + new HashSet<>(Set.of("Collection.anAsyncCollectionActionWithCall"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.aSyncCollectionActionWithCall()"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "Collection.aSyncCollectionActionWithCall()", + new HashSet<>(Set.of("Collection.aSyncCollectionActionWithCall"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.data()"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("Collection.data()", new HashSet<>(Set.of("Collection.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection2.data()"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection2.data()"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("Collection2.data()", new HashSet<>(Set.of("Collection2.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("hiddenAction1.data"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("hiddenAction1.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("hiddenAction1.data", new HashSet<>(Set.of("hiddenAction1.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("hiddenAction2.data"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("hiddenAction2.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("hiddenAction2.data", new HashSet<>(Set.of("hiddenAction2.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("hiddenAction4.data"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("hiddenAction4.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("hiddenAction4.data", new HashSet<>(Set.of("hiddenAction4.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("hiddenAction5.data"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("hiddenAction5.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("hiddenAction5.data", new HashSet<>(Set.of("hiddenAction5.data"))))); - StepVerifier - .create(testMono) + StepVerifier.create(testMono) .assertNext(layout -> { assertThat(layout).isNotNull(); assertThat(layout.getId()).isNotNull(); assertThat(layout.getLayoutOnLoadActions()).hasSize(3); - Set<String> firstSetPageLoadActions = Set.of( - "aGetAction", - "hiddenAction1", - "hiddenAction2", - "hiddenAction4", - "hiddenAction5" - ); + Set<String> firstSetPageLoadActions = + Set.of("aGetAction", "hiddenAction1", "hiddenAction2", "hiddenAction4", "hiddenAction5"); - Set<String> secondSetPageLoadActions = Set.of( - "aPostAction" - ); + Set<String> secondSetPageLoadActions = Set.of("aPostAction"); - Set<String> thirdSetPageLoadActions = Set.of( - "Collection.anAsyncCollectionActionWithoutCall" - ); + Set<String> thirdSetPageLoadActions = Set.of("Collection.anAsyncCollectionActionWithoutCall"); - assertThat(layout.getLayoutOnLoadActions().get(0).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(0).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(firstSetPageLoadActions); - assertThat(layout.getLayoutOnLoadActions().get(1).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(1).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(secondSetPageLoadActions); - assertThat(layout.getLayoutOnLoadActions().get(2).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(2).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(thirdSetPageLoadActions); Set<DslActionDTO> flatOnLoadActions = new HashSet<>(); for (Set<DslActionDTO> actions : layout.getLayoutOnLoadActions()) { @@ -893,12 +906,13 @@ public void getActionsExecuteOnLoadWithAstLogic_withAllTypesOfActionReferences() .verifyComplete(); Mono<Tuple2<ActionDTO, ActionDTO>> actionDTOMono = pageMono.flatMap(page -> { - return newActionService.findByUnpublishedNameAndPageId("aGetAction", page.getId(), AclPermission.MANAGE_ACTIONS) - .zipWith(newActionService.findByUnpublishedNameAndPageId("hiddenAction3", page.getId(), AclPermission.MANAGE_ACTIONS)); + return newActionService + .findByUnpublishedNameAndPageId("aGetAction", page.getId(), AclPermission.MANAGE_ACTIONS) + .zipWith(newActionService.findByUnpublishedNameAndPageId( + "hiddenAction3", page.getId(), AclPermission.MANAGE_ACTIONS)); }); - StepVerifier - .create(actionDTOMono) + StepVerifier.create(actionDTOMono) .assertNext(tuple -> { assertThat(tuple.getT1().getExecuteOnLoad()).isTrue(); assertThat(tuple.getT2().getExecuteOnLoad()).isNotEqualTo(Boolean.TRUE); @@ -921,8 +935,8 @@ public void getActionsExecuteOnLoadWithAstLogic_withAllTypesOfActionReferences() @Test @WithUserDetails(value = "api_user") public void getActionsExecuteOnLoadWithAstLogic() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); - + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); PageDTO testPage = new PageDTO(); testPage.setName("ActionsExecuteOnLoad Test Page1"); @@ -934,48 +948,74 @@ public void getActionsExecuteOnLoadWithAstLogic() { Mono<LayoutDTO> testMono = createComplexAppForExecuteOnLoad(pageMono); - - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("\"anIgnoredAction.data:\" + aGetAction.data"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("\"anIgnoredAction.data:\" + aGetAction.data", new HashSet<>(Set.of("aGetAction.data"))))); - String bindingValue = "\n(function(ignoredAction1){\n" + - "\tlet a = ignoredAction1.data\n" + - "\tlet ignoredAction2 = { data: \"nothing\" }\n" + - "\tlet b = ignoredAction2.data\n" + - "\tlet c = \"ignoredAction3.data\"\n" + - "\t// ignoredAction4.data\n" + - "\treturn aPostAction.data\n" + - "})(anotherPostAction.data)"; Mockito.when(astService.getPossibleReferencesFromDynamicBinding( - List.of(bindingValue), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of(bindingValue, new HashSet<>(Set.of("aPostAction.data", "anotherPostAction.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("aPostActionWithAutoExec.data"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("aPostActionWithAutoExec.data", new HashSet<>(Set.of("aPostActionWithAutoExec.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("aDBAction.data[0].irrelevant"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("aDBAction.data[0].irrelevant", new HashSet<>(Set.of("aDBAction.data[0].irrelevant"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of(" anotherDBAction.data.optional "), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of(" anotherDBAction.data.optional ", new HashSet<>(Set.of("anotherDBAction.data.optional"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("aTableAction.data.child"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("aTableAction.data.child", new HashSet<>(Set.of("aTableAction.data.child"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.anAsyncCollectionActionWithoutCall.data"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("Collection.anAsyncCollectionActionWithoutCall.data", new HashSet<>(Set.of("Collection.anAsyncCollectionActionWithoutCall.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.aSyncCollectionActionWithoutCall.data"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("Collection.aSyncCollectionActionWithoutCall.data", new HashSet<>(Set.of("Collection.aSyncCollectionActionWithoutCall.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.anAsyncCollectionActionWithCall()"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("Collection.anAsyncCollectionActionWithCall()", new HashSet<>(Set.of("Collection.anAsyncCollectionActionWithCall"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("Collection.aSyncCollectionActionWithCall()"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("Collection.aSyncCollectionActionWithCall()", new HashSet<>(Set.of("Collection.aSyncCollectionActionWithCall"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("hiddenAction4.data"), EVALUATION_VERSION)) + List.of("\"anIgnoredAction.data:\" + aGetAction.data"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "\"anIgnoredAction.data:\" + aGetAction.data", new HashSet<>(Set.of("aGetAction.data"))))); + String bindingValue = "\n(function(ignoredAction1){\n" + "\tlet a = ignoredAction1.data\n" + + "\tlet ignoredAction2 = { data: \"nothing\" }\n" + + "\tlet b = ignoredAction2.data\n" + + "\tlet c = \"ignoredAction3.data\"\n" + + "\t// ignoredAction4.data\n" + + "\treturn aPostAction.data\n" + + "})(anotherPostAction.data)"; + Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of(bindingValue), EVALUATION_VERSION)) + .thenReturn(Flux.just( + Tuples.of(bindingValue, new HashSet<>(Set.of("aPostAction.data", "anotherPostAction.data"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("aPostActionWithAutoExec.data"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "aPostActionWithAutoExec.data", new HashSet<>(Set.of("aPostActionWithAutoExec.data"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("aDBAction.data[0].irrelevant"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "aDBAction.data[0].irrelevant", new HashSet<>(Set.of("aDBAction.data[0].irrelevant"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of(" anotherDBAction.data.optional "), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + " anotherDBAction.data.optional ", new HashSet<>(Set.of("anotherDBAction.data.optional"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("aTableAction.data.child"), EVALUATION_VERSION)) + .thenReturn(Flux.just( + Tuples.of("aTableAction.data.child", new HashSet<>(Set.of("aTableAction.data.child"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.anAsyncCollectionActionWithoutCall.data"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "Collection.anAsyncCollectionActionWithoutCall.data", + new HashSet<>(Set.of("Collection.anAsyncCollectionActionWithoutCall.data"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.aSyncCollectionActionWithoutCall.data"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "Collection.aSyncCollectionActionWithoutCall.data", + new HashSet<>(Set.of("Collection.aSyncCollectionActionWithoutCall.data"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.anAsyncCollectionActionWithCall()"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "Collection.anAsyncCollectionActionWithCall()", + new HashSet<>(Set.of("Collection.anAsyncCollectionActionWithCall"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("Collection.aSyncCollectionActionWithCall()"), EVALUATION_VERSION)) + .thenReturn(Flux.just(Tuples.of( + "Collection.aSyncCollectionActionWithCall()", + new HashSet<>(Set.of("Collection.aSyncCollectionActionWithCall"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("hiddenAction4.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("hiddenAction4.data", new HashSet<>(Set.of("hiddenAction4.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("hiddenAction2.data"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("hiddenAction2.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("hiddenAction2.data", new HashSet<>(Set.of("hiddenAction2.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("hiddenAction1.data"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("hiddenAction1.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("hiddenAction1.data", new HashSet<>(Set.of("hiddenAction1.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("aPostTertiaryAction.data"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("aPostTertiaryAction.data", new HashSet<>(Set.of("aPostTertiaryAction.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("aPostSecondaryAction.data"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("aPostSecondaryAction.data", new HashSet<>(Set.of("aPostSecondaryAction.data"))))); - StepVerifier - .create(testMono) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("aPostTertiaryAction.data"), EVALUATION_VERSION)) + .thenReturn(Flux.just( + Tuples.of("aPostTertiaryAction.data", new HashSet<>(Set.of("aPostTertiaryAction.data"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("aPostSecondaryAction.data"), EVALUATION_VERSION)) + .thenReturn(Flux.just( + Tuples.of("aPostSecondaryAction.data", new HashSet<>(Set.of("aPostSecondaryAction.data"))))); + StepVerifier.create(testMono) .assertNext(layout -> { assertThat(layout).isNotNull(); assertThat(layout.getId()).isNotNull(); @@ -989,29 +1029,29 @@ public void getActionsExecuteOnLoadWithAstLogic() { "hiddenAction2", "hiddenAction4", "aPostAction", - "anotherPostAction" - ); - - Set<String> secondSetPageLoadActions = Set.of( - "aTableAction", - "anotherDBAction" - ); - - Set<String> thirdSetPageLoadActions = Set.of( - "aDBAction" - ); - - Set<String> fourthSetPageLoadActions = Set.of( - "aPostActionWithAutoExec", - "Collection.anAsyncCollectionActionWithoutCall" - ); - assertThat(layout.getLayoutOnLoadActions().get(0).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + "anotherPostAction"); + + Set<String> secondSetPageLoadActions = Set.of("aTableAction", "anotherDBAction"); + + Set<String> thirdSetPageLoadActions = Set.of("aDBAction"); + + Set<String> fourthSetPageLoadActions = + Set.of("aPostActionWithAutoExec", "Collection.anAsyncCollectionActionWithoutCall"); + assertThat(layout.getLayoutOnLoadActions().get(0).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(firstSetPageLoadActions); - assertThat(layout.getLayoutOnLoadActions().get(1).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(1).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(secondSetPageLoadActions); - assertThat(layout.getLayoutOnLoadActions().get(2).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(2).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(thirdSetPageLoadActions); - assertThat(layout.getLayoutOnLoadActions().get(3).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(3).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(fourthSetPageLoadActions); Set<DslActionDTO> flatOnLoadActions = new HashSet<>(); for (Set<DslActionDTO> actions : layout.getLayoutOnLoadActions()) { @@ -1026,12 +1066,13 @@ public void getActionsExecuteOnLoadWithAstLogic() { .verifyComplete(); Mono<Tuple2<ActionDTO, ActionDTO>> actionDTOMono = pageMono.flatMap(page -> { - return newActionService.findByUnpublishedNameAndPageId("aGetAction", page.getId(), AclPermission.MANAGE_ACTIONS) - .zipWith(newActionService.findByUnpublishedNameAndPageId("ignoredAction1", page.getId(), AclPermission.MANAGE_ACTIONS)); + return newActionService + .findByUnpublishedNameAndPageId("aGetAction", page.getId(), AclPermission.MANAGE_ACTIONS) + .zipWith(newActionService.findByUnpublishedNameAndPageId( + "ignoredAction1", page.getId(), AclPermission.MANAGE_ACTIONS)); }); - StepVerifier - .create(actionDTOMono) + StepVerifier.create(actionDTOMono) .assertNext(tuple -> { assertThat(tuple.getT1().getExecuteOnLoad()).isTrue(); assertThat(tuple.getT2().getExecuteOnLoad()).isNotEqualTo(Boolean.TRUE); @@ -1039,7 +1080,6 @@ public void getActionsExecuteOnLoadWithAstLogic() { .verifyComplete(); } - /** * This test is meant for the older string based on page load logic that persists today for older deployments. * The expectation is the same as the previous test, except that only valid global references are marked to run on page load. @@ -1057,8 +1097,10 @@ public void getActionsExecuteOnLoadWithAstLogic() { @Test @WithUserDetails(value = "api_user") public void getActionsExecuteOnLoadWithoutAstLogic() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(Mockito.anyList(), Mockito.anyInt())).thenCallRealMethod(); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding(Mockito.anyList(), Mockito.anyInt())) + .thenCallRealMethod(); PageDTO testPage = new PageDTO(); testPage.setName("ActionsExecuteOnLoad Test Page2"); @@ -1070,8 +1112,7 @@ public void getActionsExecuteOnLoadWithoutAstLogic() { Mono<LayoutDTO> testMono = createComplexAppForExecuteOnLoad(pageMono); - StepVerifier - .create(testMono) + StepVerifier.create(testMono) .assertNext(layout -> { assertThat(layout).isNotNull(); assertThat(layout.getId()).isNotNull(); @@ -1091,23 +1132,23 @@ public void getActionsExecuteOnLoadWithoutAstLogic() { "ignoredAction1", "ignoredAction2", "ignoredAction3", - "ignoredAction4" - ); - - Set<String> secondSetPageLoadActions = Set.of( - "aTableAction", - "anotherDBAction" - ); - - Set<String> thirdSetPageLoadActions = Set.of( - "aPostActionWithAutoExec", - "Collection.anAsyncCollectionActionWithoutCall" - ); - assertThat(layout.getLayoutOnLoadActions().get(0).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + "ignoredAction4"); + + Set<String> secondSetPageLoadActions = Set.of("aTableAction", "anotherDBAction"); + + Set<String> thirdSetPageLoadActions = + Set.of("aPostActionWithAutoExec", "Collection.anAsyncCollectionActionWithoutCall"); + assertThat(layout.getLayoutOnLoadActions().get(0).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(firstSetPageLoadActions); - assertThat(layout.getLayoutOnLoadActions().get(1).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(1).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(secondSetPageLoadActions); - assertThat(layout.getLayoutOnLoadActions().get(2).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(2).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(thirdSetPageLoadActions); Set<DslActionDTO> flatOnLoadActions = new HashSet<>(); for (Set<DslActionDTO> actions : layout.getLayoutOnLoadActions()) { @@ -1122,12 +1163,13 @@ public void getActionsExecuteOnLoadWithoutAstLogic() { .verifyComplete(); Mono<Tuple2<ActionDTO, ActionDTO>> actionDTOMono = pageMono.flatMap(page -> { - return newActionService.findByUnpublishedNameAndPageId("aGetAction", page.getId(), AclPermission.MANAGE_ACTIONS) - .zipWith(newActionService.findByUnpublishedNameAndPageId("ignoredAction1", page.getId(), AclPermission.MANAGE_ACTIONS)); + return newActionService + .findByUnpublishedNameAndPageId("aGetAction", page.getId(), AclPermission.MANAGE_ACTIONS) + .zipWith(newActionService.findByUnpublishedNameAndPageId( + "ignoredAction1", page.getId(), AclPermission.MANAGE_ACTIONS)); }); - StepVerifier - .create(actionDTOMono) + StepVerifier.create(actionDTOMono) .assertNext(tuple -> { assertThat(tuple.getT1().getExecuteOnLoad()).isTrue(); assertThat(tuple.getT2().getExecuteOnLoad()).isTrue(); @@ -1135,11 +1177,11 @@ public void getActionsExecuteOnLoadWithoutAstLogic() { .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void testIncorrectDynamicBindingPathInDsl() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); PageDTO testPage = new PageDTO(); testPage.setName("testIncorrectDynamicBinding Test Page"); @@ -1168,9 +1210,7 @@ public void testIncorrectDynamicBindingPathInDsl() { .zipWhen(page1 -> { Layout layout = new Layout(); - JSONObject obj = new JSONObject(Map.of( - "key", "value" - )); + JSONObject obj = new JSONObject(Map.of("key", "value")); layout.setDsl(obj); return layoutService.createLayout(page1.getId(), layout); @@ -1188,33 +1228,39 @@ public void testIncorrectDynamicBindingPathInDsl() { "type", "test_type", "key", "value-updated", "another", "Hello people of the {{input1.text}} planet!", - "dynamicGet", "some dynamic {{aGetAction.data}}" - )); + "dynamicGet", "some dynamic {{aGetAction.data}}")); JSONArray dynamicBindingsPathList = new JSONArray(); - dynamicBindingsPathList.add( - new JSONObject(Map.of("key", "dynamicGet_IncorrectKey")) - ); + dynamicBindingsPathList.add(new JSONObject(Map.of("key", "dynamicGet_IncorrectKey"))); obj.put("dynamicBindingPathList", dynamicBindingsPathList); newLayout.setDsl(obj); - return layoutActionService.updateLayout(page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); + return layoutActionService.updateLayout( + page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); }); - StepVerifier - .create(testMono) + StepVerifier.create(testMono) .expectErrorMatches(throwable -> { assertThat(throwable).isInstanceOf(AppsmithException.class); ObjectMapper objectMapper = new ObjectMapper(); Object oldParent = null; try { - oldParent = objectMapper.readTree("{\"widgetName\":\"testWidget\",\"dynamicBindingPathList\":[{\"key\":\"dynamicGet_IncorrectKey\"}],\"widgetId\":\"id\",\"another\":\"Hello people of the {{input1.text}} planet!\",\"dynamicGet\":\"some dynamic {{aGetAction.data}}\",\"type\":\"test_type\",\"key\":\"value-updated\"}"); + oldParent = objectMapper.readTree( + "{\"widgetName\":\"testWidget\",\"dynamicBindingPathList\":[{\"key\":\"dynamicGet_IncorrectKey\"}],\"widgetId\":\"id\",\"another\":\"Hello people of the {{input1.text}} planet!\",\"dynamicGet\":\"some dynamic {{aGetAction.data}}\",\"type\":\"test_type\",\"key\":\"value-updated\"}"); } catch (JsonProcessingException e) { Assertions.fail("Incorrect initialization of expected DSL"); } - assertThat(throwable.getMessage()).isEqualTo( - AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE.getMessage("test_type", "testWidget", "id", "dynamicGet_IncorrectKey", pageId, layoutId.get(), oldParent, "dynamicGet_IncorrectKey", "New element is null") - ); + assertThat(throwable.getMessage()) + .isEqualTo(AppsmithError.INVALID_DYNAMIC_BINDING_REFERENCE.getMessage( + "test_type", + "testWidget", + "id", + "dynamicGet_IncorrectKey", + pageId, + layoutId.get(), + oldParent, + "dynamicGet_IncorrectKey", + "New element is null")); return true; }) .verify(); @@ -1223,7 +1269,8 @@ public void testIncorrectDynamicBindingPathInDsl() { @Test @WithUserDetails(value = "api_user") public void testIncorrectMustacheExpressionInBindingInDsl() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); PageDTO testPage = new PageDTO(); testPage.setName("testIncorrectMustacheExpressionInBinding Test Page"); @@ -1250,9 +1297,7 @@ public void testIncorrectMustacheExpressionInBindingInDsl() { .zipWhen(page1 -> { Layout layout = new Layout(); - JSONObject obj = new JSONObject(Map.of( - "key", "value" - )); + JSONObject obj = new JSONObject(Map.of("key", "value")); layout.setDsl(obj); return layoutService.createLayout(page1.getId(), layout); @@ -1268,21 +1313,18 @@ public void testIncorrectMustacheExpressionInBindingInDsl() { "widgetId", "id", "type", "test_type", "key", "value-updated", - "dynamicGet", "a\"{{aGetAction\"/'\"'}}\"\"" - )); + "dynamicGet", "a\"{{aGetAction\"/'\"'}}\"\"")); JSONArray dynamicBindingsPathList = new JSONArray(); - dynamicBindingsPathList.add( - new JSONObject(Map.of("key", "dynamicGet")) - ); + dynamicBindingsPathList.add(new JSONObject(Map.of("key", "dynamicGet"))); obj.put("dynamicBindingPathList", dynamicBindingsPathList); newLayout.setDsl(obj); - return layoutActionService.updateLayout(page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); + return layoutActionService.updateLayout( + page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); }); - StepVerifier - .create(testMono) + StepVerifier.create(testMono) .assertNext(layoutDTO -> { // We have reached here means we didn't get a throwable. That's good assertThat(layoutDTO).isNotNull(); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/MockDataServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/MockDataServiceTest.java index 7944cc2c0b19..34bd4c52ef4c 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/MockDataServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/MockDataServiceTest.java @@ -105,16 +105,18 @@ public void setup() { Workspace toCreate = new Workspace(); toCreate.setName("MockDataServiceTest"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); } - if (testPage == null) { - //Create application and page which will be used by the tests to create actions for. + // Create application and page which will be used by the tests to create actions for. Application application = new Application(); application.setName(UUID.randomUUID().toString()); - testApp = applicationPageService.createApplication(application, workspaceId).block(); + testApp = applicationPageService + .createApplication(application, workspaceId) + .block(); final String pageId = testApp.getPages().get(0).getId(); testPage = newPageService.findPageById(pageId, READ_PAGES, false).block(); } @@ -123,13 +125,14 @@ public void setup() { @Test @WithUserDetails(value = "api_user") public void testGetMockDataSets() { - StepVerifier - .create(mockDataService.getMockDataSet()) + StepVerifier.create(mockDataService.getMockDataSet()) .assertNext(mockDataSets -> { assertThat(mockDataSets.getMockdbs()).hasSize(2); assertThat(mockDataSets.getMockdbs()) - .anyMatch(data -> data.getName().equals("Movies") && data.getPackageName().equals("mongo-plugin")) - .anyMatch(data -> data.getName().equals("Users") && data.getPackageName().equals("postgres-plugin")); + .anyMatch(data -> data.getName().equals("Movies") + && data.getPackageName().equals("mongo-plugin")) + .anyMatch(data -> data.getName().equals("Users") + && data.getPackageName().equals("postgres-plugin")); }) .verifyComplete(); } @@ -138,13 +141,15 @@ public void testGetMockDataSets() { @WithUserDetails(value = "api_user") public void testCreateMockDataSetsMongo() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("MockDataServiceTest testCreateMockDataSetsMongo"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); String workspaceId = workspace.getId(); Plugin pluginMono = pluginService.findByName("Installed Plugin Name").block(); @@ -155,7 +160,8 @@ public void testCreateMockDataSetsMongo() { mockDataSource.setPluginId(pluginMono.getId()); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); List<PermissionGroup> permissionGroups = workspaceResponse .flatMapMany(savedWorkspace -> { @@ -167,39 +173,52 @@ public void testCreateMockDataSetsMongo() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - StepVerifier - .create(mockDataService.createMockDataSet(mockDataSource, defaultEnvironmentId)) + StepVerifier.create(mockDataService.createMockDataSet(mockDataSource, defaultEnvironmentId)) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(pluginMono.getId()); assertThat(createdDatasource.getName()).isEqualTo("Movies"); - Policy manageDatasourcePolicy = Policy.builder().permission(MANAGE_DATASOURCES.getValue()) + Policy manageDatasourcePolicy = Policy.builder() + .permission(MANAGE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readDatasourcePolicy = Policy.builder().permission(READ_DATASOURCES.getValue()) + Policy readDatasourcePolicy = Policy.builder() + .permission(READ_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeDatasourcePolicy = Policy.builder().permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeDatasourcePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - DatasourceStorageDTO createdDatasourceStorageDTO = createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); - DatasourceConfiguration datasourceConfiguration = createdDatasourceStorageDTO.getDatasourceConfiguration(); + DatasourceStorageDTO createdDatasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DatasourceConfiguration datasourceConfiguration = + createdDatasourceStorageDTO.getDatasourceConfiguration(); DBAuth auth = (DBAuth) datasourceConfiguration.getAuthentication(); assertThat(createdDatasource.getPolicies()).isNotEmpty(); - assertThat(createdDatasource.getPolicies()).containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); - assertThat(datasourceConfiguration.getProperties().get(0).getValue()).isEqualTo("Yes"); - assertThat(datasourceConfiguration.getProperties().get(0).getKey()).isEqualTo("Use mongo connection string URI"); + assertThat(createdDatasource.getPolicies()) + .containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); + assertThat(datasourceConfiguration.getProperties().get(0).getValue()) + .isEqualTo("Yes"); + assertThat(datasourceConfiguration.getProperties().get(0).getKey()) + .isEqualTo("Use mongo connection string URI"); assertThat(auth.getDatabaseName()).isEqualTo("movies"); assertThat(auth.getUsername()).isEqualTo("mockdb-admin"); Assertions.assertTrue(createdDatasource.getIsMock()); @@ -211,8 +230,8 @@ public void testCreateMockDataSetsMongo() { @Test @WithUserDetails(value = "api_user") public void testCreateMockDataSetsPostgres() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); - + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Plugin pluginMono = pluginService.findByName("Installed Plugin Name").block(); MockDataSource mockDataSource = new MockDataSource(); @@ -222,7 +241,8 @@ public void testCreateMockDataSetsPostgres() { mockDataSource.setPluginId(pluginMono.getId()); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); List<PermissionGroup> permissionGroups = workspaceResponse .flatMapMany(savedWorkspace -> { @@ -234,36 +254,48 @@ public void testCreateMockDataSetsPostgres() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - StepVerifier - .create(mockDataService.createMockDataSet(mockDataSource, defaultEnvironmentId)) + StepVerifier.create(mockDataService.createMockDataSet(mockDataSource, defaultEnvironmentId)) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(pluginMono.getId()); assertThat(createdDatasource.getName()).isEqualTo("Users"); - Policy manageDatasourcePolicy = Policy.builder().permission(MANAGE_DATASOURCES.getValue()) + Policy manageDatasourcePolicy = Policy.builder() + .permission(MANAGE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readDatasourcePolicy = Policy.builder().permission(READ_DATASOURCES.getValue()) + Policy readDatasourcePolicy = Policy.builder() + .permission(READ_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeDatasourcePolicy = Policy.builder().permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeDatasourcePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - DatasourceStorageDTO createdDatasourceStorageDTO = createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); - DBAuth auth = (DBAuth) createdDatasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); + DatasourceStorageDTO createdDatasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DBAuth auth = (DBAuth) createdDatasourceStorageDTO + .getDatasourceConfiguration() + .getAuthentication(); assertThat(createdDatasource.getPolicies()).isNotEmpty(); - assertThat(createdDatasource.getPolicies()).containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); + assertThat(createdDatasource.getPolicies()) + .containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); assertThat(auth.getDatabaseName()).isEqualTo("users"); assertThat(auth.getUsername()).isEqualTo("users"); }) @@ -274,15 +306,18 @@ public void testCreateMockDataSetsPostgres() { @WithUserDetails(value = "api_user") public void testCreateMockDataSetsDuplicateName() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("MockDataServiceTest testCreateMockDataSetsDuplicateName"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); String workspaceId = workspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); Plugin pluginMono = pluginService.findByName("Installed Plugin Name").block(); @@ -292,7 +327,8 @@ public void testCreateMockDataSetsDuplicateName() { mockDataSource.setPackageName("mongo-plugin"); mockDataSource.setPluginId(pluginMono.getId()); - Mono<Datasource> datasourceMono = mockDataService.createMockDataSet(mockDataSource, defaultEnvironmentId ) + Mono<Datasource> datasourceMono = mockDataService + .createMockDataSet(mockDataSource, defaultEnvironmentId) .flatMap(datasource -> mockDataService.createMockDataSet(mockDataSource, defaultEnvironmentId)); List<PermissionGroup> permissionGroups = Mono.just(workspace) @@ -305,40 +341,53 @@ public void testCreateMockDataSetsDuplicateName() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - StepVerifier - .create(datasourceMono) + StepVerifier.create(datasourceMono) .assertNext(createdDatasource -> { assertThat(createdDatasource.getId()).isNotEmpty(); assertThat(createdDatasource.getPluginId()).isEqualTo(pluginMono.getId()); assertThat(createdDatasource.getName()).isEqualTo("Movies (1)"); - Policy manageDatasourcePolicy = Policy.builder().permission(MANAGE_DATASOURCES.getValue()) + Policy manageDatasourcePolicy = Policy.builder() + .permission(MANAGE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readDatasourcePolicy = Policy.builder().permission(READ_DATASOURCES.getValue()) + Policy readDatasourcePolicy = Policy.builder() + .permission(READ_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeDatasourcePolicy = Policy.builder().permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeDatasourcePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - DatasourceStorageDTO createdDatasourceStorageDTO = createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); - DatasourceConfiguration datasourceConfiguration = createdDatasourceStorageDTO.getDatasourceConfiguration(); + DatasourceStorageDTO createdDatasourceStorageDTO = + createdDatasource.getDatasourceStorages().get(defaultEnvironmentId); + DatasourceConfiguration datasourceConfiguration = + createdDatasourceStorageDTO.getDatasourceConfiguration(); DBAuth auth = (DBAuth) datasourceConfiguration.getAuthentication(); assertThat(createdDatasource.getPolicies()).isNotEmpty(); - assertThat(createdDatasource.getPolicies()).containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); - assertThat(datasourceConfiguration.getProperties().get(0).getValue()).isEqualTo("Yes"); - assertThat(datasourceConfiguration.getProperties().get(0).getKey()).isEqualTo("Use mongo connection string URI"); + assertThat(createdDatasource.getPolicies()) + .containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); + assertThat(datasourceConfiguration.getProperties().get(0).getValue()) + .isEqualTo("Yes"); + assertThat(datasourceConfiguration.getProperties().get(0).getKey()) + .isEqualTo("Use mongo connection string URI"); assertThat(auth.getDatabaseName()).isEqualTo("movies"); assertThat(auth.getUsername()).isEqualTo("mockdb-admin"); }) diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java index 10628e1f4408..28d86716c31f 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java @@ -53,14 +53,14 @@ public class NewPageServiceTest { @WithUserDetails("api_user") public void testCreateDefault() { Set<String> permissionGroupIds = permissionGroupRepository.findAll().collectList().block().stream() - .map(PermissionGroup::getId).collect(Collectors.toSet()); + .map(PermissionGroup::getId) + .collect(Collectors.toSet()); PageDTO pageDTO = new PageDTO(); pageDTO.setApplicationId("test-application-id"); DefaultResources testDefaultResources = new DefaultResources(); pageDTO.setDefaultResources(testDefaultResources); - Policy testPolicy = Policy.builder() - .permissionGroups(permissionGroupIds) - .build(); + Policy testPolicy = + Policy.builder().permissionGroups(permissionGroupIds).build(); pageDTO.setPolicies(Set.of(testPolicy)); StepVerifier.create(newPageService.createDefault(pageDTO)) .assertNext(pageDTO1 -> { @@ -73,9 +73,7 @@ public void testCreateDefault() { @Test @WithUserDetails("api_user") public void findApplicationPages_WhenApplicationIdAndPageIdNotPresent_ThrowsException() { - StepVerifier.create( - newPageService.findApplicationPages(null, null, "master", ApplicationMode.EDIT) - ) + StepVerifier.create(newPageService.findApplicationPages(null, null, "master", ApplicationMode.EDIT)) .expectError(AppsmithException.class) .verify(); } @@ -86,7 +84,8 @@ public void findApplicationPages_WhenApplicationIdPresent_ReturnsPages() { String randomId = UUID.randomUUID().toString(); Workspace workspace = new Workspace(); workspace.setName("org_" + randomId); - Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService.create(workspace) + Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService + .create(workspace) .flatMap(createdOrg -> { Application application = new Application(); application.setName("app_" + randomId); @@ -98,16 +97,19 @@ public void findApplicationPages_WhenApplicationIdPresent_ReturnsPages() { pageDTO.setApplicationId(application.getId()); return applicationPageService.createPage(pageDTO); }) - .flatMap(pageDTO -> - newPageService.findApplicationPages(pageDTO.getApplicationId(), null, null, ApplicationMode.EDIT) - ); + .flatMap(pageDTO -> newPageService.findApplicationPages( + pageDTO.getApplicationId(), null, null, ApplicationMode.EDIT)); - StepVerifier.create(applicationPagesDTOMono).assertNext(applicationPagesDTO -> { + StepVerifier.create(applicationPagesDTOMono) + .assertNext(applicationPagesDTO -> { assertThat(applicationPagesDTO.getApplication()).isNotNull(); - assertThat(applicationPagesDTO.getApplication().getViewMode()).isFalse(); + assertThat(applicationPagesDTO.getApplication().getViewMode()) + .isFalse(); assertThat(applicationPagesDTO.getApplication().getName()).isEqualTo("app_" + randomId); assertThat(applicationPagesDTO.getPages()).isNotEmpty(); - applicationPagesDTO.getPages().forEach(pageNameIdDTO -> assertThat(pageNameIdDTO.getUserPermissions()).isNotEmpty()); + applicationPagesDTO.getPages().forEach(pageNameIdDTO -> assertThat( + pageNameIdDTO.getUserPermissions()) + .isNotEmpty()); }) .verifyComplete(); } @@ -118,7 +120,8 @@ public void findApplicationPagesInViewMode_WhenApplicationIdPresent_ReturnsViewM String randomId = UUID.randomUUID().toString(); Workspace workspace = new Workspace(); workspace.setName("org_" + randomId); - Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService.create(workspace) + Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService + .create(workspace) .flatMap(createdOrg -> { Application application = new Application(); application.setName("app_" + randomId); @@ -128,21 +131,25 @@ public void findApplicationPagesInViewMode_WhenApplicationIdPresent_ReturnsViewM PageDTO pageDTO = new PageDTO(); pageDTO.setName("page_" + randomId); pageDTO.setApplicationId(application.getId()); - Mono<PageDTO> pageDTOMono = applicationPageService.createPage(pageDTO).cache(); + Mono<PageDTO> pageDTOMono = + applicationPageService.createPage(pageDTO).cache(); return pageDTOMono .then(applicationPageService.publish(application.getId(), true)) .then(pageDTOMono); }) - .flatMap(pageDTO -> - newPageService.findApplicationPages(pageDTO.getApplicationId(), null, null, ApplicationMode.PUBLISHED) - ); + .flatMap(pageDTO -> newPageService.findApplicationPages( + pageDTO.getApplicationId(), null, null, ApplicationMode.PUBLISHED)); - StepVerifier.create(applicationPagesDTOMono).assertNext(applicationPagesDTO -> { + StepVerifier.create(applicationPagesDTOMono) + .assertNext(applicationPagesDTO -> { assertThat(applicationPagesDTO.getApplication()).isNotNull(); - assertThat(applicationPagesDTO.getApplication().getViewMode()).isTrue(); + assertThat(applicationPagesDTO.getApplication().getViewMode()) + .isTrue(); assertThat(applicationPagesDTO.getApplication().getName()).isEqualTo("app_" + randomId); assertThat(applicationPagesDTO.getPages()).isNotEmpty(); - applicationPagesDTO.getPages().forEach(pageNameIdDTO -> assertThat(pageNameIdDTO.getUserPermissions()).isNotEmpty()); + applicationPagesDTO.getPages().forEach(pageNameIdDTO -> assertThat( + pageNameIdDTO.getUserPermissions()) + .isNotEmpty()); }) .verifyComplete(); } @@ -153,7 +160,8 @@ public void findApplicationPages_WhenPageIdPresent_ReturnsPages() { String randomId = UUID.randomUUID().toString(); Workspace workspace = new Workspace(); workspace.setName("org_" + randomId); - Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService.create(workspace) + Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application application = new Application(); application.setName("app_" + randomId); @@ -166,14 +174,16 @@ public void findApplicationPages_WhenPageIdPresent_ReturnsPages() { return applicationPageService.createPage(pageDTO); }) .flatMap(pageDTO -> - newPageService.findApplicationPages(null, pageDTO.getId(), null, ApplicationMode.EDIT) - ); + newPageService.findApplicationPages(null, pageDTO.getId(), null, ApplicationMode.EDIT)); - StepVerifier.create(applicationPagesDTOMono).assertNext(applicationPagesDTO -> { + StepVerifier.create(applicationPagesDTOMono) + .assertNext(applicationPagesDTO -> { assertThat(applicationPagesDTO.getApplication()).isNotNull(); assertThat(applicationPagesDTO.getApplication().getName()).isEqualTo("app_" + randomId); assertThat(applicationPagesDTO.getPages()).isNotEmpty(); - applicationPagesDTO.getPages().forEach(pageNameIdDTO -> assertThat(pageNameIdDTO.getUserPermissions()).isNotEmpty()); + applicationPagesDTO.getPages().forEach(pageNameIdDTO -> assertThat( + pageNameIdDTO.getUserPermissions()) + .isNotEmpty()); }) .verifyComplete(); } @@ -184,7 +194,8 @@ public void findApplicationPagesByApplicationIdViewMode_WhenApplicationHasNoHome String randomId = UUID.randomUUID().toString(); Workspace workspace = new Workspace(); workspace.setName("org_" + randomId); - Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService.create(workspace) + Mono<ApplicationPagesDTO> applicationPagesDTOMono = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application application = new Application(); application.setName("app_" + randomId); @@ -194,13 +205,16 @@ public void findApplicationPagesByApplicationIdViewMode_WhenApplicationHasNoHome // set isDefault=false to the default page ApplicationPage applicationPage = application.getPages().get(0); applicationPage.setIsDefault(false); - return applicationService.save(application).then( - newPageService.findApplicationPages(null, applicationPage.getId(), null, ApplicationMode.EDIT) - ); + return applicationService + .save(application) + .then(newPageService.findApplicationPages( + null, applicationPage.getId(), null, ApplicationMode.EDIT)); }); - StepVerifier.create(applicationPagesDTOMono).assertNext(applicationPagesDTO -> { - assertThat(applicationPagesDTO.getPages().get(0).getIsDefault()).isTrue(); + StepVerifier.create(applicationPagesDTOMono) + .assertNext(applicationPagesDTO -> { + assertThat(applicationPagesDTO.getPages().get(0).getIsDefault()) + .isTrue(); }) .verifyComplete(); } @@ -211,7 +225,8 @@ public void findApplicationPage_CheckPageIcon_IsValid() { String randomId = UUID.randomUUID().toString(); Workspace workspace = new Workspace(); workspace.setName("org_" + randomId); - Mono<PageDTO> applicationPageDTOMono = workspaceService.create(workspace) + Mono<PageDTO> applicationPageDTOMono = workspaceService + .create(workspace) .flatMap(createdWorkspace -> { Application application = new Application(); application.setName("app_" + randomId); @@ -225,15 +240,14 @@ public void findApplicationPage_CheckPageIcon_IsValid() { return applicationPageService.createPage(pageDTO); }) .flatMap(pageDTO -> - applicationPageService.getPageByBranchAndDefaultPageId(pageDTO.getId(), null, false) - ); + applicationPageService.getPageByBranchAndDefaultPageId(pageDTO.getId(), null, false)); - StepVerifier.create(applicationPageDTOMono).assertNext(applicationPageDTO -> { + StepVerifier.create(applicationPageDTOMono) + .assertNext(applicationPageDTO -> { assertThat(applicationPageDTO.getApplicationId()).isNotNull(); assertThat(applicationPageDTO.getName()).isEqualTo("page_" + randomId); assertThat(applicationPageDTO.getIcon()).isEqualTo("flight"); }) .verifyComplete(); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NotificationServiceImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NotificationServiceImplTest.java index 7af9c4fea33c..b306f413552c 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NotificationServiceImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NotificationServiceImplTest.java @@ -35,29 +35,44 @@ @ExtendWith(SpringExtension.class) public class NotificationServiceImplTest { NotificationService notificationService; + @MockBean private Scheduler scheduler; + @MockBean private Validator validator; + @MockBean private MongoConverter mongoConverter; + @MockBean private ReactiveMongoTemplate reactiveMongoTemplate; + @MockBean private NotificationRepository repository; + @MockBean private AnalyticsService analyticsService; + @MockBean private SessionUserService sessionUserService; + @MockBean private ResponseUtils responseUtils; + private User currentUser; @BeforeEach public void setUp() { notificationService = new NotificationServiceImpl( - scheduler, validator, mongoConverter, reactiveMongoTemplate, - repository, analyticsService, sessionUserService, responseUtils); + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + sessionUserService, + responseUtils); currentUser = new User(); currentUser.setEmail("sample-email"); @@ -65,7 +80,8 @@ public void setUp() { // mock the repository to return count as 100 Mockito.when(repository.countByForUsername(currentUser.getUsername())).thenReturn(Mono.just(100L)); // mock the repository to return unread count as 5 - Mockito.when(repository.countByForUsernameAndIsReadIsFalse(currentUser.getUsername())).thenReturn(Mono.just(5L)); + Mockito.when(repository.countByForUsernameAndIsReadIsFalse(currentUser.getUsername())) + .thenReturn(Mono.just(5L)); } private List<Notification> createSampleNotificationList() { @@ -85,12 +101,11 @@ public void get_WhenNoBeforeParamProvided_ReturnsData() { // mock the repository to return the sample list of notification when called with current time Mockito.when(repository.findByForUsernameAndCreatedAtBefore( - eq(currentUser.getUsername()), Mockito.any(Instant.class), Mockito.any(Pageable.class)) - ).thenReturn(Flux.fromIterable(notificationList)); + eq(currentUser.getUsername()), Mockito.any(Instant.class), Mockito.any(Pageable.class))) + .thenReturn(Flux.fromIterable(notificationList)); Flux<Notification> notificationFlux = notificationService.get(new LinkedMultiValueMap<>()); - StepVerifier - .create(notificationFlux.collectList()) + StepVerifier.create(notificationFlux.collectList()) .assertNext(listResponseDTO -> { assertThat(listResponseDTO.size()).isEqualTo(notificationList.size()); }) @@ -105,8 +120,8 @@ public void get_WhenValidBeforeParamExists_ReturnsData() { // mock the repository to return the sample list of notification Mockito.when(repository.findByForUsernameAndCreatedAtBefore( - eq(currentUser.getUsername()), eq(instant), Mockito.any(Pageable.class)) - ).thenReturn(Flux.fromIterable(notificationList)); + eq(currentUser.getUsername()), eq(instant), Mockito.any(Pageable.class))) + .thenReturn(Flux.fromIterable(notificationList)); // add the sample pagination parameters MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); @@ -114,8 +129,7 @@ public void get_WhenValidBeforeParamExists_ReturnsData() { Flux<Notification> notificationFlux = notificationService.get(params); - StepVerifier - .create(notificationFlux.collectList()) + StepVerifier.create(notificationFlux.collectList()) .assertNext(listResponseDTO -> { assertThat(listResponseDTO.size()).isEqualTo(notificationList.size()); }) @@ -130,8 +144,7 @@ public void get_WhenInvalidValidBeforeParam_ThrowsException() { Flux<Notification> notificationFlux = notificationService.get(params); - StepVerifier - .create(notificationFlux.collectList()) + StepVerifier.create(notificationFlux.collectList()) .expectErrorMessage(AppsmithError.INVALID_PARAMETER.getMessage("as beforeDate")) .verify(); } @@ -141,12 +154,10 @@ public void updateIsRead_WhenUpdateAll_ReturnSuccessfully() { UpdateIsReadNotificationDTO dto = new UpdateIsReadNotificationDTO(); dto.setIsRead(true); - Mockito.when(repository.updateIsReadByForUsername(currentUser.getUsername(), true)).thenReturn( - Mono.just(Mockito.mock(UpdateResult.class)) - ); + Mockito.when(repository.updateIsReadByForUsername(currentUser.getUsername(), true)) + .thenReturn(Mono.just(Mockito.mock(UpdateResult.class))); - StepVerifier - .create(notificationService.updateIsRead(dto)) + StepVerifier.create(notificationService.updateIsRead(dto)) .assertNext(responseDTO -> { assertThat(responseDTO.getIsRead()).isTrue(); }) @@ -159,18 +170,14 @@ public void updateIsRead_WhenUpdateById_ReturnSuccessfully() { dto.setIsRead(true); dto.setIdList(List.of("sample-id-1", "sample-id-2", "sample-id-3")); - Mockito.when(repository.updateIsReadByForUsernameAndIdList( - currentUser.getUsername(), dto.getIdList(), true) - ).thenReturn( - Mono.just(Mockito.mock(UpdateResult.class)) - ); + Mockito.when(repository.updateIsReadByForUsernameAndIdList(currentUser.getUsername(), dto.getIdList(), true)) + .thenReturn(Mono.just(Mockito.mock(UpdateResult.class))); - StepVerifier - .create(notificationService.updateIsRead(dto)) + StepVerifier.create(notificationService.updateIsRead(dto)) .assertNext(responseDTO -> { assertThat(responseDTO.getIsRead()).isTrue(); assertThat(responseDTO.getIdList()).isEqualTo(dto.getIdList()); }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PageServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PageServiceTest.java index 4afd371bfeac..f754955a36e3 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PageServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PageServiceTest.java @@ -80,34 +80,49 @@ public class PageServiceTest { static Application gitConnectedApplication = null; static String applicationId = null; static String workspaceId; + @Autowired ApplicationPageService applicationPageService; + @Autowired UserService userService; + @Autowired LayoutService layoutService; + @Autowired WorkspaceService workspaceService; + @Autowired ApplicationService applicationService; + @Autowired NewPageService newPageService; + @Autowired NewActionService newActionService; + @Autowired ActionCollectionService actionCollectionService; + @Autowired PluginRepository pluginRepository; + @MockBean PluginExecutorHelper pluginExecutorHelper; + @MockBean PluginExecutor pluginExecutor; + @Autowired LayoutActionService layoutActionService; + @Autowired LayoutCollectionService layoutCollectionService; + @Autowired ImportExportApplicationService importExportApplicationService; + @Autowired PermissionGroupRepository permissionGroupRepository; @@ -120,7 +135,8 @@ public void setup() { Workspace toCreate = new Workspace(); toCreate.setName("PageServiceTest"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); } } @@ -129,7 +145,9 @@ public void setupTestApplication() { if (application == null) { Application newApp = new Application(); newApp.setName(UUID.randomUUID().toString()); - application = applicationPageService.createApplication(newApp, workspaceId).block(); + application = applicationPageService + .createApplication(newApp, workspaceId) + .block(); applicationId = application.getId(); } } @@ -140,14 +158,18 @@ private Application setupGitConnectedTestApplication(String uniquePrefix) { GitApplicationMetadata gitData = new GitApplicationMetadata(); gitData.setBranchName(uniquePrefix + "_pageServiceTest"); newApp.setGitApplicationMetadata(gitData); - return applicationPageService.createApplication(newApp, workspaceId) + return applicationPageService + .createApplication(newApp, workspaceId) .flatMap(application -> { application.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); - return applicationService.save(application) - .zipWhen(application1 -> importExportApplicationService.exportApplicationById(application1.getId(), gitData.getBranchName())); + return applicationService + .save(application) + .zipWhen(application1 -> importExportApplicationService.exportApplicationById( + application1.getId(), gitData.getBranchName())); }) // Assign the branchName to all the resources connected to the application - .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) + .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) .block(); } @@ -155,12 +177,10 @@ private Application setupGitConnectedTestApplication(String uniquePrefix) { @WithUserDetails(value = "api_user") public void createPageWithNullName() { PageDTO page = new PageDTO(); - Mono<PageDTO> pageMono = Mono.just(page) - .flatMap(applicationPageService::createPage); - StepVerifier - .create(pageMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) + Mono<PageDTO> pageMono = Mono.just(page).flatMap(applicationPageService::createPage); + StepVerifier.create(pageMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) .verify(); } @@ -169,12 +189,12 @@ public void createPageWithNullName() { public void createPageWithNullApplication() { PageDTO page = new PageDTO(); page.setName("Page without application"); - Mono<PageDTO> pageMono = Mono.just(page) - .flatMap(applicationPageService::createPage); - StepVerifier - .create(pageMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.APPLICATION_ID))) + Mono<PageDTO> pageMono = Mono.just(page).flatMap(applicationPageService::createPage); + StepVerifier.create(pageMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.APPLICATION_ID))) .verify(); } @@ -200,8 +220,7 @@ public void createValidPage() throws ParseException { Mono<PageDTO> pageMono = applicationPageService.createPage(testPage).cache(); Object parsedJson = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(FieldName.DEFAULT_PAGE_LAYOUT); - StepVerifier - .create(Mono.zip(pageMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip(pageMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { PageDTO page = tuple.getT1(); assertThat(page).isNotNull(); @@ -216,35 +235,44 @@ public void createValidPage() throws ParseException { List<PermissionGroup> permissionGroups = tuple.getT2(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy deletePagePolicy = Policy.builder().permission(AclPermission.DELETE_PAGES.getValue()) + Policy deletePagePolicy = Policy.builder() + .permission(AclPermission.DELETE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy createPageActionsPolicy = Policy.builder().permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) + Policy createPageActionsPolicy = Policy.builder() + .permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - assertThat(page.getPolicies()).containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, - createPageActionsPolicy); + assertThat(page.getPolicies()) + .containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, createPageActionsPolicy); assertThat(page.getLayouts()).isNotEmpty(); assertThat(page.getLayouts().get(0).getDsl()).isEqualTo(parsedJson); @@ -254,8 +282,7 @@ public void createValidPage() throws ParseException { // Check if defaultResources Mono<NewPage> newPageMono = pageMono.flatMap(pageDTO -> newPageService.getById(pageDTO.getId())); - StepVerifier - .create(newPageMono) + StepVerifier.create(newPageMono) .assertNext(newPage -> { assertThat(newPage.getDefaultResources()).isNotNull(); assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); @@ -290,8 +317,7 @@ public void createValidPageWithLayout() throws ParseException { Mono<PageDTO> pageMono = applicationPageService.createPage(testPage); - StepVerifier - .create(Mono.zip(pageMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip(pageMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { PageDTO page = tuple.getT1(); assertThat(page).isNotNull(); @@ -307,36 +333,44 @@ public void createValidPageWithLayout() throws ParseException { List<PermissionGroup> permissionGroups = tuple.getT2(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy deletePagePolicy = Policy.builder().permission(AclPermission.DELETE_PAGES.getValue()) + Policy deletePagePolicy = Policy.builder() + .permission(AclPermission.DELETE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy createPageActionsPolicy = Policy.builder().permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) + Policy createPageActionsPolicy = Policy.builder() + .permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - assertThat(page.getPolicies()).containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, - createPageActionsPolicy); - + assertThat(page.getPolicies()) + .containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, createPageActionsPolicy); }) .verifyComplete(); } @@ -360,17 +394,15 @@ public void validChangePageNameAndPageIcon() { setupTestApplication(); testPage.setApplicationId(application.getId()); - Mono<PageDTO> pageMono = applicationPageService.createPage(testPage) - .flatMap(page -> { - PageDTO newPage = new PageDTO(); - newPage.setId(page.getId()); - newPage.setName("New Page Name"); - newPage.setIcon("flight"); - return newPageService.updatePage(page.getId(), newPage); - }); + Mono<PageDTO> pageMono = applicationPageService.createPage(testPage).flatMap(page -> { + PageDTO newPage = new PageDTO(); + newPage.setId(page.getId()); + newPage.setName("New Page Name"); + newPage.setIcon("flight"); + return newPageService.updatePage(page.getId(), newPage); + }); - StepVerifier - .create(Mono.zip(pageMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip(pageMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { PageDTO page = tuple.getT1(); assertThat(page).isNotNull(); @@ -385,36 +417,44 @@ public void validChangePageNameAndPageIcon() { List<PermissionGroup> permissionGroups = tuple.getT2(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy deletePagePolicy = Policy.builder().permission(AclPermission.DELETE_PAGES.getValue()) + Policy deletePagePolicy = Policy.builder() + .permission(AclPermission.DELETE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy createPageActionsPolicy = Policy.builder().permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) + Policy createPageActionsPolicy = Policy.builder() + .permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - assertThat(page.getPolicies()).containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, - createPageActionsPolicy); - + assertThat(page.getPolicies()) + .containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, createPageActionsPolicy); }) .verifyComplete(); } @@ -438,16 +478,14 @@ public void updatePage_WhenCustomSlugSet_CustomSlugIsNotUpdated() { setupTestApplication(); testPage.setApplicationId(application.getId()); - Mono<PageDTO> pageMono = applicationPageService.createPage(testPage) - .flatMap(page -> { - PageDTO newPage = new PageDTO(); - newPage.setId(page.getId()); - newPage.setName("New Page Name"); - return newPageService.updatePage(page.getId(), newPage); - }); + Mono<PageDTO> pageMono = applicationPageService.createPage(testPage).flatMap(page -> { + PageDTO newPage = new PageDTO(); + newPage.setId(page.getId()); + newPage.setName("New Page Name"); + return newPageService.updatePage(page.getId(), newPage); + }); - StepVerifier - .create(Mono.zip(pageMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip(pageMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { PageDTO page = tuple.getT1(); assertThat(page).isNotNull(); @@ -462,36 +500,44 @@ public void updatePage_WhenCustomSlugSet_CustomSlugIsNotUpdated() { List<PermissionGroup> permissionGroups = tuple.getT2(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy deletePagePolicy = Policy.builder().permission(AclPermission.DELETE_PAGES.getValue()) + Policy deletePagePolicy = Policy.builder() + .permission(AclPermission.DELETE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy createPageActionsPolicy = Policy.builder().permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) + Policy createPageActionsPolicy = Policy.builder() + .permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - assertThat(page.getPolicies()).containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, - createPageActionsPolicy); - + assertThat(page.getPolicies()) + .containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, createPageActionsPolicy); }) .verifyComplete(); } @@ -499,7 +545,8 @@ public void updatePage_WhenCustomSlugSet_CustomSlugIsNotUpdated() { @Test @WithUserDetails(value = "api_user") public void clonePage() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -513,7 +560,8 @@ public void clonePage() { setupTestApplication(); final String pageId = application.getPages().get(0).getId(); - final PageDTO page = newPageService.findPageById(pageId, READ_PAGES, false).block(); + final PageDTO page = + newPageService.findPageById(pageId, READ_PAGES, false).block(); ActionDTO action = new ActionDTO(); action.setName("PageAction"); @@ -521,7 +569,8 @@ public void clonePage() { Datasource datasource = new Datasource(); datasource.setWorkspaceId(workspaceId); datasource.setName("datasource test name for page test"); - Plugin installed_plugin = pluginRepository.findByPackageName("installed-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("installed-plugin").block(); datasource.setPluginId(installed_plugin.getId()); action.setDatasource(datasource); action.setExecuteOnLoad(true); @@ -551,7 +600,9 @@ public void clonePage() { action.setPageId(page.getId()); - final LayoutDTO layoutDTO = layoutActionService.updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout).block(); + final LayoutDTO layoutDTO = layoutActionService + .updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout) + .block(); layoutActionService.createSingleAction(action, Boolean.FALSE).block(); @@ -575,29 +626,26 @@ public void clonePage() { applicationPageService.publish(applicationId, true).block(); - final Mono<PageDTO> pageMono = applicationPageService.clonePage(page.getId()).cache(); - - Mono<List<NewAction>> actionsMono = - pageMono - .flatMapMany( - page1 -> newActionService - .findByPageId(page1.getId(), READ_ACTIONS)) - .collectList(); + final Mono<PageDTO> pageMono = + applicationPageService.clonePage(page.getId()).cache(); - Mono<List<ActionCollection>> actionCollectionMono = - pageMono - .flatMapMany( - page1 -> actionCollectionService - .findByPageId(page1.getId())) - .collectList(); + Mono<List<NewAction>> actionsMono = pageMono.flatMapMany( + page1 -> newActionService.findByPageId(page1.getId(), READ_ACTIONS)) + .collectList(); - Mono<List<ActionCollection>> actionCollectionInParentPageMono = actionCollectionService - .findByPageId(page.getId()) + Mono<List<ActionCollection>> actionCollectionMono = pageMono.flatMapMany( + page1 -> actionCollectionService.findByPageId(page1.getId())) .collectList(); + Mono<List<ActionCollection>> actionCollectionInParentPageMono = + actionCollectionService.findByPageId(page.getId()).collectList(); - StepVerifier - .create(Mono.zip(pageMono, actionsMono, actionCollectionMono, actionCollectionInParentPageMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip( + pageMono, + actionsMono, + actionCollectionMono, + actionCollectionInParentPageMono, + defaultPermissionGroupsMono)) .assertNext(tuple -> { PageDTO clonedPage = tuple.getT1(); assertThat(clonedPage).isNotNull(); @@ -609,69 +657,89 @@ public void clonePage() { List<PermissionGroup> permissionGroups = tuple.getT5(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy deletePagePolicy = Policy.builder().permission(AclPermission.DELETE_PAGES.getValue()) + Policy deletePagePolicy = Policy.builder() + .permission(AclPermission.DELETE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy createPageActionsPolicy = Policy.builder().permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) + Policy createPageActionsPolicy = Policy.builder() + .permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - assertThat(clonedPage.getPolicies()).containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, - createPageActionsPolicy); + assertThat(clonedPage.getPolicies()) + .containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, createPageActionsPolicy); assertThat(clonedPage.getLayouts()).isNotEmpty(); - assertThat(clonedPage.getLayouts().get(0).getDsl().get("widgetName")).isEqualTo("firstWidget"); + assertThat(clonedPage.getLayouts().get(0).getDsl().get("widgetName")) + .isEqualTo("firstWidget"); assertThat(clonedPage.getLayouts().get(0).getWidgetNames()).isNotEmpty(); - assertThat(clonedPage.getLayouts().get(0).getMongoEscapedWidgetNames()).isNotEmpty(); + assertThat(clonedPage.getLayouts().get(0).getMongoEscapedWidgetNames()) + .isNotEmpty(); assertThat(clonedPage.getLayouts().get(0).getPublishedDsl()).isNullOrEmpty(); // Confirm that the page action got copied as well List<NewAction> actions = tuple.getT2(); assertThat(actions.size()).isEqualTo(2); - NewAction actionWithoutCollection = actions - .stream() - .filter(newAction -> !StringUtils.hasLength(newAction.getUnpublishedAction().getCollectionId())) + NewAction actionWithoutCollection = actions.stream() + .filter(newAction -> !StringUtils.hasLength( + newAction.getUnpublishedAction().getCollectionId())) .findFirst() .orElse(null); - assertThat(actionWithoutCollection.getUnpublishedAction().getName()).isEqualTo("PageAction"); + assertThat(actionWithoutCollection.getUnpublishedAction().getName()) + .isEqualTo("PageAction"); // Confirm that executeOnLoad is cloned as well. - assertThat(actionWithoutCollection.getUnpublishedAction().getExecuteOnLoad()).isTrue(); + assertThat(actionWithoutCollection.getUnpublishedAction().getExecuteOnLoad()) + .isTrue(); // Check if collections got copied too List<ActionCollection> collections = tuple.getT3(); assertThat(collections).hasSize(1); assertThat(collections.get(0).getPublishedCollection()).isNull(); assertThat(collections.get(0).getUnpublishedCollection()).isNotNull(); - assertThat(collections.get(0).getUnpublishedCollection().getPageId()).isEqualTo(clonedPage.getId()); + assertThat(collections.get(0).getUnpublishedCollection().getPageId()) + .isEqualTo(clonedPage.getId()); // Check if the parent page collections are not altered List<ActionCollection> parentPageCollections = tuple.getT4(); assertThat(parentPageCollections).hasSize(1); - assertThat(parentPageCollections.get(0).getPublishedCollection()).isNotNull(); - assertThat(parentPageCollections.get(0).getUnpublishedCollection()).isNotNull(); - assertThat(parentPageCollections.get(0).getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(parentPageCollections.get(0).getPublishedCollection()) + .isNotNull(); + assertThat(parentPageCollections.get(0).getUnpublishedCollection()) + .isNotNull(); + assertThat(parentPageCollections + .get(0) + .getUnpublishedCollection() + .getPageId()) + .isEqualTo(page.getId()); }) .verifyComplete(); } @@ -679,7 +747,8 @@ public void clonePage() { @Test @WithUserDetails(value = "api_user") public void clonePage_whenPageCloned_defaultIdsRetained() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -692,9 +761,11 @@ public void clonePage_whenPageCloned_defaultIdsRetained() { gitConnectedApplication = setupGitConnectedTestApplication("clonePage"); final String pageId = gitConnectedApplication.getPages().get(0).getId(); - final String branchName = gitConnectedApplication.getGitApplicationMetadata().getBranchName(); + final String branchName = + gitConnectedApplication.getGitApplicationMetadata().getBranchName(); - final PageDTO page = newPageService.findPageById(pageId, READ_PAGES, false).block(); + final PageDTO page = + newPageService.findPageById(pageId, READ_PAGES, false).block(); ActionDTO action = new ActionDTO(); action.setName("PageAction"); @@ -702,7 +773,8 @@ public void clonePage_whenPageCloned_defaultIdsRetained() { Datasource datasource = new Datasource(); datasource.setWorkspaceId(workspaceId); datasource.setName("datasource test for clone page"); - Plugin installed_plugin = pluginRepository.findByPackageName("installed-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("installed-plugin").block(); datasource.setPluginId(installed_plugin.getId()); action.setDatasource(datasource); @@ -738,7 +810,9 @@ public void clonePage_whenPageCloned_defaultIdsRetained() { layoutActionService.createSingleAction(action, Boolean.FALSE).block(); - final LayoutDTO layoutDTO = layoutActionService.updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout).block(); + final LayoutDTO layoutDTO = layoutActionService + .updateLayout(page.getId(), page.getApplicationId(), layout.getId(), layout) + .block(); // Save actionCollection ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); @@ -758,36 +832,37 @@ public void clonePage_whenPageCloned_defaultIdsRetained() { layoutCollectionService.createCollection(actionCollectionDTO).block(); - final Mono<NewPage> pageMono = applicationPageService.clonePageByDefaultPageIdAndBranch(page.getId(), branchName) - .flatMap(pageDTO -> newPageService.findByBranchNameAndDefaultPageId(branchName, pageDTO.getId(), MANAGE_PAGES)) + final Mono<NewPage> pageMono = applicationPageService + .clonePageByDefaultPageIdAndBranch(page.getId(), branchName) + .flatMap(pageDTO -> + newPageService.findByBranchNameAndDefaultPageId(branchName, pageDTO.getId(), MANAGE_PAGES)) .cache(); - Mono<List<NewAction>> actionsMono = - pageMono - .flatMapMany( - page1 -> newActionService - .findByPageId(page1.getId(), READ_ACTIONS)) - .collectList(); - - Mono<List<ActionCollection>> actionCollectionMono = - pageMono - .flatMapMany( - page1 -> actionCollectionService - .findByPageId(page1.getId())) - .collectList(); - - Mono<List<ActionCollection>> actionCollectionInParentPageMono = actionCollectionService - .findByPageId(page.getId()) + Mono<List<NewAction>> actionsMono = pageMono.flatMapMany( + page1 -> newActionService.findByPageId(page1.getId(), READ_ACTIONS)) + .collectList(); + + Mono<List<ActionCollection>> actionCollectionMono = pageMono.flatMapMany( + page1 -> actionCollectionService.findByPageId(page1.getId())) .collectList(); - StepVerifier - .create(Mono.zip(pageMono, actionsMono, actionCollectionMono, actionCollectionInParentPageMono, defaultPermissionGroupsMono)) + Mono<List<ActionCollection>> actionCollectionInParentPageMono = + actionCollectionService.findByPageId(page.getId()).collectList(); + + StepVerifier.create(Mono.zip( + pageMono, + actionsMono, + actionCollectionMono, + actionCollectionInParentPageMono, + defaultPermissionGroupsMono)) .assertNext(tuple -> { NewPage clonedPage = tuple.getT1(); PageDTO unpublishedPage = clonedPage.getUnpublishedPage(); assertThat(clonedPage).isNotNull(); assertThat(clonedPage.getId()).isNotNull(); - assertEquals(page.getName() + " Copy", clonedPage.getUnpublishedPage().getName()); + assertEquals( + page.getName() + " Copy", + clonedPage.getUnpublishedPage().getName()); assertThat(clonedPage.getPolicies()).isNotEmpty(); @@ -795,67 +870,97 @@ public void clonePage_whenPageCloned_defaultIdsRetained() { List<PermissionGroup> permissionGroups = tuple.getT5(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy deletePagePolicy = Policy.builder().permission(AclPermission.DELETE_PAGES.getValue()) + Policy deletePagePolicy = Policy.builder() + .permission(AclPermission.DELETE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy createPageActionsPolicy = Policy.builder().permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) + Policy createPageActionsPolicy = Policy.builder() + .permission(AclPermission.PAGE_CREATE_PAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - assertThat(clonedPage.getPolicies()).containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, - createPageActionsPolicy); + assertThat(clonedPage.getPolicies()) + .containsOnly(managePagePolicy, readPagePolicy, deletePagePolicy, createPageActionsPolicy); assertThat(unpublishedPage.getLayouts()).isNotEmpty(); - assertThat(unpublishedPage.getLayouts().get(0).getDsl().get("widgetName")).isEqualTo("firstWidget"); - assertThat(unpublishedPage.getLayouts().get(0).getWidgetNames()).isNotEmpty(); - assertThat(unpublishedPage.getLayouts().get(0).getMongoEscapedWidgetNames()).isNotEmpty(); - assertThat(unpublishedPage.getLayouts().get(0).getPublishedDsl()).isNullOrEmpty(); + assertThat(unpublishedPage.getLayouts().get(0).getDsl().get("widgetName")) + .isEqualTo("firstWidget"); + assertThat(unpublishedPage.getLayouts().get(0).getWidgetNames()) + .isNotEmpty(); + assertThat(unpublishedPage.getLayouts().get(0).getMongoEscapedWidgetNames()) + .isNotEmpty(); + assertThat(unpublishedPage.getLayouts().get(0).getPublishedDsl()) + .isNullOrEmpty(); DefaultResources clonedPageDefaultRes = clonedPage.getDefaultResources(); assertThat(clonedPageDefaultRes).isNotNull(); - assertThat(clonedPageDefaultRes.getPageId()).isNotEqualTo(page.getDefaultResources().getPageId()); - assertThat(clonedPageDefaultRes.getApplicationId()).isEqualTo(page.getDefaultResources().getApplicationId()); + assertThat(clonedPageDefaultRes.getPageId()) + .isNotEqualTo(page.getDefaultResources().getPageId()); + assertThat(clonedPageDefaultRes.getApplicationId()) + .isEqualTo(page.getDefaultResources().getApplicationId()); assertThat(clonedPageDefaultRes.getBranchName()).isEqualTo(branchName); // Confirm that the page action got copied as well List<NewAction> actions = tuple.getT2(); assertThat(actions).hasSize(2); - NewAction actionWithoutCollection = actions - .stream() - .filter(newAction -> !StringUtils.hasLength(newAction.getUnpublishedAction().getCollectionId())) + NewAction actionWithoutCollection = actions.stream() + .filter(newAction -> !StringUtils.hasLength( + newAction.getUnpublishedAction().getCollectionId())) .findFirst() .orElse(null); DefaultResources clonedActionDefaultRes = actionWithoutCollection.getDefaultResources(); - assertThat(actionWithoutCollection.getUnpublishedAction().getName()).isEqualTo("PageAction"); + assertThat(actionWithoutCollection.getUnpublishedAction().getName()) + .isEqualTo("PageAction"); assertThat(clonedActionDefaultRes).isNotNull(); assertThat(clonedActionDefaultRes.getActionId()).isEqualTo(actionWithoutCollection.getId()); - assertThat(clonedActionDefaultRes.getApplicationId()).isEqualTo(actionWithoutCollection.getApplicationId()); + assertThat(clonedActionDefaultRes.getApplicationId()) + .isEqualTo(actionWithoutCollection.getApplicationId()); assertThat(clonedActionDefaultRes.getPageId()).isNull(); assertThat(clonedActionDefaultRes.getBranchName()).isEqualTo(branchName); - assertThat(actionWithoutCollection.getUnpublishedAction().getDefaultResources().getPageId()).isEqualTo(clonedPage.getDefaultResources().getPageId()); + assertThat(actionWithoutCollection + .getUnpublishedAction() + .getDefaultResources() + .getPageId()) + .isEqualTo(clonedPage.getDefaultResources().getPageId()); // Confirm that executeOnLoad is cloned as well. - assertThat(actions.stream().filter(clonedAction -> "PageAction".equals(clonedAction.getUnpublishedAction().getName())).findFirst().get().getUnpublishedAction().getExecuteOnLoad()).isTrue(); + assertThat(actions.stream() + .filter(clonedAction -> "PageAction" + .equals(clonedAction + .getUnpublishedAction() + .getName())) + .findFirst() + .get() + .getUnpublishedAction() + .getExecuteOnLoad()) + .isTrue(); // Check if collections got copied too List<ActionCollection> collections = tuple.getT3(); @@ -863,22 +968,33 @@ public void clonePage_whenPageCloned_defaultIdsRetained() { ActionCollection collection = collections.get(0); assertThat(collection.getPublishedCollection()).isNull(); assertThat(collection.getUnpublishedCollection()).isNotNull(); - assertThat(collection.getUnpublishedCollection().getPageId()).isEqualTo(clonedPage.getId()); + assertThat(collection.getUnpublishedCollection().getPageId()) + .isEqualTo(clonedPage.getId()); DefaultResources collectionDefaultResource = collection.getDefaultResources(); assertThat(collectionDefaultResource.getPageId()).isNull(); assertThat(collectionDefaultResource.getApplicationId()).isEqualTo(collection.getApplicationId()); assertThat(collectionDefaultResource.getBranchName()).isEqualTo(branchName); - assertThat(collection.getUnpublishedCollection().getDefaultResources().getPageId()).isEqualTo(clonedPage.getDefaultResources().getPageId()); + assertThat(collection + .getUnpublishedCollection() + .getDefaultResources() + .getPageId()) + .isEqualTo(clonedPage.getDefaultResources().getPageId()); // Check if the parent page collections are not altered List<ActionCollection> parentPageCollections = tuple.getT4(); assertThat(parentPageCollections).hasSize(1); - assertThat(parentPageCollections.get(0).getUnpublishedCollection()).isNotNull(); - assertThat(parentPageCollections.get(0).getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(parentPageCollections.get(0).getUnpublishedCollection()) + .isNotNull(); + assertThat(parentPageCollections + .get(0) + .getUnpublishedCollection() + .getPageId()) + .isEqualTo(page.getId()); assertThat(parentPageCollections.get(0).getGitSyncId()).isNotEmpty(); assertThat(collection.getGitSyncId()).isNotEmpty(); - assertThat(collection.getGitSyncId()).isNotEqualTo(parentPageCollections.get(0).getGitSyncId()); + assertThat(collection.getGitSyncId()) + .isNotEqualTo(parentPageCollections.get(0).getGitSyncId()); }) .verifyComplete(); } @@ -898,7 +1014,7 @@ public void reuseDeletedPageName() { // Publish the application applicationPageService.publish(application.getId(), true); - //Delete Page in edit mode + // Delete Page in edit mode applicationPageService.deleteUnpublishedPage(firstPage.getId()).block(); testPage.setId(null); @@ -906,19 +1022,17 @@ public void reuseDeletedPageName() { // Create Second Page PageDTO secondPage = applicationPageService.createPage(testPage).block(); - //Update the name of the new page + // Update the name of the new page PageDTO newPage = new PageDTO(); newPage.setId(secondPage.getId()); newPage.setName("reuseDeletedPageName"); Mono<PageDTO> updatePageNameMono = newPageService.updatePage(secondPage.getId(), newPage); - StepVerifier - .create(updatePageNameMono) + StepVerifier.create(updatePageNameMono) .assertNext(page -> { assertThat(page).isNotNull(); assertThat(page.getId()).isNotNull(); assertThat("reuseDeletedPageName").isEqualTo(page.getName()); - }) .verifyComplete(); } @@ -930,14 +1044,16 @@ public void reOrderPageFromHighOrderToLowOrder() { Application newApp = new Application(); newApp.setName(UUID.randomUUID().toString()); - application = applicationPageService.createApplication(newApp, workspaceId).block(); + application = + applicationPageService.createApplication(newApp, workspaceId).block(); applicationId = application.getId(); final String[] pageIds = new String[4]; PageDTO testPage1 = new PageDTO(); testPage1.setName("Page2"); testPage1.setApplicationId(applicationId); - Mono<ApplicationPagesDTO> applicationPageReOrdered = applicationPageService.createPage(testPage1) + Mono<ApplicationPagesDTO> applicationPageReOrdered = applicationPageService + .createPage(testPage1) .flatMap(pageDTO -> { PageDTO testPage = new PageDTO(); testPage.setName("Page3"); @@ -956,11 +1072,11 @@ public void reOrderPageFromHighOrderToLowOrder() { pageIds[1] = application.getPages().get(1).getId(); pageIds[2] = application.getPages().get(2).getId(); pageIds[3] = application.getPages().get(3).getId(); - return applicationPageService.reorderPage(application.getId(), application.getPages().get(3).getId(), 1, null); + return applicationPageService.reorderPage( + application.getId(), application.getPages().get(3).getId(), 1, null); }); - StepVerifier - .create(applicationPageReOrdered) + StepVerifier.create(applicationPageReOrdered) .assertNext(application -> { final List<PageNameIdDTO> pages = application.getPages(); assertThat(pages.size()).isEqualTo(4); @@ -979,14 +1095,16 @@ public void reOrderPageFromLowOrderToHighOrder() { Application newApp = new Application(); newApp.setName(UUID.randomUUID().toString()); - application = applicationPageService.createApplication(newApp, workspaceId).block(); + application = + applicationPageService.createApplication(newApp, workspaceId).block(); applicationId = application.getId(); final String[] pageIds = new String[4]; PageDTO testPage1 = new PageDTO(); testPage1.setName("Page2"); testPage1.setApplicationId(applicationId); - Mono<ApplicationPagesDTO> applicationPageReOrdered = applicationPageService.createPage(testPage1) + Mono<ApplicationPagesDTO> applicationPageReOrdered = applicationPageService + .createPage(testPage1) .flatMap(pageDTO -> { PageDTO testPage = new PageDTO(); testPage.setName("Page3"); @@ -1005,11 +1123,11 @@ public void reOrderPageFromLowOrderToHighOrder() { pageIds[1] = application.getPages().get(1).getId(); pageIds[2] = application.getPages().get(2).getId(); pageIds[3] = application.getPages().get(3).getId(); - return applicationPageService.reorderPage(application.getId(), application.getPages().get(0).getId(), 3, null); + return applicationPageService.reorderPage( + application.getId(), application.getPages().get(0).getId(), 3, null); }); - StepVerifier - .create(applicationPageReOrdered) + StepVerifier.create(applicationPageReOrdered) .assertNext(application -> { final List<PageNameIdDTO> pages = application.getPages(); assertThat(pages.size()).isEqualTo(4); @@ -1026,13 +1144,15 @@ public void reOrderPageFromLowOrderToHighOrder() { public void reorderPage_pageReordered_success() { gitConnectedApplication = setupGitConnectedTestApplication("reorderPage"); - final String branchName = gitConnectedApplication.getGitApplicationMetadata().getBranchName(); + final String branchName = + gitConnectedApplication.getGitApplicationMetadata().getBranchName(); final ApplicationPage[] pageIds = new ApplicationPage[4]; PageDTO testPage1 = new PageDTO(); testPage1.setName("Page2"); testPage1.setApplicationId(gitConnectedApplication.getId()); - Mono<ApplicationPagesDTO> applicationPageReOrdered = applicationPageService.createPageWithBranchName(testPage1, branchName) + Mono<ApplicationPagesDTO> applicationPageReOrdered = applicationPageService + .createPageWithBranchName(testPage1, branchName) .flatMap(pageDTO -> { PageDTO testPage = new PageDTO(); testPage.setName("Page3"); @@ -1051,11 +1171,11 @@ public void reorderPage_pageReordered_success() { pageIds[1] = application.getPages().get(1); pageIds[2] = application.getPages().get(2); pageIds[3] = application.getPages().get(3); - return applicationPageService.reorderPage(application.getId(), application.getPages().get(0).getId(), 3, null); + return applicationPageService.reorderPage( + application.getId(), application.getPages().get(0).getId(), 3, null); }); - StepVerifier - .create(applicationPageReOrdered) + StepVerifier.create(applicationPageReOrdered) .assertNext(application -> { final List<PageNameIdDTO> pages = application.getPages(); assertThat(pages.size()).isEqualTo(4); @@ -1079,24 +1199,20 @@ public void addDuplicatePageToApplication() { setupTestApplication(); testPage.setApplicationId(application.getId()); - Mono<PageDTO> pageMono = applicationPageService.createPage(testPage) - .flatMap(pageDTO -> { - PageDTO testPage1 = new PageDTO(); - testPage1.setName("Page3"); - testPage1.setApplicationId(applicationId); - testPage1.setId(pageDTO.getId()); - return applicationPageService.createPage(testPage1); - }); - StepVerifier - .create(pageMono) + Mono<PageDTO> pageMono = applicationPageService.createPage(testPage).flatMap(pageDTO -> { + PageDTO testPage1 = new PageDTO(); + testPage1.setName("Page3"); + testPage1.setApplicationId(applicationId); + testPage1.setId(pageDTO.getId()); + return applicationPageService.createPage(testPage1); + }); + StepVerifier.create(pageMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException) .verify(); } - @AfterEach public void purgeAllPages() { newPageService.deleteAll(); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PluginServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PluginServiceTest.java index c9dd4c65a7c0..9f89ca7df03f 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PluginServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PluginServiceTest.java @@ -50,10 +50,10 @@ public void setup() { @Test public void checkPluginExecutor() { - Mono<ActionExecutionResult> executeMono = pluginExecutor.execute(new Object(), new DatasourceConfiguration(), new ActionConfiguration()); + Mono<ActionExecutionResult> executeMono = + pluginExecutor.execute(new Object(), new DatasourceConfiguration(), new ActionConfiguration()); - StepVerifier - .create(executeMono) + StepVerifier.create(executeMono) .assertNext(result -> { assertThat(result).isInstanceOf(ActionExecutionResult.class); }) @@ -75,12 +75,11 @@ public void getPluginFormWithNullFormConfig() { Mono<Map> formConfig = pluginService.getFormConfig("random-plugin-id"); - StepVerifier.create(formConfig) - .expectError(AppsmithException.class) - .verify(); + StepVerifier.create(formConfig).expectError(AppsmithException.class).verify(); } - // The editor form config is not mandatory for plugins. The function should return successfully even if it's not present + // The editor form config is not mandatory for plugins. The function should return successfully even if it's not + // present @Test public void getPluginFormWithNullEditorConfig() { Map formMap = new HashMap(); @@ -107,7 +106,6 @@ public void getPluginFormWithNullEditorConfig() { .verifyComplete(); } - @Test public void getPluginFormValid() { Map formMap = new HashMap(); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java index 93933bce08a2..d1bb846607cf 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java @@ -61,15 +61,21 @@ public class ThemeServiceTest { @Autowired UserService userService; + Workspace workspace; + @Autowired private ThemeService themeService; + @Autowired private PermissionGroupRepository permissionGroupRepository; + @Autowired private UserWorkspaceService userWorkspaceService; + @Autowired private ThemeRepository themeRepository; + @Autowired private UserAndAccessManagementService userAndAccessManagementService; @@ -91,16 +97,17 @@ private Application createApplication() { Application application = new Application(); application.setName("ThemeTest_" + UUID.randomUUID()); application.setWorkspaceId(this.workspace.getId()); - applicationPageService.createApplication(application, this.workspace.getId()).block(); + applicationPageService + .createApplication(application, this.workspace.getId()) + .block(); return application; } public void replaceApiUserWithAnotherUserInWorkspace() { String origin = "http://random-origin.test"; - PermissionGroup adminPermissionGroup = permissionGroupRepository.findAllById( - workspace.getDefaultPermissionGroups() - ) + PermissionGroup adminPermissionGroup = permissionGroupRepository + .findAllById(workspace.getDefaultPermissionGroups()) .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) .collectList() .block() @@ -116,7 +123,9 @@ public void replaceApiUserWithAnotherUserInWorkspace() { UpdatePermissionGroupDTO updatePermissionGroupDTO = new UpdatePermissionGroupDTO(); updatePermissionGroupDTO.setNewPermissionGroupId(null); updatePermissionGroupDTO.setUsername("api_user"); - userWorkspaceService.updatePermissionGroupForMember(workspace.getId(), updatePermissionGroupDTO, origin).block(); + userWorkspaceService + .updatePermissionGroupForMember(workspace.getId(), updatePermissionGroupDTO, origin) + .block(); } @WithUserDetails("api_user") @@ -129,19 +138,20 @@ public void getApplicationTheme_WhenThemeIsSet_ThemesReturned() { Application savedApplication = createApplication(); // Apply Sharp theme to the application - Mono<Theme> applySharpTheme = themeService.changeCurrentTheme(sharpTheme.getId(), savedApplication.getId(), null); + Mono<Theme> applySharpTheme = + themeService.changeCurrentTheme(sharpTheme.getId(), savedApplication.getId(), null); // Publish app Mono<Application> publishApp = applicationPageService.publish(savedApplication.getId(), TRUE); // apply classic theme to the application - Mono<Theme> applyClassicTheme = themeService.changeCurrentTheme(classicTheme.getId(), savedApplication.getId(), null); + Mono<Theme> applyClassicTheme = + themeService.changeCurrentTheme(classicTheme.getId(), savedApplication.getId(), null); Mono<Tuple2<Theme, Theme>> applicationThemesMono = applySharpTheme .then(publishApp) .then(applyClassicTheme) .then(Mono.zip( themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.EDIT, null), - themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.PUBLISHED, null) - )); + themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.PUBLISHED, null))); StepVerifier.create(applicationThemesMono) .assertNext(themesTuple -> { @@ -149,7 +159,8 @@ public void getApplicationTheme_WhenThemeIsSet_ThemesReturned() { assertThat(themesTuple.getT1().getName()).isEqualTo("Classic"); assertThat(themesTuple.getT2().isSystemTheme()).isTrue(); assertThat(themesTuple.getT2().getName()).isEqualTo("Sharp"); - }).verifyComplete(); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -161,30 +172,27 @@ public void getApplicationTheme_WhenUserHasNoPermission_ExceptionThrows() { Theme sharpTheme = themeService.getSystemTheme("Sharp").block(); Theme classicTheme = themeService.getSystemTheme("Classic").block(); // Apply Sharp theme to the application - Mono<Theme> applySharpTheme = themeService.changeCurrentTheme(sharpTheme.getId(), savedApplication.getId(), null); + Mono<Theme> applySharpTheme = + themeService.changeCurrentTheme(sharpTheme.getId(), savedApplication.getId(), null); // Publish app Mono<Application> publishApp = applicationPageService.publish(savedApplication.getId(), TRUE); // apply classic theme to the application - Mono<Theme> applyClassicTheme = themeService.changeCurrentTheme(classicTheme.getId(), savedApplication.getId(), null); + Mono<Theme> applyClassicTheme = + themeService.changeCurrentTheme(classicTheme.getId(), savedApplication.getId(), null); // Set the themes in edit and published mode before the user is removed from the workspace - applySharpTheme - .then(publishApp) - .then(applyClassicTheme) - .block(); + applySharpTheme.then(publishApp).then(applyClassicTheme).block(); replaceApiUserWithAnotherUserInWorkspace(); // Fetch the app theme (after api_user has been removed from the workspace) Mono<Tuple2<Theme, Theme>> applicationThemesMono = Mono.zip( themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.EDIT, null), - themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.PUBLISHED, null) - ); + themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.PUBLISHED, null)); StepVerifier.create(applicationThemesMono) .expectErrorMessage( - AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, savedApplication.getId()) - ) + AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, savedApplication.getId())) .verify(); } @@ -193,9 +201,9 @@ public void getApplicationTheme_WhenUserHasNoPermission_ExceptionThrows() { public void getApplicationTheme_WhenNoThemeFoundWithId_DefaultThemeReturned() { Application savedApplication = createApplication(); savedApplication.setPublishedModeThemeId("invalid-theme-id"); - Mono<Theme> publishedThemeMono = applicationRepository.save(savedApplication).then( - themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.PUBLISHED, null) - ); + Mono<Theme> publishedThemeMono = applicationRepository + .save(savedApplication) + .then(themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.PUBLISHED, null)); StepVerifier.create(publishedThemeMono) .assertNext(theme -> { @@ -213,12 +221,15 @@ public void changeCurrentTheme_WhenUserHasPermission_ThemesSetInEditMode() { Application savedApplication = createApplication(); // Publish app - Application publishedApp = applicationPageService.publish(savedApplication.getId(), TRUE).block(); + Application publishedApp = + applicationPageService.publish(savedApplication.getId(), TRUE).block(); // apply classic theme to the application - Mono<Theme> applyClassicTheme = themeService.changeCurrentTheme(classicTheme.getId(), savedApplication.getId(), null); + Mono<Theme> applyClassicTheme = + themeService.changeCurrentTheme(classicTheme.getId(), savedApplication.getId(), null); // apply rounded theme to the application - Mono<Theme> applyRoundedTheme = themeService.changeCurrentTheme(roundedTheme.getId(), savedApplication.getId(), null); + Mono<Theme> applyRoundedTheme = + themeService.changeCurrentTheme(roundedTheme.getId(), savedApplication.getId(), null); Mono<Application> applicationPostThemeUpdatesMono = applyClassicTheme .then(applyRoundedTheme) @@ -226,20 +237,23 @@ public void changeCurrentTheme_WhenUserHasPermission_ThemesSetInEditMode() { Mono<Application> oldApplicationMono = Mono.just(publishedApp); - StepVerifier - .create(Mono.zip(applicationPostThemeUpdatesMono, oldApplicationMono)) + StepVerifier.create(Mono.zip(applicationPostThemeUpdatesMono, oldApplicationMono)) .assertNext(objects -> { Application updatedApplication = objects.getT1(); Application oldApplication = objects.getT2(); // edit mode and published mode has same theme id in old application assertThat(oldApplication.getEditModeThemeId()).isEqualTo(oldApplication.getPublishedModeThemeId()); // edit mode and published mode has different theme id in updated application - assertThat(updatedApplication.getEditModeThemeId()).isNotEqualTo(updatedApplication.getPublishedModeThemeId()); + assertThat(updatedApplication.getEditModeThemeId()) + .isNotEqualTo(updatedApplication.getPublishedModeThemeId()); // edit mode theme id has changed from old application to new application - assertThat(oldApplication.getEditModeThemeId()).isNotEqualTo(updatedApplication.getEditModeThemeId()); + assertThat(oldApplication.getEditModeThemeId()) + .isNotEqualTo(updatedApplication.getEditModeThemeId()); // published mode theme id remains same in old application and new application - assertThat(oldApplication.getPublishedModeThemeId()).isEqualTo(updatedApplication.getPublishedModeThemeId()); - }).verifyComplete(); + assertThat(oldApplication.getPublishedModeThemeId()) + .isEqualTo(updatedApplication.getPublishedModeThemeId()); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -252,20 +266,19 @@ public void changeCurrentTheme_WhenUserHasNoPermission_ThrowsException() { // Publish app Mono<Application> publishApp = applicationPageService.publish(savedApplication.getId(), TRUE); // apply classic theme to the application - Mono<Theme> applyClassicTheme = themeService.changeCurrentTheme(classicTheme.getId(), savedApplication.getId(), null); + Mono<Theme> applyClassicTheme = + themeService.changeCurrentTheme(classicTheme.getId(), savedApplication.getId(), null); // Set the themes in edit and published mode before the user is removed from the workspace - applyClassicTheme - .then(publishApp) - .block(); + applyClassicTheme.then(publishApp).block(); replaceApiUserWithAnotherUserInWorkspace(); // Change the app theme as api_user (after api_user has been removed from the workspace) - Mono<Theme> changeCurrentThemeMono = themeService.changeCurrentTheme(savedApplication.getEditModeThemeId(), savedApplication.getId(), null); + Mono<Theme> changeCurrentThemeMono = + themeService.changeCurrentTheme(savedApplication.getEditModeThemeId(), savedApplication.getId(), null); - StepVerifier - .create(changeCurrentThemeMono) + StepVerifier.create(changeCurrentThemeMono) .expectError(AppsmithException.class) .verify(); } @@ -278,18 +291,17 @@ public void changeCurrentTheme_WhenSystemThemeSet_NoNewThemeCreated() { Application savedApplication = createApplication(); - Mono<Theme> applicationThemeMono = defaultThemeIdMono - .flatMap(themeId -> themeService - .changeCurrentTheme(themeId, savedApplication.getId(), null) - .then(themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.EDIT, null)) - ); + Mono<Theme> applicationThemeMono = defaultThemeIdMono.flatMap(themeId -> themeService + .changeCurrentTheme(themeId, savedApplication.getId(), null) + .then(themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.EDIT, null))); StepVerifier.create(applicationThemeMono) .assertNext(theme -> { assertThat(theme.isSystemTheme()).isTrue(); assertThat(theme.getApplicationId()).isNull(); assertThat(theme.getWorkspaceId()).isNull(); - }).verifyComplete(); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -300,7 +312,8 @@ public void changeCurrentTheme_WhenSystemThemeSetOverCustomTheme_NewThemeNotCrea Theme customTheme = new Theme(); customTheme.setName("my-custom-theme"); - Mono<Theme> createAndApplyCustomThemeMono = themeService.persistCurrentTheme(savedApplication.getId(), null, customTheme) + Mono<Theme> createAndApplyCustomThemeMono = themeService + .persistCurrentTheme(savedApplication.getId(), null, customTheme) // Apply the newly created custom theme to the application .flatMap(theme -> themeService.changeCurrentTheme(theme.getId(), savedApplication.getId(), null)) .flatMap(theme -> { @@ -310,26 +323,27 @@ public void changeCurrentTheme_WhenSystemThemeSetOverCustomTheme_NewThemeNotCrea return themeService.save(theme); }); - Mono<Theme> applyDefaultThemeMono = themeService.getDefaultThemeId() + Mono<Theme> applyDefaultThemeMono = themeService + .getDefaultThemeId() .flatMap(themeId -> themeService.changeCurrentTheme(themeId, savedApplication.getId(), null)); Mono<Theme> newApplicationThemeMono = createAndApplyCustomThemeMono .then(applyDefaultThemeMono) .then(themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.EDIT, null)); - Mono<Theme> oldApplicationThemeMono = themeService.getThemeById(savedApplication.getEditModeThemeId(), READ_THEMES) + Mono<Theme> oldApplicationThemeMono = themeService + .getThemeById(savedApplication.getEditModeThemeId(), READ_THEMES) .defaultIfEmpty(new Theme()); // this should be deleted, return empty theme - - StepVerifier - .create(newApplicationThemeMono.zipWhen(theme -> oldApplicationThemeMono)) + StepVerifier.create(newApplicationThemeMono.zipWhen(theme -> oldApplicationThemeMono)) .assertNext(themeTuple2 -> { Theme currentTheme = themeTuple2.getT1(); Theme oldTheme = themeTuple2.getT2(); assertThat(currentTheme.isSystemTheme()).isTrue(); assertThat(currentTheme.getApplicationId()).isNull(); assertThat(currentTheme.getWorkspaceId()).isNull(); - assertThat(oldTheme.getId()).isNotNull(); // TODO : Change assertion to null if it should be deleted. + assertThat(oldTheme.getId()) + .isNotNull(); // TODO : Change assertion to null if it should be deleted. }) .verifyComplete(); } @@ -341,16 +355,19 @@ public void cloneThemeToApplication_WhenSrcThemeIsSystemTheme_NoNewThemeCreated( // Create a new application with default system theme Application newApplication = createApplication(); - Mono<Tuple2<Theme, Theme>> newAndOldThemeMono = themeService.getSystemTheme("Classic") + Mono<Tuple2<Theme, Theme>> newAndOldThemeMono = themeService + .getSystemTheme("Classic") .flatMap(theme -> { // Clone the application - return themeService.cloneThemeToApplication(theme.getId(), newApplication) + return themeService + .cloneThemeToApplication(theme.getId(), newApplication) .zipWith(Mono.just(theme)); }); StepVerifier.create(newAndOldThemeMono) .assertNext(objects -> { - assertThat(objects.getT1().getId()).isEqualTo(objects.getT2().getId()); + assertThat(objects.getT1().getId()) + .isEqualTo(objects.getT2().getId()); }) .verifyComplete(); } @@ -363,7 +380,8 @@ public void cloneThemeToApplication_WhenSrcThemeIsCustomTheme_NewThemeCreated() Theme customTheme = new Theme(); customTheme.setName("my-custom-theme"); - Mono<Theme> createCustomThemeMono = themeService.persistCurrentTheme(savedApplication.getId(), null, customTheme) + Mono<Theme> createCustomThemeMono = themeService + .persistCurrentTheme(savedApplication.getId(), null, customTheme) .flatMap(theme -> { // Mark this custom theme as not an application theme // Don't know why a theme will not be associated with an application if it is not a system theme @@ -372,16 +390,18 @@ public void cloneThemeToApplication_WhenSrcThemeIsCustomTheme_NewThemeCreated() }); // Note ^ The theme is only created but not applied to the application above - Mono<Tuple2<Theme, Theme>> newAndOldThemeMono = createCustomThemeMono - .flatMap(theme -> { - return themeService.cloneThemeToApplication(theme.getId(), savedApplication) - .zipWith(Mono.just(theme)); - }); + Mono<Tuple2<Theme, Theme>> newAndOldThemeMono = createCustomThemeMono.flatMap(theme -> { + return themeService + .cloneThemeToApplication(theme.getId(), savedApplication) + .zipWith(Mono.just(theme)); + }); StepVerifier.create(newAndOldThemeMono) .assertNext(objects -> { - assertThat(objects.getT1().getId()).isNotEqualTo(objects.getT2().getId()); - assertThat(objects.getT1().getDisplayName()).isEqualTo(objects.getT2().getDisplayName()); + assertThat(objects.getT1().getId()) + .isNotEqualTo(objects.getT2().getId()); + assertThat(objects.getT1().getDisplayName()) + .isEqualTo(objects.getT2().getDisplayName()); }) .verifyComplete(); } @@ -397,11 +417,11 @@ public void cloneThemeToApplication_WhenSrcThemeIsCustomSavedTheme_NewCustomThem Mono<Theme> createCustomTheme = themeService.persistCurrentTheme(savedApplication.getId(), null, customTheme); // ^ This theme is created with application id set. - Mono<Tuple2<Theme, Theme>> newAndOldThemeMono = createCustomTheme - .flatMap(theme -> { - return themeService.cloneThemeToApplication(theme.getId(), savedApplication) - .zipWith(Mono.just(theme)); - }); + Mono<Tuple2<Theme, Theme>> newAndOldThemeMono = createCustomTheme.flatMap(theme -> { + return themeService + .cloneThemeToApplication(theme.getId(), savedApplication) + .zipWith(Mono.just(theme)); + }); StepVerifier.create(newAndOldThemeMono) .assertNext(objects -> { @@ -416,7 +436,6 @@ public void cloneThemeToApplication_WhenSrcThemeIsCustomSavedTheme_NewCustomThem .verifyComplete(); } - @WithUserDetails("api_user") @Test public void publishTheme_WhenSystemThemeIsSet_NoNewThemeCreated() { @@ -437,10 +456,10 @@ public void publishTheme_WhenSystemThemeIsSet_NoNewThemeCreated() { Theme classicSystemTheme = objects.getT2(); assertThat(application.getEditModeThemeId()).isEqualTo(classicSystemTheme.getId()); assertThat(application.getEditModeThemeId()).isEqualTo(application.getPublishedModeThemeId()); - }).verifyComplete(); + }) + .verifyComplete(); } - @WithUserDetails("api_user") @Test public void publishTheme_WhenCustomThemeIsSet_ThemeCopiedForPublishedMode() { @@ -451,27 +470,27 @@ public void publishTheme_WhenCustomThemeIsSet_ThemeCopiedForPublishedMode() { // Set a custom theme in edit mode. Theme customTheme = new Theme(); customTheme.setName("my-custom-theme"); - Mono<Theme> createAndApplyCustomThemeMono = themeService.persistCurrentTheme(application.getId(), null, customTheme) + Mono<Theme> createAndApplyCustomThemeMono = themeService + .persistCurrentTheme(application.getId(), null, customTheme) .flatMap(theme -> themeService.changeCurrentTheme(theme.getId(), application.getId(), null)); // publish the theme Mono<Theme> publishThemeMono = themeService.publishTheme(application.getId()); Mono<Tuple2<Theme, Theme>> appThemesMono = createAndApplyCustomThemeMono .then(publishThemeMono) - .then( - Mono.zip( - themeService.getApplicationTheme(application.getId(), ApplicationMode.EDIT, null), - themeService.getApplicationTheme(application.getId(), ApplicationMode.PUBLISHED, null) - ) - ); + .then(Mono.zip( + themeService.getApplicationTheme(application.getId(), ApplicationMode.EDIT, null), + themeService.getApplicationTheme(application.getId(), ApplicationMode.PUBLISHED, null))); StepVerifier.create(appThemesMono) .assertNext(objects -> { Theme editModeTheme = objects.getT1(); Theme publishedModeTheme = objects.getT2(); - assertThat(editModeTheme.getDisplayName()).isEqualTo(publishedModeTheme.getDisplayName()); // same name + assertThat(editModeTheme.getDisplayName()) + .isEqualTo(publishedModeTheme.getDisplayName()); // same name assertThat(editModeTheme.getId()).isNotEqualTo(publishedModeTheme.getId()); // different id - }).verifyComplete(); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -479,20 +498,20 @@ public void publishTheme_WhenCustomThemeIsSet_ThemeCopiedForPublishedMode() { public void updateTheme_WhenSystemThemeIsSet_NewThemeCreated() { Application application = createApplication(); - Theme systemDefaultTheme = themeService.getThemeById(application.getEditModeThemeId(), READ_THEMES).block(); + Theme systemDefaultTheme = themeService + .getThemeById(application.getEditModeThemeId(), READ_THEMES) + .block(); // publish the app to ensure system theme gets set applicationPageService.publish(application.getId(), TRUE).block(); Theme updatesToSystemTheme = new Theme(); updatesToSystemTheme.setDisplayName("My updates to existing system theme"); - Mono<Tuple2<Theme, Theme>> appThemesMono = themeService.updateTheme(application.getId(), null, updatesToSystemTheme) - .then( - Mono.zip( - themeService.getApplicationTheme(application.getId(), ApplicationMode.EDIT, null), - themeService.getApplicationTheme(application.getId(), ApplicationMode.PUBLISHED, null) - ) - ); + Mono<Tuple2<Theme, Theme>> appThemesMono = themeService + .updateTheme(application.getId(), null, updatesToSystemTheme) + .then(Mono.zip( + themeService.getApplicationTheme(application.getId(), ApplicationMode.EDIT, null), + themeService.getApplicationTheme(application.getId(), ApplicationMode.PUBLISHED, null))); StepVerifier.create(appThemesMono) .assertNext(objects -> { @@ -502,8 +521,10 @@ public void updateTheme_WhenSystemThemeIsSet_NewThemeCreated() { assertThat(editModeTheme.getId()).isNotEqualTo(publishedModeTheme.getId()); // different id assertThat(editModeTheme.isSystemTheme()).isFalse(); assertThat(publishedModeTheme.isSystemTheme()).isTrue(); - assertThat(publishedModeTheme.getDisplayName()).isEqualToIgnoringCase(systemDefaultTheme.getDisplayName()); - }).verifyComplete(); + assertThat(publishedModeTheme.getDisplayName()) + .isEqualToIgnoringCase(systemDefaultTheme.getDisplayName()); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -511,17 +532,19 @@ public void updateTheme_WhenSystemThemeIsSet_NewThemeCreated() { public void updateTheme_WhenCustomThemeIsSet_ThemeIsOverridden() { Application application = createApplication(); - Theme systemDefaultTheme = themeService.getThemeById(application.getEditModeThemeId(), READ_THEMES).block(); + Theme systemDefaultTheme = themeService + .getThemeById(application.getEditModeThemeId(), READ_THEMES) + .block(); String applicationId = application.getId(); // publish the app to ensure system theme gets set applicationPageService.publish(application.getId(), TRUE).block(); - // Create and apply custom theme in edit mode. Theme customTheme = new Theme(); customTheme.setDisplayName("My custom theme"); - themeService.persistCurrentTheme(application.getId(), null, customTheme) + themeService + .persistCurrentTheme(application.getId(), null, customTheme) .flatMap(theme -> themeService.changeCurrentTheme(theme.getId(), applicationId, null)) .block(); application = applicationRepository.findById(applicationId).block(); @@ -531,14 +554,10 @@ public void updateTheme_WhenCustomThemeIsSet_ThemeIsOverridden() { themeCustomization.setDisplayName("Updated name"); Mono<Theme> updateThemeMono = themeService.updateTheme(application.getId(), null, themeCustomization); - Mono<Tuple3<Theme, Theme, Application>> appThemesMono = updateThemeMono - .then( - Mono.zip( - themeService.getApplicationTheme(application.getId(), ApplicationMode.EDIT, null), - themeService.getApplicationTheme(application.getId(), ApplicationMode.PUBLISHED, null), - Mono.just(application) - ) - ); + Mono<Tuple3<Theme, Theme, Application>> appThemesMono = updateThemeMono.then(Mono.zip( + themeService.getApplicationTheme(application.getId(), ApplicationMode.EDIT, null), + themeService.getApplicationTheme(application.getId(), ApplicationMode.PUBLISHED, null), + Mono.just(application))); StepVerifier.create(appThemesMono) .assertNext(objects -> { @@ -554,8 +573,10 @@ public void updateTheme_WhenCustomThemeIsSet_ThemeIsOverridden() { assertThat(editModeTheme.getDisplayName()).isEqualTo("Updated name"); assertThat(publishedModeTheme.isSystemTheme()).isTrue(); - assertThat(publishedModeTheme.getDisplayName()).isEqualToIgnoringCase(systemDefaultTheme.getDisplayName()); - }).verifyComplete(); + assertThat(publishedModeTheme.getDisplayName()) + .isEqualToIgnoringCase(systemDefaultTheme.getDisplayName()); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -568,21 +589,25 @@ public void publishTheme_WhenNoThemeIsSet_SystemDefaultThemeIsSetToPublishedMode Application updateApp = new Application(); updateApp.setEditModeThemeId(""); updateApp.setPublishedModeThemeId(""); - Application appWithoutTheme = applicationRepository.updateById(savedApplication.getId(), updateApp, MANAGE_APPLICATIONS).block(); + Application appWithoutTheme = applicationRepository + .updateById(savedApplication.getId(), updateApp, MANAGE_APPLICATIONS) + .block(); - Application publishedApp = applicationPageService.publish(savedApplication.getId(), TRUE).block(); + Application publishedApp = + applicationPageService.publish(savedApplication.getId(), TRUE).block(); Mono<Theme> classicThemeMono = themeRepository.getSystemThemeByName(Theme.LEGACY_THEME_NAME); - Mono<Tuple2<Application, Theme>> appAndThemeTuple = Mono.just(publishedApp) - .zipWith(classicThemeMono); + Mono<Tuple2<Application, Theme>> appAndThemeTuple = + Mono.just(publishedApp).zipWith(classicThemeMono); StepVerifier.create(appAndThemeTuple) .assertNext(objects -> { Application application = objects.getT1(); Theme classicSystemTheme = objects.getT2(); assertThat(application.getPublishedModeThemeId()).isEqualTo(classicSystemTheme.getId()); - }).verifyComplete(); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -597,7 +622,8 @@ public void publishTheme_WhenApplicationIsPublic_PublishedThemeIsPublic() { // Set a custom theme in edit mode. Theme customTheme = new Theme(); customTheme.setName("my-custom-theme"); - Mono<Theme> createAndApplyCustomThemeMono = themeService.persistCurrentTheme(savedApplication.getId(), null, customTheme) + Mono<Theme> createAndApplyCustomThemeMono = themeService + .persistCurrentTheme(savedApplication.getId(), null, customTheme) .flatMap(theme -> themeService.changeCurrentTheme(theme.getId(), savedApplication.getId(), null)); // Make the app public. @@ -606,25 +632,28 @@ public void publishTheme_WhenApplicationIsPublic_PublishedThemeIsPublic() { // Publish the theme Mono<Theme> publishThemeMono = themeService.publishTheme(savedApplication.getId()); - Mono<Theme> getPublishedApplicationThemeMono = themeService.getApplicationTheme(savedApplication.getId(), ApplicationMode.PUBLISHED, null) + Mono<Theme> getPublishedApplicationThemeMono = themeService + .getApplicationTheme(savedApplication.getId(), ApplicationMode.PUBLISHED, null) .switchIfEmpty(Mono.just(new Theme())) .cache(); Mono<User> anonymousUserMono = userService.findByEmail(ANONYMOUS_USER); - Mono<List<PermissionGroup>> anonymousUserPermissionsMono = Mono.zip(getPublishedApplicationThemeMono, anonymousUserMono) + Mono<List<PermissionGroup>> anonymousUserPermissionsMono = Mono.zip( + getPublishedApplicationThemeMono, anonymousUserMono) .flatMap(tuple -> { Theme theme = tuple.getT1(); User anonymousUser = tuple.getT2(); - Policy readThemePolicy = theme.getPolicies() - .stream() + Policy readThemePolicy = theme.getPolicies().stream() .filter(themePolicy -> themePolicy.getPermission().equals(READ_THEMES.getValue())) .findFirst() .get(); - return permissionGroupRepository.findAllById(readThemePolicy.getPermissionGroups()) - .filter(permissionGroup -> permissionGroup.getAssignedToUserIds().contains(anonymousUser.getId())) + return permissionGroupRepository + .findAllById(readThemePolicy.getPermissionGroups()) + .filter(permissionGroup -> + permissionGroup.getAssignedToUserIds().contains(anonymousUser.getId())) .collectList(); }); @@ -643,8 +672,8 @@ public void publishTheme_WhenApplicationIsPublic_PublishedThemeIsPublic() { // Assert that the published theme is accessible by anonymous user. assertThat(permissionGroups.size()).isGreaterThan(0); - - }).verifyComplete(); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -656,40 +685,53 @@ public void persistCurrentTheme_WhenCustomThemeIsSet_NewApplicationThemeCreated( Theme theme = new Theme(); theme.setDisplayName("My custom theme"); - Mono<Theme> persistCustomThemeMono = themeService.persistCurrentTheme(savedApplication.getId(), null, theme) + Mono<Theme> persistCustomThemeMono = themeService + .persistCurrentTheme(savedApplication.getId(), null, theme) .cache(); Mono<Tuple4<List<Theme>, Theme, Application, Theme>> tuple4Mono = persistCustomThemeMono - .then(themeService.getApplicationThemes(savedApplication.getId(), null).collectList()) + .then(themeService + .getApplicationThemes(savedApplication.getId(), null) + .collectList()) .zipWith(persistCustomThemeMono) .flatMap(tuple -> { List<Theme> themes = tuple.getT1(); Theme persistedTheme = tuple.getT2(); - return themeService.getThemeById(persistedTheme.getId(), MANAGE_THEMES) - .map(themeWithEditPermission -> Tuples.of(themes, persistedTheme, savedApplication, themeWithEditPermission)); + return themeService + .getThemeById(persistedTheme.getId(), MANAGE_THEMES) + .map(themeWithEditPermission -> + Tuples.of(themes, persistedTheme, savedApplication, themeWithEditPermission)); }); - StepVerifier.create(tuple4Mono).assertNext(tuple4 -> { - List<Theme> availableThemes = tuple4.getT1(); - Theme persistedThemeWithReadPermission = tuple4.getT2(); - Application application = tuple4.getT3(); - Theme persistedThemeWithEditPermission = tuple4.getT4(); - - long systemThemesCount = availableThemes.stream().filter(availableTheme -> availableTheme.isSystemTheme()).count(); - assertThat(availableThemes.size()).isEqualTo(systemThemesCount + 1); // one custom theme + existing system themes - - // assert permissions by asserting that the themes have been found. - assertThat(persistedThemeWithReadPermission.getId()).isNotNull(); - assertThat(persistedThemeWithEditPermission.getId()).isNotNull(); - - assertThat(persistedThemeWithReadPermission.isSystemTheme()).isFalse(); - assertThat(persistedThemeWithReadPermission.getApplicationId()).isNotEmpty(); - assertThat(persistedThemeWithReadPermission.getApplicationId()).isNotEmpty(); // theme should have application id set - assertThat(persistedThemeWithReadPermission.getWorkspaceId()).isEqualTo(this.workspace.getId()); // theme should have workspace id set - assertThat(application.getEditModeThemeId()).isNotEqualTo(persistedThemeWithReadPermission.getId()); // a new copy should be created - - }).verifyComplete(); + StepVerifier.create(tuple4Mono) + .assertNext(tuple4 -> { + List<Theme> availableThemes = tuple4.getT1(); + Theme persistedThemeWithReadPermission = tuple4.getT2(); + Application application = tuple4.getT3(); + Theme persistedThemeWithEditPermission = tuple4.getT4(); + + long systemThemesCount = availableThemes.stream() + .filter(availableTheme -> availableTheme.isSystemTheme()) + .count(); + assertThat(availableThemes.size()) + .isEqualTo(systemThemesCount + 1); // one custom theme + existing system themes + + // assert permissions by asserting that the themes have been found. + assertThat(persistedThemeWithReadPermission.getId()).isNotNull(); + assertThat(persistedThemeWithEditPermission.getId()).isNotNull(); + + assertThat(persistedThemeWithReadPermission.isSystemTheme()).isFalse(); + assertThat(persistedThemeWithReadPermission.getApplicationId()) + .isNotEmpty(); + assertThat(persistedThemeWithReadPermission.getApplicationId()) + .isNotEmpty(); // theme should have application id set + assertThat(persistedThemeWithReadPermission.getWorkspaceId()) + .isEqualTo(this.workspace.getId()); // theme should have workspace id set + assertThat(application.getEditModeThemeId()) + .isNotEqualTo(persistedThemeWithReadPermission.getId()); // a new copy should be created + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -707,7 +749,8 @@ public void delete_WhenUnsavedCustomizedTheme_NotAllowed() { Theme themeCustomization = new Theme(); themeCustomization.setDisplayName("Updated name"); - Mono<Theme> deleteThemeMono = themeService.updateTheme(savedApplication.getId(), null, themeCustomization) + Mono<Theme> deleteThemeMono = themeService + .updateTheme(savedApplication.getId(), null, themeCustomization) .flatMap(customizedTheme -> themeService.archiveById(customizedTheme.getId())); StepVerifier.create(deleteThemeMono) @@ -726,7 +769,8 @@ public void delete_WhenSavedCustomizedTheme_ThemeIsDeleted() { themeCustomization.setDisplayName("Updated name"); return themeService.persistCurrentTheme(savedApplication.getId(), null, themeCustomization); }) - .flatMap(customizedTheme -> themeService.archiveById(customizedTheme.getId()) + .flatMap(customizedTheme -> themeService + .archiveById(customizedTheme.getId()) .then(themeService.getThemeById(customizedTheme.getId(), READ_THEMES))); StepVerifier.create(deleteThemeMono).verifyComplete(); @@ -741,7 +785,9 @@ public void updateName_WhenSystemTheme_NotAllowed() { theme.setDisplayName("My theme"); return themeService.updateName(themeId, theme); }); - StepVerifier.create(updateThemeNameMono).expectError(AppsmithException.class).verify(); + StepVerifier.create(updateThemeNameMono) + .expectError(AppsmithException.class) + .verify(); } @WithUserDetails("api_user") @@ -759,18 +805,21 @@ public void updateName_WhenCustomTheme_NameUpdated() { Theme theme = new Theme(); theme.setName("new name"); theme.setDisplayName("new display name"); - return themeService.updateName(customizedTheme.getId(), theme) + return themeService + .updateName(customizedTheme.getId(), theme) .then(themeService.getThemeById(customizedTheme.getId(), READ_THEMES)); }); - StepVerifier.create(updateThemeNameMono).assertNext(theme -> { - assertThat(theme.getName()).isEqualTo("new name"); - assertThat(theme.getDisplayName()).isEqualTo("new display name"); - assertThat(theme.isSystemTheme()).isFalse(); - assertThat(theme.getApplicationId()).isNotNull(); - assertThat(theme.getWorkspaceId()).isEqualTo(this.workspace.getId()); - assertThat(theme.getConfig()).isNotNull(); - }).verifyComplete(); + StepVerifier.create(updateThemeNameMono) + .assertNext(theme -> { + assertThat(theme.getName()).isEqualTo("new name"); + assertThat(theme.getDisplayName()).isEqualTo("new display name"); + assertThat(theme.isSystemTheme()).isFalse(); + assertThat(theme.getApplicationId()).isNotNull(); + assertThat(theme.getWorkspaceId()).isEqualTo(this.workspace.getId()); + assertThat(theme.getConfig()).isNotNull(); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -787,17 +836,16 @@ public void importThemesToApplication_WhenBothImportedThemesAreCustom_NewThemesC applicationJson.setPublishedTheme(customTheme); Mono<Application> applicationMono = Mono.just(application) - .flatMap(savedApplication -> - themeService.importThemesToApplication(savedApplication, applicationJson) - .thenReturn(savedApplication.getId()) - ) - .flatMap(applicationId -> - applicationRepository.findById(applicationId, MANAGE_APPLICATIONS) - ); - - StepVerifier.create(applicationMono).assertNext(app -> { - assertThat(app.getEditModeThemeId().equals(app.getPublishedModeThemeId())).isFalse(); - }).verifyComplete(); + .flatMap(savedApplication -> themeService + .importThemesToApplication(savedApplication, applicationJson) + .thenReturn(savedApplication.getId())) + .flatMap(applicationId -> applicationRepository.findById(applicationId, MANAGE_APPLICATIONS)); + + StepVerifier.create(applicationMono) + .assertNext(app -> { + assertThat(app.getEditModeThemeId().equals(app.getPublishedModeThemeId())) + .isFalse(); + }) + .verifyComplete(); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UsagePulseServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UsagePulseServiceTest.java index 839cb7907b77..f298c64fd54d 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UsagePulseServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UsagePulseServiceTest.java @@ -133,6 +133,5 @@ public void createUsagePulse_forAppsmithCloud_pulseNotSavedInDB() { assertThat(usagePulseCount).isNotNull(); assertThat(usagePulseCountForSelfHostedInstance).isEqualTo(usagePulseCount + 1); assertThat(usagePulseCountForSelfHostedInstance).isEqualTo(usagePulseCountForCloud); - } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserDataServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserDataServiceTest.java index 8fe176c13d0c..53b5014ec550 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserDataServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserDataServiceTest.java @@ -49,22 +49,31 @@ public class UserDataServiceTest { private static final String DEFAULT_GIT_PROFILE = "default"; + @Autowired UserService userService; + @Autowired private UserDataService userDataService; + @Autowired private UserDataRepository userDataRepository; + @Autowired private AssetRepository assetRepository; + @MockBean private UserChangedHandler userChangedHandler; + @Autowired private AssetService assetService; + @Autowired private ApplicationRepository applicationRepository; + @Autowired private GitService gitService; + private Mono<User> userMono; @BeforeEach @@ -74,8 +83,8 @@ public void setup() { @Test public void ensureViewedReleaseVersionNotesIsSet() { - final Mono<UserData> resultMono = userMono - .flatMap(user -> userDataService.ensureViewedCurrentVersionReleaseNotes(user)) + final Mono<UserData> resultMono = userMono.flatMap( + user -> userDataService.ensureViewedCurrentVersionReleaseNotes(user)) .flatMap(user -> userDataService.getForUser(user)); StepVerifier.create(resultMono) @@ -87,8 +96,8 @@ public void ensureViewedReleaseVersionNotesIsSet() { @Test public void setViewedReleaseNotesVersion() { - final Mono<UserData> resultMono = userMono - .flatMap(user -> userDataService.setViewedCurrentVersionReleaseNotes(user, "version-1")) + final Mono<UserData> resultMono = userMono.flatMap( + user -> userDataService.setViewedCurrentVersionReleaseNotes(user, "version-1")) .flatMap(user -> userDataService.getForUser(user)); StepVerifier.create(resultMono) @@ -100,8 +109,8 @@ public void setViewedReleaseNotesVersion() { @Test public void updateViewedReleaseNotesVersion() { - final Mono<UserData> resultMono = userMono - .flatMap(user -> userDataService.setViewedCurrentVersionReleaseNotes(user, "version-1")) + final Mono<UserData> resultMono = userMono.flatMap( + user -> userDataService.setViewedCurrentVersionReleaseNotes(user, "version-1")) .flatMap(user -> userDataService.setViewedCurrentVersionReleaseNotes(user, "version-2")) .flatMap(user -> userDataService.getForUser(user)); @@ -116,7 +125,8 @@ public void updateViewedReleaseNotesVersion() { @WithUserDetails(value = "api_user") public void testUploadAndDeleteProfilePhoto_validImage() { FilePart filepart = createMockFilePart(); - Mono<Tuple2<UserData, Asset>> loadProfileImageMono = userDataService.getForUserEmail("api_user") + Mono<Tuple2<UserData, Asset>> loadProfileImageMono = userDataService + .getForUserEmail("api_user") .flatMap(userData -> { Mono<UserData> userDataMono = Mono.just(userData); if (StringUtils.isEmpty(userData.getProfilePhotoAssetId())) { @@ -126,10 +136,11 @@ public void testUploadAndDeleteProfilePhoto_validImage() { } }); - final Mono<UserData> saveMono = userDataService.saveProfilePhoto(filepart).cache(); + final Mono<UserData> saveMono = + userDataService.saveProfilePhoto(filepart).cache(); final Mono<Tuple2<UserData, Asset>> saveAndGetMono = saveMono.then(loadProfileImageMono); - final Mono<Tuple2<UserData, Asset>> deleteAndGetMono = saveMono.then(userDataService.deleteProfilePhoto()) - .then(loadProfileImageMono); + final Mono<Tuple2<UserData, Asset>> deleteAndGetMono = + saveMono.then(userDataService.deleteProfilePhoto()).then(loadProfileImageMono); StepVerifier.create(saveAndGetMono) .assertNext(tuple -> { @@ -154,14 +165,17 @@ public void testUploadAndDeleteProfilePhoto_validImage() { @WithUserDetails(value = "api_user") public void testUploadProfilePhoto_invalidImageFormat() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), new DefaultDataBufferFactory(), 4096) + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), + new DefaultDataBufferFactory(), + 4096) .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_GIF); - final Mono<UserData> saveMono = userDataService.saveProfilePhoto(filepart).cache(); + final Mono<UserData> saveMono = + userDataService.saveProfilePhoto(filepart).cache(); StepVerifier.create(saveMono) .expectErrorMatches(error -> error instanceof AppsmithException) @@ -169,18 +183,22 @@ public void testUploadProfilePhoto_invalidImageFormat() { } /* - This test uploads an invalid image (json file for which extension has been changed to .png) and validates the upload failure - */ + This test uploads an invalid image (json file for which extension has been changed to .png) and validates the upload failure + */ @Test @WithUserDetails(value = "api_user") public void testUploadProfilePhoto_invalidImageContent() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/json_file_to_png.png"), new DefaultDataBufferFactory(), 4096).cache(); + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/json_file_to_png.png"), + new DefaultDataBufferFactory(), + 4096) + .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); - final Mono<UserData> saveMono = userDataService.saveProfilePhoto(filepart).cache(); + final Mono<UserData> saveMono = + userDataService.saveProfilePhoto(filepart).cache(); StepVerifier.create(saveMono) .expectErrorMatches(error -> error instanceof AppsmithException) @@ -191,15 +209,18 @@ public void testUploadProfilePhoto_invalidImageContent() { @WithUserDetails(value = "api_user") public void testUploadProfilePhoto_invalidImageSize() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo_large.png"), new DefaultDataBufferFactory(), 4096) - .repeat(100) // So the file size looks like it's much larger than what it actually is. + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo_large.png"), + new DefaultDataBufferFactory(), + 4096) + .repeat(100) // So the file size looks like it's much larger than what it actually is. .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); - final Mono<UserData> saveMono = userDataService.saveProfilePhoto(filepart).cache(); + final Mono<UserData> saveMono = + userDataService.saveProfilePhoto(filepart).cache(); StepVerifier.create(saveMono) .expectErrorMatches(error -> error instanceof AppsmithException) @@ -213,37 +234,51 @@ public void updateLastUsedAppAndWorkspaceList_WhenListIsEmpty_workspaceIdPrepend Application application = new Application(); application.setWorkspaceId(sampleWorkspaceId); - final Mono<UserData> saveMono = userDataService.getForCurrentUser().flatMap(userData -> { - // set recently used org ids to null - userData.setRecentlyUsedWorkspaceIds(null); - return userDataRepository.save(userData); - }).then(userDataService.updateLastUsedAppAndWorkspaceList(application)); + final Mono<UserData> saveMono = userDataService + .getForCurrentUser() + .flatMap(userData -> { + // set recently used org ids to null + userData.setRecentlyUsedWorkspaceIds(null); + return userDataRepository.save(userData); + }) + .then(userDataService.updateLastUsedAppAndWorkspaceList(application)); - StepVerifier.create(saveMono).assertNext(userData -> { - assertEquals(1, userData.getRecentlyUsedWorkspaceIds().size()); - assertEquals(sampleWorkspaceId, userData.getRecentlyUsedWorkspaceIds().get(0)); - }).verifyComplete(); + StepVerifier.create(saveMono) + .assertNext(userData -> { + assertEquals(1, userData.getRecentlyUsedWorkspaceIds().size()); + assertEquals( + sampleWorkspaceId, + userData.getRecentlyUsedWorkspaceIds().get(0)); + }) + .verifyComplete(); } @Test @WithUserDetails(value = "api_user") public void updateLastUsedAppAndWorkspaceList_WhenListIsNotEmpty_workspaceIdPrepended() { - final Mono<UserData> resultMono = userDataService.getForCurrentUser().flatMap(userData -> { - // Set an initial list of org ids to the current user. - userData.setRecentlyUsedWorkspaceIds(Arrays.asList("123", "456")); - return userDataRepository.save(userData); - }).flatMap(userData -> { - // Now check whether a new org id is put at first. - String sampleWorkspaceId = "sample-org-id"; - Application application = new Application(); - application.setWorkspaceId(sampleWorkspaceId); - return userDataService.updateLastUsedAppAndWorkspaceList(application); - }); - - StepVerifier.create(resultMono).assertNext(userData -> { - assertEquals(3, userData.getRecentlyUsedWorkspaceIds().size()); - assertEquals("sample-org-id", userData.getRecentlyUsedWorkspaceIds().get(0)); - }).verifyComplete(); + final Mono<UserData> resultMono = userDataService + .getForCurrentUser() + .flatMap(userData -> { + // Set an initial list of org ids to the current user. + userData.setRecentlyUsedWorkspaceIds(Arrays.asList("123", "456")); + return userDataRepository.save(userData); + }) + .flatMap(userData -> { + // Now check whether a new org id is put at first. + String sampleWorkspaceId = "sample-org-id"; + Application application = new Application(); + application.setWorkspaceId(sampleWorkspaceId); + return userDataService.updateLastUsedAppAndWorkspaceList(application); + }); + + StepVerifier.create(resultMono) + .assertNext(userData -> { + assertEquals(3, userData.getRecentlyUsedWorkspaceIds().size()); + assertEquals( + "sample-org-id", + userData.getRecentlyUsedWorkspaceIds().get(0)); + }) + .verifyComplete(); } @Test @@ -251,73 +286,88 @@ public void updateLastUsedAppAndWorkspaceList_WhenListIsNotEmpty_workspaceIdPrep public void updateLastUsedAppAndOrgList_TooManyRecentIds_ListsAreTruncated() { String sampleWorkspaceId = "sample-org-id", sampleAppId = "sample-app-id"; - final Mono<UserData> resultMono = userDataService.getForCurrentUser().flatMap(userData -> { - // Set an initial list of 12 org ids to the current user - userData.setRecentlyUsedWorkspaceIds(new ArrayList<>()); - for (int i = 1; i <= 12; i++) { - userData.getRecentlyUsedWorkspaceIds().add("org-" + i); - } - - // Set an initial list of 22 app ids to the current user. - userData.setRecentlyUsedAppIds(new ArrayList<>()); - for (int i = 1; i <= 22; i++) { - userData.getRecentlyUsedAppIds().add("app-" + i); - } - return userDataRepository.save(userData); - }).flatMap(userData -> { - // Now check whether a new org id is put at first. - Application application = new Application(); - application.setId(sampleAppId); - application.setWorkspaceId(sampleWorkspaceId); - return userDataService.updateLastUsedAppAndWorkspaceList(application); - }); - - StepVerifier.create(resultMono).assertNext(userData -> { - // org id list should be truncated to 10 - assertThat(userData.getRecentlyUsedWorkspaceIds().size()).isEqualTo(10); - assertThat(userData.getRecentlyUsedWorkspaceIds().get(0)).isEqualTo(sampleWorkspaceId); - assertThat(userData.getRecentlyUsedWorkspaceIds().get(9)).isEqualTo("org-9"); - - // app id list should be truncated to 20 - assertThat(userData.getRecentlyUsedAppIds().size()).isEqualTo(20); - assertThat(userData.getRecentlyUsedAppIds().get(0)).isEqualTo(sampleAppId); - assertThat(userData.getRecentlyUsedAppIds().get(19)).isEqualTo("app-19"); - }).verifyComplete(); + final Mono<UserData> resultMono = userDataService + .getForCurrentUser() + .flatMap(userData -> { + // Set an initial list of 12 org ids to the current user + userData.setRecentlyUsedWorkspaceIds(new ArrayList<>()); + for (int i = 1; i <= 12; i++) { + userData.getRecentlyUsedWorkspaceIds().add("org-" + i); + } + + // Set an initial list of 22 app ids to the current user. + userData.setRecentlyUsedAppIds(new ArrayList<>()); + for (int i = 1; i <= 22; i++) { + userData.getRecentlyUsedAppIds().add("app-" + i); + } + return userDataRepository.save(userData); + }) + .flatMap(userData -> { + // Now check whether a new org id is put at first. + Application application = new Application(); + application.setId(sampleAppId); + application.setWorkspaceId(sampleWorkspaceId); + return userDataService.updateLastUsedAppAndWorkspaceList(application); + }); + + StepVerifier.create(resultMono) + .assertNext(userData -> { + // org id list should be truncated to 10 + assertThat(userData.getRecentlyUsedWorkspaceIds().size()).isEqualTo(10); + assertThat(userData.getRecentlyUsedWorkspaceIds().get(0)).isEqualTo(sampleWorkspaceId); + assertThat(userData.getRecentlyUsedWorkspaceIds().get(9)).isEqualTo("org-9"); + + // app id list should be truncated to 20 + assertThat(userData.getRecentlyUsedAppIds().size()).isEqualTo(20); + assertThat(userData.getRecentlyUsedAppIds().get(0)).isEqualTo(sampleAppId); + assertThat(userData.getRecentlyUsedAppIds().get(19)).isEqualTo("app-19"); + }) + .verifyComplete(); } @Test @WithUserDetails(value = "api_user") public void addTemplateIdToLastUsedList_WhenListIsEmpty_templateIdPrepended() { - final Mono<UserData> saveMono = userDataService.getForCurrentUser().flatMap(userData -> { - // set recently used template ids to null - userData.setRecentlyUsedTemplateIds(null); - return userDataRepository.save(userData); - }).then(userDataService.addTemplateIdToLastUsedList("123456")); - - StepVerifier.create(saveMono).assertNext(userData -> { - assertEquals(1, userData.getRecentlyUsedTemplateIds().size()); - assertEquals("123456", userData.getRecentlyUsedTemplateIds().get(0)); - }).verifyComplete(); + final Mono<UserData> saveMono = userDataService + .getForCurrentUser() + .flatMap(userData -> { + // set recently used template ids to null + userData.setRecentlyUsedTemplateIds(null); + return userDataRepository.save(userData); + }) + .then(userDataService.addTemplateIdToLastUsedList("123456")); + + StepVerifier.create(saveMono) + .assertNext(userData -> { + assertEquals(1, userData.getRecentlyUsedTemplateIds().size()); + assertEquals("123456", userData.getRecentlyUsedTemplateIds().get(0)); + }) + .verifyComplete(); } @Test @WithUserDetails(value = "api_user") public void addTemplateIdToLastUsedList_WhenListIsNotEmpty_templateIdPrepended() { - final Mono<UserData> resultMono = userDataService.getForCurrentUser().flatMap(userData -> { - // Set an initial list of template ids to the current user. - userData.setRecentlyUsedTemplateIds(Arrays.asList("123", "456")); - return userDataRepository.save(userData); - }).flatMap(userData -> { - // Now check whether a new template id is put at first. - String newTemplateId = "456"; - return userDataService.addTemplateIdToLastUsedList(newTemplateId); - }); - - StepVerifier.create(resultMono).assertNext(userData -> { - assertEquals(2, userData.getRecentlyUsedTemplateIds().size()); - assertEquals("456", userData.getRecentlyUsedTemplateIds().get(0)); - assertEquals("123", userData.getRecentlyUsedTemplateIds().get(1)); - }).verifyComplete(); + final Mono<UserData> resultMono = userDataService + .getForCurrentUser() + .flatMap(userData -> { + // Set an initial list of template ids to the current user. + userData.setRecentlyUsedTemplateIds(Arrays.asList("123", "456")); + return userDataRepository.save(userData); + }) + .flatMap(userData -> { + // Now check whether a new template id is put at first. + String newTemplateId = "456"; + return userDataService.addTemplateIdToLastUsedList(newTemplateId); + }); + + StepVerifier.create(resultMono) + .assertNext(userData -> { + assertEquals(2, userData.getRecentlyUsedTemplateIds().size()); + assertEquals("456", userData.getRecentlyUsedTemplateIds().get(0)); + assertEquals("123", userData.getRecentlyUsedTemplateIds().get(1)); + }) + .verifyComplete(); } @Test @@ -325,43 +375,49 @@ public void addTemplateIdToLastUsedList_WhenListIsNotEmpty_templateIdPrepended() public void addTemplateIdToLastUsedList_TooManyRecentIds_ListsAreTruncated() { String newTemplateId = "new-template-id"; - final Mono<UserData> resultMono = userDataService.getForCurrentUser().flatMap(userData -> { - // Set an initial list of 12 template ids to the current user - userData.setRecentlyUsedTemplateIds(new ArrayList<>()); - for (int i = 1; i <= 12; i++) { - userData.getRecentlyUsedTemplateIds().add("template-" + i); - } - return userDataRepository.save(userData); - }).flatMap(userData -> { - // Now check whether a new template id is put at first. - return userDataService.addTemplateIdToLastUsedList(newTemplateId); - }); - - StepVerifier.create(resultMono).assertNext(userData -> { - // org id list should be truncated to 10 - assertThat(userData.getRecentlyUsedTemplateIds().size()).isEqualTo(5); - assertThat(userData.getRecentlyUsedTemplateIds().get(0)).isEqualTo(newTemplateId); - assertThat(userData.getRecentlyUsedTemplateIds().get(4)).isEqualTo("template-4"); - }).verifyComplete(); + final Mono<UserData> resultMono = userDataService + .getForCurrentUser() + .flatMap(userData -> { + // Set an initial list of 12 template ids to the current user + userData.setRecentlyUsedTemplateIds(new ArrayList<>()); + for (int i = 1; i <= 12; i++) { + userData.getRecentlyUsedTemplateIds().add("template-" + i); + } + return userDataRepository.save(userData); + }) + .flatMap(userData -> { + // Now check whether a new template id is put at first. + return userDataService.addTemplateIdToLastUsedList(newTemplateId); + }); + + StepVerifier.create(resultMono) + .assertNext(userData -> { + // org id list should be truncated to 10 + assertThat(userData.getRecentlyUsedTemplateIds().size()).isEqualTo(5); + assertThat(userData.getRecentlyUsedTemplateIds().get(0)).isEqualTo(newTemplateId); + assertThat(userData.getRecentlyUsedTemplateIds().get(4)).isEqualTo("template-4"); + }) + .verifyComplete(); } @Test @WithUserDetails(value = "api_user") public void deleteProfilePhotot_WhenExists_RemovedFromAssetAndUserData() { // create an asset first - Mono<Tuple2<UserData, Asset>> tuple2Mono = assetRepository.save(new Asset(MediaType.IMAGE_PNG, new byte[10])) - .flatMap(savedAsset -> - userDataService.getForCurrentUser().flatMap(userData -> { - userData.setProfilePhotoAssetId(savedAsset.getId()); - return userDataRepository.save(userData); - })) + Mono<Tuple2<UserData, Asset>> tuple2Mono = assetRepository + .save(new Asset(MediaType.IMAGE_PNG, new byte[10])) + .flatMap(savedAsset -> userDataService.getForCurrentUser().flatMap(userData -> { + userData.setProfilePhotoAssetId(savedAsset.getId()); + return userDataRepository.save(userData); + })) .flatMap(userData -> { String assetId = userData.getProfilePhotoAssetId(); return userDataService.deleteProfilePhoto().thenReturn(assetId); }) .flatMap(assetId -> { Mono<UserData> forCurrentUser = userDataService.getForCurrentUser(); - return forCurrentUser.zipWith(assetRepository.findById(assetId).defaultIfEmpty(new Asset())); + return forCurrentUser.zipWith( + assetRepository.findById(assetId).defaultIfEmpty(new Asset())); }); StepVerifier.create(tuple2Mono) @@ -374,8 +430,11 @@ public void deleteProfilePhotot_WhenExists_RemovedFromAssetAndUserData() { private FilePart createMockFilePart() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), new DefaultDataBufferFactory(), 4096).cache(); + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), + new DefaultDataBufferFactory(), + 4096) + .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); return filepart; @@ -386,9 +445,11 @@ private FilePart createMockFilePart() { public void saveProfilePhoto_WhenPhotoUploaded_PhotoChangedEventTriggered() { Part mockFilePart = createMockFilePart(); Mono<UserData> userDataMono = userDataService.saveProfilePhoto(mockFilePart); - StepVerifier.create(userDataMono).assertNext(userData -> { - assertThat(userData.getProfilePhotoAssetId()).isNotNull(); - }).verifyComplete(); + StepVerifier.create(userDataMono) + .assertNext(userData -> { + assertThat(userData.getProfilePhotoAssetId()).isNotNull(); + }) + .verifyComplete(); } // Git user profile tests @@ -404,9 +465,9 @@ private GitProfile createGitProfile(String commitEmail, String author) { public void saveConfig_AuthorEmailNull_ThrowInvalidParameterError() { GitProfile gitGlobalConfigDTO = createGitProfile(null, "Test 1"); - Mono<Map<String, GitProfile>> userDataMono = gitService.updateOrCreateGitProfileForCurrentUser(gitGlobalConfigDTO); - StepVerifier - .create(userDataMono) + Mono<Map<String, GitProfile>> userDataMono = + gitService.updateOrCreateGitProfileForCurrentUser(gitGlobalConfigDTO); + StepVerifier.create(userDataMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage("Author Email"))) .verify(); @@ -417,14 +478,19 @@ public void saveConfig_AuthorEmailNull_ThrowInvalidParameterError() { public void saveRepoLevelConfig_AuthorEmailNullAndName_SavesGitProfile() { GitProfile gitProfileDTO = createGitProfile(null, null); - Mono<Map<String, GitProfile>> userDataMono = gitService.updateOrCreateGitProfileForCurrentUser(gitProfileDTO, "defaultAppId"); - StepVerifier - .create(userDataMono) + Mono<Map<String, GitProfile>> userDataMono = + gitService.updateOrCreateGitProfileForCurrentUser(gitProfileDTO, "defaultAppId"); + StepVerifier.create(userDataMono) .assertNext(gitProfileMap -> { AssertionsForClassTypes.assertThat(gitProfileMap).isNotNull(); - AssertionsForClassTypes.assertThat(gitProfileMap.get("defaultAppId").getAuthorEmail()).isNullOrEmpty(); - AssertionsForClassTypes.assertThat(gitProfileMap.get("defaultAppId").getAuthorName()).isNullOrEmpty(); - AssertionsForClassTypes.assertThat(gitProfileDTO.getUseGlobalProfile()).isFalse(); + AssertionsForClassTypes.assertThat( + gitProfileMap.get("defaultAppId").getAuthorEmail()) + .isNullOrEmpty(); + AssertionsForClassTypes.assertThat( + gitProfileMap.get("defaultAppId").getAuthorName()) + .isNullOrEmpty(); + AssertionsForClassTypes.assertThat(gitProfileDTO.getUseGlobalProfile()) + .isFalse(); }) .verifyComplete(); } @@ -434,26 +500,24 @@ public void saveRepoLevelConfig_AuthorEmailNullAndName_SavesGitProfile() { public void saveConfig_AuthorNameEmptyString_ThrowInvalidParameterError() { GitProfile gitGlobalConfigDTO = createGitProfile("[email protected]", null); - Mono<Map<String, GitProfile>> userDataMono = gitService.updateOrCreateGitProfileForCurrentUser(gitGlobalConfigDTO); - StepVerifier - .create(userDataMono) + Mono<Map<String, GitProfile>> userDataMono = + gitService.updateOrCreateGitProfileForCurrentUser(gitGlobalConfigDTO); + StepVerifier.create(userDataMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException && throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage("Author Name"))) .verify(); } - @Test @WithUserDetails(value = "api_user") public void getAndUpdateDefaultGitProfile_fallbackValueFromUserProfileIfEmpty_updateWithProfile() { Mono<GitProfile> gitConfigMono = gitService.getDefaultGitProfileOrCreateIfEmpty(); - Mono<User> userData = userDataService.getForCurrentUser() - .flatMap(userData1 -> userService.getById(userData1.getUserId())); + Mono<User> userData = + userDataService.getForCurrentUser().flatMap(userData1 -> userService.getById(userData1.getUserId())); - StepVerifier - .create(gitConfigMono.zipWhen(gitProfile -> userData)) + StepVerifier.create(gitConfigMono.zipWhen(gitProfile -> userData)) .assertNext(tuple -> { GitProfile gitProfile = tuple.getT1(); User user = tuple.getT2(); @@ -463,16 +527,17 @@ public void getAndUpdateDefaultGitProfile_fallbackValueFromUserProfileIfEmpty_up .verifyComplete(); GitProfile gitGlobalConfigDTO = createGitProfile("[email protected]", "Test 1"); - Mono<Map<String, GitProfile>> gitProfilesMono = gitService.updateOrCreateGitProfileForCurrentUser(gitGlobalConfigDTO); + Mono<Map<String, GitProfile>> gitProfilesMono = + gitService.updateOrCreateGitProfileForCurrentUser(gitGlobalConfigDTO); - StepVerifier - .create(gitProfilesMono) + StepVerifier.create(gitProfilesMono) .assertNext(gitProfileMap -> { GitProfile defaultProfile = gitProfileMap.get(DEFAULT_GIT_PROFILE); - AssertionsForClassTypes.assertThat(defaultProfile.getAuthorName()).isEqualTo(gitGlobalConfigDTO.getAuthorName()); - AssertionsForClassTypes.assertThat(defaultProfile.getAuthorEmail()).isEqualTo(gitGlobalConfigDTO.getAuthorEmail()); + AssertionsForClassTypes.assertThat(defaultProfile.getAuthorName()) + .isEqualTo(gitGlobalConfigDTO.getAuthorName()); + AssertionsForClassTypes.assertThat(defaultProfile.getAuthorEmail()) + .isEqualTo(gitGlobalConfigDTO.getAuthorEmail()); }) .verifyComplete(); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceTest.java index 655b82c39035..f04de87bd8c8 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceTest.java @@ -57,7 +57,6 @@ import java.util.UUID; import static com.appsmith.server.acl.AclPermission.MANAGE_USERS; -import static com.appsmith.server.acl.AclPermission.READ_USERS; import static com.appsmith.server.acl.AclPermission.RESET_PASSWORD_USERS; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -116,7 +115,7 @@ public void setup() { userMono = userService.findByEmail("[email protected]"); } - //Test if email params are updating correctly + // Test if email params are updating correctly @Test public void checkEmailParamsForExistingUser() { Workspace workspace = new Workspace(); @@ -152,7 +151,7 @@ public void checkEmailParamsForNewUser() { assertEquals("UserServiceTest Update Org", params.get("inviterWorkspaceName")); } - //Test the update workspace flow. + // Test the update workspace flow. @Test public void updateInvalidUserWithAnything() { User updateUser = new User(); @@ -164,8 +163,11 @@ public void updateInvalidUserWithAnything() { Mono<User> userMono1 = Mono.just(existingUser).flatMap(user -> userService.update(user.getId(), updateUser)); StepVerifier.create(userMono1) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.USER, "Random-UserId-%Not-In_The-System_For_SUre"))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.USER, "Random-UserId-%Not-In_The-System_For_SUre"))) .verify(); } @@ -178,8 +180,8 @@ public void createNewUserFormSignupNullPassword() { Mono<User> userMono = userService.create(newUser); StepVerifier.create(userMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_CREDENTIALS.getMessage())) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_CREDENTIALS.getMessage())) .verify(); } @@ -192,17 +194,20 @@ public void createNewUserValid() { Mono<User> userCreateMono = userService.create(newUser).cache(); - Mono<PermissionGroup> permissionGroupMono = userCreateMono - .flatMap(user -> { - Set<Policy> userPolicies = user.getPolicies(); - assertThat(userPolicies.size()).isNotZero(); - Optional<Policy> optionalResetPasswordPolicy = userPolicies.stream().filter(policy1 -> policy1.getPermission().equals(RESET_PASSWORD_USERS.getValue())).findFirst(); - assertThat(optionalResetPasswordPolicy.isPresent()).isTrue(); - assertThat(optionalResetPasswordPolicy.get().getPermissionGroups()).isNotEmpty(); - String permissionGroupId = optionalResetPasswordPolicy.get().getPermissionGroups().stream().findFirst().get(); - - return permissionGroupRepository.findById(permissionGroupId); - }); + Mono<PermissionGroup> permissionGroupMono = userCreateMono.flatMap(user -> { + Set<Policy> userPolicies = user.getPolicies(); + assertThat(userPolicies.size()).isNotZero(); + Optional<Policy> optionalResetPasswordPolicy = userPolicies.stream() + .filter(policy1 -> policy1.getPermission().equals(RESET_PASSWORD_USERS.getValue())) + .findFirst(); + assertThat(optionalResetPasswordPolicy.isPresent()).isTrue(); + assertThat(optionalResetPasswordPolicy.get().getPermissionGroups()).isNotEmpty(); + String permissionGroupId = optionalResetPasswordPolicy.get().getPermissionGroups().stream() + .findFirst() + .get(); + + return permissionGroupRepository.findById(permissionGroupId); + }); StepVerifier.create(Mono.zip(userCreateMono, permissionGroupMono)) .assertNext(tuple -> { @@ -223,9 +228,11 @@ public void createNewUserValid() { .filter(policy -> MANAGE_USERS.getValue().equals(policy.getPermission())) .findFirst(); assertThat(optionalManageUserPolicy.isPresent()).isTrue(); - assertThat(optionalManageUserPolicy.get().getPermissionGroups()).contains(permissionGroup.getId()); + assertThat(optionalManageUserPolicy.get().getPermissionGroups()) + .contains(permissionGroup.getId()); assertThat(optionalViewUserPolicy.isPresent()).isTrue(); - assertThat(optionalViewUserPolicy.get().getPermissionGroups()).contains(permissionGroup.getId()); + assertThat(optionalViewUserPolicy.get().getPermissionGroups()) + .contains(permissionGroup.getId()); assertThat(permissionGroup.getAssignedToUserIds()).containsAll(Set.of(user.getId())); }) .verifyComplete(); @@ -245,17 +252,20 @@ public void createNewUser_WhenEmailHasUpperCase_SavedInLowerCase() { Mono<User> userCreateMono = userService.create(newUser).cache(); - Mono<PermissionGroup> permissionGroupMono = userCreateMono - .flatMap(user -> { - Set<Policy> userPolicies = user.getPolicies(); - assertThat(userPolicies.size()).isNotZero(); - Optional<Policy> optionalResetPasswordPolicy = userPolicies.stream().filter(policy1 -> policy1.getPermission().equals(RESET_PASSWORD_USERS.getValue())).findFirst(); - assertThat(optionalResetPasswordPolicy.isPresent()).isTrue(); - assertThat(optionalResetPasswordPolicy.get().getPermissionGroups()).isNotEmpty(); - String permissionGroupId = optionalResetPasswordPolicy.get().getPermissionGroups().stream().findFirst().get(); - - return permissionGroupRepository.findById(permissionGroupId); - }); + Mono<PermissionGroup> permissionGroupMono = userCreateMono.flatMap(user -> { + Set<Policy> userPolicies = user.getPolicies(); + assertThat(userPolicies.size()).isNotZero(); + Optional<Policy> optionalResetPasswordPolicy = userPolicies.stream() + .filter(policy1 -> policy1.getPermission().equals(RESET_PASSWORD_USERS.getValue())) + .findFirst(); + assertThat(optionalResetPasswordPolicy.isPresent()).isTrue(); + assertThat(optionalResetPasswordPolicy.get().getPermissionGroups()).isNotEmpty(); + String permissionGroupId = optionalResetPasswordPolicy.get().getPermissionGroups().stream() + .findFirst() + .get(); + + return permissionGroupRepository.findById(permissionGroupId); + }); StepVerifier.create(Mono.zip(userCreateMono, permissionGroupMono)) .assertNext(tuple -> { @@ -275,9 +285,11 @@ public void createNewUser_WhenEmailHasUpperCase_SavedInLowerCase() { .filter(policy -> MANAGE_USERS.getValue().equals(policy.getPermission())) .findFirst(); assertThat(optionalManageUserPolicy.isPresent()).isTrue(); - assertThat(optionalManageUserPolicy.get().getPermissionGroups()).contains(permissionGroup.getId()); + assertThat(optionalManageUserPolicy.get().getPermissionGroups()) + .contains(permissionGroup.getId()); assertThat(optionalViewUserPolicy.isPresent()).isTrue(); - assertThat(optionalViewUserPolicy.get().getPermissionGroups()).contains(permissionGroup.getId()); + assertThat(optionalViewUserPolicy.get().getPermissionGroups()) + .contains(permissionGroup.getId()); assertThat(permissionGroup.getAssignedToUserIds()).containsAll(Set.of(user.getId())); }) .verifyComplete(); @@ -341,9 +353,7 @@ public void signUpAfterBeingInvitedToAppsmithWorkspace() { workspace.setDomain("example.com"); workspace.setWebsite("https://example.com"); - Mono<Workspace> workspaceMono = workspaceService - .create(workspace) - .cache(); + Mono<Workspace> workspaceMono = workspaceService.create(workspace).cache(); String newUserEmail = "[email protected]"; @@ -354,19 +364,22 @@ public void signUpAfterBeingInvitedToAppsmithWorkspace() { ArrayList<String> users = new ArrayList<>(); users.add(newUserEmail); inviteUsersDTO.setUsernames(users); - inviteUsersDTO.setPermissionGroupId(workspace1.getDefaultPermissionGroups().stream().findFirst().get()); + inviteUsersDTO.setPermissionGroupId(workspace1.getDefaultPermissionGroups().stream() + .findFirst() + .get()); return userAndAccessManagementService.inviteUsers(inviteUsersDTO, "http://localhost:8080"); - }).block(); + }) + .block(); // Now Sign Up as the new user User signUpUser = new User(); signUpUser.setEmail(newUserEmail); signUpUser.setPassword("123456"); - Mono<User> invitedUserSignUpMono = - userService.createUserAndSendEmail(signUpUser, "http://localhost:8080") - .map(UserSignupDTO::getUser); + Mono<User> invitedUserSignUpMono = userService + .createUserAndSendEmail(signUpUser, "http://localhost:8080") + .map(UserSignupDTO::getUser); StepVerifier.create(invitedUserSignUpMono) .assertNext(user -> { @@ -374,7 +387,6 @@ public void signUpAfterBeingInvitedToAppsmithWorkspace() { assertTrue(passwordEncoder.matches("123456", user.getPassword())); }) .verifyComplete(); - } @Test @@ -383,10 +395,9 @@ public void getAllUsersTest() { Flux<User> userFlux = userService.get(CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>())); StepVerifier.create(userFlux) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.UNSUPPORTED_OPERATION.getMessage())) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.UNSUPPORTED_OPERATION.getMessage())) .verify(); - } @Test @@ -404,8 +415,7 @@ public void createUserWithInvalidEmailAddress() { "[email protected] (Joe Smith)", "[email protected]", "[email protected]", - "[email protected]" - ); + "[email protected]"); for (String invalidAddress : invalidAddresses) { User user = new User(); user.setEmail(invalidAddress); @@ -437,11 +447,8 @@ public void updateNameOfUser_WithNotAllowedSpecialCharacter_InvalidName() { UserUpdateDTO updateUser = new UserUpdateDTO(); updateUser.setName("invalid name@symbol"); StepVerifier.create(userService.updateCurrentUser(updateUser, null)) - .expectErrorMatches(throwable -> - throwable instanceof AppsmithException - && - throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME)) - ) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) .verify(); } @@ -463,8 +470,8 @@ public void updateNameOfUser_WithAccentedCharacters_IsValid() { public void updateRoleOfUser() { UserUpdateDTO updateUser = new UserUpdateDTO(); updateUser.setRole("New role of user"); - final Mono<UserData> resultMono = userService.updateCurrentUser(updateUser, null) - .then(userDataService.getForUserEmail("api_user")); + final Mono<UserData> resultMono = + userService.updateCurrentUser(updateUser, null).then(userDataService.getForUserEmail("api_user")); StepVerifier.create(resultMono) .assertNext(userData -> { assertNotNull(userData); @@ -486,8 +493,8 @@ public void updateIntercomConsentOfUser() { UserUpdateDTO updateUser = new UserUpdateDTO(); updateUser.setIntercomConsentGiven(true); - final Mono<UserData> updateToTrueMono = userService.updateCurrentUser(updateUser, null) - .then(userDataMono); + final Mono<UserData> updateToTrueMono = + userService.updateCurrentUser(updateUser, null).then(userDataMono); StepVerifier.create(updateToTrueMono) .assertNext(userData -> { assertNotNull(userData); @@ -496,8 +503,8 @@ public void updateIntercomConsentOfUser() { .verifyComplete(); updateUser.setIntercomConsentGiven(false); - final Mono<UserData> updateToFalseAfterTrueMono = userService.updateCurrentUser(updateUser, null) - .then(userDataMono); + final Mono<UserData> updateToFalseAfterTrueMono = + userService.updateCurrentUser(updateUser, null).then(userDataMono); StepVerifier.create(updateToFalseAfterTrueMono) .assertNext(userData -> { assertNotNull(userData); @@ -511,8 +518,8 @@ public void updateIntercomConsentOfUser() { public void getIntercomConsentOfUserOnCloudHosting_AlwaysTrue() { Mockito.when(commonConfig.isCloudHosting()).thenReturn(true); - Mono<UserProfileDTO> userProfileDTOMono = sessionUserService.getCurrentUser() - .flatMap(userService::buildUserProfileDTO); + Mono<UserProfileDTO> userProfileDTOMono = + sessionUserService.getCurrentUser().flatMap(userService::buildUserProfileDTO); StepVerifier.create(userProfileDTOMono) .assertNext(userProfileDTO -> { @@ -529,11 +536,9 @@ public void updateNameRoleAndUseCaseOfUser() { updateUser.setName("New name of user here"); updateUser.setRole("New role of user"); updateUser.setUseCase("New use case"); - final Mono<Tuple2<User, UserData>> resultMono = userService.updateCurrentUser(updateUser, null) - .flatMap(user -> Mono.zip( - Mono.just(user), - userDataService.getForUserEmail("api_user") - )); + final Mono<Tuple2<User, UserData>> resultMono = userService + .updateCurrentUser(updateUser, null) + .flatMap(user -> Mono.zip(Mono.just(user), userDataService.getForUserEmail("api_user"))); StepVerifier.create(resultMono) .assertNext(tuple -> { final User user = tuple.getT1(); @@ -557,8 +562,8 @@ public void createUserAndSendEmail_WhenUserExistsWithEmailInOtherCase_ThrowsExce newUser.setEmail("[email protected]"); // same as above except c in uppercase newUser.setSource(LoginSource.FORM); newUser.setPassword("abcdefgh"); - Mono<User> userAndSendEmail = userService.createUserAndSendEmail(newUser, null) - .map(UserSignupDTO::getUser); + Mono<User> userAndSendEmail = + userService.createUserAndSendEmail(newUser, null).map(UserSignupDTO::getUser); StepVerifier.create(userAndSendEmail) .expectErrorMessage(AppsmithError.USER_ALREADY_EXISTS_SIGNUP.getMessage(existingUser.getEmail())) @@ -670,13 +675,14 @@ public void buildUserProfileDTO_WhenAnonymousUser_ReturnsProfile() { User user = new User(); user.setIsAnonymous(true); user.setEmail("anonymousUser"); - StepVerifier.create(userService.buildUserProfileDTO(user)).assertNext(userProfileDTO -> { - assertThat(userProfileDTO.getUsername()).isEqualTo("anonymousUser"); - assertThat(userProfileDTO.isAnonymous()).isTrue(); - }).verifyComplete(); + StepVerifier.create(userService.buildUserProfileDTO(user)) + .assertNext(userProfileDTO -> { + assertThat(userProfileDTO.getUsername()).isEqualTo("anonymousUser"); + assertThat(userProfileDTO.isAnonymous()).isTrue(); + }) + .verifyComplete(); } - /** * This test case asserts that on every user creation, User Management role is auto-created and associated with that user. */ @@ -690,20 +696,25 @@ public void testCreateNewUser_assertUserManagementRole() { User createdUser = userService.create(user).block(); assertThat(createdUser.getPolicies()).isNotEmpty(); - assertThat(createdUser.getPolicies().stream().anyMatch(policy -> policy.getPermission().equals(MANAGE_USERS.getValue()))).isTrue(); + assertThat(createdUser.getPolicies().stream() + .anyMatch(policy -> policy.getPermission().equals(MANAGE_USERS.getValue()))) + .isTrue(); Policy manageUserPolicy = createdUser.getPolicies().stream() .filter(policy -> policy.getPermission().equals(RESET_PASSWORD_USERS.getValue())) .findFirst() .get(); - PermissionGroup userManagementRole = permissionGroupRepository.findAll() - .filter(role -> role.getName().equals(createdUser.getUsername() + FieldName.SUFFIX_USER_MANAGEMENT_ROLE)) + PermissionGroup userManagementRole = permissionGroupRepository + .findAll() + .filter(role -> + role.getName().equals(createdUser.getUsername() + FieldName.SUFFIX_USER_MANAGEMENT_ROLE)) .blockFirst(); assertThat(manageUserPolicy.getPermissionGroups()).hasSize(1); - String userManagementRoleId = manageUserPolicy.getPermissionGroups().stream().findFirst().get(); + String userManagementRoleId = + manageUserPolicy.getPermissionGroups().stream().findFirst().get(); assertThat(userManagementRole.getId()).isEqualTo(userManagementRoleId); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceWithDisabledSignupTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceWithDisabledSignupTest.java index f6fe628a5a1e..9e8165255a2a 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceWithDisabledSignupTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceWithDisabledSignupTest.java @@ -82,8 +82,7 @@ public void createNewAdminValidWhenDisabled() { Mono<User> userMono = userService.create(newUser).cache(); - Mono<Set<String>> assignedToUsersMono = userMono - .flatMap(user -> { + Mono<Set<String>> assignedToUsersMono = userMono.flatMap(user -> { String workspaceName = user.computeFirstName() + "'s apps"; return workspaceRepository.findByName(workspaceName); }) @@ -115,8 +114,7 @@ public void createNewAdminValidWhenDisabled2() { Mono<User> userMono = userService.create(newUser).cache(); - Mono<Set<String>> assignedToUsersMono = userMono - .flatMap(user -> { + Mono<Set<String>> assignedToUsersMono = userMono.flatMap(user -> { String workspaceName = user.computeFirstName() + "'s apps"; return workspaceRepository.findByName(workspaceName); }) @@ -136,7 +134,6 @@ public void createNewAdminValidWhenDisabled2() { assertThat(user.getPolicies()).isNotEmpty(); assertThat(workspaceAssignedToUsers).contains(user.getId()); - }) .verifyComplete(); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserWorkspaceServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserWorkspaceServiceTest.java index a785f4803342..4bfd8db13db1 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserWorkspaceServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserWorkspaceServiceTest.java @@ -13,11 +13,11 @@ import com.appsmith.server.dtos.MemberInfoDTO; import com.appsmith.server.dtos.UpdatePermissionGroupDTO; import com.appsmith.server.exceptions.AppsmithError; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.PermissionGroupRepository; import com.appsmith.server.repositories.UserRepository; import com.appsmith.server.repositories.WorkspaceRepository; +import com.appsmith.server.solutions.PolicySolution; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -42,7 +42,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; - @Slf4j @SpringBootTest @DirtiesContext @@ -50,30 +49,43 @@ public class UserWorkspaceServiceTest { @Autowired WorkspaceService workspaceService; + @Autowired NewPageService newPageService; + @Autowired PermissionGroupRepository permissionGroupRepository; + @Autowired SessionUserService sessionUserService; + @Autowired UserService userService; + @Autowired private UserWorkspaceService userWorkspaceService; + @Autowired private WorkspaceRepository workspaceRepository; + @Autowired private UserRepository userRepository; + @Autowired private PolicySolution policySolution; + @Autowired private ApplicationRepository applicationRepository; + @Autowired private PolicyGenerator policyGenerator; + @Autowired private UserDataService userDataService; + @Autowired private ApplicationPageService applicationPageService; + private Workspace workspace; private User user; @@ -87,15 +99,20 @@ public void setup() { // Now add api_user as a developer of the workspace Set<String> permissionGroupIds = workspace.getDefaultPermissionGroups(); - List<PermissionGroup> permissionGroups = permissionGroupRepository.findAllById(permissionGroupIds).collectList().block(); + List<PermissionGroup> permissionGroups = permissionGroupRepository + .findAllById(permissionGroupIds) + .collectList() + .block(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); User api_user = userService.findByEmail("api_user").block(); User usertest = userService.findByEmail("[email protected]").block(); @@ -106,7 +123,6 @@ public void setup() { permissionGroupRepository.save(adminPermissionGroup).block(); developerPermissionGroup.setAssignedToUserIds(Set.of(api_user.getId())); permissionGroupRepository.save(developerPermissionGroup).block(); - } private UserRole createUserRole(String username, String userId, AppsmithRole role) { @@ -125,9 +141,8 @@ private void addRolesToWorkspace(List<UserRole> roles) { this.workspace.setUserRoles(roles); for (UserRole userRole : roles) { Set<AclPermission> rolePermissions = userRole.getRole().getPermissions(); - Map<String, Policy> workspacePolicyMap = policySolution.generatePolicyFromPermission( - rolePermissions, userRole.getUsername() - ); + Map<String, Policy> workspacePolicyMap = + policySolution.generatePolicyFromPermission(rolePermissions, userRole.getUsername()); this.workspace = policySolution.addPoliciesToExistingObject(workspacePolicyMap, workspace); } this.workspace = workspaceRepository.save(workspace).block(); @@ -145,11 +160,15 @@ public void leaveWorkspace_WhenUserExistsInWorkspace_RemovesUser() { // Now add api_user as a developer of the workspace Set<String> permissionGroupIds = testWorkspace.getDefaultPermissionGroups(); - List<PermissionGroup> permissionGroups = permissionGroupRepository.findAllById(permissionGroupIds).collectList().block(); + List<PermissionGroup> permissionGroups = permissionGroupRepository + .findAllById(permissionGroupIds) + .collectList() + .block(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); User api_user = userService.findByEmail("api_user").block(); User usertest = userService.findByEmail("[email protected]").block(); @@ -160,19 +179,24 @@ public void leaveWorkspace_WhenUserExistsInWorkspace_RemovesUser() { Application application = new Application(); application.setName("Test App " + randomString); - Application savedApplication = applicationPageService.createApplication(application, testWorkspace.getId()).block(); + Application savedApplication = applicationPageService + .createApplication(application, testWorkspace.getId()) + .block(); // Add application and workspace to the recently used list by accessing the application pages. - newPageService.findApplicationPagesByApplicationIdViewModeAndBranch(savedApplication.getId(), null, false, true).block(); + newPageService + .findApplicationPagesByApplicationIdViewModeAndBranch(savedApplication.getId(), null, false, true) + .block(); - Set<String> uniqueUsersInWorkspaceBefore = userWorkspaceService.getWorkspaceMembers(testWorkspace.getId()) + Set<String> uniqueUsersInWorkspaceBefore = userWorkspaceService + .getWorkspaceMembers(testWorkspace.getId()) .flatMapMany(workspaceMembers -> Flux.fromIterable(workspaceMembers)) .map(MemberInfoDTO::getUserId) .collect(Collectors.toSet()) .block(); - Mono<User> leaveWorkspaceMono = userWorkspaceService.leaveWorkspace(testWorkspace.getId()) - .cache(); + Mono<User> leaveWorkspaceMono = + userWorkspaceService.leaveWorkspace(testWorkspace.getId()).cache(); Mono<Set<String>> uniqueUsersInWorkspaceAfterMono = leaveWorkspaceMono .then(workspaceRepository.findById(testWorkspace.getId())) @@ -208,15 +232,15 @@ public void leaveWorkspace_WhenUserExistsInWorkspace_RemovesUser() { @Test @WithUserDetails(value = "api_user") public void leaveWorkspace_WhenUserDoesNotExistInWorkspace_ThrowsException() { - // Leave workspace once removes the api_user from the default workspace. The second time would reproduce the test + // Leave workspace once removes the api_user from the default workspace. The second time would reproduce the + // test // case scenario. - Mono<User> userMono = userWorkspaceService.leaveWorkspace(workspace.getId()) + Mono<User> userMono = userWorkspaceService + .leaveWorkspace(workspace.getId()) .then(userWorkspaceService.leaveWorkspace(workspace.getId())); StepVerifier.create(userMono) - .expectErrorMessage( - AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.WORKSPACE, workspace.getId()) - ) + .expectErrorMessage(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.WORKSPACE, workspace.getId())) .verify(); } @@ -227,15 +251,20 @@ public void updateUserGroupForMember_WhenAdminUserGroupRemovedWithNoOtherAdmin_T // Now make api_user an administrator and not a developer Set<String> permissionGroupIds = workspace.getDefaultPermissionGroups(); - List<PermissionGroup> permissionGroups = permissionGroupRepository.findAllById(permissionGroupIds).collectList().block(); + List<PermissionGroup> permissionGroups = permissionGroupRepository + .findAllById(permissionGroupIds) + .collectList() + .block(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); User api_user = userService.findByEmail("api_user").block(); @@ -251,10 +280,10 @@ public void updateUserGroupForMember_WhenAdminUserGroupRemovedWithNoOtherAdmin_T updatePermissionGroupDTO.setNewPermissionGroupId(developerPermissionGroup.getId()); String origin = "http://random-origin.test"; - Mono<MemberInfoDTO> updateUserRoleMono = userWorkspaceService.updatePermissionGroupForMember(workspace.getId(), updatePermissionGroupDTO, origin); + Mono<MemberInfoDTO> updateUserRoleMono = userWorkspaceService.updatePermissionGroupForMember( + workspace.getId(), updatePermissionGroupDTO, origin); - StepVerifier - .create(updateUserRoleMono) + StepVerifier.create(updateUserRoleMono) .expectErrorMessage(AppsmithError.REMOVE_LAST_WORKSPACE_ADMIN_ERROR.getMessage()); } @@ -265,15 +294,20 @@ public void updateUserGroupForMember_WhenAdminUserGroupRemovedButOtherAdminExist // Now make api_user an administrator along with usertest. Remove api_user as a developer Set<String> permissionGroupIds = workspace.getDefaultPermissionGroups(); - List<PermissionGroup> permissionGroups = permissionGroupRepository.findAllById(permissionGroupIds).collectList().block(); + List<PermissionGroup> permissionGroups = permissionGroupRepository + .findAllById(permissionGroupIds) + .collectList() + .block(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); User api_user = userService.findByEmail("api_user").block(); User usertest = userService.findByEmail("[email protected]").block(); @@ -291,17 +325,23 @@ public void updateUserGroupForMember_WhenAdminUserGroupRemovedButOtherAdminExist updatePermissionGroupDTO.setNewPermissionGroupId(developerPermissionGroup.getId()); String origin = "http://random-origin.test"; - Mono<MemberInfoDTO> updateUserRoleMono = userWorkspaceService.updatePermissionGroupForMember(workspace.getId(), updatePermissionGroupDTO, origin); + Mono<MemberInfoDTO> updateUserRoleMono = userWorkspaceService.updatePermissionGroupForMember( + workspace.getId(), updatePermissionGroupDTO, origin); StepVerifier.create(updateUserRoleMono) .assertNext(userRole1 -> { - assertEquals(usertest.getUsername(), userRole1.getUsername()); - assertEquals(userRole1.getRoles().size(), 1); - assertEquals(developerPermissionGroup.getId(), userRole1.getRoles().get(0).getId()); - assertEquals(developerPermissionGroup.getName(), userRole1.getRoles().get(0).getName()); - assertEquals(Workspace.class.getSimpleName(), userRole1.getRoles().get(0).getEntityType()); - } - ) + assertEquals(usertest.getUsername(), userRole1.getUsername()); + assertEquals(userRole1.getRoles().size(), 1); + assertEquals( + developerPermissionGroup.getId(), + userRole1.getRoles().get(0).getId()); + assertEquals( + developerPermissionGroup.getName(), + userRole1.getRoles().get(0).getName()); + assertEquals( + Workspace.class.getSimpleName(), + userRole1.getRoles().get(0).getEntityType()); + }) .verifyComplete(); } @@ -312,5 +352,4 @@ public void clear() { userRepository.save(currentUser); workspaceRepository.deleteById(workspace.getId()).block(); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserWorkspaceServiceUnitTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserWorkspaceServiceUnitTest.java index 5896e84cbe63..d6ff1b15608b 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserWorkspaceServiceUnitTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserWorkspaceServiceUnitTest.java @@ -38,12 +38,16 @@ public class UserWorkspaceServiceUnitTest { @Autowired UserDataRepository userDataRepository; + @Autowired UserDataService userDataService; + @Autowired WorkspaceService workspaceService; + @Autowired PermissionGroupRepository permissionGroupRepository; + @Autowired UserWorkspaceService userWorkspaceService; @@ -92,8 +96,7 @@ public void getWorkspaceMembers_WhenRoleIsNull_ReturnsEmptyList() { .block(); Mono<List<MemberInfoDTO>> workspaceMembers = userWorkspaceService.getWorkspaceMembers(testWorkspace.getId()); - StepVerifier - .create(workspaceMembers) + StepVerifier.create(workspaceMembers) .assertNext(userAndGroupDTOs -> { assertEquals(0, userAndGroupDTOs.size()); }) @@ -104,8 +107,7 @@ public void getWorkspaceMembers_WhenRoleIsNull_ReturnsEmptyList() { public void getWorkspaceMembers_WhenNoOrgFound_ThrowsException() { String sampleWorkspaceId = "test-org-id"; Mono<List<MemberInfoDTO>> workspaceMembers = userWorkspaceService.getWorkspaceMembers(sampleWorkspaceId); - StepVerifier - .create(workspaceMembers) + StepVerifier.create(workspaceMembers) .expectErrorMessage(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.WORKSPACE, sampleWorkspaceId)) .verify(); } @@ -118,16 +120,21 @@ public void getWorkspaceMembers_WhenUserHasProfilePhotoForOneWorkspace_ProfilePh workspace.setName("workspace_" + UUID.randomUUID()); Mono<Workspace> workspaceMono = workspaceService.create(workspace); - Mono<List<MemberInfoDTO>> listMono = userDataService.getForCurrentUser().flatMap(userData -> { + Mono<List<MemberInfoDTO>> listMono = userDataService + .getForCurrentUser() + .flatMap(userData -> { userData.setProfilePhotoAssetId("sample-photo-id"); return userDataRepository.save(userData); - }).then(workspaceMono) + }) + .then(workspaceMono) .flatMap(createdWorkspace -> userWorkspaceService.getWorkspaceMembers(createdWorkspace.getId())); - StepVerifier.create(listMono).assertNext(workspaceMemberInfoDTOS -> { - assertThat(workspaceMemberInfoDTOS.size()).isEqualTo(1); - assertThat(workspaceMemberInfoDTOS.get(0).getPhotoId()).isEqualTo("sample-photo-id"); - }).verifyComplete(); + StepVerifier.create(listMono) + .assertNext(workspaceMemberInfoDTOS -> { + assertThat(workspaceMemberInfoDTOS.size()).isEqualTo(1); + assertThat(workspaceMemberInfoDTOS.get(0).getPhotoId()).isEqualTo("sample-photo-id"); + }) + .verifyComplete(); } @Test @@ -140,12 +147,11 @@ public void getWorkspaceMembers_WhenUserHasProfilePhotoForMultipleWorkspace_Prof Workspace secondWorkspace = new Workspace(); secondWorkspace.setName("second-workspace-" + UUID.randomUUID()); - Mono<Tuple2<Workspace, Workspace>> createWorkspacesMono = Mono.zip( - workspaceService.create(firstWorkspace), - workspaceService.create(secondWorkspace) - ); + Mono<Tuple2<Workspace, Workspace>> createWorkspacesMono = + Mono.zip(workspaceService.create(firstWorkspace), workspaceService.create(secondWorkspace)); - Mono<Map<String, List<MemberInfoDTO>>> mapMono = userDataService.getForCurrentUser() + Mono<Map<String, List<MemberInfoDTO>>> mapMono = userDataService + .getForCurrentUser() .flatMap(userData -> { userData.setProfilePhotoAssetId("sample-photo-id"); return userDataRepository.save(userData); @@ -154,19 +160,21 @@ public void getWorkspaceMembers_WhenUserHasProfilePhotoForMultipleWorkspace_Prof .flatMap(workspaces -> { Set<String> createdIds = Set.of( Objects.requireNonNull(workspaces.getT1().getId()), - Objects.requireNonNull(workspaces.getT2().getId()) - ); + Objects.requireNonNull(workspaces.getT2().getId())); return userWorkspaceService.getWorkspaceMembers(createdIds); }); - StepVerifier.create(mapMono).assertNext(workspaceMemberInfoDTOSMap -> { - assertThat(workspaceMemberInfoDTOSMap.size()).isEqualTo(2); // should have 2 entries for 2 workspaces - workspaceMemberInfoDTOSMap.values().forEach(workspaceMemberInfoDTOS -> { - // should have one entry for the creator member only, get that - MemberInfoDTO workspaceMemberInfoDTO = workspaceMemberInfoDTOS.get(0); - // we already set profile photo for the current user, check it exists in response - assertThat(workspaceMemberInfoDTO.getPhotoId()).isEqualTo("sample-photo-id"); - }); - }).verifyComplete(); + StepVerifier.create(mapMono) + .assertNext(workspaceMemberInfoDTOSMap -> { + assertThat(workspaceMemberInfoDTOSMap.size()) + .isEqualTo(2); // should have 2 entries for 2 workspaces + workspaceMemberInfoDTOSMap.values().forEach(workspaceMemberInfoDTOS -> { + // should have one entry for the creator member only, get that + MemberInfoDTO workspaceMemberInfoDTO = workspaceMemberInfoDTOS.get(0); + // we already set profile photo for the current user, check it exists in response + assertThat(workspaceMemberInfoDTO.getPhotoId()).isEqualTo("sample-photo-id"); + }); + }) + .verifyComplete(); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/WorkspaceServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/WorkspaceServiceTest.java index be15f0993af3..27ffe060123b 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/WorkspaceServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/WorkspaceServiceTest.java @@ -97,37 +97,54 @@ public class WorkspaceServiceTest { private static final String origin = "http://appsmith-local.test"; + @Autowired WorkspaceService workspaceService; + @Autowired UserWorkspaceService userWorkspaceService; + @Autowired WorkspaceRepository workspaceRepository; + @Autowired ApplicationPageService applicationPageService; + @Autowired ApplicationService applicationService; + @Autowired UserService userService; + @Autowired DatasourceService datasourceService; + @Autowired DatasourceRepository datasourceRepository; + @Autowired UserRepository userRepository; + @Autowired RoleGraph roleGraph; + @Autowired MongoTemplate mongoTemplate; + Workspace workspace; + @Autowired private AssetRepository assetRepository; + @Autowired private PermissionGroupRepository permissionGroupRepository; + @Autowired private UserAndAccessManagementService userAndAccessManagementService; + @Autowired private PluginService pluginService; + @MockBean private PluginExecutorHelper pluginExecutorHelper; @@ -148,23 +165,24 @@ public void createDefaultWorkspace() { Mono<User> userMono = userRepository.findByEmail("api_user").cache(); - Workspace workspace = userMono - .flatMap(user -> workspaceService.createDefault(new Workspace(), user)) + Workspace workspace = userMono.flatMap(user -> workspaceService.createDefault(new Workspace(), user)) .switchIfEmpty(Mono.error(new Exception("createDefault is returning empty!!"))) .block(); Mono<Set<PermissionGroup>> defaultPermissionGroupMono = Mono.just(workspace) .flatMap(workspace1 -> { Set<String> defaultPermissionGroups = workspace1.getDefaultPermissionGroups(); - return permissionGroupRepository.findAllById(defaultPermissionGroups).collect(Collectors.toSet()); + return permissionGroupRepository + .findAllById(defaultPermissionGroups) + .collect(Collectors.toSet()); }); - Mono<Set<PermissionGroup>> userPermissionGroupsSetMono = userMono - .flatMapMany(user -> permissionGroupRepository.findByAssignedToUserIdsIn(user.getId())) + Mono<Set<PermissionGroup>> userPermissionGroupsSetMono = userMono.flatMapMany( + user -> permissionGroupRepository.findByAssignedToUserIdsIn(user.getId())) .collect(Collectors.toSet()); - - StepVerifier.create(Mono.zip(Mono.just(workspace), userMono, defaultPermissionGroupMono, userPermissionGroupsSetMono)) + StepVerifier.create(Mono.zip( + Mono.just(workspace), userMono, defaultPermissionGroupMono, userPermissionGroupsSetMono)) .assertNext(tuple -> { Workspace workspace1 = tuple.getT1(); User user = tuple.getT2(); @@ -179,14 +197,14 @@ public void createDefaultWorkspace() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); Set<String> userPermissionGroupIds = userPermissionGroups.stream() .map(PermissionGroup::getId) .collect(Collectors.toSet()); assertThat(userPermissionGroupIds).contains(adminPermissionGroup.getId()); - }) .verifyComplete(); } @@ -201,9 +219,11 @@ public void checkNewUsersDefaultWorkspace() { User user = userService.create(newUser).block(); String workspaceName = user.computeFirstName() + "'s apps"; - Workspace defaultWorkspace = workspaceRepository.findByName(workspaceName).block(); + Workspace defaultWorkspace = + workspaceRepository.findByName(workspaceName).block(); - PermissionGroup permissionGroup = permissionGroupRepository.findByDefaultDomainIdAndDefaultDomainType(defaultWorkspace.getId(), Workspace.class.getSimpleName()) + PermissionGroup permissionGroup = permissionGroupRepository + .findByDefaultDomainIdAndDefaultDomainType(defaultWorkspace.getId(), Workspace.class.getSimpleName()) .filter(pg -> pg.getName().startsWith(ADMINISTRATOR)) .blockFirst(); @@ -224,8 +244,10 @@ public void checkNewUsersDefaultWorkspace() { public void nullCreateWorkspace() { Mono<Workspace> workspaceResponse = workspaceService.create(null); StepVerifier.create(workspaceResponse) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.WORKSPACE))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.WORKSPACE))) .verify(); } @@ -235,8 +257,8 @@ public void nullName() { workspace.setName(null); Mono<Workspace> workspaceResponse = workspaceService.create(workspace); StepVerifier.create(workspaceResponse) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) .verify(); } @@ -244,7 +266,8 @@ public void nullName() { @WithUserDetails(value = "api_user") public void validCreateWorkspaceTest() { - Mono<Workspace> workspaceResponse = workspaceService.create(workspace) + Mono<Workspace> workspaceResponse = workspaceService + .create(workspace) .switchIfEmpty(Mono.error(new Exception("create is returning empty!!"))) .cache(); @@ -266,84 +289,137 @@ public void validCreateWorkspaceTest() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId())) .build(); - Policy workspaceCreateApplicationPolicy = Policy.builder().permission(AclPermission.WORKSPACE_CREATE_APPLICATION.getValue()) + Policy workspaceCreateApplicationPolicy = Policy.builder() + .permission(AclPermission.WORKSPACE_CREATE_APPLICATION.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy workspaceCreateDataSourcePolicy = Policy.builder().permission(AclPermission.WORKSPACE_CREATE_DATASOURCE.getValue()) + Policy workspaceCreateDataSourcePolicy = Policy.builder() + .permission(AclPermission.WORKSPACE_CREATE_DATASOURCE.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy deleteWorkspacePolicy = Policy.builder().permission(AclPermission.DELETE_WORKSPACES.getValue()) + Policy deleteWorkspacePolicy = Policy.builder() + .permission(AclPermission.DELETE_WORKSPACES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId())) .build(); - Policy workspaceDeleteApplicationaPolicy = Policy.builder().permission(AclPermission.WORKSPACE_DELETE_APPLICATIONS.getValue()) + Policy workspaceDeleteApplicationaPolicy = Policy.builder() + .permission(AclPermission.WORKSPACE_DELETE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy workspaceDeleteDatasourcesPolicy = Policy.builder().permission(AclPermission.WORKSPACE_DELETE_DATASOURCES.getValue()) + Policy workspaceDeleteDatasourcesPolicy = Policy.builder() + .permission(AclPermission.WORKSPACE_DELETE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); assertThat(workspace1.getPolicies()).isNotEmpty(); - assertThat(workspace1.getPolicies()).containsAll(Set.of(manageWorkspaceAppPolicy, manageWorkspacePolicy, - workspaceCreateApplicationPolicy, workspaceCreateDataSourcePolicy, deleteWorkspacePolicy, - workspaceDeleteApplicationaPolicy, workspaceDeleteDatasourcesPolicy)); + assertThat(workspace1.getPolicies()) + .containsAll(Set.of( + manageWorkspaceAppPolicy, + manageWorkspacePolicy, + workspaceCreateApplicationPolicy, + workspaceCreateDataSourcePolicy, + deleteWorkspacePolicy, + workspaceDeleteApplicationaPolicy, + workspaceDeleteDatasourcesPolicy)); assertThat(workspace1.getSlug()).isEqualTo(TextUtils.makeSlug(workspace.getName())); assertThat(workspace1.getEmail()).isEqualTo("api_user"); assertThat(workspace1.getIsAutoGeneratedWorkspace()).isNull(); assertThat(workspace1.getTenantId()).isEqualTo(user.getTenantId()); // Assert admin permission group policies - adminPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(ASSIGN_PERMISSION_GROUPS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).contains(adminPermissionGroup.getId())); - - adminPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(READ_PERMISSION_GROUP_MEMBERS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).containsAll(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId()))); - - adminPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(UNASSIGN_PERMISSION_GROUPS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).contains(adminPermissionGroup.getId())); - + adminPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(ASSIGN_PERMISSION_GROUPS.getValue())) + .findFirst() + .ifPresent(policy -> + assertThat(policy.getPermissionGroups()).contains(adminPermissionGroup.getId())); + + adminPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(READ_PERMISSION_GROUP_MEMBERS.getValue())) + .findFirst() + .ifPresent(policy -> assertThat(policy.getPermissionGroups()) + .containsAll(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId()))); + + adminPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(UNASSIGN_PERMISSION_GROUPS.getValue())) + .findFirst() + .ifPresent(policy -> + assertThat(policy.getPermissionGroups()).contains(adminPermissionGroup.getId())); // Assert developer permission group policies - developerPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(ASSIGN_PERMISSION_GROUPS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).containsAll(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId()))); - - developerPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(READ_PERMISSION_GROUP_MEMBERS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).containsAll(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId()))); - - developerPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(UNASSIGN_PERMISSION_GROUPS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).containsAll(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId()))); - + developerPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(ASSIGN_PERMISSION_GROUPS.getValue())) + .findFirst() + .ifPresent(policy -> assertThat(policy.getPermissionGroups()) + .containsAll( + Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId()))); + + developerPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(READ_PERMISSION_GROUP_MEMBERS.getValue())) + .findFirst() + .ifPresent(policy -> assertThat(policy.getPermissionGroups()) + .containsAll(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId()))); + + developerPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(UNASSIGN_PERMISSION_GROUPS.getValue())) + .findFirst() + .ifPresent(policy -> assertThat(policy.getPermissionGroups()) + .containsAll( + Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId()))); // Assert viewer permission group policies - viewerPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(ASSIGN_PERMISSION_GROUPS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).containsAll(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId()))); - viewerPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(READ_PERMISSION_GROUP_MEMBERS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).containsAll(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId()))); - viewerPermissionGroup.getPolicies().stream().filter(policy -> policy.getPermission().equals(UNASSIGN_PERMISSION_GROUPS.getValue())) - .findFirst().ifPresent(policy -> assertThat(policy.getPermissionGroups()).containsAll(Set.of(adminPermissionGroup.getId(), viewerPermissionGroup.getId()))); - - + viewerPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(ASSIGN_PERMISSION_GROUPS.getValue())) + .findFirst() + .ifPresent(policy -> assertThat(policy.getPermissionGroups()) + .containsAll(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId()))); + viewerPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(READ_PERMISSION_GROUP_MEMBERS.getValue())) + .findFirst() + .ifPresent(policy -> assertThat(policy.getPermissionGroups()) + .containsAll(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId()))); + viewerPermissionGroup.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(UNASSIGN_PERMISSION_GROUPS.getValue())) + .findFirst() + .ifPresent(policy -> assertThat(policy.getPermissionGroups()) + .containsAll(Set.of(adminPermissionGroup.getId(), viewerPermissionGroup.getId()))); }) .verifyComplete(); } @@ -364,8 +440,8 @@ public void getWorkspaceInvalidId() { public void getWorkspaceNullId() { Mono<Workspace> workspaceMono = workspaceService.getById(null); StepVerifier.create(workspaceMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ID))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ID))) .verify(); } @@ -378,7 +454,8 @@ public void validGetWorkspaceByName() { workspace.setWebsite("https://example.com"); workspace.setSlug("test-for-get-name"); Mono<Workspace> createWorkspace = workspaceService.create(workspace); - Mono<Workspace> getWorkspace = createWorkspace.flatMap(t -> workspaceService.findById(t.getId(), READ_WORKSPACES)); + Mono<Workspace> getWorkspace = + createWorkspace.flatMap(t -> workspaceService.findById(t.getId(), READ_WORKSPACES)); StepVerifier.create(getWorkspace) .assertNext(t -> { assertThat(t).isNotNull(); @@ -398,14 +475,12 @@ public void validUpdateWorkspace() { workspace.setWebsite("https://example.com"); workspace.setSlug("test-update-name"); - Mono<Workspace> createWorkspace = workspaceService.create(workspace) - .cache(); - Mono<Workspace> updateWorkspace = createWorkspace - .flatMap(t -> { - Workspace newWorkspace = new Workspace(); - newWorkspace.setDomain("abc.com"); - return workspaceService.update(t.getId(), newWorkspace); - }); + Mono<Workspace> createWorkspace = workspaceService.create(workspace).cache(); + Mono<Workspace> updateWorkspace = createWorkspace.flatMap(t -> { + Workspace newWorkspace = new Workspace(); + newWorkspace.setDomain("abc.com"); + return workspaceService.update(t.getId(), newWorkspace); + }); Mono<List<PermissionGroup>> defaultPermissionGroupsMono = createWorkspace .flatMapMany(savedWorkspace -> { @@ -425,21 +500,26 @@ public void validUpdateWorkspace() { List<PermissionGroup> permissionGroups = tuple.getT2(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId())) .build(); @@ -472,11 +552,14 @@ void validUpdateCorrectWorkspace() { final Workspace changes = new Workspace(); changes.setId(t.getT2().getId()); changes.setDomain("abc.com"); - return workspaceService.update(t.getT1().getId(), changes) - .zipWhen(updatedWorkspace -> - workspaceRepository.findById(t.getT2().getId(), READ_WORKSPACES) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.WORKSPACE, t.getT2().getId()))) - ); + return workspaceService + .update(t.getT1().getId(), changes) + .zipWhen(updatedWorkspace -> workspaceRepository + .findById(t.getT2().getId(), READ_WORKSPACES) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, + FieldName.WORKSPACE, + t.getT2().getId())))); }); StepVerifier.create(updateWorkspace) @@ -499,11 +582,13 @@ void validUpdateCorrectWorkspace() { @Test @WithUserDetails(value = "api_user") public void inValidupdateWorkspaceEmptyName() { - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .users(Set.of("api_user")) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .users(Set.of("api_user")) .build(); @@ -513,27 +598,28 @@ public void inValidupdateWorkspaceEmptyName() { workspace.setWebsite("https://example.com"); workspace.setSlug("test-update-name"); Mono<Workspace> createWorkspace = workspaceService.create(workspace); - Mono<Workspace> updateWorkspace = createWorkspace - .flatMap(t -> { - Workspace newWorkspace = new Workspace(); - newWorkspace.setName(""); - return workspaceService.update(t.getId(), newWorkspace); - }); + Mono<Workspace> updateWorkspace = createWorkspace.flatMap(t -> { + Workspace newWorkspace = new Workspace(); + newWorkspace.setName(""); + return workspaceService.update(t.getId(), newWorkspace); + }); StepVerifier.create(updateWorkspace) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) .verify(); } @Test @WithUserDetails(value = "api_user") public void validUpdateWorkspaceValidEmail() { - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .users(Set.of("api_user")) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .users(Set.of("api_user")) .build(); @@ -544,12 +630,11 @@ public void validUpdateWorkspaceValidEmail() { workspace.setDomain("example.com"); workspace.setWebsite("https://example.com"); workspace.setSlug("test-update-name"); - Mono<Workspace> updateWorkspace = workspaceService.create(workspace) - .flatMap(t -> { - Workspace newWorkspace = new Workspace(); - newWorkspace.setEmail(validEmail); - return workspaceService.update(t.getId(), newWorkspace); - }); + Mono<Workspace> updateWorkspace = workspaceService.create(workspace).flatMap(t -> { + Workspace newWorkspace = new Workspace(); + newWorkspace.setEmail(validEmail); + return workspaceService.update(t.getId(), newWorkspace); + }); StepVerifier.create(updateWorkspace) .assertNext(t -> { assertThat(t).isNotNull(); @@ -562,11 +647,13 @@ public void validUpdateWorkspaceValidEmail() { @Test @WithUserDetails(value = "api_user") public void validUpdateWorkspaceInvalidEmail() { - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .users(Set.of("api_user")) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .users(Set.of("api_user")) .build(); @@ -577,15 +664,16 @@ public void validUpdateWorkspaceInvalidEmail() { workspace.setDomain("example.com"); workspace.setWebsite("https://example.com"); workspace.setSlug("test-update-name"); - Mono<Workspace> updateWorkspace = workspaceService.create(workspace) - .flatMap(t -> { - Workspace newWorkspace = new Workspace(); - newWorkspace.setEmail(invalidEmail); - return workspaceService.update(t.getId(), newWorkspace); - }); + Mono<Workspace> updateWorkspace = workspaceService.create(workspace).flatMap(t -> { + Workspace newWorkspace = new Workspace(); + newWorkspace.setEmail(invalidEmail); + return workspaceService.update(t.getId(), newWorkspace); + }); StepVerifier.create(updateWorkspace) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.EMAIL))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.EMAIL))) .verify(); } } @@ -593,31 +681,47 @@ public void validUpdateWorkspaceInvalidEmail() { @Test @WithUserDetails(value = "api_user") public void validUpdateWorkspaceValidWebsite() { - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .users(Set.of("api_user")) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .users(Set.of("api_user")) .build(); - String[] validWebsites = {"https://www.valid.website.com", "http://www.valid.website.com", - "https://valid.website.com", "http://valid.website.com", "www.valid.website.com", "valid.website.com", - "valid-website.com", "valid.12345.com", "12345.com", "https://www.valid.website.com/", - "http://www.valid.website.com/", "https://valid.website.complete/", "http://valid.website.com/", - "www.valid.website.com/", "valid.website.com/", "valid-website.com/", "valid.12345.com/", "12345.com/"}; + String[] validWebsites = { + "https://www.valid.website.com", + "http://www.valid.website.com", + "https://valid.website.com", + "http://valid.website.com", + "www.valid.website.com", + "valid.website.com", + "valid-website.com", + "valid.12345.com", + "12345.com", + "https://www.valid.website.com/", + "http://www.valid.website.com/", + "https://valid.website.complete/", + "http://valid.website.com/", + "www.valid.website.com/", + "valid.website.com/", + "valid-website.com/", + "valid.12345.com/", + "12345.com/" + }; for (String validWebsite : validWebsites) { Workspace workspace = new Workspace(); workspace.setName("Test Update Name"); workspace.setDomain("example.com"); workspace.setWebsite("https://example.com"); workspace.setSlug("test-update-name"); - Mono<Workspace> updateWorkspace = workspaceService.create(workspace) - .flatMap(t -> { - Workspace newWorkspace = new Workspace(); - newWorkspace.setWebsite(validWebsite); - return workspaceService.update(t.getId(), newWorkspace); - }); + Mono<Workspace> updateWorkspace = workspaceService.create(workspace).flatMap(t -> { + Workspace newWorkspace = new Workspace(); + newWorkspace.setWebsite(validWebsite); + return workspaceService.update(t.getId(), newWorkspace); + }); StepVerifier.create(updateWorkspace) .assertNext(t -> { assertThat(t).isNotNull(); @@ -630,36 +734,39 @@ public void validUpdateWorkspaceValidWebsite() { @Test @WithUserDetails(value = "api_user") public void validUpdateWorkspaceInvalidWebsite() { - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .users(Set.of("api_user")) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .users(Set.of("api_user")) .build(); - String[] invalidWebsites = {"htp://www.invalid.website.com", "htp://invalid.website.com", "htp://www", "www", - "www."}; + String[] invalidWebsites = { + "htp://www.invalid.website.com", "htp://invalid.website.com", "htp://www", "www", "www." + }; for (String invalidWebsite : invalidWebsites) { Workspace workspace = new Workspace(); workspace.setName("Test Update Name"); workspace.setDomain("example.com"); workspace.setWebsite("https://example.com"); workspace.setSlug("test-update-name"); - Mono<Workspace> updateWorkspace = workspaceService.create(workspace) - .flatMap(t -> { - Workspace newWorkspace = new Workspace(); - newWorkspace.setWebsite(invalidWebsite); - return workspaceService.update(t.getId(), newWorkspace); - }); + Mono<Workspace> updateWorkspace = workspaceService.create(workspace).flatMap(t -> { + Workspace newWorkspace = new Workspace(); + newWorkspace.setWebsite(invalidWebsite); + return workspaceService.update(t.getId(), newWorkspace); + }); StepVerifier.create(updateWorkspace) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.WEBSITE))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.WEBSITE))) .verify(); } } - @Test @WithUserDetails(value = "api_user") public void createDuplicateNameWorkspace() { @@ -673,7 +780,8 @@ public void createDuplicateNameWorkspace() { secondWorkspace.setDomain(firstWorkspace.getDomain()); secondWorkspace.setWebsite(firstWorkspace.getWebsite()); - Mono<Workspace> firstWorkspaceCreation = workspaceService.create(firstWorkspace).cache(); + Mono<Workspace> firstWorkspaceCreation = + workspaceService.create(firstWorkspace).cache(); Mono<Workspace> secondWorkspaceCreation = firstWorkspaceCreation.then(workspaceService.create(secondWorkspace)); StepVerifier.create(Mono.zip(firstWorkspaceCreation, secondWorkspaceCreation)) @@ -690,15 +798,20 @@ public void createDuplicateNameWorkspace() { @Test @WithUserDetails(value = "api_user") public void getAllUserRolesForWorkspaceDomainAsAdministrator() { - Mono<List<PermissionGroupInfoDTO>> userRolesForWorkspace = workspaceService.create(workspace) - .flatMap(createdWorkspace -> workspaceService.getPermissionGroupsForWorkspace(createdWorkspace.getId())); + Mono<List<PermissionGroupInfoDTO>> userRolesForWorkspace = workspaceService + .create(workspace) + .flatMap( + createdWorkspace -> workspaceService.getPermissionGroupsForWorkspace(createdWorkspace.getId())); StepVerifier.create(userRolesForWorkspace) .assertNext(userGroupInfos -> { assertThat(userGroupInfos).isNotEmpty(); - assertThat(userGroupInfos).anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.ADMINISTRATOR)); - assertThat(userGroupInfos).anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.VIEWER)); - assertThat(userGroupInfos).anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.DEVELOPER)); + assertThat(userGroupInfos) + .anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.ADMINISTRATOR)); + assertThat(userGroupInfos) + .anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.VIEWER)); + assertThat(userGroupInfos) + .anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.DEVELOPER)); }) .verifyComplete(); } @@ -714,21 +827,26 @@ public void getAllMembersForWorkspace() { Workspace createdWorkspace = workspaceService.create(testWorkspace).block(); List<PermissionGroup> permissionGroups = permissionGroupRepository - .findAllById(createdWorkspace.getDefaultPermissionGroups()).collectList().block(); + .findAllById(createdWorkspace.getDefaultPermissionGroups()) + .collectList() + .block(); String adminPermissionGroupId = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get() + .findFirst() + .get() .getId(); String developerPermissionGroupId = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get() + .findFirst() + .get() .getId(); String viewerPermissionGroupId = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get() + .findFirst() + .get() .getId(); // Invite another admin @@ -757,8 +875,7 @@ public void getAllMembersForWorkspace() { Mono<List<MemberInfoDTO>> usersMono = userWorkspaceService.getWorkspaceMembers(createdWorkspace.getId()); - StepVerifier - .create(usersMono) + StepVerifier.create(usersMono) .assertNext(users -> { assertThat(users).isNotNull(); assertThat(users.size()).isEqualTo(6); @@ -787,7 +904,6 @@ public void getAllMembersForWorkspace() { assertEquals(userAndGroupDTO.getRoles().size(), 1); assertThat(userAndGroupDTO.getUsername()).isEqualTo("[email protected]"); assertThat(userAndGroupDTO.getRoles().get(0).getName()).startsWith(VIEWER); - }) .verifyComplete(); } @@ -804,16 +920,17 @@ public void addNewUserToWorkspaceAsAdmin() { toCreate.setDomain("example.com"); toCreate.setWebsite("https://example.com"); - Workspace workspace = workspaceService - .create(toCreate) - .block(); + Workspace workspace = workspaceService.create(toCreate).block(); List<PermissionGroup> permissionGroups = permissionGroupRepository - .findAllById(workspace.getDefaultPermissionGroups()).collectList().block(); + .findAllById(workspace.getDefaultPermissionGroups()) + .collectList() + .block(); String adminPermissionGroupId = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get() + .findFirst() + .get() .getId(); InviteUsersDTO inviteUsersDTO = new InviteUsersDTO(); @@ -822,10 +939,14 @@ public void addNewUserToWorkspaceAsAdmin() { inviteUsersDTO.setUsernames(users); inviteUsersDTO.setPermissionGroupId(adminPermissionGroupId); - List<User> createdUsers = userAndAccessManagementService.inviteUsers(inviteUsersDTO, origin).block(); + List<User> createdUsers = userAndAccessManagementService + .inviteUsers(inviteUsersDTO, origin) + .block(); List<PermissionGroup> permissionGroupsAfterInvite = permissionGroupRepository - .findAllById(workspace.getDefaultPermissionGroups()).collectList().block(); + .findAllById(workspace.getDefaultPermissionGroups()) + .collectList() + .block(); // Do the assertions now assertThat(workspace).isNotNull(); @@ -833,15 +954,18 @@ public void addNewUserToWorkspaceAsAdmin() { PermissionGroup adminPermissionGroup = permissionGroupsAfterInvite.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroupsAfterInvite.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroupsAfterInvite.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); User api_user = userService.findByEmail("api_user").block(); User newUser = createdUsers.get(0); @@ -849,20 +973,25 @@ public void addNewUserToWorkspaceAsAdmin() { // assert that both the new user and api_user have admin roles assertThat(adminPermissionGroup.getAssignedToUserIds()).containsAll(Set.of(newUser.getId(), api_user.getId())); - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId())) .build(); - Policy readWorkspacePolicy = Policy.builder().permission(READ_WORKSPACES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readWorkspacePolicy = Policy.builder() + .permission(READ_WORKSPACES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); assertThat(workspace.getPolicies()).isNotEmpty(); - assertThat(workspace.getPolicies()).containsAll(Set.of(manageWorkspaceAppPolicy, manageWorkspacePolicy, readWorkspacePolicy)); + assertThat(workspace.getPolicies()) + .containsAll(Set.of(manageWorkspaceAppPolicy, manageWorkspacePolicy, readWorkspacePolicy)); assertThat(newUser).isNotNull(); assertThat(newUser.getIsEnabled()).isFalse(); @@ -880,16 +1009,17 @@ public void addNewUserToWorkspaceAsViewer() { toCreate.setDomain("example.com"); toCreate.setWebsite("https://example.com"); - Workspace workspace = workspaceService - .create(toCreate) - .block(); + Workspace workspace = workspaceService.create(toCreate).block(); List<PermissionGroup> permissionGroups = permissionGroupRepository - .findAllById(workspace.getDefaultPermissionGroups()).collectList().block(); + .findAllById(workspace.getDefaultPermissionGroups()) + .collectList() + .block(); String viewerPermissionGroupId = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get() + .findFirst() + .get() .getId(); InviteUsersDTO inviteUsersDTO = new InviteUsersDTO(); @@ -898,10 +1028,14 @@ public void addNewUserToWorkspaceAsViewer() { inviteUsersDTO.setUsernames(users); inviteUsersDTO.setPermissionGroupId(viewerPermissionGroupId); - List<User> createdUsers = userAndAccessManagementService.inviteUsers(inviteUsersDTO, origin).block(); + List<User> createdUsers = userAndAccessManagementService + .inviteUsers(inviteUsersDTO, origin) + .block(); List<PermissionGroup> permissionGroupsAfterInvite = permissionGroupRepository - .findAllById(workspace.getDefaultPermissionGroups()).collectList().block(); + .findAllById(workspace.getDefaultPermissionGroups()) + .collectList() + .block(); // Do the assertions now assertThat(workspace).isNotNull(); @@ -909,15 +1043,18 @@ public void addNewUserToWorkspaceAsViewer() { PermissionGroup adminPermissionGroup = permissionGroupsAfterInvite.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroupsAfterInvite.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroupsAfterInvite.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); User api_user = userService.findByEmail("api_user").block(); User newUser = createdUsers.get(0); @@ -927,20 +1064,25 @@ public void addNewUserToWorkspaceAsViewer() { // assert that api_user has admin role assertThat(adminPermissionGroup.getAssignedToUserIds()).containsAll(Set.of(api_user.getId())); - Policy manageWorkspaceAppPolicy = Policy.builder().permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) + Policy manageWorkspaceAppPolicy = Policy.builder() + .permission(WORKSPACE_MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy manageWorkspacePolicy = Policy.builder().permission(MANAGE_WORKSPACES.getValue()) + Policy manageWorkspacePolicy = Policy.builder() + .permission(MANAGE_WORKSPACES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId())) .build(); - Policy readWorkspacePolicy = Policy.builder().permission(READ_WORKSPACES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readWorkspacePolicy = Policy.builder() + .permission(READ_WORKSPACES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); assertThat(workspace.getPolicies()).isNotEmpty(); - assertThat(workspace.getPolicies()).containsAll(Set.of(manageWorkspaceAppPolicy, manageWorkspacePolicy, readWorkspacePolicy)); + assertThat(workspace.getPolicies()) + .containsAll(Set.of(manageWorkspaceAppPolicy, manageWorkspacePolicy, readWorkspacePolicy)); assertThat(newUser).isNotNull(); assertThat(newUser.getIsEnabled()).isFalse(); @@ -961,7 +1103,8 @@ public void addUserToWorkspaceAsAdminAndCheckApplicationAndDatasourcePermissions Workspace workspace1 = workspaceService.create(workspace).block(); - Flux<PermissionGroup> permissionGroupFlux = permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups()); + Flux<PermissionGroup> permissionGroupFlux = + permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups()); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) .thenReturn(Mono.just(new MockPluginExecutor())); Mono<PermissionGroup> adminPermissionGroupMono = permissionGroupFlux @@ -972,11 +1115,11 @@ public void addUserToWorkspaceAsAdminAndCheckApplicationAndDatasourcePermissions Application application = new Application(); application.setName("User Management Admin Test Application"); - Mono<Application> applicationMono = applicationPageService - .createApplication(application, workspace1.getId()); + Mono<Application> applicationMono = applicationPageService.createApplication(application, workspace1.getId()); // Create datasource for this workspace - Mono<Datasource> datasourceMono = workspaceService.getDefaultEnvironmentId(workspace1.getId()) + Mono<Datasource> datasourceMono = workspaceService + .getDefaultEnvironmentId(workspace1.getId()) .zipWith(pluginService.findByPackageName("postgres-plugin")) .flatMap(tuple2 -> { String defaultEnvironmentId = tuple2.getT1(); @@ -1003,33 +1146,38 @@ public void addUserToWorkspaceAsAdminAndCheckApplicationAndDatasourcePermissions return userAndAccessManagementService.inviteUsers(inviteUsersDTO, origin); }) - .flatMap(tuple -> workspaceService - .findById(workspace1.getId(), READ_WORKSPACES)); + .flatMap(tuple -> workspaceService.findById(workspace1.getId(), READ_WORKSPACES)); - Mono<Application> readApplicationByNameMono = applicationService.findByName("User Management Admin Test Application", - READ_APPLICATIONS) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "application by name"))); + Mono<Application> readApplicationByNameMono = applicationService + .findByName("User Management Admin Test Application", READ_APPLICATIONS) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "application by name"))); - Mono<Workspace> readWorkspaceByNameMono = workspaceRepository.findByName("Member Management Admin Test Workspace") + Mono<Workspace> readWorkspaceByNameMono = workspaceRepository + .findByName("Member Management Admin Test Workspace") .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "workspace by name"))); Mono<Datasource> readDatasourceByNameMono = datasourceRepository .findByNameAndWorkspaceId("test datasource", workspace1.getId(), READ_DATASOURCES) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "Datasource"))); - Mono<User> userTestMono = userService.findByEmail("[email protected]"); Mono<User> api_userMono = userService.findByEmail("api_user"); - Mono<Tuple6<Application, Workspace, Datasource, List<PermissionGroup>, User, User>> testMono = Mono.zip(applicationMono, datasourceMono) + Mono<Tuple6<Application, Workspace, Datasource, List<PermissionGroup>, User, User>> testMono = Mono.zip( + applicationMono, datasourceMono) // Now add the user .then(userAddedToWorkspaceMono) // Read application, workspace and datasource now to confirm the policies. - .then(Mono.zip(readApplicationByNameMono, readWorkspaceByNameMono, readDatasourceByNameMono, - permissionGroupFlux.collectList(), userTestMono, api_userMono)); - - StepVerifier - .create(testMono) + .then(Mono.zip( + readApplicationByNameMono, + readWorkspaceByNameMono, + readDatasourceByNameMono, + permissionGroupFlux.collectList(), + userTestMono, + api_userMono)); + + StepVerifier.create(testMono) .assertNext(tuple -> { Application app = tuple.getT1(); Workspace workspace2 = tuple.getT2(); @@ -1040,28 +1188,37 @@ public void addUserToWorkspaceAsAdminAndCheckApplicationAndDatasourcePermissions PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); // assert that both the user test and api_user have admin roles - assertThat(adminPermissionGroup.getAssignedToUserIds()).containsAll(Set.of(userTest.getId(), api_user.getId())); + assertThat(adminPermissionGroup.getAssignedToUserIds()) + .containsAll(Set.of(userTest.getId(), api_user.getId())); assertThat(workspace2).isNotNull(); // Now assert that the application and datasource have correct permissions in the policies - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); assertThat(app.getPolicies()).isNotEmpty(); @@ -1070,20 +1227,25 @@ public void addUserToWorkspaceAsAdminAndCheckApplicationAndDatasourcePermissions /* * Check for datasource permissions after the user addition */ - Policy manageDatasourcePolicy = Policy.builder().permission(MANAGE_DATASOURCES.getValue()) + Policy manageDatasourcePolicy = Policy.builder() + .permission(MANAGE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readDatasourcePolicy = Policy.builder().permission(READ_DATASOURCES.getValue()) + Policy readDatasourcePolicy = Policy.builder() + .permission(READ_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeDatasourcePolicy = Policy.builder().permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeDatasourcePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); assertThat(datasource.getPolicies()).isNotEmpty(); - assertThat(datasource.getPolicies()).containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, - executeDatasourcePolicy)); - + assertThat(datasource.getPolicies()) + .containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); }) .verifyComplete(); } @@ -1101,24 +1263,21 @@ public void addUserToWorkspaceAsViewerAndCheckApplicationPermissions() { workspace.setDomain("example.com"); workspace.setWebsite("https://example.com"); - Mono<Workspace> workspaceMono = workspaceService - .create(workspace) - .cache(); + Mono<Workspace> workspaceMono = workspaceService.create(workspace).cache(); - Flux<PermissionGroup> permissionGroupFlux = workspaceMono - .flatMapMany(workspace1 -> permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups())); + Flux<PermissionGroup> permissionGroupFlux = workspaceMono.flatMapMany( + workspace1 -> permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups())); Mono<PermissionGroup> viewerPermissionGroupMono = permissionGroupFlux .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) .single(); // Create an application for this workspace - Mono<Application> applicationMono = workspaceMono - .flatMap(workspace1 -> { - Application application = new Application(); - application.setName("User Management Viewer Test Application"); - return applicationPageService.createApplication(application, workspace1.getId()); - }); + Mono<Application> applicationMono = workspaceMono.flatMap(workspace1 -> { + Application application = new Application(); + application.setName("User Management Viewer Test Application"); + return applicationPageService.createApplication(application, workspace1.getId()); + }); Mono<Workspace> userAddedToWorkspaceMono = Mono.zip(workspaceMono, viewerPermissionGroupMono) .flatMap(tuple -> { @@ -1131,18 +1290,22 @@ public void addUserToWorkspaceAsViewerAndCheckApplicationPermissions() { inviteUsersDTO.setUsernames(users); inviteUsersDTO.setPermissionGroupId(viewerPermissionGroup.getId()); - return userAndAccessManagementService.inviteUsers(inviteUsersDTO, origin).zipWith(workspaceMono); + return userAndAccessManagementService + .inviteUsers(inviteUsersDTO, origin) + .zipWith(workspaceMono); }) .flatMap(tuple -> { Workspace t2 = tuple.getT2(); return workspaceService.findById(t2.getId(), READ_WORKSPACES); }); - Mono<Application> readApplicationByNameMono = applicationService.findByName("User Management Viewer Test Application", - READ_APPLICATIONS) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "application by name"))); + Mono<Application> readApplicationByNameMono = applicationService + .findByName("User Management Viewer Test Application", READ_APPLICATIONS) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "application by name"))); - Mono<Workspace> readWorkspaceByNameMono = workspaceRepository.findByName("Member Management Viewer Test Workspace") + Mono<Workspace> readWorkspaceByNameMono = workspaceRepository + .findByName("Member Management Viewer Test Workspace") .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "workspace by name"))); Mono<User> userTestMono = userService.findByEmail("[email protected]"); @@ -1151,11 +1314,14 @@ public void addUserToWorkspaceAsViewerAndCheckApplicationPermissions() { Mono<Tuple5<Application, Workspace, List<PermissionGroup>, User, User>> testMono = workspaceMono .then(applicationMono) .then(userAddedToWorkspaceMono) - .then(Mono.zip(readApplicationByNameMono, readWorkspaceByNameMono, permissionGroupFlux.collectList(), - userTestMono, api_userMono)); - - StepVerifier - .create(testMono) + .then(Mono.zip( + readApplicationByNameMono, + readWorkspaceByNameMono, + permissionGroupFlux.collectList(), + userTestMono, + api_userMono)); + + StepVerifier.create(testMono) .assertNext(tuple -> { Application application = tuple.getT1(); Workspace workspace1 = tuple.getT2(); @@ -1167,30 +1333,37 @@ public void addUserToWorkspaceAsViewerAndCheckApplicationPermissions() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); // assert that api_user has admin role and usertest has viewer role assertThat(adminPermissionGroup.getAssignedToUserIds()).contains(api_user.getId()); assertThat(viewerPermissionGroup.getAssignedToUserIds()).contains(userTest.getId()); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); assertThat(application.getPolicies()).isNotEmpty(); assertThat(application.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); - }) .verifyComplete(); } @@ -1206,12 +1379,11 @@ public void addNewUsersBulkToWorkspaceAsViewer() { workspace.setDomain("example.com"); workspace.setWebsite("https://example.com"); - Mono<Workspace> workspaceMono = workspaceService - .create(workspace) - .cache(); + Mono<Workspace> workspaceMono = workspaceService.create(workspace).cache(); Mono<PermissionGroup> viewerGroupMono = workspaceMono - .flatMapMany(workspace1 -> permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups())) + .flatMapMany( + workspace1 -> permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups())) .filter(userGroup -> userGroup.getName().startsWith(FieldName.VIEWER)) .single(); @@ -1232,17 +1404,16 @@ public void addNewUsersBulkToWorkspaceAsViewer() { Mono<Workspace> readWorkspaceMono = workspaceRepository.findByName("Add Bulk Viewers to Test Workspace"); - Mono<Workspace> workspaceAfterUpdateMono = userAddedToWorkspaceMono - .then(readWorkspaceMono); + Mono<Workspace> workspaceAfterUpdateMono = userAddedToWorkspaceMono.then(readWorkspaceMono); Mono<PermissionGroup> viewerGroupMonoAfterInvite = userAddedToWorkspaceMono .then(workspaceMono) - .flatMapMany(workspace1 -> permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups())) + .flatMapMany( + workspace1 -> permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups())) .filter(userGroup -> userGroup.getName().startsWith(FieldName.VIEWER)) .single(); - StepVerifier - .create(Mono.zip(userAddedToWorkspaceMono, workspaceAfterUpdateMono, viewerGroupMonoAfterInvite)) + StepVerifier.create(Mono.zip(userAddedToWorkspaceMono, workspaceAfterUpdateMono, viewerGroupMonoAfterInvite)) .assertNext(tuple -> { List<User> users = tuple.getT1(); Workspace workspace1 = tuple.getT2(); @@ -1252,7 +1423,8 @@ public void addNewUsersBulkToWorkspaceAsViewer() { assertThat(workspace1.getName()).isEqualTo("Add Bulk Viewers to Test Workspace"); // assert that the created users are assigned the viewer role - assertThat(viewerPermissionGroup.getAssignedToUserIds()).containsAll(users.stream().map(User::getId).collect(Collectors.toList())); + assertThat(viewerPermissionGroup.getAssignedToUserIds()) + .containsAll(users.stream().map(User::getId).collect(Collectors.toList())); for (User user : users) { assertThat(user.getId()).isNotNull(); @@ -1270,12 +1442,10 @@ public void addUserToWorkspaceIfUserAlreadyMember_throwsError() { workspace.setDomain("example.com"); workspace.setWebsite("https://example.com"); - Mono<Workspace> workspaceMono = workspaceService - .create(workspace) - .cache(); + Mono<Workspace> workspaceMono = workspaceService.create(workspace).cache(); - Flux<PermissionGroup> permissionGroupFlux = workspaceMono - .flatMapMany(workspace1 -> permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups())); + Flux<PermissionGroup> permissionGroupFlux = workspaceMono.flatMapMany( + workspace1 -> permissionGroupRepository.findAllById(workspace1.getDefaultPermissionGroups())); Mono<PermissionGroup> adminPermissionGroupMono = permissionGroupFlux .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) @@ -1290,7 +1460,6 @@ public void addUserToWorkspaceIfUserAlreadyMember_throwsError() { users.add("[email protected]"); inviteUsersDTO.setUsernames(users); - Mono<List<User>> userAddedToWorkspaceTwiceMono = adminPermissionGroupMono .flatMap(adminPermissionGroup -> { @@ -1308,13 +1477,13 @@ public void addUserToWorkspaceIfUserAlreadyMember_throwsError() { return userAndAccessManagementService.inviteUsers(inviteUsersDTO, origin); }); - - StepVerifier - .create(userAddedToWorkspaceTwiceMono) + StepVerifier.create(userAddedToWorkspaceTwiceMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage() - .equals(AppsmithError.USER_ALREADY_EXISTS_IN_WORKSPACE - .getMessage("[email protected]", "Administrator - addUserToWorkspaceIfUserAlreadyMember_throwsError"))) + && throwable + .getMessage() + .equals(AppsmithError.USER_ALREADY_EXISTS_IN_WORKSPACE.getMessage( + "[email protected]", + "Administrator - addUserToWorkspaceIfUserAlreadyMember_throwsError"))) .verify(); } @@ -1368,12 +1537,14 @@ public void inviteRolesGivenViewer() { @WithUserDetails(value = "api_user") public void uploadWorkspaceLogo_nullFilePart() throws IOException { Mono<Workspace> createWorkspace = workspaceService.create(workspace).cache(); - final Mono<Workspace> resultMono = createWorkspace - .flatMap(workspace -> workspaceService.uploadLogo(workspace.getId(), null)); + final Mono<Workspace> resultMono = + createWorkspace.flatMap(workspace -> workspaceService.uploadLogo(workspace.getId(), null)); StepVerifier.create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.VALIDATION_FAILURE.getMessage("Please upload a valid image."))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.VALIDATION_FAILURE.getMessage("Please upload a valid image."))) .verify(); } @@ -1381,23 +1552,32 @@ public void uploadWorkspaceLogo_nullFilePart() throws IOException { @WithUserDetails(value = "api_user") public void uploadWorkspaceLogo_largeFilePart() throws IOException { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo_large.png"), new DefaultDataBufferFactory(), 4096); - assertThat(dataBufferFlux.count().block()).isGreaterThan((int) Math.ceil(Constraint.WORKSPACE_LOGO_SIZE_KB / 4.0)); + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo_large.png"), + new DefaultDataBufferFactory(), + 4096); + assertThat(dataBufferFlux.count().block()) + .isGreaterThan((int) Math.ceil(Constraint.WORKSPACE_LOGO_SIZE_KB / 4.0)); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); // The pre-requisite of creating an workspace has been blocked for code readability // The duration sets an upper limit for this test to run - String workspaceId = workspaceService.create(workspace).blockOptional(Duration.ofSeconds(3)).map(Workspace::getId).orElse(null); + String workspaceId = workspaceService + .create(workspace) + .blockOptional(Duration.ofSeconds(3)) + .map(Workspace::getId) + .orElse(null); assertThat(workspaceId).isNotNull(); final Mono<Workspace> resultMono = workspaceService.uploadLogo(workspaceId, filepart); StepVerifier.create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.PAYLOAD_TOO_LARGE.getMessage(Constraint.WORKSPACE_LOGO_SIZE_KB))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.PAYLOAD_TOO_LARGE.getMessage(Constraint.WORKSPACE_LOGO_SIZE_KB))) .verify(); } @@ -1406,8 +1586,10 @@ public void uploadWorkspaceLogo_largeFilePart() throws IOException { public void testDeleteLogo_invalidWorkspace() { Mono<Workspace> deleteLogo = workspaceService.deleteLogo(""); StepVerifier.create(deleteLogo) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.WORKSPACE, ""))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.WORKSPACE, ""))) .verify(); } @@ -1415,21 +1597,23 @@ public void testDeleteLogo_invalidWorkspace() { @WithUserDetails(value = "api_user") public void testUpdateAndDeleteLogo_validLogo() throws IOException { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), new DefaultDataBufferFactory(), 4096).cache(); - assertThat(dataBufferFlux.count().block()).isLessThanOrEqualTo((int) Math.ceil(Constraint.WORKSPACE_LOGO_SIZE_KB / 4.0)); + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), + new DefaultDataBufferFactory(), + 4096) + .cache(); + assertThat(dataBufferFlux.count().block()) + .isLessThanOrEqualTo((int) Math.ceil(Constraint.WORKSPACE_LOGO_SIZE_KB / 4.0)); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); Mono<Workspace> createWorkspace = workspaceService.create(workspace).cache(); - final Mono<Tuple2<Workspace, Asset>> resultMono = createWorkspace - .flatMap(workspace -> workspaceService.uploadLogo(workspace.getId(), filepart) - .flatMap(workspaceWithLogo -> Mono.zip( - Mono.just(workspaceWithLogo), - assetRepository.findById(workspaceWithLogo.getLogoAssetId())) - )); + final Mono<Tuple2<Workspace, Asset>> resultMono = createWorkspace.flatMap(workspace -> workspaceService + .uploadLogo(workspace.getId(), filepart) + .flatMap(workspaceWithLogo -> Mono.zip( + Mono.just(workspaceWithLogo), assetRepository.findById(workspaceWithLogo.getLogoAssetId())))); StepVerifier.create(resultMono) .assertNext(tuple -> { @@ -1442,7 +1626,8 @@ public void testUpdateAndDeleteLogo_validLogo() throws IOException { }) .verifyComplete(); - Mono<Workspace> deleteLogo = createWorkspace.flatMap(workspace -> workspaceService.deleteLogo(workspace.getId())); + Mono<Workspace> deleteLogo = + createWorkspace.flatMap(workspace -> workspaceService.deleteLogo(workspace.getId())); StepVerifier.create(deleteLogo) .assertNext(x -> { assertThat(x.getLogoAssetId()).isNull(); @@ -1457,18 +1642,17 @@ public void delete_WhenWorkspaceHasApp_ThrowsException() { Workspace workspace = new Workspace(); workspace.setName("Test org to test delete org"); - Mono<Workspace> deleteWorkspaceMono = workspaceService.create(workspace) + Mono<Workspace> deleteWorkspaceMono = workspaceService + .create(workspace) .flatMap(savedWorkspace -> { Application application = new Application(); application.setWorkspaceId(savedWorkspace.getId()); application.setName("Test app to test delete org"); return applicationPageService.createApplication(application); - }).flatMap(application -> - workspaceService.archiveById(application.getWorkspaceId()) - ); + }) + .flatMap(application -> workspaceService.archiveById(application.getWorkspaceId())); - StepVerifier - .create(deleteWorkspaceMono) + StepVerifier.create(deleteWorkspaceMono) .expectErrorMessage(AppsmithError.UNSUPPORTED_OPERATION.getMessage()) .verify(); } @@ -1490,13 +1674,11 @@ public void delete_WithoutManagePermission_ThrowsException() { // api user has read org permission but no manage org permission workspace.setPolicies(new HashSet<>(Set.of(readWorkspacePolicy, manageWorkspacePolicy))); - Mono<Workspace> deleteWorkspaceMono = workspaceRepository.save(workspace) - .flatMap(savedWorkspace -> - workspaceService.archiveById(savedWorkspace.getId()) - ); + Mono<Workspace> deleteWorkspaceMono = workspaceRepository + .save(workspace) + .flatMap(savedWorkspace -> workspaceService.archiveById(savedWorkspace.getId())); - StepVerifier - .create(deleteWorkspaceMono) + StepVerifier.create(deleteWorkspaceMono) .expectError(AppsmithException.class) .verify(); } @@ -1509,18 +1691,18 @@ public void delete_WhenWorkspaceHasNoApp_WorkspaceIsDeleted() { Workspace savedWorkspace = workspaceService.create(workspace).block(); - Mono<Workspace> deleteWorkspaceMono = workspaceService.archiveById(savedWorkspace.getId()) + Mono<Workspace> deleteWorkspaceMono = workspaceService + .archiveById(savedWorkspace.getId()) .then(workspaceRepository.findById(savedWorkspace.getId())); // using verifyComplete() only. If the Mono emits any data, it will fail the stepverifier // as it doesn't expect an onNext signal at this point. - StepVerifier - .create(deleteWorkspaceMono) - .verifyComplete(); + StepVerifier.create(deleteWorkspaceMono).verifyComplete(); // verify that all the default permision groups are also deleted - Mono<List<PermissionGroup>> defaultPermissionGroupsMono = - permissionGroupRepository.findAllById(savedWorkspace.getDefaultPermissionGroups()).collectList(); + Mono<List<PermissionGroup>> defaultPermissionGroupsMono = permissionGroupRepository + .findAllById(savedWorkspace.getDefaultPermissionGroups()) + .collectList(); StepVerifier.create(defaultPermissionGroupsMono) .assertNext(permissionGroups -> { @@ -1532,17 +1714,16 @@ public void delete_WhenWorkspaceHasNoApp_WorkspaceIsDeleted() { @Test @WithUserDetails(value = "api_user") public void save_WhenNameIsPresent_SlugGenerated() { - String uniqueString = UUID.randomUUID().toString(); // to make sure name is not conflicted with other tests + String uniqueString = UUID.randomUUID().toString(); // to make sure name is not conflicted with other tests Workspace workspace = new Workspace(); workspace.setName("My Workspace " + uniqueString); String finalName = "Renamed Workspace " + uniqueString; - Mono<Workspace> workspaceMono = workspaceService.create(workspace) - .flatMap(savedWorkspace -> { - savedWorkspace.setName(finalName); - return workspaceService.save(savedWorkspace); - }); + Mono<Workspace> workspaceMono = workspaceService.create(workspace).flatMap(savedWorkspace -> { + savedWorkspace.setName(finalName); + return workspaceService.save(savedWorkspace); + }); StepVerifier.create(workspaceMono) .assertNext(savedWorkspace -> { @@ -1554,17 +1735,16 @@ public void save_WhenNameIsPresent_SlugGenerated() { @Test @WithUserDetails(value = "api_user") public void update_WhenNameIsNotPresent_SlugIsNotGenerated() { - String uniqueString = UUID.randomUUID().toString(); // to make sure name is not conflicted with other tests + String uniqueString = UUID.randomUUID().toString(); // to make sure name is not conflicted with other tests String initialName = "My Workspace " + uniqueString; Workspace workspace = new Workspace(); workspace.setName(initialName); - Mono<Workspace> workspaceMono = workspaceService.create(workspace) - .flatMap(savedWorkspace -> { - Workspace workspaceDto = new Workspace(); - workspaceDto.setWebsite("https://appsmith.com"); - return workspaceService.update(savedWorkspace.getId(), workspaceDto); - }); + Mono<Workspace> workspaceMono = workspaceService.create(workspace).flatMap(savedWorkspace -> { + Workspace workspaceDto = new Workspace(); + workspaceDto.setWebsite("https://appsmith.com"); + return workspaceService.update(savedWorkspace.getId(), workspaceDto); + }); StepVerifier.create(workspaceMono) .assertNext(savedWorkspace -> { @@ -1577,13 +1757,14 @@ public void update_WhenNameIsNotPresent_SlugIsNotGenerated() { @Test @WithUserDetails(value = "api_user") public void update_NewName_GroupNamesUpdated() { - String uniqueString = UUID.randomUUID().toString(); // to make sure name is not conflicted with other tests + String uniqueString = UUID.randomUUID().toString(); // to make sure name is not conflicted with other tests String initialName = "My Workspace " + uniqueString; String newName = "New Name " + uniqueString; Workspace workspace = new Workspace(); workspace.setName(initialName); - Mono<Workspace> workspaceNameUpdateMono = workspaceService.create(workspace) + Mono<Workspace> workspaceNameUpdateMono = workspaceService + .create(workspace) .flatMap(savedWorkspace -> { Workspace workspaceDto = new Workspace(); workspaceDto.setName(newName); @@ -1591,8 +1772,10 @@ public void update_NewName_GroupNamesUpdated() { }) .cache(); - Mono<List<PermissionGroup>> permissionGroupsMono = workspaceNameUpdateMono - .flatMap(savedWorkspace -> permissionGroupRepository.findAllById(savedWorkspace.getDefaultPermissionGroups()).collectList()); + Mono<List<PermissionGroup>> permissionGroupsMono = + workspaceNameUpdateMono.flatMap(savedWorkspace -> permissionGroupRepository + .findAllById(savedWorkspace.getDefaultPermissionGroups()) + .collectList()); StepVerifier.create(Mono.zip(workspaceNameUpdateMono, permissionGroupsMono)) .assertNext(tuple -> { @@ -1610,7 +1793,6 @@ public void update_NewName_GroupNamesUpdated() { assertThat(name).isEqualTo(generateDefaultRoleNameForResource(VIEWER, newName)); } } - }) .verifyComplete(); } @@ -1625,25 +1807,34 @@ void testWorkspaceUpdate_checkAdditionalFieldsArePresentAfterUpdate() { Workspace createdWorkspace = workspaceService.create(workspace).block(); Update updateAddAdditionalField = new Update().set(additionalField, true); - Query queryWorkspace = new Query(Criteria.where(fieldName(QWorkspace.workspace.id)).is(createdWorkspace.getId())); - UpdateResult updateResult = mongoTemplate.updateMulti(queryWorkspace, updateAddAdditionalField, Workspace.class); + Query queryWorkspace = + new Query(Criteria.where(fieldName(QWorkspace.workspace.id)).is(createdWorkspace.getId())); + UpdateResult updateResult = + mongoTemplate.updateMulti(queryWorkspace, updateAddAdditionalField, Workspace.class); assertThat(updateResult.wasAcknowledged()).isTrue(); assertThat(updateResult.getMatchedCount()).isEqualTo(1); assertThat(updateResult.getModifiedCount()).isEqualTo(1); - Criteria criteriaAdditionalField = new Criteria().andOperator(Criteria.where(fieldName(QWorkspace.workspace.id)).is(createdWorkspace.getId()), Criteria.where(additionalField).exists(true)); + Criteria criteriaAdditionalField = new Criteria() + .andOperator( + Criteria.where(fieldName(QWorkspace.workspace.id)).is(createdWorkspace.getId()), + Criteria.where(additionalField).exists(true)); Query queryWorkspaceWithAdditionalField = new Query(criteriaAdditionalField); - long countWorkspaceWithAdditionalField = mongoTemplate.count(queryWorkspaceWithAdditionalField, Workspace.class); + long countWorkspaceWithAdditionalField = + mongoTemplate.count(queryWorkspaceWithAdditionalField, Workspace.class); assertThat(countWorkspaceWithAdditionalField).isEqualTo(1); Workspace updateWorkspace = new Workspace(); updateWorkspace.setName(testName + " updated"); - Workspace updatedWorkspace = workspaceService.update(createdWorkspace.getId(), updateWorkspace).block(); + Workspace updatedWorkspace = workspaceService + .update(createdWorkspace.getId(), updateWorkspace) + .block(); assertThat(updatedWorkspace.getName()).isEqualTo(testName + " updated"); - long countWorkspaceWithAdditionalFieldAfterUpdate = mongoTemplate.count(queryWorkspaceWithAdditionalField, Workspace.class); + long countWorkspaceWithAdditionalFieldAfterUpdate = + mongoTemplate.count(queryWorkspaceWithAdditionalField, Workspace.class); assertThat(countWorkspaceWithAdditionalFieldAfterUpdate).isEqualTo(1); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ActionServiceCE_Test.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ActionServiceCE_Test.java index a45395a2e456..b31b1494cc2b 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ActionServiceCE_Test.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ActionServiceCE_Test.java @@ -5,6 +5,7 @@ import com.appsmith.external.helpers.AppsmithEventContextType; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.AnalyticsInfo; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceStorage; @@ -13,7 +14,6 @@ import com.appsmith.external.models.PaginationType; import com.appsmith.external.models.Policy; import com.appsmith.external.models.Property; -import com.appsmith.external.models.AnalyticsInfo; import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.server.acl.AclPermission; import com.appsmith.server.constants.FieldName; @@ -159,6 +159,7 @@ public class ActionServiceCE_Test { @SpyBean AstService astService; + @Autowired DatasourceRepository datasourceRepository; @@ -188,17 +189,21 @@ public void setup() { toCreate.setName("ActionServiceCE_Test"); if (workspaceId == null) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } if (testApp == null && testPage == null) { - //Create application and page which will be used by the tests to create actions for. + // Create application and page which will be used by the tests to create actions for. Application application = new Application(); application.setName(UUID.randomUUID().toString()); - testApp = applicationPageService.createApplication(application, workspaceId).block(); + testApp = applicationPageService + .createApplication(application, workspaceId) + .block(); final String pageId = testApp.getPages().get(0).getId(); @@ -232,17 +237,23 @@ public void setup() { GitApplicationMetadata gitData = new GitApplicationMetadata(); gitData.setBranchName("actionServiceTest"); newApp.setGitApplicationMetadata(gitData); - gitConnectedApp = applicationPageService.createApplication(newApp, workspaceId) + gitConnectedApp = applicationPageService + .createApplication(newApp, workspaceId) .flatMap(application -> { application.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); - return applicationService.save(application) - .zipWhen(application1 -> importExportApplicationService.exportApplicationById(application1.getId(), gitData.getBranchName())); + return applicationService + .save(application) + .zipWhen(application1 -> importExportApplicationService.exportApplicationById( + application1.getId(), gitData.getBranchName())); }) // Assign the branchName to all the resources connected to the application - .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) + .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) .block(); - gitConnectedPage = newPageService.findPageById(gitConnectedApp.getPages().get(0).getId(), READ_PAGES, false).block(); + gitConnectedPage = newPageService + .findPageById(gitConnectedApp.getPages().get(0).getId(), READ_PAGES, false) + .block(); branchName = gitConnectedApp.getGitApplicationMetadata().getBranchName(); } @@ -250,7 +261,8 @@ public void setup() { datasource = new Datasource(); datasource.setName("Default Database"); datasource.setWorkspaceId(workspaceId); - Plugin installed_plugin = pluginRepository.findByPackageName("restapi-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("restapi-plugin").block(); datasource.setPluginId(installed_plugin.getId()); datasource.setDatasourceConfiguration(new DatasourceConfiguration()); } @@ -261,14 +273,14 @@ public void cleanup() { applicationPageService.deleteApplication(testApp.getId()).block(); testApp = null; testPage = null; - } @Test @WithUserDetails(value = "api_user") public void findByIdAndBranchName_forGitConnectedAction_getBranchedAction() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("findActionByBranchNameTest"); action.setPageId(gitConnectedPage.getId()); @@ -278,15 +290,17 @@ public void findByIdAndBranchName_forGitConnectedAction_getBranchedAction() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<NewAction> actionMono = layoutActionService.createSingleActionWithBranch(action, branchName) - .flatMap(createdAction -> newActionService.findByBranchNameAndDefaultActionId(branchName, createdAction.getId(), READ_ACTIONS)); + Mono<NewAction> actionMono = layoutActionService + .createSingleActionWithBranch(action, branchName) + .flatMap(createdAction -> newActionService.findByBranchNameAndDefaultActionId( + branchName, createdAction.getId(), READ_ACTIONS)); - StepVerifier - .create(actionMono) + StepVerifier.create(actionMono) .assertNext(newAction -> { assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(gitConnectedPage.getId()); assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(gitConnectedApp.getId()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(gitConnectedApp.getId()); }) .verifyComplete(); } @@ -294,7 +308,8 @@ public void findByIdAndBranchName_forGitConnectedAction_getBranchedAction() { @Test @WithUserDetails(value = "api_user") public void createValidActionAndCheckPermissions() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -316,8 +331,7 @@ public void createValidActionAndCheckPermissions() { Mono<ActionDTO> actionMono = layoutActionService.createSingleAction(action, Boolean.FALSE); - StepVerifier - .create(Mono.zip(actionMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip(actionMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { ActionDTO createdAction = tuple.getT1(); assertThat(createdAction.getId()).isNotEmpty(); @@ -328,27 +342,37 @@ public void createValidActionAndCheckPermissions() { List<PermissionGroup> permissionGroups = tuple.getT2(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageActionPolicy = Policy.builder().permission(MANAGE_ACTIONS.getValue()) + Policy manageActionPolicy = Policy.builder() + .permission(MANAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readActionPolicy = Policy.builder().permission(READ_ACTIONS.getValue()) + Policy readActionPolicy = Policy.builder() + .permission(READ_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeActionPolicy = Policy.builder().permission(EXECUTE_ACTIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeActionPolicy = Policy.builder() + .permission(EXECUTE_ACTIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - assertThat(createdAction.getPolicies()).containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); + assertThat(createdAction.getPolicies()) + .containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); }) .verifyComplete(); } @@ -356,7 +380,8 @@ public void createValidActionAndCheckPermissions() { @Test @WithUserDetails(value = "api_user") public void createValidAction_forGitConnectedApp_getValidPermissionAndDefaultIds() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -378,41 +403,52 @@ public void createValidAction_forGitConnectedApp_getValidPermissionAndDefaultIds Mono<ActionDTO> actionMono = layoutActionService.createSingleActionWithBranch(action, branchName); - StepVerifier - .create(Mono.zip(actionMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip(actionMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { ActionDTO createdAction = tuple.getT1(); assertThat(createdAction.getExecuteOnLoad()).isFalse(); assertThat(createdAction.getDefaultResources()).isNotNull(); assertThat(createdAction.getUserPermissions()).isNotEmpty(); - assertThat(createdAction.getDefaultResources().getActionId()).isEqualTo(createdAction.getId()); + assertThat(createdAction.getDefaultResources().getActionId()) + .isEqualTo(createdAction.getId()); assertThat(createdAction.getDefaultResources().getPageId()).isEqualTo(gitConnectedPage.getId()); - assertThat(createdAction.getDefaultResources().getApplicationId()).isEqualTo(gitConnectedPage.getApplicationId()); + assertThat(createdAction.getDefaultResources().getApplicationId()) + .isEqualTo(gitConnectedPage.getApplicationId()); List<PermissionGroup> permissionGroups = tuple.getT2(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageActionPolicy = Policy.builder().permission(MANAGE_ACTIONS.getValue()) + Policy manageActionPolicy = Policy.builder() + .permission(MANAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readActionPolicy = Policy.builder().permission(READ_ACTIONS.getValue()) + Policy readActionPolicy = Policy.builder() + .permission(READ_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeActionPolicy = Policy.builder().permission(EXECUTE_ACTIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeActionPolicy = Policy.builder() + .permission(EXECUTE_ACTIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - assertThat(createdAction.getPolicies()).containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); + assertThat(createdAction.getPolicies()) + .containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); }) .verifyComplete(); } @@ -420,7 +456,8 @@ public void createValidAction_forGitConnectedApp_getValidPermissionAndDefaultIds @Test @WithUserDetails(value = "api_user") public void validMoveAction() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); PageDTO newPage = new PageDTO(); newPage.setName("Destination Page"); @@ -435,19 +472,18 @@ public void validMoveAction() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> createActionMono = layoutActionService.createSingleAction(action, Boolean.FALSE).cache(); + Mono<ActionDTO> createActionMono = + layoutActionService.createSingleAction(action, Boolean.FALSE).cache(); - Mono<ActionDTO> movedActionMono = createActionMono - .flatMap(savedAction -> { - ActionMoveDTO actionMoveDTO = new ActionMoveDTO(); - actionMoveDTO.setAction(savedAction); - actionMoveDTO.setDestinationPageId(destinationPage.getId()); - assertThat(savedAction.getUserPermissions()).isNotEmpty(); - return layoutActionService.moveAction(actionMoveDTO); - }); + Mono<ActionDTO> movedActionMono = createActionMono.flatMap(savedAction -> { + ActionMoveDTO actionMoveDTO = new ActionMoveDTO(); + actionMoveDTO.setAction(savedAction); + actionMoveDTO.setDestinationPageId(destinationPage.getId()); + assertThat(savedAction.getUserPermissions()).isNotEmpty(); + return layoutActionService.moveAction(actionMoveDTO); + }); - StepVerifier - .create(Mono.zip(createActionMono, movedActionMono)) + StepVerifier.create(Mono.zip(createActionMono, movedActionMono)) .assertNext(tuple -> { ActionDTO originalAction = tuple.getT1(); ActionDTO movedAction = tuple.getT2(); @@ -458,18 +494,20 @@ public void validMoveAction() { assertThat(movedAction.getPageId()).isEqualTo(destinationPage.getId()); }) .verifyComplete(); - } @Test @WithUserDetails(value = "api_user") public void moveAction_forGitConnectedApp_defaultResourceIdsUpdateSuccess() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); PageDTO newPage = new PageDTO(); newPage.setName("Destination Page"); newPage.setApplicationId(gitConnectedApp.getId()); - PageDTO destinationPage = applicationPageService.createPageWithBranchName(newPage, branchName).block(); + PageDTO destinationPage = applicationPageService + .createPageWithBranchName(newPage, branchName) + .block(); ActionDTO action = new ActionDTO(); action.setName("validAction"); @@ -479,20 +517,20 @@ public void moveAction_forGitConnectedApp_defaultResourceIdsUpdateSuccess() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> createActionMono = layoutActionService.createSingleActionWithBranch(action, branchName).cache(); + Mono<ActionDTO> createActionMono = layoutActionService + .createSingleActionWithBranch(action, branchName) + .cache(); DefaultResources sourceActionDefaultRes = new DefaultResources(); - Mono<ActionDTO> movedActionMono = createActionMono - .flatMap(savedAction -> { - ActionMoveDTO actionMoveDTO = new ActionMoveDTO(); - actionMoveDTO.setAction(savedAction); - actionMoveDTO.setDestinationPageId(destinationPage.getId()); - AppsmithBeanUtils.copyNestedNonNullProperties(savedAction.getDefaultResources(), sourceActionDefaultRes); - return layoutActionService.moveAction(actionMoveDTO, branchName); - }); + Mono<ActionDTO> movedActionMono = createActionMono.flatMap(savedAction -> { + ActionMoveDTO actionMoveDTO = new ActionMoveDTO(); + actionMoveDTO.setAction(savedAction); + actionMoveDTO.setDestinationPageId(destinationPage.getId()); + AppsmithBeanUtils.copyNestedNonNullProperties(savedAction.getDefaultResources(), sourceActionDefaultRes); + return layoutActionService.moveAction(actionMoveDTO, branchName); + }); - StepVerifier - .create(Mono.zip(createActionMono, movedActionMono)) + StepVerifier.create(Mono.zip(createActionMono, movedActionMono)) .assertNext(tuple -> { ActionDTO originalAction = tuple.getT1(); ActionDTO movedAction = tuple.getT2(); @@ -504,17 +542,19 @@ public void moveAction_forGitConnectedApp_defaultResourceIdsUpdateSuccess() { // Check if the defaultIds are updated as per destination page default Id assertThat(movedAction.getDefaultResources()).isNotNull(); - assertThat(movedAction.getDefaultResources().getPageId()).isEqualTo(destinationPage.getDefaultResources().getPageId()); - assertThat(sourceActionDefaultRes.getPageId()).isEqualTo(gitConnectedPage.getDefaultResources().getPageId()); + assertThat(movedAction.getDefaultResources().getPageId()) + .isEqualTo(destinationPage.getDefaultResources().getPageId()); + assertThat(sourceActionDefaultRes.getPageId()) + .isEqualTo(gitConnectedPage.getDefaultResources().getPageId()); }) .verifyComplete(); - } @Test @WithUserDetails(value = "api_user") public void createValidActionWithJustName() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("randomActionName"); @@ -523,10 +563,9 @@ public void createValidActionWithJustName() { actionConfiguration.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> actionMono = Mono.just(action) - .flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); - StepVerifier - .create(actionMono) + Mono<ActionDTO> actionMono = + Mono.just(action).flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); + StepVerifier.create(actionMono) .assertNext(createdAction -> { assertThat(createdAction.getId()).isNotEmpty(); assertThat(createdAction.getName()).isEqualTo(action.getName()); @@ -538,21 +577,22 @@ public void createValidActionWithJustName() { @Test @WithUserDetails(value = "api_user") public void createValidActionNullActionConfiguration() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("randomActionName2"); action.setPageId(testPage.getId()); action.setDatasource(datasource); - Mono<ActionDTO> actionMono = Mono.just(action) - .flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); - StepVerifier - .create(actionMono) + Mono<ActionDTO> actionMono = + Mono.just(action).flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); + StepVerifier.create(actionMono) .assertNext(createdAction -> { assertThat(createdAction.getId()).isNotEmpty(); assertThat(createdAction.getName()).isEqualTo(action.getName()); assertThat(createdAction.getIsValid()).isFalse(); - assertThat(createdAction.getInvalids()).contains(AppsmithError.NO_CONFIGURATION_FOUND_IN_ACTION.getMessage()); + assertThat(createdAction.getInvalids()) + .contains(AppsmithError.NO_CONFIGURATION_FOUND_IN_ACTION.getMessage()); }) .verifyComplete(); } @@ -566,12 +606,11 @@ public void invalidCreateActionNullName() { actionConfiguration.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> actionMono = Mono.just(action) - .flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); - StepVerifier - .create(actionMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) + Mono<ActionDTO> actionMono = + Mono.just(action).flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); + StepVerifier.create(actionMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) .verify(); } @@ -584,10 +623,9 @@ public void invalidCreateActionNullPageId() { actionConfiguration.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration); Mono<ActionDTO> actionMono = layoutActionService.createSingleAction(action, Boolean.FALSE); - StepVerifier - .create(actionMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PAGE_ID))) + StepVerifier.create(actionMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PAGE_ID))) .verify(); } @@ -601,10 +639,9 @@ public void createActionWithBranchName_withNullPageId_throwException() { action.setActionConfiguration(actionConfiguration); Mono<ActionDTO> actionMono = layoutActionService.createSingleActionWithBranch(action, branchName); - StepVerifier - .create(actionMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PAGE_ID))) + StepVerifier.create(actionMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PAGE_ID))) .verify(); } @@ -617,13 +654,13 @@ public void invalidCreateActionInvalidPageId() { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration); - Mono<ActionDTO> actionMono = Mono.just(action) - .flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); - StepVerifier - .create(actionMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals( - AppsmithError.NO_RESOURCE_FOUND.getMessage("page", "invalid page id here"))) + Mono<ActionDTO> actionMono = + Mono.just(action).flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); + StepVerifier.create(actionMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage("page", "invalid page id here"))) .verify(); } @@ -637,18 +674,20 @@ public void createAction_forGitConnectedAppWithInvalidBranchName_throwException( actionConfiguration.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration); Mono<ActionDTO> actionMono = layoutActionService.createSingleActionWithBranch(action, "randomTestBranch"); - StepVerifier - .create(actionMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PAGE, action.getPageId() + ", randomTestBranch"))) + StepVerifier.create(actionMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.PAGE, action.getPageId() + ", randomTestBranch"))) .verify(); } - @Test @WithUserDetails(value = "api_user") public void checkActionInViewMode() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); String key = "bodyMustacheKey"; ActionDTO action = new ActionDTO(); @@ -674,31 +713,40 @@ public void checkActionInViewMode() { action2.setPageId(testPage.getId()); action2.setDatasource(datasource); - Mono<List<ActionViewDTO>> actionsListMono = layoutActionService.createSingleAction(action, Boolean.FALSE) + Mono<List<ActionViewDTO>> actionsListMono = layoutActionService + .createSingleAction(action, Boolean.FALSE) .then(layoutActionService.createSingleAction(action1, Boolean.FALSE)) .then(layoutActionService.createSingleAction(action2, Boolean.FALSE)) .then(applicationPageService.publish(testPage.getApplicationId(), true)) .then(newActionService.getActionsForViewMode(testApp.getId()).collectList()); - StepVerifier - .create(actionsListMono) + StepVerifier.create(actionsListMono) .assertNext(actionsList -> { assertThat(actionsList.size()).isGreaterThan(0); - ActionViewDTO actionViewDTO = actionsList.stream().filter(dto -> dto.getName().equals(action.getName())).findFirst().get(); + ActionViewDTO actionViewDTO = actionsList.stream() + .filter(dto -> dto.getName().equals(action.getName())) + .findFirst() + .get(); assertThat(actionViewDTO).isNotNull(); assertThat(actionViewDTO.getJsonPathKeys()).containsAll(Set.of(key)); assertThat(actionViewDTO.getPageId()).isEqualTo(testPage.getId()); assertThat(actionViewDTO.getTimeoutInMillisecond()).isEqualTo(DEFAULT_ACTION_EXECUTION_TIMEOUT_MS); - ActionViewDTO actionViewDTO1 = actionsList.stream().filter(dto -> dto.getName().equals(action1.getName())).findFirst().get(); + ActionViewDTO actionViewDTO1 = actionsList.stream() + .filter(dto -> dto.getName().equals(action1.getName())) + .findFirst() + .get(); assertThat(actionViewDTO1).isNotNull(); assertThat(actionViewDTO1.getJsonPathKeys()).isNullOrEmpty(); assertThat(actionViewDTO1.getPageId()).isEqualTo(testPage.getId()); assertThat(actionViewDTO1.getTimeoutInMillisecond()).isEqualTo(20000); - ActionViewDTO actionViewDTO2 = actionsList.stream().filter(dto -> dto.getName().equals(action2.getName())).findFirst().get(); + ActionViewDTO actionViewDTO2 = actionsList.stream() + .filter(dto -> dto.getName().equals(action2.getName())) + .findFirst() + .get(); assertThat(actionViewDTO2).isNotNull(); assertThat(actionViewDTO2.getPageId()).isEqualTo(testPage.getId()); @@ -710,7 +758,8 @@ public void checkActionInViewMode() { @Test @WithUserDetails(value = "api_user") public void getActionInViewMode() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("view-mode-action-test"); @@ -740,16 +789,17 @@ public void getActionInViewMode() { .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void updateShouldNotResetUserSetOnLoad() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Datasource externalDatasource = new Datasource(); externalDatasource.setName("updateShouldNotResetUserSetOnLoad Database"); externalDatasource.setWorkspaceId(workspaceId); - Plugin installed_plugin = pluginRepository.findByPackageName("installed-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("installed-plugin").block(); externalDatasource.setPluginId(installed_plugin.getId()); DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setUrl("some url here"); @@ -768,23 +818,23 @@ public void updateShouldNotResetUserSetOnLoad() { action.setActionConfiguration(actionConfiguration); action.setDatasource(savedDs); - Mono<ActionDTO> newActionMono = layoutActionService - .createSingleAction(action, Boolean.FALSE) - .cache(); + Mono<ActionDTO> newActionMono = + layoutActionService.createSingleAction(action, Boolean.FALSE).cache(); - Mono<ActionDTO> setExecuteOnLoadMono = newActionMono - .flatMap(savedAction -> layoutActionService.setExecuteOnLoad(savedAction.getId(), true)); + Mono<ActionDTO> setExecuteOnLoadMono = + newActionMono.flatMap(savedAction -> layoutActionService.setExecuteOnLoad(savedAction.getId(), true)); - Mono<ActionDTO> updateActionMono = newActionMono - .flatMap(preUpdateAction -> { - ActionDTO actionUpdate = action; - actionUpdate.getActionConfiguration().setBody("New Body"); - return layoutActionService.updateSingleAction(preUpdateAction.getId(), actionUpdate) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); - }); + Mono<ActionDTO> updateActionMono = newActionMono.flatMap(preUpdateAction -> { + ActionDTO actionUpdate = action; + actionUpdate.getActionConfiguration().setBody("New Body"); + return layoutActionService + .updateSingleAction(preUpdateAction.getId(), actionUpdate) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); + }); - StepVerifier - .create(setExecuteOnLoadMono.then(updateActionMono)) + StepVerifier.create(setExecuteOnLoadMono.then(updateActionMono)) .assertNext(updatedAction -> { assertThat(updatedAction).isNotNull(); assertThat(updatedAction.getActionConfiguration().getBody()).isEqualTo("New Body"); @@ -796,7 +846,8 @@ public void updateShouldNotResetUserSetOnLoad() { @Test @WithUserDetails(value = "api_user") public void checkNewActionAndNewDatasourceAnonymousPermissionInPublicApp() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Application testApplication = new Application(); testApplication.setName("checkNewActionAndNewDatasourceAnonymousPermissionInPublicApp TestApp"); @@ -810,7 +861,9 @@ public void checkNewActionAndNewDatasourceAnonymousPermissionInPublicApp() { }) .collectList(); - Application createdApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); String pageId = createdApplication.getPages().get(0).getId(); @@ -845,20 +898,19 @@ public void checkNewActionAndNewDatasourceAnonymousPermissionInPublicApp() { actionConfiguration1.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration1); - ActionDTO savedAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO savedAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); - Mono<Datasource> datasourceMono = publicAppMono - .then(datasourceService.findById(savedDatasource.getId())); + Mono<Datasource> datasourceMono = publicAppMono.then(datasourceService.findById(savedDatasource.getId())); - Mono<NewAction> actionMono = publicAppMono - .then(newActionService.findById(savedAction.getId())); + Mono<NewAction> actionMono = publicAppMono.then(newActionService.findById(savedAction.getId())); Mono<PermissionGroup> publicAppPermissionGroupMono = permissionGroupService.getPublicPermissionGroup(); User anonymousUser = userService.findByEmail("anonymousUser").block(); - StepVerifier - .create(Mono.zip(datasourceMono, actionMono, defaultPermissionGroupsMono, publicAppPermissionGroupMono)) + StepVerifier.create( + Mono.zip(datasourceMono, actionMono, defaultPermissionGroupsMono, publicAppPermissionGroupMono)) .assertNext(tuple -> { Datasource datasourceFromDb = tuple.getT1(); NewAction actionFromDb = tuple.getT2(); @@ -867,43 +919,60 @@ public void checkNewActionAndNewDatasourceAnonymousPermissionInPublicApp() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageDatasourcePolicy = Policy.builder().permission(MANAGE_DATASOURCES.getValue()) + Policy manageDatasourcePolicy = Policy.builder() + .permission(MANAGE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readDatasourcePolicy = Policy.builder().permission(READ_DATASOURCES.getValue()) + Policy readDatasourcePolicy = Policy.builder() + .permission(READ_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeDatasourcePolicy = Policy.builder().permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), publicAppPermissionGroup.getId())) + Policy executeDatasourcePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + publicAppPermissionGroup.getId())) .build(); - Policy manageActionPolicy = Policy.builder().permission(MANAGE_ACTIONS.getValue()) + Policy manageActionPolicy = Policy.builder() + .permission(MANAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readActionPolicy = Policy.builder().permission(READ_ACTIONS.getValue()) + Policy readActionPolicy = Policy.builder() + .permission(READ_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeActionPolicy = Policy.builder().permission(EXECUTE_ACTIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), publicAppPermissionGroup.getId())) + Policy executeActionPolicy = Policy.builder() + .permission(EXECUTE_ACTIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + publicAppPermissionGroup.getId())) .build(); // Check that the datasource used in the app contains public execute permission - assertThat(datasourceFromDb.getPolicies()).containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); + assertThat(datasourceFromDb.getPolicies()) + .containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); // Check that the action used in the app contains public execute permission - assertThat(actionFromDb.getPolicies()).containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); + assertThat(actionFromDb.getPolicies()) + .containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); // Assert that viewerPermissionGroup has been assigned to anonymous user. assertThat(publicAppPermissionGroup.getAssignedToUserIds()).contains(anonymousUser.getId()); @@ -914,7 +983,8 @@ public void checkNewActionAndNewDatasourceAnonymousPermissionInPublicApp() { @Test @WithUserDetails(value = "api_user") public void testExecuteOnLoadParamOnActionCreateWithDefaultContext() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("testAction"); @@ -926,8 +996,7 @@ public void testExecuteOnLoadParamOnActionCreateWithDefaultContext() { action.setDatasource(datasource); Mono<ActionDTO> actionMono = layoutActionService.createSingleAction(action, Boolean.FALSE); - StepVerifier - .create(actionMono) + StepVerifier.create(actionMono) .assertNext(createdAction -> { // executeOnLoad is expected to be set to false in case of default context assertThat(createdAction.getExecuteOnLoad()).isFalse(); @@ -938,7 +1007,8 @@ public void testExecuteOnLoadParamOnActionCreateWithDefaultContext() { @Test @WithUserDetails(value = "api_user") public void testExecuteOnLoadParamOnActionCreateWithClonePageContext() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("testAction"); @@ -951,8 +1021,7 @@ public void testExecuteOnLoadParamOnActionCreateWithClonePageContext() { AppsmithEventContext eventContext = new AppsmithEventContext(AppsmithEventContextType.CLONE_PAGE); Mono<ActionDTO> actionMono = layoutActionService.createAction(action, eventContext, Boolean.FALSE); - StepVerifier - .create(actionMono) + StepVerifier.create(actionMono) .assertNext(createdAction -> { // executeOnLoad is expected to be set to false in case of default context assertThat(createdAction.getExecuteOnLoad()).isTrue(); @@ -963,7 +1032,8 @@ public void testExecuteOnLoadParamOnActionCreateWithClonePageContext() { @Test @WithUserDetails(value = "api_user") public void testUpdateActionWithOutOfRangeTimeout() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("testAction"); @@ -973,27 +1043,25 @@ public void testUpdateActionWithOutOfRangeTimeout() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> newActionMono = layoutActionService - .createSingleAction(action, Boolean.FALSE); + Mono<ActionDTO> newActionMono = layoutActionService.createSingleAction(action, Boolean.FALSE); - Mono<ActionDTO> updateActionMono = newActionMono - .flatMap(preUpdateAction -> { - ActionDTO actionUpdate = action; - actionUpdate.getActionConfiguration().setBody("New Body"); - return layoutActionService.updateSingleAction(preUpdateAction.getId(), actionUpdate) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); - }); + Mono<ActionDTO> updateActionMono = newActionMono.flatMap(preUpdateAction -> { + ActionDTO actionUpdate = action; + actionUpdate.getActionConfiguration().setBody("New Body"); + return layoutActionService + .updateSingleAction(preUpdateAction.getId(), actionUpdate) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); + }); - StepVerifier - .create(updateActionMono) + StepVerifier.create(updateActionMono) .assertNext(updatedAction -> { assertThat(updatedAction).isNotNull(); - assertThat(updatedAction - .getInvalids() - .stream() - .anyMatch(errorMsg -> errorMsg.contains("'Query timeout' field must be an integer between" + - " 0 and 60000")) - ).isTrue(); + assertThat(updatedAction.getInvalids().stream() + .anyMatch(errorMsg -> errorMsg.contains( + "'Query timeout' field must be an integer between" + " 0 and 60000"))) + .isTrue(); }) .verifyComplete(); } @@ -1001,7 +1069,8 @@ public void testUpdateActionWithOutOfRangeTimeout() { @Test @WithUserDetails(value = "api_user") public void testUpdateActionWithValidRangeTimeout() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("testAction"); @@ -1011,25 +1080,24 @@ public void testUpdateActionWithValidRangeTimeout() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> newActionMono = layoutActionService - .createSingleAction(action, Boolean.FALSE); + Mono<ActionDTO> newActionMono = layoutActionService.createSingleAction(action, Boolean.FALSE); - Mono<ActionDTO> updateActionMono = newActionMono - .flatMap(preUpdateAction -> { - action.getActionConfiguration().setBody("New Body"); - return layoutActionService.updateSingleAction(preUpdateAction.getId(), action) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)); - }); + Mono<ActionDTO> updateActionMono = newActionMono.flatMap(preUpdateAction -> { + action.getActionConfiguration().setBody("New Body"); + return layoutActionService + .updateSingleAction(preUpdateAction.getId(), action) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)); + }); - StepVerifier - .create(updateActionMono) + StepVerifier.create(updateActionMono) .assertNext(updatedAction -> { assertThat(updatedAction).isNotNull(); - assertThat(updatedAction - .getInvalids() - .stream() - .anyMatch(errorMsg -> errorMsg.contains("'Query timeout' field must be an integer between")) - ).isFalse(); + assertThat(updatedAction.getInvalids().stream() + .anyMatch(errorMsg -> + errorMsg.contains("'Query timeout' field must be an integer between"))) + .isFalse(); }) .verifyComplete(); } @@ -1037,7 +1105,8 @@ public void testUpdateActionWithValidRangeTimeout() { @Test @WithUserDetails(value = "api_user") public void testCreateActionWithOutOfRangeTimeout() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("validAction"); @@ -1049,20 +1118,18 @@ public void testCreateActionWithOutOfRangeTimeout() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> actionMono = layoutActionService.createSingleAction(action, Boolean.FALSE) + Mono<ActionDTO> actionMono = layoutActionService + .createSingleAction(action, Boolean.FALSE) .flatMap(createdAction -> newActionService.findById(createdAction.getId(), READ_ACTIONS)) .flatMap(newAction -> newActionService.generateActionByViewMode(newAction, false)); - StepVerifier - .create(actionMono) + StepVerifier.create(actionMono) .assertNext(createdAction -> { assertThat(createdAction).isNotNull(); - assertThat(createdAction - .getInvalids() - .stream() - .anyMatch(errorMsg -> errorMsg.contains("'Query timeout' field must be an integer between" + - " 0 and 60000")) - ).isTrue(); + assertThat(createdAction.getInvalids().stream() + .anyMatch(errorMsg -> errorMsg.contains( + "'Query timeout' field must be an integer between" + " 0 and 60000"))) + .isTrue(); }) .verifyComplete(); } @@ -1070,7 +1137,8 @@ public void testCreateActionWithOutOfRangeTimeout() { @Test @WithUserDetails(value = "api_user") public void testCreateActionWithValidRangeTimeout() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("validAction"); @@ -1082,28 +1150,27 @@ public void testCreateActionWithValidRangeTimeout() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> actionMono = layoutActionService.createSingleAction(action, Boolean.FALSE) + Mono<ActionDTO> actionMono = layoutActionService + .createSingleAction(action, Boolean.FALSE) .flatMap(createdAction -> newActionService.findById(createdAction.getId(), READ_ACTIONS)) .flatMap(newAction -> newActionService.generateActionByViewMode(newAction, false)); - StepVerifier - .create(actionMono) + StepVerifier.create(actionMono) .assertNext(createdAction -> { assertThat(createdAction).isNotNull(); - assertThat(createdAction - .getInvalids() - .stream() - .anyMatch(errorMsg -> errorMsg.contains("'Query timeout' field must be an integer between")) - ).isFalse(); + assertThat(createdAction.getInvalids().stream() + .anyMatch(errorMsg -> + errorMsg.contains("'Query timeout' field must be an integer between"))) + .isFalse(); }) .verifyComplete(); } - private Mono<PageDTO> createPage(Application app, PageDTO page) { return newPageService .findByNameAndViewMode(page.getName(), AclPermission.READ_PAGES, false) - .switchIfEmpty(applicationPageService.createApplication(app, workspaceId) + .switchIfEmpty(applicationPageService + .createApplication(app, workspaceId) .map(application -> { page.setApplicationId(application.getId()); return page; @@ -1114,7 +1181,8 @@ private Mono<PageDTO> createPage(Application app, PageDTO page) { @Test @WithUserDetails(value = "api_user") public void getActionsExecuteOnLoadPaginatedApi() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); PageDTO testPage = new PageDTO(); testPage.setName("ActionsExecuteOnLoad Paginated Api Test Page"); @@ -1124,8 +1192,7 @@ public void getActionsExecuteOnLoadPaginatedApi() { Mono<PageDTO> pageMono = createPage(app, testPage).cache(); - Mono<LayoutDTO> testMono = pageMono - .flatMap(page1 -> { + Mono<LayoutDTO> testMono = pageMono.flatMap(page1 -> { List<Mono<ActionDTO>> monos = new ArrayList<>(); ActionDTO action = new ActionDTO(); @@ -1145,9 +1212,7 @@ public void getActionsExecuteOnLoadPaginatedApi() { .zipWhen(page1 -> { Layout layout = new Layout(); - JSONObject obj = new JSONObject(Map.of( - "key", "value" - )); + JSONObject obj = new JSONObject(Map.of("key", "value")); layout.setDsl(obj); return layoutService.createLayout(page1.getId(), layout); @@ -1161,40 +1226,41 @@ public void getActionsExecuteOnLoadPaginatedApi() { JSONObject obj = new JSONObject(Map.of( "widgetName", "testWidget", "key", "value-updated", - "bindingPath", "{{paginatedApi.data}}" - )); + "bindingPath", "{{paginatedApi.data}}")); JSONArray dynamicBindingsPathList = new JSONArray(); - dynamicBindingsPathList.add( - new JSONObject(Map.of("key", "bindingPath")) - ); + dynamicBindingsPathList.add(new JSONObject(Map.of("key", "bindingPath"))); obj.put("dynamicBindingPathList", dynamicBindingsPathList); newLayout.setDsl(obj); - return layoutActionService.updateLayout(page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); - + return layoutActionService.updateLayout( + page1.getId(), page1.getApplicationId(), layout.getId(), newLayout); }); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("paginatedApi.data"), EVALUATION_VERSION)) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("paginatedApi.data"), EVALUATION_VERSION)) .thenReturn(Flux.just(Tuples.of("paginatedApi.data", new HashSet<>(Set.of("paginatedApi.data"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("paginatedApi.data.prev"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("paginatedApi.data.prev", new HashSet<>(Set.of("paginatedApi.data.prev"))))); - Mockito.when(astService.getPossibleReferencesFromDynamicBinding(List.of("paginatedApi.data.next"), EVALUATION_VERSION)) - .thenReturn(Flux.just(Tuples.of("paginatedApi.data.next", new HashSet<>(Set.of("paginatedApi.data.next"))))); - - StepVerifier - .create(testMono) + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("paginatedApi.data.prev"), EVALUATION_VERSION)) + .thenReturn(Flux.just( + Tuples.of("paginatedApi.data.prev", new HashSet<>(Set.of("paginatedApi.data.prev"))))); + Mockito.when(astService.getPossibleReferencesFromDynamicBinding( + List.of("paginatedApi.data.next"), EVALUATION_VERSION)) + .thenReturn(Flux.just( + Tuples.of("paginatedApi.data.next", new HashSet<>(Set.of("paginatedApi.data.next"))))); + + StepVerifier.create(testMono) .assertNext(layout -> { assertThat(layout).isNotNull(); assertThat(layout.getId()).isNotNull(); assertThat(layout.getLayoutOnLoadActions()).hasSize(1); assertThat(layout.getLayoutOnLoadActions().get(0)).hasSize(1); - Set<String> firstSetPageLoadActions = Set.of( - "paginatedApi" - ); + Set<String> firstSetPageLoadActions = Set.of("paginatedApi"); - assertThat(layout.getLayoutOnLoadActions().get(0).stream().map(DslActionDTO::getName).collect(Collectors.toSet())) + assertThat(layout.getLayoutOnLoadActions().get(0).stream() + .map(DslActionDTO::getName) + .collect(Collectors.toSet())) .hasSameElementsAs(firstSetPageLoadActions); }) .verifyComplete(); @@ -1204,7 +1270,8 @@ public void getActionsExecuteOnLoadPaginatedApi() { @WithUserDetails(value = "api_user") public void updateAction_withoutWorkspaceId_withOrganizationId() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("validAction_nestedDatasource"); @@ -1215,8 +1282,8 @@ public void updateAction_withoutWorkspaceId_withOrganizationId() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); - Mono<ActionDTO> createActionMono = layoutActionService.createSingleAction(action, Boolean.FALSE).cache(); - + Mono<ActionDTO> createActionMono = + layoutActionService.createSingleAction(action, Boolean.FALSE).cache(); ActionDTO updateAction = new ActionDTO(); Datasource nestedDatasource = new Datasource(); @@ -1226,11 +1293,10 @@ public void updateAction_withoutWorkspaceId_withOrganizationId() { nestedDatasource.setDatasourceConfiguration(new DatasourceConfiguration()); updateAction.setDatasource(nestedDatasource); - Mono<ActionDTO> actionMono = createActionMono - .flatMap(savedAction -> layoutActionService.updateAction(savedAction.getId(), updateAction)); + Mono<ActionDTO> actionMono = createActionMono.flatMap( + savedAction -> layoutActionService.updateAction(savedAction.getId(), updateAction)); - StepVerifier - .create(actionMono) + StepVerifier.create(actionMono) .assertNext(updatedAction -> { Datasource datasource1 = updatedAction.getDatasource(); assertThat(datasource1.getWorkspaceId()).isNotNull(); @@ -1242,7 +1308,8 @@ public void updateAction_withoutWorkspaceId_withOrganizationId() { @Test @WithUserDetails("api_user") public void validateAndSaveActionToRepository_noDatasourceEditPermission() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mockito.when(pluginService.getEditorConfigLabelMap(Mockito.anyString())).thenReturn(Mono.just(new HashMap<>())); Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); @@ -1255,14 +1322,16 @@ public void validateAndSaveActionToRepository_noDatasourceEditPermission() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); NewAction newAction = newActionService.findById(createdAction.getId()).block(); Set<Policy> datasourceExistingPolicies = datasource.getPolicies(); datasource.setPolicies(Set.of()); Datasource updatedDatasource = datasourceRepository.save(datasource).block(); - ActionDTO savedAction = newActionService.validateAndSaveActionToRepository(newAction).block(); + ActionDTO savedAction = + newActionService.validateAndSaveActionToRepository(newAction).block(); assertThat(savedAction.getIsValid()).isTrue(); datasource.setPolicies(datasourceExistingPolicies); datasource = datasourceRepository.save(datasource).block(); @@ -1271,7 +1340,8 @@ public void validateAndSaveActionToRepository_noDatasourceEditPermission() { @Test @WithUserDetails(value = "api_user") public void createCopyActionWithAnalyticsData_validateAnalyticsDataPersistsInResponse() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("CopyOfQuery1"); @@ -1290,18 +1360,20 @@ public void createCopyActionWithAnalyticsData_validateAnalyticsDataPersistsInRes action.setActionConfiguration(actionConfiguration); - - Mono<ActionDTO> actionMono = Mono.just(action) - .flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); - StepVerifier - .create(actionMono) + Mono<ActionDTO> actionMono = + Mono.just(action).flatMap(action1 -> layoutActionService.createSingleAction(action1, Boolean.FALSE)); + StepVerifier.create(actionMono) .assertNext(createdAction -> { assertThat(createdAction.getId()).isNotEmpty(); assertThat(createdAction.getName()).isEqualTo(action.getName()); assertThat(createdAction.getIsValid()).isTrue(); - assertThat(createdAction.getEventData().getAnalyticsData().get(keyOriginalActionId).toString().equalsIgnoreCase(valueOriginalActionId)); + assertThat(createdAction + .getEventData() + .getAnalyticsData() + .get(keyOriginalActionId) + .toString() + .equalsIgnoreCase(valueOriginalActionId)); }) .verifyComplete(); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationServiceCETest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationServiceCETest.java index 3f1b3be4c746..54ff4627c244 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationServiceCETest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationServiceCETest.java @@ -150,60 +150,88 @@ public class ApplicationServiceCETest { static Plugin testPlugin = new Plugin(); static Datasource testDatasource = new Datasource(); static Application gitConnectedApp = new Application(); + @Autowired ApplicationService applicationService; + @Autowired ApplicationPageServiceCE applicationPageService; + @Autowired UserService userService; + @Autowired WorkspaceService workspaceService; + @Autowired DatasourceService datasourceService; + @Autowired PluginService pluginService; + @Autowired NewActionService newActionService; + @MockBean PluginExecutorHelper pluginExecutorHelper; + @Autowired ApplicationFetcher applicationFetcher; + @Autowired NewPageService newPageService; + @Autowired NewPageRepository newPageRepository; + @Autowired ApplicationRepository applicationRepository; + @Autowired LayoutActionService layoutActionService; + @Autowired LayoutCollectionService layoutCollectionService; + @Autowired ActionCollectionService actionCollectionService; + @Autowired CustomJSLibService customJSLibService; + @Autowired PluginRepository pluginRepository; + @Autowired ImportExportApplicationService importExportApplicationService; + @Autowired ThemeService themeService; + @Autowired PermissionGroupService permissionGroupService; + @MockBean ReleaseNotesService releaseNotesService; + @MockBean PluginExecutor pluginExecutor; + @Autowired ReactiveMongoOperations mongoOperations; + @Autowired PermissionGroupRepository permissionGroupRepository; + @Autowired UserRepository userRepository; + @Autowired SessionUserService sessionUserService; + String workspaceId; String defaultEnvironmentId; + @Autowired private AssetRepository assetRepository; @@ -217,20 +245,25 @@ public void setup() { return; } - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); User apiUser = userService.findByEmail("api_user").block(); Workspace toCreate = new Workspace(); toCreate.setName("ApplicationServiceTest"); if (workspaceId == null) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); if (StringUtils.hasLength(gitConnectedApp.getId())) { - applicationPageService.deleteApplication(gitConnectedApp.getId()).block(); + applicationPageService + .deleteApplication(gitConnectedApp.getId()) + .block(); } gitConnectedApp = new Application(); @@ -244,14 +277,17 @@ public void setup() { gitConnectedApp.setGitApplicationMetadata(gitData); // This will be altered in update app by branch test gitConnectedApp.setName("gitConnectedApp"); - gitConnectedApp = applicationPageService.createApplication(gitConnectedApp) + gitConnectedApp = applicationPageService + .createApplication(gitConnectedApp) .flatMap(application -> { application.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); return applicationService.save(application); }) // Assign the branchName to all the resources connected to the application - .flatMap(application -> importExportApplicationService.exportApplicationById(application.getId(), gitData.getBranchName())) - .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, applicationJson, gitConnectedApp.getId(), gitData.getBranchName())) + .flatMap(application -> importExportApplicationService.exportApplicationById( + application.getId(), gitData.getBranchName())) + .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, applicationJson, gitConnectedApp.getId(), gitData.getBranchName())) .block(); testPlugin = pluginService.findByPackageName("restapi-plugin").block(); @@ -274,8 +310,11 @@ public void setup() { private Mono<? extends BaseDomain> getArchivedResource(String id, Class<? extends BaseDomain> domainClass) { Query query = new Query(where("id").is(id)); - final Query actionQuery = query(where(fieldName(QNewAction.newAction.applicationId)).exists(true)) - .addCriteria(where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)).exists(true)); + final Query actionQuery = query( + where(fieldName(QNewAction.newAction.applicationId)).exists(true)) + .addCriteria(where(fieldName(QNewAction.newAction.unpublishedAction) + "." + + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)) + .exists(true)); return mongoOperations.findOne(query, domainClass); } @@ -284,16 +323,14 @@ private Mono<? extends BaseDomain> getArchivedResource(String id, Class<? extend @WithUserDetails(value = "api_user") public void createApplicationWithNullName() { Application application = new Application(); - Mono<Application> applicationMono = Mono.just(application) - .flatMap(app -> applicationPageService.createApplication(app, workspaceId)); - StepVerifier - .create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) + Mono<Application> applicationMono = + Mono.just(application).flatMap(app -> applicationPageService.createApplication(app, workspaceId)); + StepVerifier.create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME))) .verify(); } - /** * Create an application and validate it. * @@ -316,8 +353,7 @@ private void createAndVerifyValidApplication(String applicationName, String appl }) .collectList(); - StepVerifier - .create(Mono.zip(applicationMono, themeService.getDefaultThemeId(), defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip(applicationMono, themeService.getDefaultThemeId(), defaultPermissionGroupsMono)) .assertNext(tuple2 -> { Application application = tuple2.getT1(); String defaultThemeId = tuple2.getT2(); @@ -340,37 +376,55 @@ private void createAndVerifyValidApplication(String applicationName, String appl List<PermissionGroup> permissionGroups = tuple2.getT3(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - Policy publishAppPolicy = Policy.builder().permission(PUBLISH_APPLICATIONS.getValue()) + Policy publishAppPolicy = Policy.builder() + .permission(PUBLISH_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy exportAppPolicy = Policy.builder().permission(EXPORT_APPLICATIONS.getValue()) + Policy exportAppPolicy = Policy.builder() + .permission(EXPORT_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId())) .build(); - Policy deleteApplicationsPolicy = Policy.builder().permission(AclPermission.DELETE_APPLICATIONS.getValue()) + Policy deleteApplicationsPolicy = Policy.builder() + .permission(AclPermission.DELETE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy createPagesPolicy = Policy.builder().permission(AclPermission.APPLICATION_CREATE_PAGES.getValue()) + Policy createPagesPolicy = Policy.builder() + .permission(AclPermission.APPLICATION_CREATE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - assertThat(application.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy, publishAppPolicy, - exportAppPolicy, deleteApplicationsPolicy, createPagesPolicy)); + assertThat(application.getPolicies()) + .containsAll(Set.of( + manageAppPolicy, + readAppPolicy, + publishAppPolicy, + exportAppPolicy, + deleteApplicationsPolicy, + createPagesPolicy)); }) .verifyComplete(); } @@ -402,22 +456,29 @@ public void defaultPageCreateOnCreateApplicationTest() { // Fetch the unpublished pages by applicationId .flatMapMany(application -> newPageService.findByApplicationId(application.getId(), READ_PAGES, false)); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .users(Set.of("api_user")) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) .users(Set.of("api_user")) .build(); - StepVerifier - .create(pagesFlux) + StepVerifier.create(pagesFlux) .assertNext(page -> { assertThat(page).isNotNull(); assertThat(page.getName()).isEqualTo(FieldName.DEFAULT_PAGE_NAME); assertThat(page.getLayouts()).isNotEmpty(); assertThat(page.getPolicies()).isNotEmpty(); - assertThat(page.getPolicies().stream().map(Policy::getPermission).collect(Collectors.toSet())) - .containsExactlyInAnyOrder(MANAGE_PAGES.getValue(), READ_PAGES.getValue(), PAGE_CREATE_PAGE_ACTIONS.getValue(), DELETE_PAGES.getValue()); + assertThat(page.getPolicies().stream() + .map(Policy::getPermission) + .collect(Collectors.toSet())) + .containsExactlyInAnyOrder( + MANAGE_PAGES.getValue(), + READ_PAGES.getValue(), + PAGE_CREATE_PAGE_ACTIONS.getValue(), + DELETE_PAGES.getValue()); }) .verifyComplete(); } @@ -429,8 +490,10 @@ public void defaultPageCreateOnCreateApplicationTest() { public void getApplicationInvalidId() { Mono<Application> applicationMono = applicationService.getById("random-id"); StepVerifier.create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, "random-id"))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, "random-id"))) .verify(); } @@ -439,8 +502,8 @@ public void getApplicationInvalidId() { public void getApplicationNullId() { Mono<Application> applicationMono = applicationService.getById(null); StepVerifier.create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ID))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ID))) .verify(); } @@ -485,7 +548,8 @@ public void validGetApplicationsByName() { @Test @WithUserDetails(value = "api_user") public void getApplicationByDefaultIdAndBranchName_emptyBranchName_success() { - Mono<Application> applicationMono = applicationService.findByBranchNameAndDefaultApplicationId("", gitConnectedApp.getId(), READ_APPLICATIONS); + Mono<Application> applicationMono = applicationService.findByBranchNameAndDefaultApplicationId( + "", gitConnectedApp.getId(), READ_APPLICATIONS); StepVerifier.create(applicationMono) .assertNext(application -> { assertThat(application.getId()).isEqualTo(gitConnectedApp.getId()); @@ -496,20 +560,26 @@ public void getApplicationByDefaultIdAndBranchName_emptyBranchName_success() { @Test @WithUserDetails(value = "api_user") public void getApplicationByDefaultIdAndBranchName_invalidBranchName_throwException() { - Mono<Application> applicationMono = applicationService.findByBranchNameAndDefaultApplicationId("randomBranch", gitConnectedApp.getId(), READ_APPLICATIONS); + Mono<Application> applicationMono = applicationService.findByBranchNameAndDefaultApplicationId( + "randomBranch", gitConnectedApp.getId(), READ_APPLICATIONS); StepVerifier.create(applicationMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, gitConnectedApp.getId() + "," + "randomBranch"))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.APPLICATION, gitConnectedApp.getId() + "," + "randomBranch"))) .verify(); } @Test @WithUserDetails(value = "api_user") public void getApplicationByDefaultIdAndBranchName_validBranchName_success() { - Mono<Application> applicationMono = applicationService.findByBranchNameAndDefaultApplicationId("testBranch", gitConnectedApp.getId(), READ_APPLICATIONS); + Mono<Application> applicationMono = applicationService.findByBranchNameAndDefaultApplicationId( + "testBranch", gitConnectedApp.getId(), READ_APPLICATIONS); StepVerifier.create(applicationMono) .assertNext(application -> { - assertThat(application.getGitApplicationMetadata()).isEqualTo(gitConnectedApp.getGitApplicationMetadata()); + assertThat(application.getGitApplicationMetadata()) + .isEqualTo(gitConnectedApp.getGitApplicationMetadata()); }) .verifyComplete(); } @@ -518,13 +588,17 @@ public void getApplicationByDefaultIdAndBranchName_validBranchName_success() { @WithUserDetails(value = "api_user") public void getApplicationsByBranchName_validBranchName_success() { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); - params.set(FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME, gitConnectedApp.getGitApplicationMetadata().getBranchName()); + params.set( + FieldName.DEFAULT_RESOURCES + "." + FieldName.BRANCH_NAME, + gitConnectedApp.getGitApplicationMetadata().getBranchName()); Flux<Application> getApplication = applicationService.get(params); StepVerifier.create(getApplication) .assertNext(t -> { assertThat(t).isNotNull(); - assertThat(t.getGitApplicationMetadata().getBranchName()).isEqualTo(gitConnectedApp.getGitApplicationMetadata().getBranchName()); + assertThat(t.getGitApplicationMetadata().getBranchName()) + .isEqualTo( + gitConnectedApp.getGitApplicationMetadata().getBranchName()); assertThat(t.getId()).isEqualTo(gitConnectedApp.getId()); }) .verifyComplete(); @@ -548,18 +622,23 @@ public void validGetApplications() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); Mono<Application> createApplication = applicationPageService.createApplication(application, workspaceId); @@ -569,8 +648,7 @@ public void validGetApplications() { .block(); assertThat(applicationList).isNotEmpty(); - applicationList - .stream() + applicationList.stream() .filter(t -> t.getName().equals("validGetApplications-Test")) .forEach(t -> { assertThat(t.getId()).isNotNull(); @@ -587,9 +665,7 @@ public void validUpdateApplication() { Application application = new Application(); application.setName("validUpdateApplication-Test"); - Mono<Application> createApplication = - applicationPageService - .createApplication(application, workspaceId); + Mono<Application> createApplication = applicationPageService.createApplication(application, workspaceId); Mono<Application> updateApplication = createApplication .map(t -> { t.setName("NewValidUpdateApplication-Test"); @@ -641,10 +717,12 @@ public void invalidUpdateApplication() { public void updateApplicationByIdAndBranchName_validBranchName_success() { gitConnectedApp.setName("updatedGitConnectedApplication"); - Mono<Application> updateApplication = applicationService.update(gitConnectedApp.getId(), gitConnectedApp) + Mono<Application> updateApplication = applicationService + .update(gitConnectedApp.getId(), gitConnectedApp) .flatMap(t -> { GitApplicationMetadata gitData = t.getGitApplicationMetadata(); - return applicationService.findByBranchNameAndDefaultApplicationId(gitData.getBranchName(), gitData.getDefaultApplicationId(), READ_APPLICATIONS); + return applicationService.findByBranchNameAndDefaultApplicationId( + gitData.getBranchName(), gitData.getDefaultApplicationId(), READ_APPLICATIONS); }); StepVerifier.create(updateApplication) @@ -672,11 +750,10 @@ public void reuseDeletedAppName() { .flatMap(app -> applicationService.archive(app)) .cache(); - Mono<Application> secondAppCreation = firstAppDeletion.then( - applicationPageService.createApplication(secondApp, workspaceId)); + Mono<Application> secondAppCreation = + firstAppDeletion.then(applicationPageService.createApplication(secondApp, workspaceId)); - StepVerifier - .create(Mono.zip(firstAppDeletion, secondAppCreation)) + StepVerifier.create(Mono.zip(firstAppDeletion, secondAppCreation)) .assertNext(tuple2 -> { Application first = tuple2.getT1(), second = tuple2.getT2(); assertThat(first.getName()).isEqualTo("Ghost app"); @@ -694,33 +771,39 @@ public void getAllApplicationsForHome() { Mono<UserHomepageDTO> allApplications = applicationFetcher.getAllApplications(); - StepVerifier - .create(allApplications) + StepVerifier.create(allApplications) .assertNext(userHomepageDTO -> { assertThat(userHomepageDTO).isNotNull(); - //In case of anonymous user, we should have errored out. Assert that the user is not anonymous. + // In case of anonymous user, we should have errored out. Assert that the user is not anonymous. assertThat(userHomepageDTO.getUser().getIsAnonymous()).isFalse(); - List<WorkspaceApplicationsDTO> workspaceApplicationsDTOs = userHomepageDTO.getWorkspaceApplications(); + List<WorkspaceApplicationsDTO> workspaceApplicationsDTOs = + userHomepageDTO.getWorkspaceApplications(); assertThat(workspaceApplicationsDTOs.size()).isPositive(); for (WorkspaceApplicationsDTO workspaceApplicationDTO : workspaceApplicationsDTOs) { if (workspaceApplicationDTO.getWorkspace().getName().equals("Spring Test Workspace")) { - assertThat(workspaceApplicationDTO.getWorkspace().getUserPermissions()).contains("read:workspaces"); + assertThat(workspaceApplicationDTO.getWorkspace().getUserPermissions()) + .contains("read:workspaces"); - Application application = workspaceApplicationDTO.getApplications().get(0); + Application application = + workspaceApplicationDTO.getApplications().get(0); assertThat(application.getUserPermissions()).contains("read:applications"); assertThat(application.isAppIsExample()).isFalse(); assertThat(workspaceApplicationDTO.getUsers()).isNotEmpty(); - assertThat(workspaceApplicationDTO.getUsers().get(0).getRoles()).hasSize(1); - assertThat(workspaceApplicationDTO.getUsers().get(0).getRoles().get(0).getName()).startsWith(FieldName.ADMINISTRATOR); + assertThat(workspaceApplicationDTO.getUsers().get(0).getRoles()) + .hasSize(1); + assertThat(workspaceApplicationDTO + .getUsers() + .get(0) + .getRoles() + .get(0) + .getName()) + .startsWith(FieldName.ADMINISTRATOR); } } - - }) .verifyComplete(); - } @Test @@ -740,29 +823,27 @@ public void getOnlyDefaultApplicationsConnectedToGitForHome() { Mono<Application> branchedApplicationMono = applicationPageService.createApplication(branchedApplication); - Mono<List<Application>> gitConnectedAppsMono = applicationService.findByWorkspaceId(workspaceId, READ_APPLICATIONS) + Mono<List<Application>> gitConnectedAppsMono = applicationService + .findByWorkspaceId(workspaceId, READ_APPLICATIONS) .filter(application -> application.getGitApplicationMetadata() != null) .collectList(); - StepVerifier - .create(branchedApplicationMono - .then(Mono.zip(allApplications, gitConnectedAppsMono))) + StepVerifier.create(branchedApplicationMono.then(Mono.zip(allApplications, gitConnectedAppsMono))) .assertNext(tuple -> { UserHomepageDTO userHomepageDTO = tuple.getT1(); List<Application> gitConnectedApps = tuple.getT2(); assertThat(userHomepageDTO).isNotNull(); - //In case of anonymous user, we should have errored out. Assert that the user is not anonymous. + // In case of anonymous user, we should have errored out. Assert that the user is not anonymous. assertThat(userHomepageDTO.getUser().getIsAnonymous()).isFalse(); - List<WorkspaceApplicationsDTO> workspaceApplicationsDTOs = userHomepageDTO.getWorkspaceApplications(); + List<WorkspaceApplicationsDTO> workspaceApplicationsDTOs = + userHomepageDTO.getWorkspaceApplications(); assertThat(workspaceApplicationsDTOs.size()).isPositive(); for (WorkspaceApplicationsDTO workspaceApplicationDTO : workspaceApplicationsDTOs) { if (workspaceApplicationDTO.getWorkspace().getId().equals(workspaceId)) { - List<Application> applications = workspaceApplicationDTO - .getApplications() - .stream() + List<Application> applications = workspaceApplicationDTO.getApplications().stream() .filter(application -> application.getGitApplicationMetadata() != null) .collect(Collectors.toList()); assertThat(applications).hasSize(1); @@ -772,7 +853,6 @@ public void getOnlyDefaultApplicationsConnectedToGitForHome() { } }) .verifyComplete(); - } @Test @@ -785,14 +865,12 @@ public void getAllApplicationsForHomeWhenNoApplicationPresent() { workspace.setName("usertest's workspace"); Mono<Workspace> workspaceMono = workspaceService.create(workspace); - Mono<UserHomepageDTO> allApplications = workspaceMono - .then(applicationFetcher.getAllApplications()); + Mono<UserHomepageDTO> allApplications = workspaceMono.then(applicationFetcher.getAllApplications()); - StepVerifier - .create(allApplications) + StepVerifier.create(allApplications) .assertNext(userHomepageDTO -> { assertThat(userHomepageDTO).isNotNull(); - //In case of anonymous user, we should have errored out. Assert that the user is not anonymous. + // In case of anonymous user, we should have errored out. Assert that the user is not anonymous. assertThat(userHomepageDTO.getUser().getIsAnonymous()).isFalse(); List<WorkspaceApplicationsDTO> workspaceApplications = userHomepageDTO.getWorkspaceApplications(); @@ -802,7 +880,6 @@ public void getAllApplicationsForHomeWhenNoApplicationPresent() { assertThat(orgAppDto.getWorkspace().getUserPermissions()).contains("read:workspaces"); }) .verifyComplete(); - } @Test @@ -811,7 +888,9 @@ public void validMakeApplicationPublic() { Application application = new Application(); application.setName("validMakeApplicationPublic-Test"); - Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -825,15 +904,18 @@ public void validMakeApplicationPublic() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(true); @@ -842,18 +924,16 @@ public void validMakeApplicationPublic() { .changeViewAccess(createdApplication.getId(), applicationAccessDTO) .cache(); - Mono<PageDTO> pageMono = publicAppMono - .flatMap(app -> { - String pageId = app.getPages().get(0).getId(); - return newPageService.findPageById(pageId, READ_PAGES, false); - }); + Mono<PageDTO> pageMono = publicAppMono.flatMap(app -> { + String pageId = app.getPages().get(0).getId(); + return newPageService.findPageById(pageId, READ_PAGES, false); + }); Mono<PermissionGroup> publicPermissionGroupMono = permissionGroupService.getPublicPermissionGroup(); User anonymousUser = userRepository.findByEmail(ANONYMOUS_USER).block(); - StepVerifier - .create(Mono.zip(publicAppMono, pageMono, publicPermissionGroupMono)) + StepVerifier.create(Mono.zip(publicAppMono, pageMono, publicPermissionGroupMono)) .assertNext(tuple -> { Application publicApp = tuple.getT1(); PageDTO page = tuple.getT2(); @@ -863,20 +943,30 @@ public void validMakeApplicationPublic() { assertThat(publicApp.getIsPublic()).isTrue(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), permissionGroupId)) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + permissionGroupId)) .build(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), permissionGroupId)) + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + permissionGroupId)) .build(); assertThat(publicApp.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); @@ -897,7 +987,8 @@ public void validMakeApplicationPrivate() { Application application = new Application(); application.setName("validMakeApplicationPrivate-Test"); - List<PermissionGroup> permissionGroups = workspaceService.findById(workspaceId, READ_WORKSPACES) + List<PermissionGroup> permissionGroups = workspaceService + .findById(workspaceId, READ_WORKSPACES) .flatMapMany(savedWorkspace -> { Set<String> defaultPermissionGroups = savedWorkspace.getDefaultPermissionGroups(); return permissionGroupRepository.findAllById(defaultPermissionGroups); @@ -907,15 +998,18 @@ public void validMakeApplicationPrivate() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); Mono<Application> createApplication = applicationPageService.createApplication(application, workspaceId); @@ -931,31 +1025,37 @@ public void validMakeApplicationPrivate() { }) .cache(); - Mono<PageDTO> pageMono = privateAppMono - .flatMap(app -> { - String pageId = app.getPages().get(0).getId(); - return newPageService.findPageById(pageId, READ_PAGES, false); - }); + Mono<PageDTO> pageMono = privateAppMono.flatMap(app -> { + String pageId = app.getPages().get(0).getId(); + return newPageService.findPageById(pageId, READ_PAGES, false); + }); - StepVerifier - .create(Mono.zip(privateAppMono, pageMono)) + StepVerifier.create(Mono.zip(privateAppMono, pageMono)) .assertNext(tuple -> { Application app = tuple.getT1(); PageDTO page = tuple.getT2(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); @@ -985,15 +1085,18 @@ public void makeApplicationPublic_applicationWithGitMetadata_success() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(true); @@ -1006,25 +1109,24 @@ public void makeApplicationPublic_applicationWithGitMetadata_success() { gitApplicationMetadata.setDefaultApplicationId(gitConnectedApp.getId()); gitApplicationMetadata.setBranchName("test"); testApplication.setGitApplicationMetadata(gitApplicationMetadata); - Application application = applicationPageService.createApplication(testApplication).block(); + Application application = + applicationPageService.createApplication(testApplication).block(); Mono<Application> publicAppMono = applicationService .changeViewAccess(gitConnectedApp.getId(), "testBranch", applicationAccessDTO) .cache(); - Mono<PageDTO> pageMono = publicAppMono - .flatMap(app -> { - String pageId = app.getPages().get(0).getId(); - return newPageService.findPageById(pageId, READ_PAGES, false); - }); - + Mono<PageDTO> pageMono = publicAppMono.flatMap(app -> { + String pageId = app.getPages().get(0).getId(); + return newPageService.findPageById(pageId, READ_PAGES, false); + }); - Mono<PermissionGroup> publicPermissionGroupMono = permissionGroupService.getPublicPermissionGroup().cache(); + Mono<PermissionGroup> publicPermissionGroupMono = + permissionGroupService.getPublicPermissionGroup().cache(); User anonymousUser = userRepository.findByEmail(ANONYMOUS_USER).block(); - StepVerifier - .create(Mono.zip(publicAppMono, pageMono, publicPermissionGroupMono)) + StepVerifier.create(Mono.zip(publicAppMono, pageMono, publicPermissionGroupMono)) .assertNext(tuple -> { Application publicApp = tuple.getT1(); PageDTO page = tuple.getT2(); @@ -1034,20 +1136,30 @@ public void makeApplicationPublic_applicationWithGitMetadata_success() { assertThat(publicApp.getIsPublic()).isTrue(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), permissionGroupId)) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + permissionGroupId)) .build(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), permissionGroupId)) + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + permissionGroupId)) .build(); assertThat(publicApp.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); @@ -1062,19 +1174,24 @@ public void makeApplicationPublic_applicationWithGitMetadata_success() { .verifyComplete(); // Get branch application - Mono<Application> branchApplicationMono = applicationService.findById(application.getId()).cache(); + Mono<Application> branchApplicationMono = + applicationService.findById(application.getId()).cache(); - StepVerifier - .create(Mono.zip(branchApplicationMono, publicPermissionGroupMono)) + StepVerifier.create(Mono.zip(branchApplicationMono, publicPermissionGroupMono)) .assertNext(tuple -> { Application branchApplication = tuple.getT1(); String permissionGroupId = tuple.getT2().getId(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), permissionGroupId)) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + permissionGroupId)) .build(); assertThat(branchApplication.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); @@ -1098,30 +1215,37 @@ public void makeApplicationPrivate_applicationWithGitMetadata_success() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId())) + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); // Create a branch @@ -1132,29 +1256,27 @@ public void makeApplicationPrivate_applicationWithGitMetadata_success() { gitApplicationMetadata.setDefaultApplicationId(gitConnectedApp.getId()); gitApplicationMetadata.setBranchName("test2"); testApplication.setGitApplicationMetadata(gitApplicationMetadata); - Application application = applicationPageService.createApplication(testApplication).block(); - + Application application = + applicationPageService.createApplication(testApplication).block(); ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(true); Mono<Tuple2<Application, PageDTO>> privateAppAndPageTupleMono = // First make the git connected app public - applicationService.changeViewAccess(gitConnectedApp.getId(), "testBranch", applicationAccessDTO) + applicationService + .changeViewAccess(gitConnectedApp.getId(), "testBranch", applicationAccessDTO) .flatMap(application1 -> { applicationAccessDTO.setPublicAccess(false); // Then make the test branch private - return applicationService.changeViewAccess(application1.getId(), "testBranch", applicationAccessDTO); + return applicationService.changeViewAccess( + application1.getId(), "testBranch", applicationAccessDTO); }) .flatMap(app -> { String pageId = app.getPages().get(0).getId(); - return Mono.zip( - Mono.just(app), - newPageService.findPageById(pageId, READ_PAGES, false) - ); + return Mono.zip(Mono.just(app), newPageService.findPageById(pageId, READ_PAGES, false)); }); - StepVerifier - .create(privateAppAndPageTupleMono) + StepVerifier.create(privateAppAndPageTupleMono) .assertNext(tuple -> { Application app = tuple.getT1(); PageDTO page = tuple.getT2(); @@ -1169,8 +1291,7 @@ public void makeApplicationPrivate_applicationWithGitMetadata_success() { // Get branch application Mono<Application> branchApplicationMono = applicationService.findById(application.getId()); - StepVerifier - .create(branchApplicationMono) + StepVerifier.create(branchApplicationMono) .assertNext(branchApplication -> { assertThat(branchApplication.getIsPublic()).isFalse(); assertThat(branchApplication.getPolicies()).containsAll(Set.of(readAppPolicy, manageAppPolicy)); @@ -1194,20 +1315,25 @@ public void validMakeApplicationPublicWithActions() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); Application application = new Application(); application.setName("validMakeApplicationPublic-ExplicitDatasource-Test"); - Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); String pageId = createdApplication.getPages().get(0).getId(); @@ -1236,12 +1362,14 @@ public void validMakeApplicationPublicWithActions() { actionConfiguration.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration); - ActionDTO savedAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO savedAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(true); - Plugin installedJsPlugin = pluginRepository.findByPackageName("installed-js-plugin").block(); + Plugin installedJsPlugin = + pluginRepository.findByPackageName("installed-js-plugin").block(); assert installedJsPlugin != null; ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); @@ -1252,7 +1380,8 @@ public void validMakeApplicationPublicWithActions() { actionCollectionDTO.setPluginId(installedJsPlugin.getId()); actionCollectionDTO.setPluginType(PluginType.JS); - ActionCollectionDTO savedActionCollection = layoutCollectionService.createCollection(actionCollectionDTO).block(); + ActionCollectionDTO savedActionCollection = + layoutCollectionService.createCollection(actionCollectionDTO).block(); Mono<Application> publicAppMono = applicationService .changeViewAccess(createdApplication.getId(), applicationAccessDTO) @@ -1262,54 +1391,65 @@ public void validMakeApplicationPublicWithActions() { User anonymousUser = userRepository.findByEmail(ANONYMOUS_USER).block(); - Mono<Datasource> datasourceMono = publicAppMono - .then(datasourceService.findById(savedDatasource.getId())); + Mono<Datasource> datasourceMono = publicAppMono.then(datasourceService.findById(savedDatasource.getId())); - Mono<NewAction> actionMono = publicAppMono - .then(newActionService.findById(savedAction.getId())); + Mono<NewAction> actionMono = publicAppMono.then(newActionService.findById(savedAction.getId())); - final Mono<ActionCollection> actionCollectionMono = publicAppMono - .then(actionCollectionService.findById(savedActionCollection.getId(), READ_ACTIONS)); + final Mono<ActionCollection> actionCollectionMono = + publicAppMono.then(actionCollectionService.findById(savedActionCollection.getId(), READ_ACTIONS)); - StepVerifier - .create(Mono.zip(datasourceMono, actionMono, actionCollectionMono, publicPermissionGroupMono)) + StepVerifier.create(Mono.zip(datasourceMono, actionMono, actionCollectionMono, publicPermissionGroupMono)) .assertNext(tuple -> { Datasource datasource1 = tuple.getT1(); NewAction action1 = tuple.getT2(); PermissionGroup publicPermissionGroup = tuple.getT4(); final ActionCollection actionCollection1 = tuple.getT3(); - Policy manageDatasourcePolicy = Policy.builder().permission(MANAGE_DATASOURCES.getValue()) + Policy manageDatasourcePolicy = Policy.builder() + .permission(MANAGE_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readDatasourcePolicy = Policy.builder().permission(READ_DATASOURCES.getValue()) + Policy readDatasourcePolicy = Policy.builder() + .permission(READ_DATASOURCES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeDatasourcePolicy = Policy.builder().permission(EXECUTE_DATASOURCES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), publicPermissionGroup.getId())) + Policy executeDatasourcePolicy = Policy.builder() + .permission(EXECUTE_DATASOURCES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + publicPermissionGroup.getId())) .build(); - Policy manageActionPolicy = Policy.builder().permission(MANAGE_ACTIONS.getValue()) + Policy manageActionPolicy = Policy.builder() + .permission(MANAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readActionPolicy = Policy.builder().permission(READ_ACTIONS.getValue()) + Policy readActionPolicy = Policy.builder() + .permission(READ_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeActionPolicy = Policy.builder().permission(EXECUTE_ACTIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), publicPermissionGroup.getId())) + Policy executeActionPolicy = Policy.builder() + .permission(EXECUTE_ACTIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + publicPermissionGroup.getId())) .build(); // Check that the datasource used in the app contains public execute permission - assertThat(datasource1.getPolicies()).containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); + assertThat(datasource1.getPolicies()) + .containsAll(Set.of(manageDatasourcePolicy, readDatasourcePolicy, executeDatasourcePolicy)); // Check that the action used in the app contains public execute permission - assertThat(action1.getPolicies()).containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); + assertThat(action1.getPolicies()) + .containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); // Check that the action collection used in the app contains public execute permission - assertThat(actionCollection1.getPolicies()).containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); - + assertThat(actionCollection1.getPolicies()) + .containsAll(Set.of(manageActionPolicy, readActionPolicy, executeActionPolicy)); }) .verifyComplete(); } @@ -1319,7 +1459,8 @@ public void validMakeApplicationPublicWithActions() { public void cloneApplication_applicationWithGitMetadata_success() { final String branchName = gitConnectedApp.getGitApplicationMetadata().getBranchName(); - Mono<Application> clonedApplicationMono = applicationPageService.cloneApplication(gitConnectedApp.getId(), branchName) + Mono<Application> clonedApplicationMono = applicationPageService + .cloneApplication(gitConnectedApp.getId(), branchName) .cache(); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -1340,8 +1481,8 @@ public void cloneApplication_applicationWithGitMetadata_success() { .flatMap(applicationPage -> newPageService.findPageById(applicationPage.getId(), READ_PAGES, false)) .collectList(); - StepVerifier - .create(Mono.zip(clonedApplicationMono, clonedPageListMono, srcPageListMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip( + clonedApplicationMono, clonedPageListMono, srcPageListMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { Application clonedApplication = tuple.getT1(); // cloned application List<PageDTO> clonedPageList = tuple.getT2(); @@ -1350,29 +1491,42 @@ public void cloneApplication_applicationWithGitMetadata_success() { List<PermissionGroup> permissionGroups = tuple.getT4(); PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); assertThat(clonedApplication).isNotNull(); @@ -1384,19 +1538,27 @@ public void cloneApplication_applicationWithGitMetadata_success() { assertThat(clonedApplication.getModifiedBy()).isEqualTo("api_user"); assertThat(clonedApplication.getUpdatedAt()).isNotNull(); assertThat(clonedApplication.getEvaluationVersion()).isNotNull(); - assertThat(clonedApplication.getEvaluationVersion()).isEqualTo(gitConnectedApp.getEvaluationVersion()); + assertThat(clonedApplication.getEvaluationVersion()) + .isEqualTo(gitConnectedApp.getEvaluationVersion()); assertThat(clonedApplication.getApplicationVersion()).isNotNull(); - assertThat(clonedApplication.getApplicationVersion()).isEqualTo(gitConnectedApp.getApplicationVersion()); + assertThat(clonedApplication.getApplicationVersion()) + .isEqualTo(gitConnectedApp.getApplicationVersion()); List<ApplicationPage> pages = clonedApplication.getPages(); - Set<String> clonedPageIdsFromApplication = pages.stream().map(page -> page.getId()).collect(Collectors.toSet()); - Set<String> clonedPageIdsFromDb = clonedPageList.stream().map(page -> page.getId()).collect(Collectors.toSet()); + Set<String> clonedPageIdsFromApplication = + pages.stream().map(page -> page.getId()).collect(Collectors.toSet()); + Set<String> clonedPageIdsFromDb = + clonedPageList.stream().map(page -> page.getId()).collect(Collectors.toSet()); assertThat(clonedPageIdsFromApplication).containsAll(clonedPageIdsFromDb); - Set<String> srcPageIdsFromDb = srcPageList.stream().map(page -> page.getId()).collect(Collectors.toSet()); - Set<String> defaultSrcPageIdsFromDb = srcPageList.stream().map(page -> page.getDefaultResources().getPageId()).collect(Collectors.toSet()); - assertThat(Collections.disjoint(srcPageIdsFromDb, clonedPageIdsFromDb)).isTrue(); + Set<String> srcPageIdsFromDb = + srcPageList.stream().map(page -> page.getId()).collect(Collectors.toSet()); + Set<String> defaultSrcPageIdsFromDb = srcPageList.stream() + .map(page -> page.getDefaultResources().getPageId()) + .collect(Collectors.toSet()); + assertThat(Collections.disjoint(srcPageIdsFromDb, clonedPageIdsFromDb)) + .isTrue(); assertThat(clonedPageList).isNotEmpty(); for (PageDTO page : clonedPageList) { @@ -1414,34 +1576,35 @@ public void cloneApplication_applicationWithGitMetadata_success() { .collectList(); Mono<List<NewPage>> srcNewPageListMono = Flux.fromIterable(gitConnectedApp.getPages()) - .flatMap(applicationPage -> newPageService.findByBranchNameAndDefaultPageId(branchName, applicationPage.getDefaultPageId(), READ_PAGES)) + .flatMap(applicationPage -> newPageService.findByBranchNameAndDefaultPageId( + branchName, applicationPage.getDefaultPageId(), READ_PAGES)) .collectList(); - StepVerifier - .create(Mono.zip(clonedNewPageListMono, srcNewPageListMono)) + StepVerifier.create(Mono.zip(clonedNewPageListMono, srcNewPageListMono)) .assertNext(tuple -> { List<NewPage> clonedNewPageList = tuple.getT1(); List<NewPage> srcNewPageList = tuple.getT2(); List<String> clonedPageIdList = new ArrayList<>(); List<String> clonedDefaultPageIdList = new ArrayList<>(); - clonedNewPageList - .forEach(newPage -> { - clonedPageIdList.add(newPage.getId()); - clonedDefaultPageIdList.add(newPage.getDefaultResources().getPageId()); - assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(newPage.getApplicationId()); - assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); - }); + clonedNewPageList.forEach(newPage -> { + clonedPageIdList.add(newPage.getId()); + clonedDefaultPageIdList.add( + newPage.getDefaultResources().getPageId()); + assertThat(newPage.getDefaultResources().getApplicationId()) + .isEqualTo(newPage.getApplicationId()); + assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); + }); List<String> srcPageIdList = new ArrayList<>(); List<String> srcDefaultPageIdList = new ArrayList<>(); - srcNewPageList - .forEach(newPage -> { - srcPageIdList.add(newPage.getId()); - srcDefaultPageIdList.add(newPage.getDefaultResources().getPageId()); - assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(newPage.getApplicationId()); - assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); - }); + srcNewPageList.forEach(newPage -> { + srcPageIdList.add(newPage.getId()); + srcDefaultPageIdList.add(newPage.getDefaultResources().getPageId()); + assertThat(newPage.getDefaultResources().getApplicationId()) + .isEqualTo(newPage.getApplicationId()); + assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); + }); assertThat(clonedPageIdList).doesNotContainAnyElementsOf(srcPageIdList); assertThat(clonedDefaultPageIdList).doesNotContainAnyElementsOf(srcDefaultPageIdList); @@ -1460,8 +1623,7 @@ public void cloneApplication_applicationWithGitMetadata_success() { .map(newPage -> newPage.getUnpublishedPage().getName()) .collectList(); - StepVerifier - .create(Mono.zip(pageNameListMono, testPageNameListMono)) + StepVerifier.create(Mono.zip(pageNameListMono, testPageNameListMono)) .assertNext(tuple -> { List<String> pageNameList = tuple.getT1(); List<String> testPageNameList = tuple.getT2(); @@ -1496,21 +1658,24 @@ public void cloneApplication_applicationWithGitMetadataAndActions_success() { actionConfiguration.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration); - ActionDTO savedAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO savedAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); - Mono<Application> clonedApplicationMono = applicationPageService.cloneApplication(gitConnectedApp.getId(), branchName) + Mono<Application> clonedApplicationMono = applicationPageService + .cloneApplication(gitConnectedApp.getId(), branchName) .cache(); - Mono<List<NewAction>> clonedActionListMono = clonedApplicationMono - .flatMapMany(application -> newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null)) + .flatMapMany(application -> newActionService.findAllByApplicationIdAndViewMode( + application.getId(), false, READ_ACTIONS, null)) .collectList(); - Mono<List<NewAction>> srcActionListMono = newActionService.findAllByApplicationIdAndViewMode(gitConnectedApp.getId(), false, READ_ACTIONS, null) + Mono<List<NewAction>> srcActionListMono = newActionService + .findAllByApplicationIdAndViewMode(gitConnectedApp.getId(), false, READ_ACTIONS, null) .collectList(); - StepVerifier - .create(Mono.zip(clonedApplicationMono, clonedActionListMono, srcActionListMono, defaultPermissionGroupsMono)) + StepVerifier.create(Mono.zip( + clonedApplicationMono, clonedActionListMono, srcActionListMono, defaultPermissionGroupsMono)) .assertNext(tuple -> { Application clonedApplication = tuple.getT1(); // cloned application List<NewAction> clonedActionList = tuple.getT2(); @@ -1519,32 +1684,46 @@ public void cloneApplication_applicationWithGitMetadataAndActions_success() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageActionPolicy = Policy.builder().permission(MANAGE_ACTIONS.getValue()) + Policy manageActionPolicy = Policy.builder() + .permission(MANAGE_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readActionPolicy = Policy.builder().permission(READ_ACTIONS.getValue()) + Policy readActionPolicy = Policy.builder() + .permission(READ_ACTIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy executeActionPolicy = Policy.builder().permission(EXECUTE_ACTIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy executeActionPolicy = Policy.builder() + .permission(EXECUTE_ACTIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); assertThat(clonedApplication.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); @@ -1552,30 +1731,62 @@ public void cloneApplication_applicationWithGitMetadataAndActions_success() { assertThat(clonedApplication.getModifiedBy()).isEqualTo("api_user"); assertThat(clonedApplication.getUpdatedAt()).isNotNull(); - Set<String> clonedPageId = clonedApplication.getPages().stream().map(page -> page.getId()).collect(Collectors.toSet()); - Set<String> clonedActionIdsFromDb = clonedActionList.stream().map(action1 -> action1.getId()).collect(Collectors.toSet()); - Set<String> clonedPageIdsInActionFromDb = clonedActionList.stream().map(action1 -> action1.getUnpublishedAction().getPageId()).collect(Collectors.toSet()); - Set<String> defaultPageIdsInClonedActionFromDb = clonedActionList.stream().map(action1 -> action1.getUnpublishedAction().getDefaultResources().getPageId()).collect(Collectors.toSet()); - Set<String> defaultClonedActionIdsFromDb = clonedActionList.stream().map(newAction -> newAction.getDefaultResources().getActionId()).collect(Collectors.toSet()); - - Set<String> srcActionIdsFromDb = srcActionList.stream().map(action1 -> action1.getId()).collect(Collectors.toSet()); - Set<String> srcPageIdsInActionFromDb = srcActionList.stream().map(action1 -> action1.getUnpublishedAction().getPageId()).collect(Collectors.toSet()); - Set<String> defaultPageIdsInSrcActionFromDb = srcActionList.stream().map(action1 -> action1.getUnpublishedAction().getDefaultResources().getPageId()).collect(Collectors.toSet()); - Set<String> defaultSrcActionIdsFromDb = srcActionList.stream().map(newAction -> newAction.getDefaultResources().getActionId()).collect(Collectors.toSet()); - - assertThat(Collections.disjoint(clonedActionIdsFromDb, srcActionIdsFromDb)).isTrue(); + Set<String> clonedPageId = clonedApplication.getPages().stream() + .map(page -> page.getId()) + .collect(Collectors.toSet()); + Set<String> clonedActionIdsFromDb = clonedActionList.stream() + .map(action1 -> action1.getId()) + .collect(Collectors.toSet()); + Set<String> clonedPageIdsInActionFromDb = clonedActionList.stream() + .map(action1 -> action1.getUnpublishedAction().getPageId()) + .collect(Collectors.toSet()); + Set<String> defaultPageIdsInClonedActionFromDb = clonedActionList.stream() + .map(action1 -> action1.getUnpublishedAction() + .getDefaultResources() + .getPageId()) + .collect(Collectors.toSet()); + Set<String> defaultClonedActionIdsFromDb = clonedActionList.stream() + .map(newAction -> newAction.getDefaultResources().getActionId()) + .collect(Collectors.toSet()); + + Set<String> srcActionIdsFromDb = srcActionList.stream() + .map(action1 -> action1.getId()) + .collect(Collectors.toSet()); + Set<String> srcPageIdsInActionFromDb = srcActionList.stream() + .map(action1 -> action1.getUnpublishedAction().getPageId()) + .collect(Collectors.toSet()); + Set<String> defaultPageIdsInSrcActionFromDb = srcActionList.stream() + .map(action1 -> action1.getUnpublishedAction() + .getDefaultResources() + .getPageId()) + .collect(Collectors.toSet()); + Set<String> defaultSrcActionIdsFromDb = srcActionList.stream() + .map(newAction -> newAction.getDefaultResources().getActionId()) + .collect(Collectors.toSet()); + + assertThat(Collections.disjoint(clonedActionIdsFromDb, srcActionIdsFromDb)) + .isTrue(); assertThat(clonedPageId).containsAll(clonedPageIdsInActionFromDb); - assertThat(Collections.disjoint(defaultClonedActionIdsFromDb, defaultSrcActionIdsFromDb)).isTrue(); - assertThat(Collections.disjoint(clonedPageIdsInActionFromDb, srcPageIdsInActionFromDb)).isTrue(); - assertThat(Collections.disjoint(defaultPageIdsInClonedActionFromDb, defaultPageIdsInSrcActionFromDb)).isTrue(); + assertThat(Collections.disjoint(defaultClonedActionIdsFromDb, defaultSrcActionIdsFromDb)) + .isTrue(); + assertThat(Collections.disjoint(clonedPageIdsInActionFromDb, srcPageIdsInActionFromDb)) + .isTrue(); + assertThat(Collections.disjoint( + defaultPageIdsInClonedActionFromDb, defaultPageIdsInSrcActionFromDb)) + .isTrue(); assertThat(defaultPageIdsInClonedActionFromDb).isNotEmpty(); assertThat(clonedActionList).isNotEmpty(); assertThat(defaultClonedActionIdsFromDb).isNotEmpty(); for (NewAction newAction : clonedActionList) { - assertThat(newAction.getPolicies()).containsAll(Set.of(readActionPolicy, executeActionPolicy, manageActionPolicy)); + assertThat(newAction.getPolicies()) + .containsAll(Set.of(readActionPolicy, executeActionPolicy, manageActionPolicy)); assertThat(newAction.getApplicationId()).isEqualTo(clonedApplication.getId()); - assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(newAction.getUnpublishedAction().getDefaultResources().getPageId()); + assertThat(newAction.getUnpublishedAction().getPageId()) + .isEqualTo(newAction + .getUnpublishedAction() + .getDefaultResources() + .getPageId()); } }) .verifyComplete(); @@ -1587,7 +1798,8 @@ public void cloneApplication_withActionAndActionCollection_success() { Application testApplication = new Application(); testApplication.setName("ApplicationServiceTest Clone Source TestApp"); - Mono<Application> originalApplicationMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Application> originalApplicationMono = applicationPageService + .createApplication(testApplication, workspaceId) .cache(); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -1601,7 +1813,8 @@ public void cloneApplication_withActionAndActionCollection_success() { Map<String, List<String>> originalResourceIds = new HashMap<>(); Mono<Application> resultMono = originalApplicationMono - .zipWhen(application -> newPageService.findPageById(application.getPages().get(0).getId(), READ_PAGES, false)) + .zipWhen(application -> newPageService.findPageById( + application.getPages().get(0).getId(), READ_PAGES, false)) .flatMap(tuple -> { Application application = tuple.getT1(); PageDTO testPage = tuple.getT2(); @@ -1618,8 +1831,8 @@ public void cloneApplication_withActionAndActionCollection_success() { ObjectMapper objectMapper = new ObjectMapper(); JSONObject parentDsl = null; try { - parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + parentDsl = new JSONObject(objectMapper.readValue( + DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); } catch (JsonProcessingException e) { log.debug("Error while creating JSONObj from defaultPageLayout: ", e); } @@ -1652,42 +1865,39 @@ public void cloneApplication_withActionAndActionCollection_success() { actionCollectionDTO.setWorkspaceId(application.getWorkspaceId()); actionCollectionDTO.setPluginId(testPlugin.getId()); actionCollectionDTO.setVariables(List.of(new JSValue("test", "String", "test", true))); - actionCollectionDTO.setBody("export default {\n" + - "\tgetData: async () => {\n" + - "\t\tconst data = await cloneActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}\n" + - "\tanotherMethod: async () => {\n" + - "\t\tconst data = await cloneActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}\n" + - "}"); + actionCollectionDTO.setBody("export default {\n" + "\tgetData: async () => {\n" + + "\t\tconst data = await cloneActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}\n" + + "\tanotherMethod: async () => {\n" + + "\t\tconst data = await cloneActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}\n" + + "}"); ActionDTO action1 = new ActionDTO(); action1.setName("getData"); action1.setActionConfiguration(new ActionConfiguration()); - action1.getActionConfiguration().setBody( - "async () => {\n" + - "\t\tconst data = await cloneActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}"); + action1.getActionConfiguration() + .setBody("async () => {\n" + "\t\tconst data = await cloneActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}"); ActionDTO action2 = new ActionDTO(); action2.setName("anotherMethod"); action2.setActionConfiguration(new ActionConfiguration()); - action2.getActionConfiguration().setBody( - "async () => {\n" + - "\t\tconst data = await cloneActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}"); + action2.getActionConfiguration() + .setBody("async () => {\n" + "\t\tconst data = await cloneActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}"); actionCollectionDTO.setActions(List.of(action1, action2)); actionCollectionDTO.setPluginType(PluginType.JS); return Mono.zip( layoutCollectionService.createCollection(actionCollectionDTO), layoutActionService.createSingleAction(action, Boolean.FALSE), - layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout), - Mono.just(application) - ); + layoutActionService.updateLayout( + testPage.getId(), testPage.getApplicationId(), layout.getId(), layout), + Mono.just(application)); }) .flatMap(tuple -> { List<String> pageIds = new ArrayList<>(), collectionIds = new ArrayList<>(); @@ -1696,23 +1906,31 @@ public void cloneApplication_withActionAndActionCollection_success() { originalResourceIds.put("pageIds", pageIds); originalResourceIds.put("collectionIds", collectionIds); - return newActionService.findAllByApplicationIdAndViewMode(tuple.getT4().getId(), false, READ_ACTIONS, null) + return newActionService + .findAllByApplicationIdAndViewMode(tuple.getT4().getId(), false, READ_ACTIONS, null) .collectList() .flatMap(actionList -> { - List<String> actionIds = actionList.stream().map(BaseDomain::getId).collect(Collectors.toList()); + List<String> actionIds = actionList.stream() + .map(BaseDomain::getId) + .collect(Collectors.toList()); originalResourceIds.put("actionIds", actionIds); - return applicationPageService.cloneApplication(tuple.getT4().getId(), null); + return applicationPageService.cloneApplication( + tuple.getT4().getId(), null); }); }) .cache(); - StepVerifier.create(resultMono - .zipWhen(application -> Mono.zip( - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findNewPagesByApplicationId(application.getId(), READ_PAGES).collectList(), - defaultPermissionGroupsMono - ))) + StepVerifier.create(resultMono.zipWhen(application -> Mono.zip( + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findNewPagesByApplicationId(application.getId(), READ_PAGES) + .collectList(), + defaultPermissionGroupsMono))) .assertNext(tuple -> { Application application = tuple.getT1(); // cloned application List<NewAction> actionList = tuple.getT2().getT1(); @@ -1722,29 +1940,42 @@ public void cloneApplication_withActionAndActionCollection_success() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); assertThat(application).isNotNull(); @@ -1756,8 +1987,10 @@ public void cloneApplication_withActionAndActionCollection_success() { assertThat(application.getModifiedBy()).isEqualTo("api_user"); assertThat(application.getUpdatedAt()).isNotNull(); List<ApplicationPage> pages = application.getPages(); - Set<String> pageIdsFromApplication = pages.stream().map(page -> page.getId()).collect(Collectors.toSet()); - Set<String> pageIdsFromDb = pageList.stream().map(page -> page.getId()).collect(Collectors.toSet()); + Set<String> pageIdsFromApplication = + pages.stream().map(page -> page.getId()).collect(Collectors.toSet()); + Set<String> pageIdsFromDb = + pageList.stream().map(page -> page.getId()).collect(Collectors.toSet()); assertThat(pageIdsFromApplication).containsAll(pageIdsFromDb); @@ -1771,52 +2004,61 @@ public void cloneApplication_withActionAndActionCollection_success() { pageList.forEach(newPage -> { assertThat(newPage.getDefaultResources()).isNotNull(); assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); - assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); - - newPage.getUnpublishedPage() - .getLayouts() - .forEach(layout -> { - assertThat(layout.getLayoutOnLoadActions()).hasSize(2); - layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { - assertThat(dslActionDTOS).hasSize(1); - dslActionDTOS.forEach(actionDTO -> { - assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); - if (StringUtils.hasLength(actionDTO.getCollectionId())) { - assertThat(actionDTO.getDefaultCollectionId()).isEqualTo(actionDTO.getCollectionId()); - } - }); - }); + assertThat(newPage.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); + + newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + assertThat(layout.getLayoutOnLoadActions()).hasSize(2); + layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { + assertThat(dslActionDTOS).hasSize(1); + dslActionDTOS.forEach(actionDTO -> { + assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); + if (StringUtils.hasLength(actionDTO.getCollectionId())) { + assertThat(actionDTO.getDefaultCollectionId()) + .isEqualTo(actionDTO.getCollectionId()); + } }); + }); + }); }); assertThat(actionList).hasSize(3); actionList.forEach(newAction -> { assertThat(newAction.getDefaultResources()).isNotNull(); - assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + assertThat(newAction.getDefaultResources().getActionId()) + .isEqualTo(newAction.getId()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); ActionDTO action = newAction.getUnpublishedAction(); assertThat(action.getDefaultResources()).isNotNull(); - assertThat(action.getDefaultResources().getPageId()).isEqualTo(application.getPages().get(0).getId()); + assertThat(action.getDefaultResources().getPageId()) + .isEqualTo(application.getPages().get(0).getId()); if (!StringUtils.isEmpty(action.getDefaultResources().getCollectionId())) { - assertThat(action.getDefaultResources().getCollectionId()).isEqualTo(action.getCollectionId()); + assertThat(action.getDefaultResources().getCollectionId()) + .isEqualTo(action.getCollectionId()); } }); assertThat(actionCollectionList).hasSize(1); actionCollectionList.forEach(actionCollection -> { assertThat(actionCollection.getDefaultResources()).isNotNull(); - assertThat(actionCollection.getDefaultResources().getCollectionId()).isEqualTo(actionCollection.getId()); - assertThat(actionCollection.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + assertThat(actionCollection.getDefaultResources().getCollectionId()) + .isEqualTo(actionCollection.getId()); + assertThat(actionCollection.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); assertThat(unpublishedCollection.getDefaultToBranchedActionIdsMap()) .hasSize(2); - unpublishedCollection.getDefaultToBranchedActionIdsMap().keySet() - .forEach(key -> - assertThat(key).isEqualTo(unpublishedCollection.getDefaultToBranchedActionIdsMap().get(key)) - ); + unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .keySet() + .forEach(key -> assertThat(key) + .isEqualTo(unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .get(key))); assertThat(unpublishedCollection.getDefaultResources()).isNotNull(); assertThat(unpublishedCollection.getDefaultResources().getPageId()) @@ -1826,21 +2068,27 @@ public void cloneApplication_withActionAndActionCollection_success() { .verifyComplete(); // Check if the resources from original application are intact - StepVerifier - .create(originalApplicationMono - .zipWhen(application -> Mono.zip( - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findNewPagesByApplicationId(application.getId(), READ_PAGES).collectList() - ))) + StepVerifier.create(originalApplicationMono.zipWhen(application -> Mono.zip( + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findNewPagesByApplicationId(application.getId(), READ_PAGES) + .collectList()))) .assertNext(tuple -> { List<NewAction> actionList = tuple.getT2().getT1(); List<ActionCollection> actionCollectionList = tuple.getT2().getT2(); List<NewPage> pageList = tuple.getT2().getT3(); - List<String> pageIds = pageList.stream().map(BaseDomain::getId).collect(Collectors.toList()); - List<String> actionIds = actionList.stream().map(BaseDomain::getId).collect(Collectors.toList()); - List<String> collectionIds = actionCollectionList.stream().map(BaseDomain::getId).collect(Collectors.toList()); + List<String> pageIds = + pageList.stream().map(BaseDomain::getId).collect(Collectors.toList()); + List<String> actionIds = + actionList.stream().map(BaseDomain::getId).collect(Collectors.toList()); + List<String> collectionIds = + actionCollectionList.stream().map(BaseDomain::getId).collect(Collectors.toList()); assertThat(originalResourceIds.get("pageIds")).containsAll(pageIds); assertThat(originalResourceIds.get("actionIds")).containsAll(actionIds); @@ -1859,18 +2107,15 @@ public void cloneApplication_withActionAndActionCollection_success() { .flatMap(applicationPage -> newPageRepository.findById(applicationPage.getId())) .collectList(); - Mono<List<String>> pageIdListMono = pageListMono - .flatMapMany(Flux::fromIterable) - .map(PageDTO::getId) - .collectList(); + Mono<List<String>> pageIdListMono = + pageListMono.flatMapMany(Flux::fromIterable).map(PageDTO::getId).collectList(); Mono<List<String>> testPageIdListMono = testPageListMono .flatMapMany(Flux::fromIterable) .map(NewPage::getId) .collectList(); - StepVerifier - .create(Mono.zip(pageIdListMono, testPageIdListMono)) + StepVerifier.create(Mono.zip(pageIdListMono, testPageIdListMono)) .assertNext(tuple -> { List<String> pageIdList = tuple.getT1(); List<String> testPageIdList = tuple.getT2(); @@ -1891,8 +2136,7 @@ public void cloneApplication_withActionAndActionCollection_success() { .map(newPage -> newPage.getUnpublishedPage().getName()) .collectList(); - StepVerifier - .create(Mono.zip(pageNameListMono, testPageNameListMono)) + StepVerifier.create(Mono.zip(pageNameListMono, testPageNameListMono)) .assertNext(tuple -> { List<String> pageNameList = tuple.getT1(); List<String> testPageNameList = tuple.getT2(); @@ -1908,7 +2152,8 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs Application testApplication = new Application(); testApplication.setName("ApplicationServiceTest-clone-application-deleted-action-within-collection"); - Mono<Application> originalApplicationMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Application> originalApplicationMono = applicationPageService + .createApplication(testApplication, workspaceId) .cache(); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -1922,7 +2167,8 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs Map<String, List<String>> originalResourceIds = new HashMap<>(); Mono<Application> resultMono = originalApplicationMono - .zipWhen(application -> newPageService.findPageById(application.getPages().get(0).getId(), READ_PAGES, false)) + .zipWhen(application -> newPageService.findPageById( + application.getPages().get(0).getId(), READ_PAGES, false)) .flatMap(tuple -> { Application application = tuple.getT1(); PageDTO testPage = tuple.getT2(); @@ -1936,7 +2182,6 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs action.setActionConfiguration(actionConfiguration); action.setDatasource(testDatasource); - // Save actionCollection ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); actionCollectionDTO.setName("testCollection1"); @@ -1945,40 +2190,37 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs actionCollectionDTO.setWorkspaceId(application.getWorkspaceId()); actionCollectionDTO.setPluginId(testPlugin.getId()); actionCollectionDTO.setVariables(List.of(new JSValue("test", "String", "test", true))); - actionCollectionDTO.setBody("export default {\n" + - "\tgetData: async () => {\n" + - "\t\tconst data = await cloneActionTest.run();\n" + - "\t\treturn data;\n" + - "\t},\n" + - "\tanotherMethod: async () => {\n" + - "\t\tconst data = await cloneActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}\n" + - "}"); + actionCollectionDTO.setBody("export default {\n" + "\tgetData: async () => {\n" + + "\t\tconst data = await cloneActionTest.run();\n" + + "\t\treturn data;\n" + + "\t},\n" + + "\tanotherMethod: async () => {\n" + + "\t\tconst data = await cloneActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}\n" + + "}"); ActionDTO action1 = new ActionDTO(); action1.setName("getData"); action1.setActionConfiguration(new ActionConfiguration()); - action1.getActionConfiguration().setBody( - "async () => {\n" + - "\t\tconst data = await cloneActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}"); + action1.getActionConfiguration() + .setBody("async () => {\n" + "\t\tconst data = await cloneActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}"); ActionDTO action2 = new ActionDTO(); action2.setName("anotherMethod"); action2.setActionConfiguration(new ActionConfiguration()); - action2.getActionConfiguration().setBody( - "async () => {\n" + - "\t\tconst data = await cloneActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}"); + action2.getActionConfiguration() + .setBody("async () => {\n" + "\t\tconst data = await cloneActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}"); actionCollectionDTO.setActions(List.of(action1, action2)); actionCollectionDTO.setPluginType(PluginType.JS); ObjectMapper objectMapper = new ObjectMapper(); JSONObject parentDsl = null; try { - parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + parentDsl = new JSONObject(objectMapper.readValue( + DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); } catch (JsonProcessingException e) { log.debug("Error while creating JSONObj from defaultPageLayout: ", e); } @@ -2016,8 +2258,7 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs layoutActionService.createSingleAction(action, Boolean.FALSE), Mono.just(application), Mono.just(testPage), - Mono.just(layout) - ); + Mono.just(layout)); }) .flatMap(tuple -> { PageDTO testPage = tuple.getT4(); @@ -2025,7 +2266,8 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs return Mono.zip( Mono.just(tuple.getT1()), Mono.just(tuple.getT2()), - layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout), + layoutActionService.updateLayout( + testPage.getId(), testPage.getApplicationId(), layout.getId(), layout), Mono.just(tuple.getT3())); }) .flatMap(tuple -> { @@ -2037,28 +2279,38 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs originalResourceIds.put("pageIds", pageIds); originalResourceIds.put("collectionIds", collectionIds); - String deletedActionIdWithinActionCollection = String - .valueOf(collectionDTO.getDefaultToBranchedActionIdsMap().values().stream().findAny().orElse(null)); + String deletedActionIdWithinActionCollection = + String.valueOf(collectionDTO.getDefaultToBranchedActionIdsMap().values().stream() + .findAny() + .orElse(null)); - return newActionService.deleteUnpublishedAction(deletedActionIdWithinActionCollection) - .thenMany(newActionService.findAllByApplicationIdAndViewMode(tuple.getT4().getId(), false, READ_ACTIONS, null)) + return newActionService + .deleteUnpublishedAction(deletedActionIdWithinActionCollection) + .thenMany(newActionService.findAllByApplicationIdAndViewMode( + tuple.getT4().getId(), false, READ_ACTIONS, null)) .collectList() .flatMap(actionList -> { - List<String> actionIds = actionList.stream().map(BaseDomain::getId).collect(Collectors.toList()); + List<String> actionIds = actionList.stream() + .map(BaseDomain::getId) + .collect(Collectors.toList()); originalResourceIds.put("actionIds", actionIds); - return applicationPageService.cloneApplication(tuple.getT4().getId(), null); + return applicationPageService.cloneApplication( + tuple.getT4().getId(), null); }); }) .cache(); - - StepVerifier.create(resultMono - .zipWhen(application -> Mono.zip( - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findNewPagesByApplicationId(application.getId(), READ_PAGES).collectList(), - defaultPermissionGroupsMono - ))) + StepVerifier.create(resultMono.zipWhen(application -> Mono.zip( + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findNewPagesByApplicationId(application.getId(), READ_PAGES) + .collectList(), + defaultPermissionGroupsMono))) .assertNext(tuple -> { Application application = tuple.getT1(); // cloned application List<NewAction> actionList = tuple.getT2().getT1(); @@ -2068,42 +2320,59 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); - Policy managePagePolicy = Policy.builder().permission(MANAGE_PAGES.getValue()) + Policy managePagePolicy = Policy.builder() + .permission(MANAGE_PAGES.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readPagePolicy = Policy.builder().permission(READ_PAGES.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy readPagePolicy = Policy.builder() + .permission(READ_PAGES.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) .build(); assertThat(application).isNotNull(); assertThat(application.isAppIsExample()).isFalse(); assertThat(application.getId()).isNotNull(); - assertThat(application.getName()).isEqualTo("ApplicationServiceTest-clone-application-deleted-action-within-collection Copy"); + assertThat(application.getName()) + .isEqualTo( + "ApplicationServiceTest-clone-application-deleted-action-within-collection Copy"); assertThat(application.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); assertThat(application.getWorkspaceId()).isEqualTo(workspaceId); assertThat(application.getModifiedBy()).isEqualTo("api_user"); assertThat(application.getUpdatedAt()).isNotNull(); List<ApplicationPage> pages = application.getPages(); - Set<String> pageIdsFromApplication = pages.stream().map(ApplicationPage::getId).collect(Collectors.toSet()); - Set<String> pageIdsFromDb = pageList.stream().map(BaseDomain::getId).collect(Collectors.toSet()); + Set<String> pageIdsFromApplication = + pages.stream().map(ApplicationPage::getId).collect(Collectors.toSet()); + Set<String> pageIdsFromDb = + pageList.stream().map(BaseDomain::getId).collect(Collectors.toSet()); assertThat(pageIdsFromApplication).containsAll(pageIdsFromDb); @@ -2117,52 +2386,62 @@ public void cloneApplication_withDeletedActionInActionCollection_deletedActionIs pageList.forEach(newPage -> { assertThat(newPage.getDefaultResources()).isNotNull(); assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); - assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); - - newPage.getUnpublishedPage() - .getLayouts() - .forEach(layout -> { - assertThat(layout.getLayoutOnLoadActions()).hasSize(2); - layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { - assertThat(dslActionDTOS).hasSize(1); - dslActionDTOS.forEach(actionDTO -> { - assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); - if (StringUtils.hasLength(actionDTO.getCollectionId())) { - assertThat(actionDTO.getDefaultCollectionId()).isEqualTo(actionDTO.getCollectionId()); - } - }); - }); + assertThat(newPage.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); + + newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + assertThat(layout.getLayoutOnLoadActions()).hasSize(2); + layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { + assertThat(dslActionDTOS).hasSize(1); + dslActionDTOS.forEach(actionDTO -> { + assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); + if (StringUtils.hasLength(actionDTO.getCollectionId())) { + assertThat(actionDTO.getDefaultCollectionId()) + .isEqualTo(actionDTO.getCollectionId()); + } }); + }); + }); }); assertThat(actionList).hasSize(2); actionList.forEach(newAction -> { assertThat(newAction.getDefaultResources()).isNotNull(); - assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + assertThat(newAction.getDefaultResources().getActionId()) + .isEqualTo(newAction.getId()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); ActionDTO action = newAction.getUnpublishedAction(); assertThat(action.getDefaultResources()).isNotNull(); - assertThat(action.getDefaultResources().getPageId()).isEqualTo(application.getPages().get(0).getId()); + assertThat(action.getDefaultResources().getPageId()) + .isEqualTo(application.getPages().get(0).getId()); if (!StringUtils.isEmpty(action.getDefaultResources().getCollectionId())) { - assertThat(action.getDefaultResources().getCollectionId()).isEqualTo(action.getCollectionId()); + assertThat(action.getDefaultResources().getCollectionId()) + .isEqualTo(action.getCollectionId()); } }); assertThat(actionCollectionList).hasSize(1); actionCollectionList.forEach(actionCollection -> { assertThat(actionCollection.getDefaultResources()).isNotNull(); - assertThat(actionCollection.getDefaultResources().getCollectionId()).isEqualTo(actionCollection.getId()); - assertThat(actionCollection.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + assertThat(actionCollection.getDefaultResources().getCollectionId()) + .isEqualTo(actionCollection.getId()); + assertThat(actionCollection.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); // We should have single entry as other action is deleted from the parent application - assertThat(unpublishedCollection.getDefaultToBranchedActionIdsMap()).hasSize(1); - unpublishedCollection.getDefaultToBranchedActionIdsMap().keySet() - .forEach(key -> - assertThat(key).isEqualTo(unpublishedCollection.getDefaultToBranchedActionIdsMap().get(key)) - ); + assertThat(unpublishedCollection.getDefaultToBranchedActionIdsMap()) + .hasSize(1); + unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .keySet() + .forEach(key -> assertThat(key) + .isEqualTo(unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .get(key))); assertThat(unpublishedCollection.getDefaultResources()).isNotNull(); assertThat(unpublishedCollection.getDefaultResources().getPageId()) @@ -2178,7 +2457,8 @@ public void cloneGitConnectedApplication_withUpdatedDefaultBranch_sucess() { Application application = new Application(); application.setName("cloneGitConnectedApplication_withUpdatedDefaultBranch_sucess"); application.setWorkspaceId(workspaceId); - Application defaultApp = applicationPageService.createApplication(application) + Application defaultApp = applicationPageService + .createApplication(application) .flatMap(application1 -> { GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); gitApplicationMetadata.setDefaultApplicationId(application1.getId()); @@ -2192,13 +2472,15 @@ public void cloneGitConnectedApplication_withUpdatedDefaultBranch_sucess() { gitApplicationMetadata.setGitAuth(gitAuth); application1.setGitApplicationMetadata(gitApplicationMetadata); return applicationService.save(application1); - }).block(); + }) + .block(); // Add a branch to the git connected app application = new Application(); application.setName("cloneGitConnectedApplication_withUpdatedDefaultBranch_sucess"); application.setWorkspaceId(workspaceId); - Mono<Application> forkedApp = applicationPageService.createApplication(application) + Mono<Application> forkedApp = applicationPageService + .createApplication(application) .flatMap(application1 -> { GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); gitApplicationMetadata.setDefaultApplicationId(application1.getId()); @@ -2217,13 +2499,12 @@ public void cloneGitConnectedApplication_withUpdatedDefaultBranch_sucess() { PageDTO pageDTO = new PageDTO(); pageDTO.setName("testDuplicatePage"); pageDTO.setApplicationId(application1.getId()); - return applicationPageService.createPage(pageDTO) - .then(Mono.just(application1)); + return applicationPageService.createPage(pageDTO).then(Mono.just(application1)); }) - .flatMap(application1 -> applicationPageService.cloneApplication(application1.getGitApplicationMetadata().getDefaultApplicationId(), null)); + .flatMap(application1 -> applicationPageService.cloneApplication( + application1.getGitApplicationMetadata().getDefaultApplicationId(), null)); - StepVerifier - .create(forkedApp) + StepVerifier.create(forkedApp) .assertNext(application1 -> { assertThat(application1.getPages().size()).isEqualTo(2); }) @@ -2238,11 +2519,14 @@ public void basicPublishApplicationTest() { testApplication.setName(appName); testApplication.setAppLayout(new Application.AppLayout(Application.AppLayout.Type.DESKTOP)); testApplication.setUnpublishedApplicationDetail(new ApplicationDetail()); - testApplication.getUnpublishedApplicationDetail().setAppPositioning(new Application.AppPositioning(Application.AppPositioning.Type.FIXED)); + testApplication + .getUnpublishedApplicationDetail() + .setAppPositioning(new Application.AppPositioning(Application.AppPositioning.Type.FIXED)); Application.NavigationSetting appNavigationSetting = new Application.NavigationSetting(); appNavigationSetting.setOrientation("top"); testApplication.getUnpublishedApplicationDetail().setNavigationSetting(appNavigationSetting); - Mono<Application> applicationMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Application> applicationMono = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> applicationPageService.publish(application.getId(), true)) .then(applicationService.findByName(appName, MANAGE_APPLICATIONS)) .cache(); @@ -2253,8 +2537,7 @@ public void basicPublishApplicationTest() { .flatMap(applicationPage -> newPageService.findById(applicationPage.getId(), READ_PAGES)) .collectList(); - StepVerifier - .create(Mono.zip(applicationMono, applicationPagesMono)) + StepVerifier.create(Mono.zip(applicationMono, applicationPagesMono)) .assertNext(tuple -> { Application application = tuple.getT1(); List<NewPage> pages = tuple.getT2(); @@ -2268,13 +2551,28 @@ public void basicPublishApplicationTest() { assertThat(pages).hasSize(1); NewPage newPage = pages.get(0); - assertThat(newPage.getUnpublishedPage().getName()).isEqualTo(newPage.getPublishedPage().getName()); - assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getId()).isEqualTo(newPage.getPublishedPage().getLayouts().get(0).getId()); - assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isEqualTo(newPage.getPublishedPage().getLayouts().get(0).getDsl()); + assertThat(newPage.getUnpublishedPage().getName()) + .isEqualTo(newPage.getPublishedPage().getName()); + assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getId()) + .isEqualTo(newPage.getPublishedPage() + .getLayouts() + .get(0) + .getId()); + assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getDsl()) + .isEqualTo(newPage.getPublishedPage() + .getLayouts() + .get(0) + .getDsl()); assertThat(application.getPublishedAppLayout()).isEqualTo(application.getUnpublishedAppLayout()); - assertThat(application.getPublishedApplicationDetail().getAppPositioning()).isEqualTo(application.getUnpublishedApplicationDetail().getAppPositioning()); - assertThat(application.getPublishedApplicationDetail().getNavigationSetting()).isEqualTo(application.getUnpublishedApplicationDetail().getNavigationSetting()); + assertThat(application.getPublishedApplicationDetail().getAppPositioning()) + .isEqualTo(application + .getUnpublishedApplicationDetail() + .getAppPositioning()); + assertThat(application.getPublishedApplicationDetail().getNavigationSetting()) + .isEqualTo(application + .getUnpublishedApplicationDetail() + .getNavigationSetting()); }) .verifyComplete(); } @@ -2299,11 +2597,14 @@ public void publishApplication_withArchivedUnpublishedResources_resourcesArchive testApplication.setName(appName); testApplication.setAppLayout(new Application.AppLayout(Application.AppLayout.Type.DESKTOP)); testApplication.setUnpublishedApplicationDetail(new ApplicationDetail()); - testApplication.getUnpublishedApplicationDetail().setAppPositioning(new Application.AppPositioning(Application.AppPositioning.Type.FIXED)); + testApplication + .getUnpublishedApplicationDetail() + .setAppPositioning(new Application.AppPositioning(Application.AppPositioning.Type.FIXED)); Application.NavigationSetting appNavigationSetting = new Application.NavigationSetting(); appNavigationSetting.setOrientation("top"); testApplication.getUnpublishedApplicationDetail().setNavigationSetting(appNavigationSetting); - Mono<Tuple3<NewAction, ActionCollection, NewPage>> resultMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Tuple3<NewAction, ActionCollection, NewPage>> resultMono = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { PageDTO page = new PageDTO(); page.setName("New Page"); @@ -2314,8 +2615,7 @@ public void publishApplication_withArchivedUnpublishedResources_resourcesArchive page.setLayouts(layouts); return Mono.zip( applicationPageService.createPage(page), - pluginRepository.findByPackageName("installed-plugin") - ); + pluginRepository.findByPackageName("installed-plugin")); }) .flatMap(tuple -> { final PageDTO page = tuple.getT1(); @@ -2349,34 +2649,34 @@ public void publishApplication_withArchivedUnpublishedResources_resourcesArchive actionCollectionDTO.setActions(List.of(action1)); actionCollectionDTO.setPluginType(PluginType.JS); - return layoutActionService.createSingleAction(action, Boolean.FALSE) + return layoutActionService + .createSingleAction(action, Boolean.FALSE) .zipWith(layoutCollectionService.createCollection(actionCollectionDTO)) .flatMap(tuple1 -> { ActionDTO savedAction = tuple1.getT1(); ActionCollectionDTO savedActionCollection = tuple1.getT2(); - return applicationPageService.publish(testApplication.getId(), true) + return applicationPageService + .publish(testApplication.getId(), true) .then(applicationPageService.deleteUnpublishedPage(page.getId())) .then(applicationPageService.publish(testApplication.getId(), true)) - .then( - Mono.zip( - (Mono<NewAction>) this.getArchivedResource(savedAction.getId(), NewAction.class), - (Mono<ActionCollection>) this.getArchivedResource(savedActionCollection.getId(), ActionCollection.class), - (Mono<NewPage>) this.getArchivedResource(page.getId(), NewPage.class) - )); + .then(Mono.zip( + (Mono<NewAction>) + this.getArchivedResource(savedAction.getId(), NewAction.class), + (Mono<ActionCollection>) this.getArchivedResource( + savedActionCollection.getId(), ActionCollection.class), + (Mono<NewPage>) this.getArchivedResource(page.getId(), NewPage.class))); }); }) .cache(); - Mono<NewAction> archivedActionFromActionCollectionMono = resultMono - .flatMap(tuple -> { - final Optional<String> actionId = tuple.getT2().getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values() - .stream() + Mono<NewAction> archivedActionFromActionCollectionMono = resultMono.flatMap(tuple -> { + final Optional<String> actionId = + tuple.getT2().getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values().stream() .findFirst(); - return (Mono<NewAction>) this.getArchivedResource(actionId.get(), NewAction.class); - }); + return (Mono<NewAction>) this.getArchivedResource(actionId.get(), NewAction.class); + }); - StepVerifier - .create(resultMono.zipWith(archivedActionFromActionCollectionMono)) + StepVerifier.create(resultMono.zipWith(archivedActionFromActionCollectionMono)) .assertNext(tuple -> { NewAction archivedAction = tuple.getT1().getT1(); ActionCollection archivedActionCollection = tuple.getT1().getT2(); @@ -2392,7 +2692,8 @@ public void publishApplication_withArchivedUnpublishedResources_resourcesArchive assertThat(archivedPage.getDeletedAt()).isNotNull(); assertThat(archivedPage.getDeleted()).isTrue(); - assertThat(archivedActionFromActionCollection.getDeletedAt()).isNotNull(); + assertThat(archivedActionFromActionCollection.getDeletedAt()) + .isNotNull(); assertThat(archivedActionFromActionCollection.getDeleted()).isTrue(); }) .verifyComplete(); @@ -2404,15 +2705,20 @@ public void publishApplication_withGitConnectedApp_success() { GitApplicationMetadata gitData = gitConnectedApp.getGitApplicationMetadata(); gitConnectedApp.setAppLayout(new Application.AppLayout(Application.AppLayout.Type.DESKTOP)); gitConnectedApp.setUnpublishedApplicationDetail(new ApplicationDetail()); - gitConnectedApp.getUnpublishedApplicationDetail().setAppPositioning(new Application.AppPositioning(Application.AppPositioning.Type.FIXED)); + gitConnectedApp + .getUnpublishedApplicationDetail() + .setAppPositioning(new Application.AppPositioning(Application.AppPositioning.Type.FIXED)); Application.NavigationSetting appNavigationSetting = new Application.NavigationSetting(); appNavigationSetting.setOrientation("top"); gitConnectedApp.getUnpublishedApplicationDetail().setNavigationSetting(appNavigationSetting); - Mono<Application> applicationMono = applicationService.update(gitConnectedApp.getId(), gitConnectedApp) - .flatMap(updatedApp -> applicationPageService.publish(updatedApp.getId(), gitData.getBranchName(), true)) - .flatMap(application -> applicationService.findByBranchNameAndDefaultApplicationId(gitData.getBranchName(), gitData.getDefaultApplicationId(), MANAGE_APPLICATIONS)) + Mono<Application> applicationMono = applicationService + .update(gitConnectedApp.getId(), gitConnectedApp) + .flatMap( + updatedApp -> applicationPageService.publish(updatedApp.getId(), gitData.getBranchName(), true)) + .flatMap(application -> applicationService.findByBranchNameAndDefaultApplicationId( + gitData.getBranchName(), gitData.getDefaultApplicationId(), MANAGE_APPLICATIONS)) .cache(); Mono<List<NewPage>> applicationPagesMono = applicationMono @@ -2421,8 +2727,7 @@ public void publishApplication_withGitConnectedApp_success() { .flatMap(applicationPage -> newPageService.findById(applicationPage.getId(), READ_PAGES)) .collectList(); - StepVerifier - .create(Mono.zip(applicationMono, applicationPagesMono)) + StepVerifier.create(Mono.zip(applicationMono, applicationPagesMono)) .assertNext(tuple -> { Application application = tuple.getT1(); List<NewPage> pages = tuple.getT2(); @@ -2433,14 +2738,29 @@ public void publishApplication_withGitConnectedApp_success() { assertThat(pages.size()).isEqualTo(1); NewPage newPage = pages.get(0); - assertThat(newPage.getUnpublishedPage().getName()).isEqualTo(newPage.getPublishedPage().getName()); - assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getId()).isEqualTo(newPage.getPublishedPage().getLayouts().get(0).getId()); - assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isEqualTo(newPage.getPublishedPage().getLayouts().get(0).getDsl()); + assertThat(newPage.getUnpublishedPage().getName()) + .isEqualTo(newPage.getPublishedPage().getName()); + assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getId()) + .isEqualTo(newPage.getPublishedPage() + .getLayouts() + .get(0) + .getId()); + assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getDsl()) + .isEqualTo(newPage.getPublishedPage() + .getLayouts() + .get(0) + .getDsl()); assertThat(newPage.getDefaultResources()).isNotNull(); assertThat(application.getPublishedAppLayout()).isEqualTo(application.getUnpublishedAppLayout()); - assertThat(application.getPublishedApplicationDetail().getAppPositioning()).isEqualTo(application.getUnpublishedApplicationDetail().getAppPositioning()); - assertThat(application.getPublishedApplicationDetail().getNavigationSetting()).isEqualTo(application.getUnpublishedApplicationDetail().getNavigationSetting()); + assertThat(application.getPublishedApplicationDetail().getAppPositioning()) + .isEqualTo(application + .getUnpublishedApplicationDetail() + .getAppPositioning()); + assertThat(application.getPublishedApplicationDetail().getNavigationSetting()) + .isEqualTo(application + .getUnpublishedApplicationDetail() + .getNavigationSetting()); }) .verifyComplete(); } @@ -2451,7 +2771,9 @@ public void publishApplication_withPageIconSet_success() { Application testApplication = new Application(); String appName = "ApplicationServiceTest Publish Application Page Icon"; testApplication.setName(appName); - testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + testApplication = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); PageDTO page = new PageDTO(); page.setName("Page2"); @@ -2468,8 +2790,7 @@ public void publishApplication_withPageIconSet_success() { .collectList(); PageDTO finalPage = page; - StepVerifier - .create(Mono.zip(applicationMono, applicationPagesMono)) + StepVerifier.create(Mono.zip(applicationMono, applicationPagesMono)) .assertNext(tuple -> { Application application = tuple.getT1(); List<NewPage> pages = tuple.getT2(); @@ -2481,13 +2802,17 @@ public void publishApplication_withPageIconSet_success() { assertThat(application.getPublishedPages()).hasSize(2); assertThat(pages).hasSize(2); - Optional<NewPage> optionalNewPage = pages.stream().filter(thisPage -> finalPage.getId().equals(thisPage.getId())).findFirst(); + Optional<NewPage> optionalNewPage = pages.stream() + .filter(thisPage -> finalPage.getId().equals(thisPage.getId())) + .findFirst(); assertThat(optionalNewPage.isPresent()).isTrue(); NewPage newPage = optionalNewPage.get(); assertThat(newPage.getUnpublishedPage().getName()).isEqualTo("Page2"); - assertThat(newPage.getUnpublishedPage().getName()).isEqualTo(newPage.getPublishedPage().getName()); + assertThat(newPage.getUnpublishedPage().getName()) + .isEqualTo(newPage.getPublishedPage().getName()); assertThat(newPage.getUnpublishedPage().getIcon()).isEqualTo("flight"); - assertThat(newPage.getUnpublishedPage().getIcon()).isEqualTo(newPage.getPublishedPage().getIcon()); + assertThat(newPage.getUnpublishedPage().getIcon()) + .isEqualTo(newPage.getPublishedPage().getIcon()); }) .verifyComplete(); } @@ -2498,7 +2823,8 @@ public void deleteUnpublishedPageFromApplication() { Application testApplication = new Application(); String appName = "ApplicationServiceTest Publish Application Delete Page"; testApplication.setName(appName); - Mono<Application> applicationMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Application> applicationMono = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { PageDTO page = new PageDTO(); page.setName("New Page"); @@ -2517,17 +2843,16 @@ public void deleteUnpublishedPageFromApplication() { .flatMap(application -> newPageService .findByNameAndApplicationIdAndViewMode("New Page", application.getId(), READ_PAGES, false) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "page"))) - .flatMap(page -> applicationPageService.deleteUnpublishedPage(page.getId()))).block(); + .flatMap(page -> applicationPageService.deleteUnpublishedPage(page.getId()))) + .block(); ApplicationPage applicationPage = new ApplicationPage(); applicationPage.setId(newPage.getId()); applicationPage.setIsDefault(false); applicationPage.setDefaultPageId(newPage.getId()); - StepVerifier - .create(applicationService.findById(newPage.getApplicationId(), MANAGE_APPLICATIONS)) + StepVerifier.create(applicationService.findById(newPage.getApplicationId(), MANAGE_APPLICATIONS)) .assertNext(editedApplication -> { - List<ApplicationPage> publishedPages = editedApplication.getPublishedPages(); assertThat(publishedPages).size().isEqualTo(2); assertThat(publishedPages).containsAnyOf(applicationPage); @@ -2552,25 +2877,26 @@ public void deleteUnpublishedPage_FromApplicationConnectedToGit_success() { layouts.add(defaultLayout); page.setLayouts(layouts); - Mono<Application> applicationMono = applicationPageService.createPageWithBranchName(page, branchName) + Mono<Application> applicationMono = applicationPageService + .createPageWithBranchName(page, branchName) .flatMap(pageDTO -> applicationPageService.publish(pageDTO.getApplicationId(), branchName, true)) .cache(); PageDTO newPage = applicationMono .flatMap(application -> newPageService - .findByNameAndApplicationIdAndViewMode("Test delete unPublish page test", application.getId(), READ_PAGES, false) + .findByNameAndApplicationIdAndViewMode( + "Test delete unPublish page test", application.getId(), READ_PAGES, false) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "page"))) - .flatMap(pageDTO -> applicationPageService.deleteUnpublishedPage(pageDTO.getId()))).block(); + .flatMap(pageDTO -> applicationPageService.deleteUnpublishedPage(pageDTO.getId()))) + .block(); ApplicationPage applicationPage = new ApplicationPage(); applicationPage.setId(newPage.getId()); applicationPage.setIsDefault(false); applicationPage.setDefaultPageId(newPage.getId()); - StepVerifier - .create(applicationService.findById(newPage.getApplicationId(), MANAGE_APPLICATIONS)) + StepVerifier.create(applicationService.findById(newPage.getApplicationId(), MANAGE_APPLICATIONS)) .assertNext(editedApplication -> { - List<ApplicationPage> publishedPages = editedApplication.getPublishedPages(); assertThat(publishedPages).size().isEqualTo(2); assertThat(publishedPages).containsAnyOf(applicationPage); @@ -2588,7 +2914,8 @@ public void changeDefaultPageForAPublishedApplication() { Application testApplication = new Application(); String appName = "ApplicationServiceTest Publish Application Change Default Page"; testApplication.setName(appName); - Mono<Application> applicationMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Application> applicationMono = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { PageDTO page = new PageDTO(); page.setName("New Page"); @@ -2606,10 +2933,12 @@ public void changeDefaultPageForAPublishedApplication() { PageDTO newPage = applicationMono .flatMap(application -> newPageService .findByNameAndApplicationIdAndViewMode("New Page", application.getId(), READ_PAGES, false) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "unpublishedEditedPage")))).block(); + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "unpublishedEditedPage")))) + .block(); - Mono<Application> updatedDefaultPageApplicationMono = applicationMono - .flatMap(application -> applicationPageService.makePageDefault(application.getId(), newPage.getId())); + Mono<Application> updatedDefaultPageApplicationMono = applicationMono.flatMap( + application -> applicationPageService.makePageDefault(application.getId(), newPage.getId())); ApplicationPage publishedEditedPage = new ApplicationPage(); publishedEditedPage.setId(newPage.getId()); @@ -2619,15 +2948,14 @@ public void changeDefaultPageForAPublishedApplication() { unpublishedEditedPage.setId(newPage.getId()); unpublishedEditedPage.setIsDefault(true); - StepVerifier - .create(updatedDefaultPageApplicationMono) + StepVerifier.create(updatedDefaultPageApplicationMono) .assertNext(editedApplication -> { - List<ApplicationPage> publishedPages = editedApplication.getPublishedPages(); assertThat(publishedPages).size().isEqualTo(2); boolean isFound = false; for (ApplicationPage page : publishedPages) { - if (page.getId().equals(publishedEditedPage.getId()) && page.getIsDefault().equals(publishedEditedPage.getIsDefault())) { + if (page.getId().equals(publishedEditedPage.getId()) + && page.getIsDefault().equals(publishedEditedPage.getIsDefault())) { isFound = true; break; } @@ -2638,7 +2966,8 @@ public void changeDefaultPageForAPublishedApplication() { assertThat(editedApplicationPages.size()).isEqualTo(2); isFound = false; for (ApplicationPage page : editedApplicationPages) { - if (page.getId().equals(unpublishedEditedPage.getId()) && page.getIsDefault().equals(unpublishedEditedPage.getIsDefault())) { + if (page.getId().equals(unpublishedEditedPage.getId()) + && page.getIsDefault().equals(unpublishedEditedPage.getIsDefault())) { isFound = true; break; } @@ -2654,11 +2983,13 @@ public void getApplicationInViewMode() { Application testApplication = new Application(); String appName = "ApplicationServiceTest Get Application In View Mode"; testApplication.setName(appName); - Mono<Application> applicationMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Application> applicationMono = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { - CustomJSLib jsLib = new CustomJSLib("name1", Set.of("accessor"), "url", "docsUrl", "version", - "defs"); - return customJSLibService.addJSLibToApplication(application.getId(), jsLib, null, false) + CustomJSLib jsLib = + new CustomJSLib("name1", Set.of("accessor"), "url", "docsUrl", "version", "defs"); + return customJSLibService + .addJSLibToApplication(application.getId(), jsLib, null, false) .then(applicationService.getById(application.getId())); }) .flatMap(application -> { @@ -2679,23 +3010,24 @@ public void getApplicationInViewMode() { .flatMap(application -> newPageService .findByNameAndApplicationIdAndViewMode("New Page", application.getId(), READ_PAGES, false) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "page"))) - .flatMap(page -> applicationPageService.deleteUnpublishedPage(page.getId()))).block(); + .flatMap(page -> applicationPageService.deleteUnpublishedPage(page.getId()))) + .block(); - Mono<Application> viewModeApplicationMono = applicationMono - .flatMap(application -> applicationService.getApplicationInViewMode(application.getId())); + Mono<Application> viewModeApplicationMono = applicationMono.flatMap( + application -> applicationService.getApplicationInViewMode(application.getId())); ApplicationPage applicationPage = new ApplicationPage(); applicationPage.setId(newPage.getId()); applicationPage.setIsDefault(false); - StepVerifier - .create(viewModeApplicationMono) + StepVerifier.create(viewModeApplicationMono) .assertNext(viewApplication -> { List<ApplicationPage> editedApplicationPages = viewApplication.getPages(); assertThat(editedApplicationPages.size()).isEqualTo(2); boolean isFound = false; for (ApplicationPage page : editedApplicationPages) { - if (page.getId().equals(applicationPage.getId()) && page.getIsDefault().equals(applicationPage.getIsDefault())) { + if (page.getId().equals(applicationPage.getId()) + && page.getIsDefault().equals(applicationPage.getIsDefault())) { isFound = true; break; } @@ -2703,9 +3035,11 @@ public void getApplicationInViewMode() { assertThat(isFound).isTrue(); assertEquals(1, viewApplication.getPublishedCustomJSLibs().size()); - CustomJSLib jsLib = new CustomJSLib("name1", Set.of("accessor"), "url", "docsUrl", "version", - "defs"); - assertEquals(getDTOFromCustomJSLib(jsLib), viewApplication.getPublishedCustomJSLibs().toArray()[0]); + CustomJSLib jsLib = + new CustomJSLib("name1", Set.of("accessor"), "url", "docsUrl", "version", "defs"); + assertEquals( + getDTOFromCustomJSLib(jsLib), + viewApplication.getPublishedCustomJSLibs().toArray()[0]); }) .verifyComplete(); } @@ -2720,7 +3054,8 @@ public void validCloneApplicationWhenCancelledMidWay() { String appName = "ApplicationServiceTest Clone Application Midway Cancellation"; testApplication.setName(appName); - Application originalApplication = applicationPageService.createApplication(testApplication, workspaceId) + Application originalApplication = applicationPageService + .createApplication(testApplication, workspaceId) .block(); String pageId = originalApplication.getPages().get(0).getId(); @@ -2750,7 +3085,8 @@ public void validCloneApplicationWhenCancelledMidWay() { actionConfiguration.setHttpMethod(HttpMethod.GET); action1.setActionConfiguration(actionConfiguration); - ActionDTO savedAction1 = layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); + ActionDTO savedAction1 = + layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); ActionDTO action2 = new ActionDTO(); action2.setName("Clone App Test action2"); @@ -2758,7 +3094,8 @@ public void validCloneApplicationWhenCancelledMidWay() { action2.setDatasource(savedDatasource); action2.setActionConfiguration(actionConfiguration); - ActionDTO savedAction2 = layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); + ActionDTO savedAction2 = + layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); ActionDTO action3 = new ActionDTO(); action3.setName("Clone App Test action3"); @@ -2766,7 +3103,8 @@ public void validCloneApplicationWhenCancelledMidWay() { action3.setDatasource(savedDatasource); action3.setActionConfiguration(actionConfiguration); - ActionDTO savedAction3 = layoutActionService.createSingleAction(action3, Boolean.FALSE).block(); + ActionDTO savedAction3 = + layoutActionService.createSingleAction(action3, Boolean.FALSE).block(); // Testing JS Objects here ActionCollectionDTO actionCollectionDTO1 = new ActionCollectionDTO(); @@ -2782,10 +3120,12 @@ public void validCloneApplicationWhenCancelledMidWay() { actionCollectionDTO1.setActions(List.of(jsAction)); actionCollectionDTO1.setPluginType(PluginType.JS); - final ActionCollectionDTO createdActionCollectionDTO1 = layoutCollectionService.createCollection(actionCollectionDTO1).block(); + final ActionCollectionDTO createdActionCollectionDTO1 = + layoutCollectionService.createCollection(actionCollectionDTO1).block(); // Trigger the clone of application now. - applicationPageService.cloneApplication(originalApplication.getId(), null) + applicationPageService + .cloneApplication(originalApplication.getId(), null) .timeout(Duration.ofMillis(50)) .subscribe(); @@ -2793,21 +3133,22 @@ public void validCloneApplicationWhenCancelledMidWay() { Mono<Application> clonedAppFromDbMono = Mono.just(originalApplication) .flatMap(originalApp -> { try { - // Before fetching the cloned application, sleep for 5 seconds to ensure that the cloning finishes + // Before fetching the cloned application, sleep for 5 seconds to ensure that the cloning + // finishes Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } - return applicationRepository.findByClonedFromApplicationId(originalApp.getId()).next(); + return applicationRepository + .findByClonedFromApplicationId(originalApp.getId()) + .next(); }) .cache(); // Find all actions in new app - Mono<List<NewAction>> actionsMono = clonedAppFromDbMono - .flatMap(clonedAppFromDb -> newActionService - .findAllByApplicationIdAndViewMode(clonedAppFromDb.getId(), false, READ_ACTIONS, null) - .collectList() - ); + Mono<List<NewAction>> actionsMono = clonedAppFromDbMono.flatMap(clonedAppFromDb -> newActionService + .findAllByApplicationIdAndViewMode(clonedAppFromDb.getId(), false, READ_ACTIONS, null) + .collectList()); // Find all pages in new app Mono<List<PageDTO>> pagesMono = clonedAppFromDbMono @@ -2816,14 +3157,12 @@ public void validCloneApplicationWhenCancelledMidWay() { .collectList(); // Find all action collections in new app - final Mono<List<ActionCollection>> actionCollectionsMono = clonedAppFromDbMono - .flatMap(clonedAppFromDb -> actionCollectionService + final Mono<List<ActionCollection>> actionCollectionsMono = + clonedAppFromDbMono.flatMap(clonedAppFromDb -> actionCollectionService .findAllByApplicationIdAndViewMode(clonedAppFromDb.getId(), false, READ_ACTIONS, null) - .collectList() - ); + .collectList()); - StepVerifier - .create(Mono.zip(clonedAppFromDbMono, actionsMono, pagesMono, actionCollectionsMono)) + StepVerifier.create(Mono.zip(clonedAppFromDbMono, actionsMono, pagesMono, actionCollectionsMono)) .assertNext(tuple -> { Application cloneApp = tuple.getT1(); List<NewAction> actions = tuple.getT2(); @@ -2833,14 +3172,23 @@ public void validCloneApplicationWhenCancelledMidWay() { assertThat(cloneApp).isNotNull(); assertThat(pages.get(0).getId()).isNotEqualTo(pageId); assertThat(actions.size()).isEqualTo(4); - Set<String> actionNames = actions.stream().map(action -> action.getUnpublishedAction().getName()).collect(Collectors.toSet()); - assertThat(actionNames).containsExactlyInAnyOrder("Clone App Test action1", "Clone App Test action2", "Clone App Test action3", "jsFunc"); + Set<String> actionNames = actions.stream() + .map(action -> action.getUnpublishedAction().getName()) + .collect(Collectors.toSet()); + assertThat(actionNames) + .containsExactlyInAnyOrder( + "Clone App Test action1", + "Clone App Test action2", + "Clone App Test action3", + "jsFunc"); assertThat(actionCollections.size()).isEqualTo(1); - Set<String> actionCollectionNames = actionCollections.stream().map(actionCollection -> actionCollection.getUnpublishedCollection().getName()).collect(Collectors.toSet()); + Set<String> actionCollectionNames = actionCollections.stream() + .map(actionCollection -> + actionCollection.getUnpublishedCollection().getName()) + .collect(Collectors.toSet()); assertThat(actionCollectionNames).containsExactlyInAnyOrder("testCollection1"); }) .verifyComplete(); - } @Test @@ -2848,16 +3196,16 @@ public void validCloneApplicationWhenCancelledMidWay() { public void newApplicationShouldHavePublishedState() { Application testApplication = new Application(); testApplication.setName("ApplicationServiceTest NewApp PublishedState"); - Mono<Application> applicationMono = applicationPageService.createApplication(testApplication, workspaceId).cache(); + Mono<Application> applicationMono = applicationPageService + .createApplication(testApplication, workspaceId) + .cache(); - Mono<PageDTO> publishedPageMono = applicationMono - .flatMap(application -> { - List<ApplicationPage> publishedPages = application.getPublishedPages(); - return applicationPageService.getPage(publishedPages.get(0).getId(), true); - }); + Mono<PageDTO> publishedPageMono = applicationMono.flatMap(application -> { + List<ApplicationPage> publishedPages = application.getPublishedPages(); + return applicationPageService.getPage(publishedPages.get(0).getId(), true); + }); - StepVerifier - .create(Mono.zip(applicationMono, publishedPageMono)) + StepVerifier.create(Mono.zip(applicationMono, publishedPageMono)) .assertNext(tuple -> { Application application = tuple.getT1(); PageDTO publishedPage = tuple.getT2(); @@ -2866,7 +3214,8 @@ public void newApplicationShouldHavePublishedState() { assertThat(application.getPublishedPages()).hasSize(1); // Assert that the published page and the unpublished page are one and the same - assertThat(application.getPages().get(0).getId()).isEqualTo(application.getPublishedPages().get(0).getId()); + assertThat(application.getPages().get(0).getId()) + .isEqualTo(application.getPublishedPages().get(0).getId()); // Assert that the published page has 1 layout assertThat(publishedPage.getLayouts()).hasSize(1); @@ -2880,8 +3229,8 @@ public void validGetApplicationPagesMultiPageApp() { Application app = new Application(); app.setName("validGetApplicationPagesMultiPageApp-Test"); - Mono<Application> createApplicationMono = applicationPageService.createApplication(app, workspaceId) - .cache(); + Mono<Application> createApplicationMono = + applicationPageService.createApplication(app, workspaceId).cache(); // Create all the pages for this application in a blocking manner. createApplicationMono @@ -2890,16 +3239,14 @@ public void validGetApplicationPagesMultiPageApp() { testPage.setName("Page2"); testPage.setIcon("flight"); testPage.setApplicationId(application.getId()); - return applicationPageService.createPage(testPage) - .then(Mono.just(application)); + return applicationPageService.createPage(testPage).then(Mono.just(application)); }) .flatMap(application -> { PageDTO testPage = new PageDTO(); testPage.setName("Page3"); testPage.setIcon("bag"); testPage.setApplicationId(application.getId()); - return applicationPageService.createPage(testPage) - .then(Mono.just(application)); + return applicationPageService.createPage(testPage).then(Mono.just(application)); }) .flatMap(application -> { PageDTO testPage = new PageDTO(); @@ -2912,15 +3259,21 @@ public void validGetApplicationPagesMultiPageApp() { Mono<ApplicationPagesDTO> applicationPagesDTOMono = createApplicationMono .map(application -> application.getId()) - .flatMap(applicationId -> newPageService.findApplicationPagesByApplicationIdViewMode(applicationId, false, false)); + .flatMap(applicationId -> + newPageService.findApplicationPagesByApplicationIdViewMode(applicationId, false, false)); - StepVerifier - .create(applicationPagesDTOMono) + StepVerifier.create(applicationPagesDTOMono) .assertNext(applicationPagesDTO -> { assertThat(applicationPagesDTO.getPages().size()).isEqualTo(4); - List<String> pageNames = applicationPagesDTO.getPages().stream().map(pageNameIdDTO -> pageNameIdDTO.getName()).collect(Collectors.toList()); - List<String> slugNames = applicationPagesDTO.getPages().stream().map(pageNameIdDTO -> pageNameIdDTO.getSlug()).collect(Collectors.toList()); - List<String> pageIconNames = applicationPagesDTO.getPages().stream().map(pageNameIdDTO -> pageNameIdDTO.getIcon()).collect(Collectors.toList()); + List<String> pageNames = applicationPagesDTO.getPages().stream() + .map(pageNameIdDTO -> pageNameIdDTO.getName()) + .collect(Collectors.toList()); + List<String> slugNames = applicationPagesDTO.getPages().stream() + .map(pageNameIdDTO -> pageNameIdDTO.getSlug()) + .collect(Collectors.toList()); + List<String> pageIconNames = applicationPagesDTO.getPages().stream() + .map(pageNameIdDTO -> pageNameIdDTO.getIcon()) + .collect(Collectors.toList()); assertThat(pageNames).containsExactly("Page1", "Page2", "Page3", "Page4"); assertThat(slugNames).containsExactly("page1", "page2", "page3", "page4"); assertThat(pageIconNames).containsExactly(null, "flight", "bag", "bus"); @@ -2936,7 +3289,8 @@ public void validChangeViewAccessCancelledMidWay() { String appName = "ApplicationServiceTest Public View Application Midway Cancellation"; testApplication.setName(appName); - Application originalApplication = applicationPageService.createApplication(testApplication, workspaceId) + Application originalApplication = applicationPageService + .createApplication(testApplication, workspaceId) .block(); String pageId = originalApplication.getPages().get(0).getId(); @@ -2966,7 +3320,8 @@ public void validChangeViewAccessCancelledMidWay() { actionConfiguration.setHttpMethod(HttpMethod.GET); action1.setActionConfiguration(actionConfiguration); - ActionDTO savedAction1 = layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); + ActionDTO savedAction1 = + layoutActionService.createSingleAction(action1, Boolean.FALSE).block(); ActionDTO action2 = new ActionDTO(); action2.setName("Public View Test action2"); @@ -2974,7 +3329,8 @@ public void validChangeViewAccessCancelledMidWay() { action2.setDatasource(savedDatasource); action2.setActionConfiguration(actionConfiguration); - ActionDTO savedAction2 = layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); + ActionDTO savedAction2 = + layoutActionService.createSingleAction(action2, Boolean.FALSE).block(); ActionDTO action3 = new ActionDTO(); action3.setName("Public View Test action3"); @@ -2982,13 +3338,15 @@ public void validChangeViewAccessCancelledMidWay() { action3.setDatasource(savedDatasource); action3.setActionConfiguration(actionConfiguration); - ActionDTO savedAction3 = layoutActionService.createSingleAction(action3, Boolean.FALSE).block(); + ActionDTO savedAction3 = + layoutActionService.createSingleAction(action3, Boolean.FALSE).block(); ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(true); // Trigger the change view access of application now. - applicationService.changeViewAccess(originalApplication.getId(), applicationAccessDTO) + applicationService + .changeViewAccess(originalApplication.getId(), applicationAccessDTO) .timeout(Duration.ofMillis(10)) .subscribe(); @@ -3001,26 +3359,26 @@ public void validChangeViewAccessCancelledMidWay() { } catch (InterruptedException e) { e.printStackTrace(); } - return applicationRepository.findById(originalApplication.getId(), READ_APPLICATIONS) + return applicationRepository + .findById(originalApplication.getId(), READ_APPLICATIONS) .flatMap(applicationService::setTransientFields); }) .cache(); - Mono<List<NewAction>> actionsMono = applicationFromDbPostViewChange - .flatMap(clonedAppFromDb -> newActionService - .findAllByApplicationIdAndViewMode(clonedAppFromDb.getId(), false, READ_ACTIONS, null) - .collectList() - ); + Mono<List<NewAction>> actionsMono = applicationFromDbPostViewChange.flatMap(clonedAppFromDb -> newActionService + .findAllByApplicationIdAndViewMode(clonedAppFromDb.getId(), false, READ_ACTIONS, null) + .collectList()); Mono<List<PageDTO>> pagesMono = applicationFromDbPostViewChange .flatMapMany(application -> Flux.fromIterable(application.getPages())) .flatMap(applicationPage -> newPageService.findPageById(applicationPage.getId(), READ_PAGES, false)) .collectList(); - Mono<Datasource> datasourceMono = applicationFromDbPostViewChange - .flatMap(application -> datasourceService.findById(savedDatasource.getId(), READ_DATASOURCES)); + Mono<Datasource> datasourceMono = applicationFromDbPostViewChange.flatMap( + application -> datasourceService.findById(savedDatasource.getId(), READ_DATASOURCES)); - List<PermissionGroup> permissionGroups = workspaceService.findById(workspaceId, READ_WORKSPACES) + List<PermissionGroup> permissionGroups = workspaceService + .findById(workspaceId, READ_WORKSPACES) .flatMapMany(savedWorkspace -> { Set<String> defaultPermissionGroups = savedWorkspace.getDefaultPermissionGroups(); return permissionGroupRepository.findAllById(defaultPermissionGroups); @@ -3030,22 +3388,29 @@ public void validChangeViewAccessCancelledMidWay() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(VIEWER)) - .findFirst().get(); + .findFirst() + .get(); Mono<PermissionGroup> publicPermissionGroupMono = permissionGroupService.getPublicPermissionGroup(); User anonymousUser = userRepository.findByEmail(ANONYMOUS_USER).block(); - StepVerifier - .create(Mono.zip(applicationFromDbPostViewChange, actionsMono, pagesMono, datasourceMono, publicPermissionGroupMono)) + StepVerifier.create(Mono.zip( + applicationFromDbPostViewChange, + actionsMono, + pagesMono, + datasourceMono, + publicPermissionGroupMono)) .assertNext(tuple -> { Application updatedApplication = tuple.getT1(); List<NewAction> actions = tuple.getT2(); @@ -3057,49 +3422,39 @@ public void validChangeViewAccessCancelledMidWay() { assertThat(updatedApplication).isNotNull(); assertThat(updatedApplication.getIsPublic()).isTrue(); - assertThat(updatedApplication - .getPolicies() - .stream() - .filter(policy -> policy.getPermission().equals(READ_APPLICATIONS.getValue())) - .findFirst() - .get() - .getPermissionGroups() - ).contains(permissionGroup.getId()); + assertThat(updatedApplication.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(READ_APPLICATIONS.getValue())) + .findFirst() + .get() + .getPermissionGroups()) + .contains(permissionGroup.getId()); for (PageDTO page : pages) { - assertThat(page - .getPolicies() - .stream() - .filter(policy -> policy.getPermission().equals(READ_PAGES.getValue())) - .findFirst() - .get() - .getPermissionGroups() - ).contains(permissionGroup.getId()); + assertThat(page.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(READ_PAGES.getValue())) + .findFirst() + .get() + .getPermissionGroups()) + .contains(permissionGroup.getId()); } for (NewAction action : actions) { - assertThat(action - .getPolicies() - .stream() - .filter(policy -> policy.getPermission().equals(EXECUTE_ACTIONS.getValue())) - .findFirst() - .get() - .getPermissionGroups() - ).contains(permissionGroup.getId()); + assertThat(action.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(EXECUTE_ACTIONS.getValue())) + .findFirst() + .get() + .getPermissionGroups()) + .contains(permissionGroup.getId()); } - assertThat(datasource1 - .getPolicies() - .stream() - .filter(policy -> policy.getPermission().equals(EXECUTE_DATASOURCES.getValue())) - .findFirst() - .get() - .getPermissionGroups() - ).contains(permissionGroup.getId()); - + assertThat(datasource1.getPolicies().stream() + .filter(policy -> policy.getPermission().equals(EXECUTE_DATASOURCES.getValue())) + .findFirst() + .get() + .getPermissionGroups()) + .contains(permissionGroup.getId()); }) .verifyComplete(); - } @WithUserDetails("api_user") @@ -3110,22 +3465,23 @@ public void saveLastEditInformation_WhenUserHasPermission_Updated() { testApplication.setModifiedBy("test-user"); testApplication.setIsPublic(true); - Mono<Application> updatedApplication = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Application> updatedApplication = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(TRUE); return applicationService.changeViewAccess(application.getId(), applicationAccessDTO); }) - .flatMap(application -> - applicationService.saveLastEditInformation(application.getId()) - ); - StepVerifier.create(updatedApplication).assertNext(application -> { - assertThat(application.getLastUpdateTime()).isNotNull(); - assertThat(application.getPolicies()).isNotNull().isNotEmpty(); - assertThat(application.getModifiedBy()).isEqualTo("api_user"); - assertThat(application.getIsPublic()).isTrue(); - assertThat(application.getIsManualUpdate()).isTrue(); - }).verifyComplete(); + .flatMap(application -> applicationService.saveLastEditInformation(application.getId())); + StepVerifier.create(updatedApplication) + .assertNext(application -> { + assertThat(application.getLastUpdateTime()).isNotNull(); + assertThat(application.getPolicies()).isNotNull().isNotEmpty(); + assertThat(application.getModifiedBy()).isEqualTo("api_user"); + assertThat(application.getIsPublic()).isTrue(); + assertThat(application.getIsManualUpdate()).isTrue(); + }) + .verifyComplete(); } @WithUserDetails("api_user") @@ -3135,18 +3491,22 @@ public void generateSshKeyPair_WhenDefaultApplicationIdNotSet_CurrentAppUpdated( unsavedApplication.setWorkspaceId(workspaceId); unsavedApplication.setName("ssh-test-app"); - Mono<Application> applicationMono = applicationPageService.createApplication(unsavedApplication) - .flatMap(savedApplication -> applicationService.createOrUpdateSshKeyPair(savedApplication.getId(), null) - .thenReturn(savedApplication.getId()) - ).flatMap(testApplicationId -> applicationRepository.findById(testApplicationId, MANAGE_APPLICATIONS)); + Mono<Application> applicationMono = applicationPageService + .createApplication(unsavedApplication) + .flatMap(savedApplication -> applicationService + .createOrUpdateSshKeyPair(savedApplication.getId(), null) + .thenReturn(savedApplication.getId())) + .flatMap(testApplicationId -> applicationRepository.findById(testApplicationId, MANAGE_APPLICATIONS)); StepVerifier.create(applicationMono) .assertNext(testApplication -> { - GitAuth gitAuth = testApplication.getGitApplicationMetadata().getGitAuth(); + GitAuth gitAuth = + testApplication.getGitApplicationMetadata().getGitAuth(); assertThat(gitAuth.getPublicKey()).isNotNull(); assertThat(gitAuth.getPrivateKey()).isNotNull(); assertThat(gitAuth.getGeneratedAt()).isNotNull(); - assertThat(testApplication.getGitApplicationMetadata().getDefaultApplicationId()).isNotNull(); + assertThat(testApplication.getGitApplicationMetadata().getDefaultApplicationId()) + .isNotNull(); }) .verifyComplete(); } @@ -3159,9 +3519,12 @@ public void generateSshKeyPair_WhenDefaultApplicationIdSet_DefaultApplicationUpd unsavedMainApp.setName("ssh-key-master-app"); unsavedMainApp.setWorkspaceId(workspaceId); - Application savedApplication = applicationPageService.createApplication(unsavedMainApp, workspaceId).block(); + Application savedApplication = applicationPageService + .createApplication(unsavedMainApp, workspaceId) + .block(); - Mono<Tuple2<Application, Application>> tuple2Mono = applicationService.createOrUpdateSshKeyPair(savedApplication.getId(), null) + Mono<Tuple2<Application, Application>> tuple2Mono = applicationService + .createOrUpdateSshKeyPair(savedApplication.getId(), null) .thenReturn(savedApplication) .flatMap(savedMainApp -> { Application unsavedChildApp = new Application(); @@ -3171,14 +3534,17 @@ public void generateSshKeyPair_WhenDefaultApplicationIdSet_DefaultApplicationUpd unsavedChildApp.setWorkspaceId(workspaceId); return applicationPageService.createApplication(unsavedChildApp, workspaceId); }) - .flatMap(savedChildApp -> - applicationService.createOrUpdateSshKeyPair(savedChildApp.getId(), null).thenReturn(savedChildApp) - ) + .flatMap(savedChildApp -> applicationService + .createOrUpdateSshKeyPair(savedChildApp.getId(), null) + .thenReturn(savedChildApp)) .flatMap(savedChildApp -> { // fetch and return both child and main applications - String mainApplicationId = savedChildApp.getGitApplicationMetadata().getDefaultApplicationId(); - Mono<Application> childAppMono = applicationRepository.findById(savedChildApp.getId(), MANAGE_APPLICATIONS); - Mono<Application> mainAppMono = applicationRepository.findById(mainApplicationId, MANAGE_APPLICATIONS); + String mainApplicationId = + savedChildApp.getGitApplicationMetadata().getDefaultApplicationId(); + Mono<Application> childAppMono = + applicationRepository.findById(savedChildApp.getId(), MANAGE_APPLICATIONS); + Mono<Application> mainAppMono = + applicationRepository.findById(mainApplicationId, MANAGE_APPLICATIONS); return Mono.zip(childAppMono, mainAppMono); }); @@ -3215,7 +3581,8 @@ public void deleteApplication_withPagesActionsAndActionCollections_resourcesArch String appName = "deleteApplicationWithPagesAndActions"; testApplication.setName(appName); - Mono<Tuple3<NewAction, ActionCollection, NewPage>> resultMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Tuple3<NewAction, ActionCollection, NewPage>> resultMono = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { PageDTO page = new PageDTO(); page.setName("New Page"); @@ -3226,8 +3593,7 @@ public void deleteApplication_withPagesActionsAndActionCollections_resourcesArch page.setLayouts(layouts); return Mono.zip( applicationPageService.createPage(page), - pluginRepository.findByPackageName("installed-plugin") - ); + pluginRepository.findByPackageName("installed-plugin")); }) .flatMap(tuple -> { final PageDTO page = tuple.getT1(); @@ -3262,33 +3628,34 @@ public void deleteApplication_withPagesActionsAndActionCollections_resourcesArch actionCollectionDTO.setActions(List.of(action1)); actionCollectionDTO.setPluginType(PluginType.JS); - return layoutActionService.createSingleAction(action, Boolean.FALSE) + return layoutActionService + .createSingleAction(action, Boolean.FALSE) .zipWith(layoutCollectionService.createCollection(actionCollectionDTO)) .flatMap(tuple1 -> { ActionDTO savedAction = tuple1.getT1(); ActionCollectionDTO savedActionCollection = tuple1.getT2(); - return applicationService.findById(page.getApplicationId(), MANAGE_APPLICATIONS) - .flatMap(application -> applicationPageService.deleteApplication(application.getId())) - .flatMap(ignored -> - Mono.zip( - (Mono<NewAction>) this.getArchivedResource(savedAction.getId(), NewAction.class), - (Mono<ActionCollection>) this.getArchivedResource(savedActionCollection.getId(), ActionCollection.class), - (Mono<NewPage>) this.getArchivedResource(page.getId(), NewPage.class) - )); + return applicationService + .findById(page.getApplicationId(), MANAGE_APPLICATIONS) + .flatMap(application -> + applicationPageService.deleteApplication(application.getId())) + .flatMap(ignored -> Mono.zip( + (Mono<NewAction>) + this.getArchivedResource(savedAction.getId(), NewAction.class), + (Mono<ActionCollection>) this.getArchivedResource( + savedActionCollection.getId(), ActionCollection.class), + (Mono<NewPage>) this.getArchivedResource(page.getId(), NewPage.class))); }); }) .cache(); - Mono<NewAction> archivedActionFromActionCollectionMono = resultMono - .flatMap(tuple -> { - final Optional<String> actionId = tuple.getT2().getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values() - .stream() + Mono<NewAction> archivedActionFromActionCollectionMono = resultMono.flatMap(tuple -> { + final Optional<String> actionId = + tuple.getT2().getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values().stream() .findFirst(); - return (Mono<NewAction>) this.getArchivedResource(actionId.get(), NewAction.class); - }); + return (Mono<NewAction>) this.getArchivedResource(actionId.get(), NewAction.class); + }); - StepVerifier - .create(resultMono.zipWith(archivedActionFromActionCollectionMono)) + StepVerifier.create(resultMono.zipWith(archivedActionFromActionCollectionMono)) .assertNext(tuple -> { NewAction archivedAction = tuple.getT1().getT1(); ActionCollection archivedActionCollection = tuple.getT1().getT2(); @@ -3304,7 +3671,8 @@ public void deleteApplication_withPagesActionsAndActionCollections_resourcesArch assertThat(archivedPage.getDeletedAt()).isNotNull(); assertThat(archivedPage.getDeleted()).isTrue(); - assertThat(archivedActionFromActionCollection.getDeletedAt()).isNotNull(); + assertThat(archivedActionFromActionCollection.getDeletedAt()) + .isNotNull(); assertThat(archivedActionFromActionCollection.getDeleted()).isTrue(); }) .verifyComplete(); @@ -3316,12 +3684,13 @@ public void deleteApplication_withNullGitData_Success() { Application testApplication = new Application(); String appName = "deleteApplication_withNullGitData_Success"; testApplication.setName(appName); - Application application = applicationPageService.createApplication(testApplication, workspaceId).block(); + Application application = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); Mono<Application> applicationMono = applicationPageService.deleteApplication(application.getId()); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application1 -> { assertThat(application1.isDeleted()).isTrue(); }) @@ -3340,12 +3709,13 @@ public void deleteApplication_WithDeployKeysNotConnectedToRemote_Success() { gitAuth.setPublicKey("publicKey"); gitApplicationMetadata.setGitAuth(gitAuth); testApplication.setGitApplicationMetadata(gitApplicationMetadata); - Application application = applicationPageService.createApplication(testApplication, workspaceId).block(); + Application application = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); Mono<Application> applicationMono = applicationPageService.deleteApplication(application.getId()); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application1 -> { assertThat(application1.isDeleted()).isTrue(); }) @@ -3366,18 +3736,16 @@ public void cloneApplication_WithCustomSavedTheme_ThemesAlsoCopied() { Mono<Tuple2<Theme, Tuple2<Application, Application>>> tuple2Application = createTheme .then(applicationPageService.createApplication(testApplication, workspaceId)) - .flatMap(application -> - themeService.updateTheme(application.getId(), null, theme).then( - themeService.persistCurrentTheme(application.getId(), null, new Theme()) - .flatMap(theme1 -> Mono.zip( - applicationPageService.cloneApplication(application.getId(), null), - Mono.just(application)) - ) - ) - ).flatMap(objects -> - themeService.getThemeById(objects.getT1().getEditModeThemeId(), MANAGE_THEMES) - .zipWith(Mono.just(objects)) - ); + .flatMap(application -> themeService + .updateTheme(application.getId(), null, theme) + .then(themeService + .persistCurrentTheme(application.getId(), null, new Theme()) + .flatMap(theme1 -> Mono.zip( + applicationPageService.cloneApplication(application.getId(), null), + Mono.just(application))))) + .flatMap(objects -> themeService + .getThemeById(objects.getT1().getEditModeThemeId(), MANAGE_THEMES) + .zipWith(Mono.just(objects))); StepVerifier.create(tuple2Application) .assertNext(objects -> { @@ -3405,26 +3773,29 @@ public void getApplicationConnectedToGit_defaultBranchUpdated_returnBranchSpecif gitData.setBranchName("release"); gitData.setDefaultApplicationId(gitConnectedApp.getId()); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication) - .flatMap(application1 -> importExportApplicationService.exportApplicationById(gitConnectedApp.getId(), gitData.getBranchName()) - .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, applicationJson, application1.getId(), gitData.getBranchName()))) + Application application = applicationPageService + .createApplication(testApplication) + .flatMap(application1 -> importExportApplicationService + .exportApplicationById(gitConnectedApp.getId(), gitData.getBranchName()) + .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, applicationJson, application1.getId(), gitData.getBranchName()))) .block(); - Mono<Application> getApplication = applicationService.findByIdAndBranchName(gitConnectedApp.getId(), "release"); StepVerifier.create(getApplication) .assertNext(application1 -> { assertThat(application1).isNotNull(); - assertThat(application1.getGitApplicationMetadata().getBranchName()).isNotEqualTo(gitConnectedApp.getGitApplicationMetadata().getBranchName()); - assertThat(application1.getGitApplicationMetadata().getBranchName()).isEqualTo(application.getGitApplicationMetadata().getBranchName()); + assertThat(application1.getGitApplicationMetadata().getBranchName()) + .isNotEqualTo( + gitConnectedApp.getGitApplicationMetadata().getBranchName()); + assertThat(application1.getGitApplicationMetadata().getBranchName()) + .isEqualTo(application.getGitApplicationMetadata().getBranchName()); assertThat(application1.getId()).isEqualTo(gitConnectedApp.getId()); assertThat(application1.getName()).isEqualTo(application.getName()); }) .verifyComplete(); - } - /** * Test case which proves the non-dependency of isPublic Field in Update Application API Response * on the deprecated Application collection isPublic field for a public application @@ -3439,14 +3810,18 @@ public void validPublicAppUpdateApplication() { Application application = new Application(); application.setName("validPublicAppUpdateApplication-Test"); - Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); /** * Making the App public using changeViewAccess method which changes the permission groups of the app to allow public access */ ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(true); - Application publicAccessApplication = applicationService.changeViewAccess(createdApplication.getId(), applicationAccessDTO).block(); + Application publicAccessApplication = applicationService + .changeViewAccess(createdApplication.getId(), applicationAccessDTO) + .block(); /** * setIsPublic to False, purposely set to prove non-dependency on this field of the output @@ -3458,7 +3833,8 @@ public void validPublicAppUpdateApplication() { * which proves it's non-dependency on the deprecated Application collection isPublic field * and shows it dependency on the actual app permissions and state of the app which has been set public in this case **/ - Mono<Application> updatedApplication = applicationService.update(createdApplication.getId(), publicAccessApplication); + Mono<Application> updatedApplication = + applicationService.update(createdApplication.getId(), publicAccessApplication); StepVerifier.create(updatedApplication) .assertNext(t -> { assertThat(t).isNotNull(); @@ -3482,7 +3858,9 @@ public void validPrivateAppUpdateApplication() { Application application = new Application(); application.setName("validPrivateAppUpdateApplication-Test"); - Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); /** * Making the App private using changeViewAccess method which changes the permission groups of the app to restrict public access @@ -3490,7 +3868,9 @@ public void validPrivateAppUpdateApplication() { ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(false); - Application privateAccessApplication = applicationService.changeViewAccess(createdApplication.getId(), applicationAccessDTO).block(); + Application privateAccessApplication = applicationService + .changeViewAccess(createdApplication.getId(), applicationAccessDTO) + .block(); /** * setIsPublic to True, purposely set to prove non-dependency on this field of the output @@ -3502,7 +3882,8 @@ public void validPrivateAppUpdateApplication() { * which proves it's non-dependency on the deprecated Application collection isPublic field * and shows it dependency on the actual app permissions and state of the app which has been set private in this case **/ - Mono<Application> updatedApplication = applicationService.update(createdApplication.getId(), privateAccessApplication); + Mono<Application> updatedApplication = + applicationService.update(createdApplication.getId(), privateAccessApplication); StepVerifier.create(updatedApplication) .assertNext(t -> { assertThat(t).isNotNull(); @@ -3514,8 +3895,11 @@ public void validPrivateAppUpdateApplication() { private FilePart createMockFilePart() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), new DefaultDataBufferFactory(), 4096).cache(); + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), + new DefaultDataBufferFactory(), + 4096) + .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); return filepart; @@ -3524,7 +3908,9 @@ private FilePart createMockFilePart() { private String createTestApplication(String applicationName) { Application testApplication = new Application(); testApplication.setName(applicationName); - Application application = applicationPageService.createApplication(testApplication, workspaceId).block(); + Application application = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); return application.getId(); } @@ -3534,26 +3920,40 @@ public void testUploadAndDeleteNavigationLogo_validImage() { FilePart filepart = createMockFilePart(); String createdApplicationId = createTestApplication("ApplicationServiceTest Upload/Delete Nav Logo"); - final Mono<Application> saveMono = applicationService.saveAppNavigationLogo(null, createdApplicationId, filepart).cache(); + final Mono<Application> saveMono = applicationService + .saveAppNavigationLogo(null, createdApplicationId, filepart) + .cache(); - Mono<Tuple2<Application, Asset>> loadLogoImageMono = applicationService.findById(createdApplicationId) + Mono<Tuple2<Application, Asset>> loadLogoImageMono = applicationService + .findById(createdApplicationId) .flatMap(fetchedApplication -> { Mono<Application> fetchedApplicationMono = Mono.just(fetchedApplication); - if (StringUtils.isEmpty(fetchedApplication.getUnpublishedApplicationDetail().getNavigationSetting().getLogoAssetId())) { + if (StringUtils.isEmpty(fetchedApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getLogoAssetId())) { return fetchedApplicationMono.zipWith(Mono.just(new Asset())); } else { - return fetchedApplicationMono.zipWith(assetRepository.findById(fetchedApplication.getUnpublishedApplicationDetail().getNavigationSetting().getLogoAssetId())); + return fetchedApplicationMono.zipWith(assetRepository.findById(fetchedApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getLogoAssetId())); } }); - final Mono<Tuple2<Application, Asset>> saveAndGetMono = saveMono.then(loadLogoImageMono); - final Mono<Tuple2<Application, Asset>> deleteAndGetMono = saveMono.then(applicationService.deleteAppNavigationLogo(null, createdApplicationId)).then(loadLogoImageMono); + final Mono<Tuple2<Application, Asset>> deleteAndGetMono = saveMono.then( + applicationService.deleteAppNavigationLogo(null, createdApplicationId)) + .then(loadLogoImageMono); StepVerifier.create(saveAndGetMono) .assertNext(tuple -> { final Application application1 = tuple.getT1(); - assertThat(application1.getUnpublishedApplicationDetail().getNavigationSetting().getLogoAssetId()).isNotNull(); + assertThat(application1 + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getLogoAssetId()) + .isNotNull(); final Asset asset = tuple.getT2(); assertThat(asset).isNotNull(); @@ -3562,7 +3962,11 @@ public void testUploadAndDeleteNavigationLogo_validImage() { StepVerifier.create(deleteAndGetMono) .assertNext(objects -> { - assertThat(objects.getT1().getUnpublishedApplicationDetail().getNavigationSetting().getLogoAssetId()).isNull(); + assertThat(objects.getT1() + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getLogoAssetId()) + .isNull(); assertThat(objects.getT2().getId()).isNull(); }) // Should be empty since the profile photo has been deleted. @@ -3573,8 +3977,10 @@ public void testUploadAndDeleteNavigationLogo_validImage() { @WithUserDetails(value = "api_user") public void testUploadNavigationLogo_invalidImageFormat() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), new DefaultDataBufferFactory(), 4096) + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), + new DefaultDataBufferFactory(), + 4096) .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); @@ -3582,7 +3988,9 @@ public void testUploadNavigationLogo_invalidImageFormat() { String createdApplicationId = createTestApplication("ApplicationServiceTest Upload Invalid Nav Logo"); - final Mono<Application> saveMono = applicationService.saveAppNavigationLogo(null, createdApplicationId, filepart).cache(); + final Mono<Application> saveMono = applicationService + .saveAppNavigationLogo(null, createdApplicationId, filepart) + .cache(); StepVerifier.create(saveMono) .expectErrorMatches(error -> error instanceof AppsmithException) .verify(); @@ -3592,9 +4000,11 @@ public void testUploadNavigationLogo_invalidImageFormat() { @WithUserDetails(value = "api_user") public void testUploadNavigationLogo_invalidImageSize() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo_large.png"), new DefaultDataBufferFactory(), 4096) - .repeat(100) // So the file size looks like it's much larger than what it actually is. + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo_large.png"), + new DefaultDataBufferFactory(), + 4096) + .repeat(100) // So the file size looks like it's much larger than what it actually is. .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); @@ -3602,7 +4012,9 @@ public void testUploadNavigationLogo_invalidImageSize() { String createdApplicationId = createTestApplication("ApplicationServiceTest Upload Invalid Nav Logo Size"); - final Mono<Application> saveMono = applicationService.saveAppNavigationLogo(null, createdApplicationId, filepart).cache(); + final Mono<Application> saveMono = applicationService + .saveAppNavigationLogo(null, createdApplicationId, filepart) + .cache(); StepVerifier.create(saveMono) .expectErrorMatches(error -> error instanceof AppsmithException) .verify(); @@ -3618,14 +4030,17 @@ public void cloneApplication_WhenClonedSuccessfully_InternalFieldsResetToNull() testApplication.setForkWithConfiguration(TRUE); testApplication.setForkingEnabled(TRUE); - Application application = applicationPageService.createApplication(testApplication, workspaceId).block(); + Application application = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); Mono<Application> clonedApplicationMono = applicationPageService.cloneApplication(application.getId(), null); - - StepVerifier.create(clonedApplicationMono).assertNext(clonedApplication -> { - assertThat(clonedApplication.getExportWithConfiguration()).isNull(); - assertThat(clonedApplication.getForkWithConfiguration()).isNull(); - assertThat(clonedApplication.getForkingEnabled()).isNull(); - }).verifyComplete(); + StepVerifier.create(clonedApplicationMono) + .assertNext(clonedApplication -> { + assertThat(clonedApplication.getExportWithConfiguration()).isNull(); + assertThat(clonedApplication.getForkWithConfiguration()).isNull(); + assertThat(clonedApplication.getForkingEnabled()).isNull(); + }) + .verifyComplete(); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceUnitTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceUnitTest.java index 8383dd0dc3c6..95d759c166e1 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceUnitTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceUnitTest.java @@ -61,9 +61,7 @@ public class ApplicationSnapshotServiceUnitTest { @Test public void createApplicationSnapshot_WhenApplicationTooLarge_SnapshotCreatedSuccessfully() { - String defaultAppId = "default-app-id", - branchName = "develop", - branchedAppId = "branched-app-id"; + String defaultAppId = "default-app-id", branchName = "develop", branchedAppId = "branched-app-id"; // Create a large ApplicationJson object that exceeds the 15 MB size JSONObject jsonObject = new JSONObject(); @@ -81,17 +79,20 @@ public void createApplicationSnapshot_WhenApplicationTooLarge_SnapshotCreatedSuc ApplicationJson applicationJson = new ApplicationJson(); applicationJson.setPageList(List.of(newPage)); - Mockito.when(applicationService.findBranchedApplicationId(branchName, defaultAppId, AclPermission.MANAGE_APPLICATIONS)) + Mockito.when(applicationService.findBranchedApplicationId( + branchName, defaultAppId, AclPermission.MANAGE_APPLICATIONS)) .thenReturn(Mono.just(branchedAppId)); - Mockito.when(importExportApplicationService.exportApplicationById(branchedAppId, SerialiseApplicationObjective.VERSION_CONTROL)) + Mockito.when(importExportApplicationService.exportApplicationById( + branchedAppId, SerialiseApplicationObjective.VERSION_CONTROL)) .thenReturn(Mono.just(applicationJson)); Mockito.when(applicationSnapshotRepository.deleteAllByApplicationId(branchedAppId)) .thenReturn(Mono.just("").then()); // we're expecting to receive two application snapshots, create a matcher to check the size - ArgumentMatcher<List<ApplicationSnapshot>> snapshotListHasTwoSnapshot = snapshotList -> snapshotList.size() == 2; + ArgumentMatcher<List<ApplicationSnapshot>> snapshotListHasTwoSnapshot = + snapshotList -> snapshotList.size() == 2; Mockito.when(applicationSnapshotRepository.saveAll(argThat(snapshotListHasTwoSnapshot))) .thenReturn(Flux.just(new ApplicationSnapshot(), new ApplicationSnapshot())); @@ -115,7 +116,8 @@ public void restoreSnapshot_WhenSnapshotHasMultipleChunks_RestoredSuccessfully() application.setWorkspaceId(workspaceId); application.setId(branchedAppId); - Mockito.when(applicationService.findByBranchNameAndDefaultApplicationId(branch, defaultAppId, AclPermission.MANAGE_APPLICATIONS)) + Mockito.when(applicationService.findByBranchNameAndDefaultApplicationId( + branch, defaultAppId, AclPermission.MANAGE_APPLICATIONS)) .thenReturn(Mono.just(application)); ApplicationJson applicationJson = new ApplicationJson(); @@ -129,16 +131,17 @@ public void restoreSnapshot_WhenSnapshotHasMultipleChunks_RestoredSuccessfully() List<ApplicationSnapshot> snapshots = List.of( createSnapshot(branchedAppId, copyOfRange(jsonStringBytes, chunkSize * 2, jsonStringBytes.length), 3), createSnapshot(branchedAppId, copyOfRange(jsonStringBytes, 0, chunkSize), 1), - createSnapshot(branchedAppId, copyOfRange(jsonStringBytes, chunkSize, chunkSize * 2), 2) - ); + createSnapshot(branchedAppId, copyOfRange(jsonStringBytes, chunkSize, chunkSize * 2), 2)); Mockito.when(applicationSnapshotRepository.findByApplicationId(branchedAppId)) .thenReturn(Flux.fromIterable(snapshots)); // matcher to check that ApplicationJson created from chunks matches the original one ArgumentMatcher<ApplicationJson> matchApplicationJson; - matchApplicationJson = applicationJson1 -> applicationJson1.getExportedApplication().getName().equals(application.getName()); - Mockito.when(importExportApplicationService.restoreSnapshot(eq(application.getWorkspaceId()), argThat(matchApplicationJson), eq(branchedAppId), eq(branch))) + matchApplicationJson = applicationJson1 -> + applicationJson1.getExportedApplication().getName().equals(application.getName()); + Mockito.when(importExportApplicationService.restoreSnapshot( + eq(application.getWorkspaceId()), argThat(matchApplicationJson), eq(branchedAppId), eq(branch))) .thenReturn(Mono.just(application)); Mockito.when(applicationSnapshotRepository.deleteAllByApplicationId(branchedAppId)) @@ -171,7 +174,8 @@ public void restoreSnapshot_WhenApplicationHasDefaultPageIds_IdReplacedWithDefau application.setPages(List.of(applicationPage)); - Mockito.when(applicationService.findByBranchNameAndDefaultApplicationId(branch, defaultAppId, AclPermission.MANAGE_APPLICATIONS)) + Mockito.when(applicationService.findByBranchNameAndDefaultApplicationId( + branch, defaultAppId, AclPermission.MANAGE_APPLICATIONS)) .thenReturn(Mono.just(application)); ApplicationJson applicationJson = new ApplicationJson(); @@ -180,14 +184,13 @@ public void restoreSnapshot_WhenApplicationHasDefaultPageIds_IdReplacedWithDefau String jsonString = gson.toJson(applicationJson); byte[] jsonStringBytes = jsonString.getBytes(StandardCharsets.UTF_8); - List<ApplicationSnapshot> snapshots = List.of( - createSnapshot(branchedAppId, jsonStringBytes, 1) - ); + List<ApplicationSnapshot> snapshots = List.of(createSnapshot(branchedAppId, jsonStringBytes, 1)); Mockito.when(applicationSnapshotRepository.findByApplicationId(branchedAppId)) .thenReturn(Flux.fromIterable(snapshots)); - Mockito.when(importExportApplicationService.restoreSnapshot(eq(application.getWorkspaceId()), any(), eq(branchedAppId), eq(branch))) + Mockito.when(importExportApplicationService.restoreSnapshot( + eq(application.getWorkspaceId()), any(), eq(branchedAppId), eq(branch))) .thenReturn(Mono.just(application)); Mockito.when(applicationSnapshotRepository.deleteAllByApplicationId(branchedAppId)) @@ -203,7 +206,7 @@ public void restoreSnapshot_WhenApplicationHasDefaultPageIds_IdReplacedWithDefau .verifyComplete(); } - private ApplicationSnapshot createSnapshot(String applicationId, byte [] data, int chunkOrder) { + private ApplicationSnapshot createSnapshot(String applicationId, byte[] data, int chunkOrder) { ApplicationSnapshot applicationSnapshot = new ApplicationSnapshot(); applicationSnapshot.setApplicationId(applicationId); applicationSnapshot.setData(data); @@ -253,7 +256,8 @@ public void restoreSnapshot_WhenApplicationConnectedToGit_ReturnApplicationWithD ApplicationSnapshot applicationSnapshot = createSnapshot("branched-app-id", jsonStringBytes, 1); // mock so that this application is returned - Mockito.when(applicationService.findByBranchNameAndDefaultApplicationId("development", "default-app-id", applicationPermission.getEditPermission())) + Mockito.when(applicationService.findByBranchNameAndDefaultApplicationId( + "development", "default-app-id", applicationPermission.getEditPermission())) .thenReturn(Mono.just(application)); // mock so that this application snapshot is returned when queried with branched application id @@ -261,7 +265,14 @@ public void restoreSnapshot_WhenApplicationConnectedToGit_ReturnApplicationWithD .thenReturn(Flux.just(applicationSnapshot)); // mock the import application service to return the application that was passed to it - Mockito.when(importExportApplicationService.restoreSnapshot(eq(application.getWorkspaceId()), argThat(applicationJson1 -> applicationJson1.getExportedApplication().getName().equals(application.getName())), eq("branched-app-id"), eq("development"))) + Mockito.when(importExportApplicationService.restoreSnapshot( + eq(application.getWorkspaceId()), + argThat(applicationJson1 -> applicationJson1 + .getExportedApplication() + .getName() + .equals(application.getName())), + eq("branched-app-id"), + eq("development"))) .thenReturn(Mono.just(application)); // mock the delete spanshot to return an empty mono @@ -271,8 +282,10 @@ public void restoreSnapshot_WhenApplicationConnectedToGit_ReturnApplicationWithD StepVerifier.create(applicationSnapshotService.restoreSnapshot("default-app-id", "development")) .assertNext(application1 -> { assertThat(application1.getName()).isEqualTo(application.getName()); - assertThat(application1.getId()).isEqualTo(application.getGitApplicationMetadata().getDefaultApplicationId()); - assertThat(application1.getPages().get(0).getId()).isEqualTo(application.getPages().get(0).getDefaultPageId()); + assertThat(application1.getId()) + .isEqualTo(application.getGitApplicationMetadata().getDefaultApplicationId()); + assertThat(application1.getPages().get(0).getId()) + .isEqualTo(application.getPages().get(0).getDefaultPageId()); }) .verifyComplete(); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/GitServiceCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/GitServiceCEImplTest.java index 79c8686ecec7..a7f8768c0b6e 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/GitServiceCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/GitServiceCEImplTest.java @@ -38,7 +38,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.doReturn; - @ExtendWith(SpringExtension.class) @Slf4j public class GitServiceCEImplTest { @@ -47,78 +46,120 @@ public class GitServiceCEImplTest { @MockBean AnalyticsService analyticsService; + @MockBean DatasourceService datasourceService; + @MockBean PluginService pluginService; + @MockBean NewPageService newPageService; + @MockBean ApplicationService applicationService; + @MockBean SessionUserService sessionUserService; + @MockBean ResponseUtils responseUtils; + @MockBean UserService userService; + @MockBean UserDataService userDataService; + @MockBean ApplicationPageService applicationPageService; + @MockBean NewActionService newActionService; + @MockBean ActionCollectionService actionCollectionService; + @MockBean GitFileUtils gitFileUtils; + @MockBean ImportExportApplicationService importExportApplicationService; + @MockBean GitExecutor gitExecutor; + @MockBean EmailConfig emailConfig; + @MockBean GitCloudServicesUtils gitCloudServicesUtils; + @MockBean GitDeployKeysRepository gitDeployKeysRepository; + @MockBean DatasourcePermission datasourcePermission; + @MockBean ApplicationPermission applicationPermission; + @MockBean PagePermission pagePermission; + @MockBean ActionPermission actionPermission; + @MockBean WorkspaceService workspaceService; + @MockBean RedisUtils redisUtils; + @MockBean ExecutionTimeLogging executionTimeLogging; @BeforeEach public void setup() { gitService = new GitServiceCEImpl( - userService, userDataService, sessionUserService, applicationService, applicationPageService, - newPageService, newActionService, actionCollectionService, gitFileUtils, importExportApplicationService, - gitExecutor, responseUtils, emailConfig, analyticsService, gitCloudServicesUtils, gitDeployKeysRepository, - datasourceService, pluginService, datasourcePermission, applicationPermission, pagePermission, - actionPermission, workspaceService, redisUtils, executionTimeLogging - ); + userService, + userDataService, + sessionUserService, + applicationService, + applicationPageService, + newPageService, + newActionService, + actionCollectionService, + gitFileUtils, + importExportApplicationService, + gitExecutor, + responseUtils, + emailConfig, + analyticsService, + gitCloudServicesUtils, + gitDeployKeysRepository, + datasourceService, + pluginService, + datasourcePermission, + applicationPermission, + pagePermission, + actionPermission, + workspaceService, + redisUtils, + executionTimeLogging); } @Test public void isRepoLimitReached_connectedAppCountIsLessThanLimit_Success() { doReturn(Mono.just(3)) - .when(gitCloudServicesUtils).getPrivateRepoLimitForOrg(Mockito.any(String.class), Mockito.any(Boolean.class)); + .when(gitCloudServicesUtils) + .getPrivateRepoLimitForOrg(Mockito.any(String.class), Mockito.any(Boolean.class)); GitServiceCE gitService1 = Mockito.spy(gitService); - doReturn(Mono.just(1L)) - .when(gitService1).getApplicationCountWithPrivateRepo(Mockito.any(String.class)); + doReturn(Mono.just(1L)).when(gitService1).getApplicationCountWithPrivateRepo(Mockito.any(String.class)); - StepVerifier - .create(gitService1.isRepoLimitReached("workspaceId", false)) + StepVerifier.create(gitService1.isRepoLimitReached("workspaceId", false)) .assertNext(aBoolean -> assertEquals(false, aBoolean)) .verifyComplete(); } @@ -126,14 +167,13 @@ public void isRepoLimitReached_connectedAppCountIsLessThanLimit_Success() { @Test public void isRepoLimitReached_connectedAppCountIsSameAsLimit_Success() { doReturn(Mono.just(3)) - .when(gitCloudServicesUtils).getPrivateRepoLimitForOrg(Mockito.any(String.class), Mockito.any(Boolean.class)); + .when(gitCloudServicesUtils) + .getPrivateRepoLimitForOrg(Mockito.any(String.class), Mockito.any(Boolean.class)); GitServiceCE gitService1 = Mockito.spy(gitService); - doReturn(Mono.just(3L)) - .when(gitService1).getApplicationCountWithPrivateRepo(Mockito.any(String.class)); + doReturn(Mono.just(3L)).when(gitService1).getApplicationCountWithPrivateRepo(Mockito.any(String.class)); - StepVerifier - .create(gitService1.isRepoLimitReached("workspaceId", true)) + StepVerifier.create(gitService1.isRepoLimitReached("workspaceId", true)) .assertNext(aBoolean -> assertEquals(true, aBoolean)) .verifyComplete(); } @@ -143,15 +183,14 @@ public void isRepoLimitReached_connectedAppCountIsSameAsLimit_Success() { @Test public void isRepoLimitReached_connectedAppCountIsMoreThanLimit_Success() { doReturn(Mono.just(3)) - .when(gitCloudServicesUtils).getPrivateRepoLimitForOrg(Mockito.any(String.class), Mockito.any(Boolean.class)); + .when(gitCloudServicesUtils) + .getPrivateRepoLimitForOrg(Mockito.any(String.class), Mockito.any(Boolean.class)); GitServiceCE gitService1 = Mockito.spy(gitService); - doReturn(Mono.just(4L)) - .when(gitService1).getApplicationCountWithPrivateRepo(Mockito.any(String.class)); + doReturn(Mono.just(4L)).when(gitService1).getApplicationCountWithPrivateRepo(Mockito.any(String.class)); - StepVerifier - .create(gitService1.isRepoLimitReached("workspaceId", false)) + StepVerifier.create(gitService1.isRepoLimitReached("workspaceId", false)) .assertNext(aBoolean -> assertEquals(true, aBoolean)) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/NewActionServiceCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/NewActionServiceCEImplTest.java index 24e437763a85..c2c88d6c0ed7 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/NewActionServiceCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/NewActionServiceCEImplTest.java @@ -7,7 +7,6 @@ import com.appsmith.server.domains.NewAction; import com.appsmith.server.domains.Plugin; import com.appsmith.server.helpers.PluginExecutorHelper; -import com.appsmith.server.solutions.PolicySolution; import com.appsmith.server.helpers.ResponseUtils; import com.appsmith.server.repositories.NewActionRepository; import com.appsmith.server.services.AnalyticsService; @@ -25,6 +24,7 @@ import com.appsmith.server.solutions.ApplicationPermission; import com.appsmith.server.solutions.DatasourcePermission; import com.appsmith.server.solutions.PagePermission; +import com.appsmith.server.solutions.PolicySolution; import io.micrometer.observation.ObservationRegistry; import jakarta.validation.Validator; import lombok.extern.slf4j.Slf4j; @@ -43,7 +43,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; - @ExtendWith(SpringExtension.class) @Slf4j public class NewActionServiceCEImplTest { @@ -52,58 +51,83 @@ public class NewActionServiceCEImplTest { @MockBean Scheduler scheduler; + @MockBean Validator validator; + @MockBean MongoConverter mongoConverter; + @MockBean ReactiveMongoTemplate reactiveMongoTemplate; + @MockBean AnalyticsService analyticsService; + @MockBean DatasourceService datasourceService; + @MockBean PluginService pluginService; + @MockBean DatasourceContextService datasourceContextService; + @MockBean PluginExecutorHelper pluginExecutorHelper; + @MockBean MarketplaceService marketplaceService; + @MockBean PolicyGenerator policyGenerator; + @MockBean NewPageService newPageService; + @MockBean ApplicationService applicationService; + @MockBean SessionUserService sessionUserService; + @MockBean PolicySolution policySolution; + @MockBean AuthenticationValidator authenticationValidator; + @MockBean ConfigService configService; + @MockBean ResponseUtils responseUtils; + @MockBean PermissionGroupService permissionGroupService; + @MockBean NewActionRepository newActionRepository; + @MockBean DatasourcePermission datasourcePermission; + @MockBean ApplicationPermission applicationPermission; + @MockBean PagePermission pagePermission; + @MockBean ActionPermission actionPermission; + @MockBean ObservationRegistry observationRegistry; @BeforeEach public void setup() { - newActionService = new NewActionServiceCEImpl(scheduler, + newActionService = new NewActionServiceCEImpl( + scheduler, validator, mongoConverter, reactiveMongoTemplate, @@ -126,7 +150,8 @@ public void setup() { actionPermission, observationRegistry); - ObservationRegistry.ObservationConfig mockObservationConfig = Mockito.mock(ObservationRegistry.ObservationConfig.class); + ObservationRegistry.ObservationConfig mockObservationConfig = + Mockito.mock(ObservationRegistry.ObservationConfig.class); Mockito.when(observationRegistry.observationConfig()).thenReturn(mockObservationConfig); } @@ -136,8 +161,7 @@ public void testMissingPluginIdAndTypeFixForNonJSPluginType() { Plugin testPlugin = new Plugin(); testPlugin.setId("testId"); testPlugin.setType(PluginType.DB); - Mockito.when(pluginService.findById(anyString())) - .thenReturn(Mono.just(testPlugin)); + Mockito.when(pluginService.findById(anyString())).thenReturn(Mono.just(testPlugin)); NewAction action = new NewAction(); action.setPluginId(null); @@ -164,8 +188,7 @@ public void testMissingPluginIdAndTypeFixForJSPluginType() { Plugin testPlugin = new Plugin(); testPlugin.setId("testId"); testPlugin.setType(PluginType.JS); - Mockito.when(pluginService.findByPackageName(anyString())) - .thenReturn(Mono.just(testPlugin)); + Mockito.when(pluginService.findByPackageName(anyString())).thenReturn(Mono.just(testPlugin)); NewAction action = new NewAction(); action.setPluginId(null); @@ -183,5 +206,4 @@ public void testMissingPluginIdAndTypeFixForJSPluginType() { }) .verifyComplete(); } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/PluginServiceCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/PluginServiceCEImplTest.java index cf269d0fb510..d2c5ea976993 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/PluginServiceCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/PluginServiceCEImplTest.java @@ -35,22 +35,31 @@ public class PluginServiceCEImplTest { @MockBean Scheduler scheduler; + @MockBean Validator validator; + @MockBean MongoConverter mongoConverter; + @MockBean ReactiveMongoTemplate reactiveMongoTemplate; + @MockBean PluginRepository repository; + @MockBean AnalyticsService analyticsService; + @MockBean WorkspaceService workspaceService; + @MockBean PluginManager pluginManager; + @MockBean ReactiveRedisTemplate<String, String> reactiveTemplate; + @MockBean ChannelTopic topic; @@ -62,8 +71,17 @@ public class PluginServiceCEImplTest { public void setUp() { objectMapper = new ObjectMapper(); pluginService = new PluginServiceCEImpl( - scheduler, validator, mongoConverter, reactiveMongoTemplate, - repository, analyticsService, workspaceService, pluginManager, reactiveTemplate, topic, objectMapper); + scheduler, + validator, + mongoConverter, + reactiveMongoTemplate, + repository, + analyticsService, + workspaceService, + pluginManager, + reactiveTemplate, + topic, + objectMapper); } @Test @@ -72,7 +90,8 @@ public void testLoadEditorPluginResourceUqi_withMockPlugin_returnsValidEditorCon final ClassPathResource mockExample = new ClassPathResource("test_assets/PluginServiceTest/mock-example.json"); final ClassLoader classLoader = Mockito.mock(ClassLoader.class); Mockito.when(classLoader.getResourceAsStream("editor/root.json")).thenReturn(mockEditor.getInputStream()); - Mockito.when(classLoader.getResourceAsStream("editor/mock-example.json")).thenReturn(mockExample.getInputStream()); + Mockito.when(classLoader.getResourceAsStream("editor/mock-example.json")) + .thenReturn(mockExample.getInputStream()); final PluginWrapper pluginWrapper = Mockito.mock(PluginWrapper.class); Mockito.when(pluginWrapper.getPluginClassLoader()).thenReturn(classLoader); Mockito.when(pluginManager.getPlugin("test-plugin")).thenReturn(pluginWrapper); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/TenantServiceCETest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/TenantServiceCETest.java index e5807601ed1c..6f3745c1cc47 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/TenantServiceCETest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/TenantServiceCETest.java @@ -17,7 +17,6 @@ import static org.assertj.core.api.Assertions.assertThat; - @SpringBootTest @ExtendWith(SpringExtension.class) public class TenantServiceCETest { @@ -40,9 +39,9 @@ public void getTenantConfig_Valid_AnonymousUser() { .assertNext(tenant -> { assertThat(tenant.getTenantConfiguration()).isNotNull(); assertThat(tenant.getTenantConfiguration().getLicense()).isNotNull(); - assertThat(tenant.getTenantConfiguration().getLicense().getPlan()).isEqualTo(LicensePlan.FREE); + assertThat(tenant.getTenantConfiguration().getLicense().getPlan()) + .isEqualTo(LicensePlan.FREE); }) .verifyComplete(); - } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationFetcherTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationFetcherTest.java index bcab9b9c5d1f..aa3d9cc0be1e 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationFetcherTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationFetcherTest.java @@ -40,26 +40,32 @@ public void getAllApplications_WhenUnpublishedPageExists_ReturnsApplications() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("org_" + randomUUID); - Mono<UserHomepageDTO> homepageDTOMono = workspaceService.create(newWorkspace).flatMap(workspace -> { - Application application = new Application(); - application.setName("app_" + randomUUID); - return applicationPageService.createApplication(application, workspace.getId()); - }).flatMap(application -> { - PageDTO pageDTO = new PageDTO(); - pageDTO.setName("New page"); - return applicationPageService.createPage(pageDTO).thenReturn(application); - }).then(applicationFetcher.getAllApplications()); + Mono<UserHomepageDTO> homepageDTOMono = workspaceService + .create(newWorkspace) + .flatMap(workspace -> { + Application application = new Application(); + application.setName("app_" + randomUUID); + return applicationPageService.createApplication(application, workspace.getId()); + }) + .flatMap(application -> { + PageDTO pageDTO = new PageDTO(); + pageDTO.setName("New page"); + return applicationPageService.createPage(pageDTO).thenReturn(application); + }) + .then(applicationFetcher.getAllApplications()); StepVerifier.create(homepageDTOMono).assertNext(userHomepageDTO -> { assertThat(userHomepageDTO.getWorkspaceApplications()).isNotNull(); - WorkspaceApplicationsDTO orgApps = userHomepageDTO.getWorkspaceApplications().stream().filter( - x -> x.getWorkspace().getName().equals(newWorkspace.getName()) - ).findFirst().orElse(new WorkspaceApplicationsDTO()); + WorkspaceApplicationsDTO orgApps = userHomepageDTO.getWorkspaceApplications().stream() + .filter(x -> x.getWorkspace().getName().equals(newWorkspace.getName())) + .findFirst() + .orElse(new WorkspaceApplicationsDTO()); assertThat(orgApps.getApplications().size()).isEqualTo(1); - assertThat(orgApps.getApplications().get(0).getPublishedPages().size()).isEqualTo(1); + assertThat(orgApps.getApplications().get(0).getPublishedPages().size()) + .isEqualTo(1); assertThat(orgApps.getApplications().get(0).getPages().size()).isEqualTo(2); }); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationFetcherUnitTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationFetcherUnitTest.java index 0547448b143b..d5c67fd5ad72 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationFetcherUnitTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationFetcherUnitTest.java @@ -45,29 +45,41 @@ @ExtendWith(SpringExtension.class) public class ApplicationFetcherUnitTest { - final static String defaultPageId = "defaultPageId"; - final static String defaultTenantId = "defaultTenantId"; + static final String defaultPageId = "defaultPageId"; + static final String defaultTenantId = "defaultTenantId"; + @MockBean WorkspaceService workspaceService; + @MockBean SessionUserService sessionUserService; + @MockBean UserService userService; + @MockBean UserDataService userDataService; + @MockBean ApplicationRepository applicationRepository; + @MockBean ReleaseNotesService releaseNotesService; + @MockBean ResponseUtils responseUtils; + @MockBean NewPageService newPageService; + ApplicationFetcher applicationFetcher; + @MockBean ApplicationService applicationService; + @MockBean UserWorkspaceService userWorkspaceService; + WorkspacePermission workspacePermission; ApplicationPermission applicationPermission; PagePermission pagePermission; @@ -78,7 +90,8 @@ public void setup() { workspacePermission = new WorkspacePermissionImpl(); applicationPermission = new ApplicationPermissionImpl(); pagePermission = new PagePermissionImpl(); - applicationFetcher = new ApplicationFetcherImpl(sessionUserService, + applicationFetcher = new ApplicationFetcherImpl( + sessionUserService, userService, userDataService, workspaceService, @@ -175,12 +188,13 @@ private void initMocks() { Mockito.when(sessionUserService.getCurrentUser()).thenReturn(Mono.just(testUser)); Mockito.when(userService.findByEmail(testUser.getEmail())).thenReturn(Mono.just(testUser)); - Mockito.when(workspaceService.getAll(READ_WORKSPACES)) - .thenReturn(Flux.fromIterable(createDummyWorkspaces())); + Mockito.when(workspaceService.getAll(READ_WORKSPACES)).thenReturn(Flux.fromIterable(createDummyWorkspaces())); Mockito.when(releaseNotesService.getReleaseNodes()).thenReturn(Mono.empty()); Mockito.when(releaseNotesService.computeNewFrom(any())).thenReturn("0"); - Mockito.when(userDataService.ensureViewedCurrentVersionReleaseNotes(testUser)).thenReturn(Mono.just(testUser)); - Mockito.when(userWorkspaceService.getWorkspaceMembers((Set<String>) any())).thenReturn(Mono.just(Map.of())); + Mockito.when(userDataService.ensureViewedCurrentVersionReleaseNotes(testUser)) + .thenReturn(Mono.just(testUser)); + Mockito.when(userWorkspaceService.getWorkspaceMembers((Set<String>) any())) + .thenReturn(Mono.just(Map.of())); } @Test @@ -194,15 +208,14 @@ public void getAllApplications_NoRecentOrgAndApps_AllEntriesReturned() { List<Application> applications = createDummyApplications(4, 4); List<NewPage> pageList = createDummyPages(4, 4); - Mockito.when(applicationRepository.findAllUserApps(READ_APPLICATIONS) - ).thenReturn(Flux.fromIterable(applications)); + Mockito.when(applicationRepository.findAllUserApps(READ_APPLICATIONS)) + .thenReturn(Flux.fromIterable(applications)); Mockito.when(newPageService.findPageSlugsByApplicationIds(anyList(), eq(READ_PAGES))) .thenReturn(Flux.fromIterable(pageList)); for (Application application : applications) { - Mockito - .when(responseUtils.updateApplicationWithDefaultResources(application)) + Mockito.when(responseUtils.updateApplicationWithDefaultResources(application)) .thenReturn(updateDefaultPageIdsWithinApplication(application)); } @@ -218,15 +231,14 @@ public void getAllApplications_NoRecentOrgAndApps_AllEntriesReturned() { assertThat(dto.getApplications().size()).isEqualTo(4); List<Application> applicationList = dto.getApplications(); for (Application application : applicationList) { - application.getPages().forEach( - page -> assertThat(page.getSlug()).isEqualTo(page.getId() + "-unpublished-slug") - ); - application.getPublishedPages().forEach( - page -> assertThat(page.getSlug()).isEqualTo(page.getId() + "-published-slug") - ); + application.getPages().forEach(page -> assertThat(page.getSlug()) + .isEqualTo(page.getId() + "-unpublished-slug")); + application.getPublishedPages().forEach(page -> assertThat(page.getSlug()) + .isEqualTo(page.getId() + "-published-slug")); } } - }).verifyComplete(); + }) + .verifyComplete(); } @Test @@ -240,15 +252,14 @@ public void getAllApplications_gitConnectedAppScenarios_OnlyTheDefaultBranchedAp List<Application> applications = createDummyApplications(4, 4); List<NewPage> pageList = createDummyPages(4, 4); - Mockito.when(applicationRepository.findAllUserApps(READ_APPLICATIONS) - ).thenReturn(Flux.fromIterable(applications)); + Mockito.when(applicationRepository.findAllUserApps(READ_APPLICATIONS)) + .thenReturn(Flux.fromIterable(applications)); Mockito.when(newPageService.findPageSlugsByApplicationIds(anyList(), eq(READ_PAGES))) .thenReturn(Flux.fromIterable(pageList)); for (Application application : applications) { - Mockito - .when(responseUtils.updateApplicationWithDefaultResources(application)) + Mockito.when(responseUtils.updateApplicationWithDefaultResources(application)) .thenReturn(updateDefaultPageIdsWithinApplication(application)); } @@ -264,20 +275,20 @@ public void getAllApplications_gitConnectedAppScenarios_OnlyTheDefaultBranchedAp assertThat(dto.getApplications().size()).isEqualTo(4); List<Application> applicationList = dto.getApplications(); for (Application application : applicationList) { - application.getPages().forEach( - page -> assertThat(page.getSlug()).isEqualTo(page.getId() + "-unpublished-slug") - ); - application.getPublishedPages().forEach( - page -> assertThat(page.getSlug()).isEqualTo(page.getId() + "-published-slug") - ); + application.getPages().forEach(page -> assertThat(page.getSlug()) + .isEqualTo(page.getId() + "-unpublished-slug")); + application.getPublishedPages().forEach(page -> assertThat(page.getSlug()) + .isEqualTo(page.getId() + "-published-slug")); } } - }).verifyComplete(); + }) + .verifyComplete(); - // Generate SSH keys for an app - to test if the app is visible in home page when the git connect step is aborted in middle - Mockito.when(applicationService.save(Mockito.any(Application.class))) - .thenReturn(Mono.just(new Application())); - Mono<UserHomepageDTO> userHomepageDTOMono = applicationFetcher.getAllApplications() + // Generate SSH keys for an app - to test if the app is visible in home page when the git connect step is + // aborted in middle + Mockito.when(applicationService.save(Mockito.any(Application.class))).thenReturn(Mono.just(new Application())); + Mono<UserHomepageDTO> userHomepageDTOMono = applicationFetcher + .getAllApplications() .flatMap(userHomepageDTO -> { List<WorkspaceApplicationsDTO> dtos = userHomepageDTO.getWorkspaceApplications(); List<Application> applicationList = dtos.get(0).getApplications(); @@ -295,25 +306,26 @@ public void getAllApplications_gitConnectedAppScenarios_OnlyTheDefaultBranchedAp assertThat(dto.getApplications().size()).isEqualTo(4); List<Application> applicationList = dto.getApplications(); for (Application application : applicationList) { - application.getPages().forEach( - page -> assertThat(page.getSlug()).isEqualTo(page.getId() + "-unpublished-slug") - ); - application.getPublishedPages().forEach( - page -> assertThat(page.getSlug()).isEqualTo(page.getId() + "-published-slug") - ); + application.getPages().forEach(page -> assertThat(page.getSlug()) + .isEqualTo(page.getId() + "-unpublished-slug")); + application.getPublishedPages().forEach(page -> assertThat(page.getSlug()) + .isEqualTo(page.getId() + "-published-slug")); } } - }).verifyComplete(); + }) + .verifyComplete(); // For connect and create branch flow scenarios where - defaultBranchName is somehow not saved in DB - userHomepageDTOMono = applicationFetcher.getAllApplications() + userHomepageDTOMono = applicationFetcher + .getAllApplications() .flatMap(userHomepageDTO -> { List<WorkspaceApplicationsDTO> dtos = userHomepageDTO.getWorkspaceApplications(); List<Application> applicationList = dtos.get(0).getApplications(); return Mono.just(applicationList.get(0)); }) .flatMap(application -> { - // Create a new branched App resource in the same org and verify that branch App does not show up in the response. + // Create a new branched App resource in the same org and verify that branch App does not show up in + // the response. Application branchApp = new Application(); branchApp.setName("branched App"); branchApp.setWorkspaceId(application.getWorkspaceId()); @@ -351,16 +363,14 @@ public void getAllApplications_gitConnectedAppScenarios_OnlyTheDefaultBranchedAp assertThat(dto.getApplications().size()).isEqualTo(4); List<Application> applicationList = dto.getApplications(); for (Application application : applicationList) { - application.getPages().forEach( - page -> assertThat(page.getSlug()).isEqualTo(page.getId() + "-unpublished-slug") - ); - application.getPublishedPages().forEach( - page -> assertThat(page.getSlug()).isEqualTo(page.getId() + "-published-slug") - ); + application.getPages().forEach(page -> assertThat(page.getSlug()) + .isEqualTo(page.getId() + "-unpublished-slug")); + application.getPublishedPages().forEach(page -> assertThat(page.getSlug()) + .isEqualTo(page.getId() + "-published-slug")); } } - }).verifyComplete(); - + }) + .verifyComplete(); } @Test @@ -376,15 +386,14 @@ public void getAllApplications_WhenUserHasRecentOrgAndApp_RecentEntriesComeFirst List<Application> applications = createDummyApplications(4, 4); List<NewPage> pageList = createDummyPages(4, 4); - Mockito.when(applicationRepository.findAllUserApps(READ_APPLICATIONS) - ).thenReturn(Flux.fromIterable(applications)); + Mockito.when(applicationRepository.findAllUserApps(READ_APPLICATIONS)) + .thenReturn(Flux.fromIterable(applications)); Mockito.when(newPageService.findPageSlugsByApplicationIds(anyList(), eq(READ_PAGES))) .thenReturn(Flux.fromIterable(pageList)); for (Application application : applications) { - Mockito - .when(responseUtils.updateApplicationWithDefaultResources(application)) + Mockito.when(responseUtils.updateApplicationWithDefaultResources(application)) .thenReturn(updateDefaultPageIdsWithinApplication(application)); } @@ -395,25 +404,36 @@ public void getAllApplications_WhenUserHasRecentOrgAndApp_RecentEntriesComeFirst assertThat(workspaceApplications.size()).isEqualTo(4); // apps under first org should be sorted as org-2-app-2, org-2-app-1, org-2-app-3, org-2-app-4 - checkAppsAreSorted(workspaceApplications.get(0).getApplications(), - List.of("org-2-app-2", "org-2-app-1", "org-2-app-3", "org-2-app-4") - ); + checkAppsAreSorted( + workspaceApplications.get(0).getApplications(), + List.of("org-2-app-2", "org-2-app-1", "org-2-app-3", "org-2-app-4")); // apps should be sorted as org-4-app-3, org-4-app-1, org-4-app-2, org-4-app-4 - checkAppsAreSorted(workspaceApplications.get(1).getApplications(), - List.of("org-4-app-3", "org-4-app-1", "org-4-app-2", "org-4-app-4") - ); + checkAppsAreSorted( + workspaceApplications.get(1).getApplications(), + List.of("org-4-app-3", "org-4-app-1", "org-4-app-2", "org-4-app-4")); // rest two orgs should have apps sorted in default order e.g. 1,2,3,4 - String org3AppPrefix = workspaceApplications.get(2).getWorkspace().getId() + "-app-"; - checkAppsAreSorted(workspaceApplications.get(2).getApplications(), - List.of(org3AppPrefix + "1", org3AppPrefix + "2", org3AppPrefix + "3", org3AppPrefix + "4") - ); - String org4AppPrefix = workspaceApplications.get(3).getWorkspace().getId() + "-app-"; - checkAppsAreSorted(workspaceApplications.get(3).getApplications(), - List.of(org4AppPrefix + "1", org4AppPrefix + "2", org4AppPrefix + "3", org4AppPrefix + "4") - ); - }).verifyComplete(); + String org3AppPrefix = + workspaceApplications.get(2).getWorkspace().getId() + "-app-"; + checkAppsAreSorted( + workspaceApplications.get(2).getApplications(), + List.of( + org3AppPrefix + "1", + org3AppPrefix + "2", + org3AppPrefix + "3", + org3AppPrefix + "4")); + String org4AppPrefix = + workspaceApplications.get(3).getWorkspace().getId() + "-app-"; + checkAppsAreSorted( + workspaceApplications.get(3).getApplications(), + List.of( + org4AppPrefix + "1", + org4AppPrefix + "2", + org4AppPrefix + "3", + org4AppPrefix + "4")); + }) + .verifyComplete(); } @Test @@ -428,15 +448,14 @@ public void getAllApplications_WhenUserHasRecentOrgButNoRecentApp_AppsAreSortedI List<Application> applications = createDummyApplications(3, 3); List<NewPage> pageList = createDummyPages(4, 4); - Mockito.when(applicationRepository.findAllUserApps(READ_APPLICATIONS) - ).thenReturn(Flux.fromIterable(applications)); + Mockito.when(applicationRepository.findAllUserApps(READ_APPLICATIONS)) + .thenReturn(Flux.fromIterable(applications)); Mockito.when(newPageService.findPageSlugsByApplicationIds(anyList(), eq(READ_PAGES))) .thenReturn(Flux.fromIterable(pageList)); for (Application application : applications) { - Mockito - .when(responseUtils.updateApplicationWithDefaultResources(application)) + Mockito.when(responseUtils.updateApplicationWithDefaultResources(application)) .thenReturn(updateDefaultPageIdsWithinApplication(application)); } @@ -447,15 +466,16 @@ public void getAllApplications_WhenUserHasRecentOrgButNoRecentApp_AppsAreSortedI assertThat(workspaceApplications.size()).isEqualTo(4); // apps under first org should be sorted as 1,2,3 - checkAppsAreSorted(workspaceApplications.get(0).getApplications(), - List.of("org-3-app-1", "org-3-app-2", "org-3-app-3") - ); + checkAppsAreSorted( + workspaceApplications.get(0).getApplications(), + List.of("org-3-app-1", "org-3-app-2", "org-3-app-3")); // apps under second org should be sorted as 1,2,3 - checkAppsAreSorted(workspaceApplications.get(1).getApplications(), - List.of("org-1-app-1", "org-1-app-2", "org-1-app-3") - ); - }).verifyComplete(); + checkAppsAreSorted( + workspaceApplications.get(1).getApplications(), + List.of("org-1-app-1", "org-1-app-2", "org-1-app-3")); + }) + .verifyComplete(); } /** @@ -468,4 +488,4 @@ private void checkAppsAreSorted(List<Application> applications, List<String> app assertThat(applications.get(i).getId()).isEqualTo(appIds.get(i)); } } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationForkingServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationForkingServiceTests.java index e1da7ebabe09..11945afce2ed 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationForkingServiceTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationForkingServiceTests.java @@ -113,64 +113,85 @@ public class ApplicationForkingServiceTests { private static String sourceEnvironmentId; private static String testUserWorkspaceId; private static boolean isSetupDone = false; + @Autowired private ApplicationForkingService applicationForkingService; + @Autowired private ApplicationService applicationService; + @Autowired private DatasourceService datasourceService; + @Autowired private WorkspaceService workspaceService; + @Autowired private ApplicationPageService applicationPageService; + @Autowired private SessionUserService sessionUserService; + @Autowired private NewActionService newActionService; + @Autowired private ActionCollectionService actionCollectionService; + @Autowired private PluginRepository pluginRepository; + @Autowired private EncryptionService encryptionService; + @MockBean private PluginExecutorHelper pluginExecutorHelper; + @Autowired private LayoutActionService layoutActionService; + @Autowired private MongoTemplate mongoTemplate; + @Autowired private NewPageService newPageService; + @Autowired private UserService userService; + @Autowired private LayoutCollectionService layoutCollectionService; + @Autowired private ThemeService themeService; + @Autowired private PermissionGroupService permissionGroupService; + @Autowired private UserAndAccessManagementService userAndAccessManagementService; + @Autowired private ImportExportApplicationService importExportApplicationService; @SneakyThrows @BeforeEach public void setup() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); // Run setup only once if (isSetupDone) { return; } - Workspace sourceWorkspace = new Workspace(); sourceWorkspace.setName("Source Workspace"); sourceWorkspace = workspaceService.create(sourceWorkspace).block(); sourceWorkspaceId = sourceWorkspace.getId(); - sourceEnvironmentId = workspaceService.getDefaultEnvironmentId(sourceWorkspaceId).block(); + sourceEnvironmentId = + workspaceService.getDefaultEnvironmentId(sourceWorkspaceId).block(); Application app1 = new Application(); app1.setName("1 - public app"); @@ -179,13 +200,16 @@ public void setup() { app1 = applicationPageService.createApplication(app1).block(); sourceAppId = app1.getId(); - PageDTO testPage = newPageService.findPageById(app1.getPages().get(0).getId(), READ_PAGES, false).block(); + PageDTO testPage = newPageService + .findPageById(app1.getPages().get(0).getId(), READ_PAGES, false) + .block(); // Save action Datasource datasource = new Datasource(); datasource.setName("Default Database"); datasource.setWorkspaceId(app1.getWorkspaceId()); - Plugin installed_plugin = pluginRepository.findByPackageName("installed-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("installed-plugin").block(); datasource.setPluginId(installed_plugin.getId()); datasource.setDatasourceConfiguration(new DatasourceConfiguration()); @@ -200,7 +224,6 @@ public void setup() { layoutActionService.createSingleAction(action, Boolean.FALSE).block(); - // Save actionCollection ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); actionCollectionDTO.setName("testCollection1"); @@ -209,28 +232,26 @@ public void setup() { actionCollectionDTO.setWorkspaceId(sourceWorkspaceId); actionCollectionDTO.setPluginId(datasource.getPluginId()); actionCollectionDTO.setVariables(List.of(new JSValue("test", "String", "test", true))); - actionCollectionDTO.setBody("export default {\n" + - "\tgetData: async () => {\n" + - "\t\tconst data = await forkActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}\n" + - "}"); + actionCollectionDTO.setBody("export default {\n" + "\tgetData: async () => {\n" + + "\t\tconst data = await forkActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}\n" + + "}"); ActionDTO action1 = new ActionDTO(); action1.setName("getData"); action1.setActionConfiguration(new ActionConfiguration()); - action1.getActionConfiguration().setBody( - "async () => {\n" + - "\t\tconst data = await forkActionTest.run();\n" + - "\t\treturn data;\n" + - "\t}"); + action1.getActionConfiguration() + .setBody("async () => {\n" + "\t\tconst data = await forkActionTest.run();\n" + + "\t\treturn data;\n" + + "\t}"); actionCollectionDTO.setActions(List.of(action1)); actionCollectionDTO.setPluginType(PluginType.JS); layoutCollectionService.createCollection(actionCollectionDTO).block(); ObjectMapper objectMapper = new ObjectMapper(); - JSONObject parentDsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + JSONObject parentDsl = new JSONObject( + objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); ArrayList children = (ArrayList) parentDsl.get("children"); JSONObject testWidget = new JSONObject(); testWidget.put("widgetName", "firstWidget"); @@ -251,23 +272,30 @@ public void setup() { Layout layout = testPage.getLayouts().get(0); layout.setDsl(parentDsl); - layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout).block(); + layoutActionService + .updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout) + .block(); // Invite "[email protected]" with VIEW access, api_user will be the admin of sourceWorkspace and we are // controlling this with @FixMethodOrder(MethodSorters.NAME_ASCENDING) to run the TCs in a sequence. // Running TC in a sequence is a bad practice for unit TCs but here we are testing the invite user and then fork // application as a part of this flow. // We need to test with VIEW user access so that any user should be able to fork template applications - PermissionGroup permissionGroup = permissionGroupService.getByDefaultWorkspace(sourceWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + PermissionGroup permissionGroup = permissionGroupService + .getByDefaultWorkspace(sourceWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.VIEWER)) - .findFirst().get(); + .findFirst() + .get(); InviteUsersDTO inviteUsersDTO = new InviteUsersDTO(); ArrayList<String> users = new ArrayList<>(); users.add("[email protected]"); inviteUsersDTO.setUsernames(users); inviteUsersDTO.setPermissionGroupId(permissionGroup.getId()); - userAndAccessManagementService.inviteUsers(inviteUsersDTO, "http://localhost:8080").block(); + userAndAccessManagementService + .inviteUsers(inviteUsersDTO, "http://localhost:8080") + .block(); isSetupDone = true; } @@ -276,17 +304,14 @@ public Mono<WorkspaceData> loadWorkspaceData(Workspace workspace) { final WorkspaceData data = new WorkspaceData(); data.workspace = workspace; - return Mono - .when( + return Mono.when( applicationService .findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) .map(data.applications::add), datasourceService .getAllByWorkspaceIdWithStorages(workspace.getId(), Optional.of(READ_DATASOURCES)) .map(data.datasources::add), - getActionsInWorkspace(workspace) - .map(data.actions::add) - ) + getActionsInWorkspace(workspace).map(data.actions::add)) .thenReturn(data); } @@ -297,24 +322,27 @@ public void test1_cloneWorkspaceWithItsContents() { Workspace targetWorkspace = new Workspace(); targetWorkspace.setName("Target Workspace"); - final Mono<ApplicationImportDTO> resultMono = workspaceService.create(targetWorkspace) + final Mono<ApplicationImportDTO> resultMono = workspaceService + .create(targetWorkspace) .map(Workspace::getId) - .flatMap(targetWorkspaceId -> - applicationForkingService.forkApplicationToWorkspaceWithEnvironment(sourceAppId, targetWorkspaceId, sourceEnvironmentId) - .flatMap(application -> importExportApplicationService - .getApplicationImportDTO( - application.getId(), - application.getWorkspaceId(), - application - )) - ); - - StepVerifier.create(resultMono - .zipWhen(applicationImportDTO -> Mono.zip( - newActionService.findAllByApplicationIdAndViewMode(applicationImportDTO.getApplication().getId(), false, READ_ACTIONS, null).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(applicationImportDTO.getApplication().getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findNewPagesByApplicationId(applicationImportDTO.getApplication().getId(), READ_PAGES).collectList() - ))) + .flatMap(targetWorkspaceId -> applicationForkingService + .forkApplicationToWorkspaceWithEnvironment(sourceAppId, targetWorkspaceId, sourceEnvironmentId) + .flatMap(application -> importExportApplicationService.getApplicationImportDTO( + application.getId(), application.getWorkspaceId(), application))); + + StepVerifier.create(resultMono.zipWhen(applicationImportDTO -> Mono.zip( + newActionService + .findAllByApplicationIdAndViewMode( + applicationImportDTO.getApplication().getId(), false, READ_ACTIONS, null) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode( + applicationImportDTO.getApplication().getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findNewPagesByApplicationId( + applicationImportDTO.getApplication().getId(), READ_PAGES) + .collectList()))) .assertNext(tuple -> { Application application = tuple.getT1().getApplication(); List<NewAction> actionList = tuple.getT2().getT1(); @@ -332,59 +360,66 @@ public void test1_cloneWorkspaceWithItsContents() { pageList.forEach(newPage -> { assertThat(newPage.getDefaultResources()).isNotNull(); assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); - assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); - - newPage.getUnpublishedPage() - .getLayouts() - .forEach(layout -> { - assertThat(layout.getLayoutOnLoadActions()).hasSize(2); - layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { - assertThat(dslActionDTOS).hasSize(1); - dslActionDTOS.forEach(actionDTO -> { - assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); - if (!StringUtils.isEmpty(actionDTO.getCollectionId())) { - assertThat(actionDTO.getCollectionId()).isEqualTo(actionDTO.getDefaultCollectionId()); - } - }); - }); - } - ); + assertThat(newPage.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); + + newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + assertThat(layout.getLayoutOnLoadActions()).hasSize(2); + layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { + assertThat(dslActionDTOS).hasSize(1); + dslActionDTOS.forEach(actionDTO -> { + assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); + if (!StringUtils.isEmpty(actionDTO.getCollectionId())) { + assertThat(actionDTO.getCollectionId()) + .isEqualTo(actionDTO.getDefaultCollectionId()); + } + }); + }); + }); }); assertThat(actionList).hasSize(2); actionList.forEach(newAction -> { assertThat(newAction.getDefaultResources()).isNotNull(); - assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + assertThat(newAction.getDefaultResources().getActionId()) + .isEqualTo(newAction.getId()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); ActionDTO action = newAction.getUnpublishedAction(); assertThat(action.getDefaultResources()).isNotNull(); - assertThat(action.getDefaultResources().getPageId()).isEqualTo(application.getPages().get(0).getId()); + assertThat(action.getDefaultResources().getPageId()) + .isEqualTo(application.getPages().get(0).getId()); if (!StringUtils.isEmpty(action.getDefaultResources().getCollectionId())) { - assertThat(action.getDefaultResources().getCollectionId()).isEqualTo(action.getCollectionId()); + assertThat(action.getDefaultResources().getCollectionId()) + .isEqualTo(action.getCollectionId()); } }); assertThat(actionCollectionList).hasSize(1); actionCollectionList.forEach(actionCollection -> { assertThat(actionCollection.getDefaultResources()).isNotNull(); - assertThat(actionCollection.getDefaultResources().getCollectionId()).isEqualTo(actionCollection.getId()); - assertThat(actionCollection.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + assertThat(actionCollection.getDefaultResources().getCollectionId()) + .isEqualTo(actionCollection.getId()); + assertThat(actionCollection.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); assertThat(unpublishedCollection.getDefaultToBranchedActionIdsMap()) .hasSize(1); - unpublishedCollection.getDefaultToBranchedActionIdsMap().keySet() - .forEach(key -> - assertThat(key).isEqualTo(unpublishedCollection.getDefaultToBranchedActionIdsMap().get(key)) - ); + unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .keySet() + .forEach(key -> assertThat(key) + .isEqualTo(unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .get(key))); assertThat(unpublishedCollection.getDefaultResources()).isNotNull(); assertThat(unpublishedCollection.getDefaultResources().getPageId()) .isEqualTo(application.getPages().get(0).getId()); }); - }) .verifyComplete(); } @@ -396,11 +431,14 @@ public void test2_forkApplicationWithReadApplicationUserAccess() { Workspace targetWorkspace = new Workspace(); targetWorkspace.setName("test-user-workspace"); - // Fork application is currently a slow API because it needs to create application, clone all the pages, and then + // Fork application is currently a slow API because it needs to create application, clone all the pages, and + // then // copy all the actions and collections. This process may take time and since some of the test cases in - // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this temporarily, + // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this + // temporarily, // synchronous block() is being used until it is fixed. - // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the timeoutException. + // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the + // timeoutException. Workspace workspace = workspaceService.create(targetWorkspace).block(); testUserWorkspaceId = workspace.getId(); Application targetApplication = applicationForkingService @@ -422,16 +460,15 @@ public void test3_failForkApplicationWithInvalidPermission() { final Mono<ApplicationImportDTO> resultMono = applicationForkingService .forkApplicationToWorkspaceWithEnvironment(sourceAppId, testUserWorkspaceId, sourceEnvironmentId) - .flatMap(application -> importExportApplicationService - .getApplicationImportDTO( - application.getId(), - application.getWorkspaceId(), - application - )); + .flatMap(application -> importExportApplicationService.getApplicationImportDTO( + application.getId(), application.getWorkspaceId(), application)); StepVerifier.create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.WORKSPACE, testUserWorkspaceId))) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.WORKSPACE, testUserWorkspaceId))) .verify(); } @@ -453,22 +490,28 @@ public void test4_validForkApplication_cancelledMidWay_createValidApplication() Mono<Application> forkedAppFromDbMono = Mono.just(targetWorkspace) .flatMap(workspace -> { try { - // Before fetching the forked application, sleep for 5 seconds to ensure that the forking finishes + // Before fetching the forked application, sleep for 5 seconds to ensure that the forking + // finishes Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } - return applicationService.findByWorkspaceId(workspace.getId(), READ_APPLICATIONS).next(); + return applicationService + .findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) + .next(); }) .cache(); - StepVerifier - .create(forkedAppFromDbMono.zipWhen(application -> - Mono.zip( - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findNewPagesByApplicationId(application.getId(), READ_PAGES).collectList())) - ) + StepVerifier.create(forkedAppFromDbMono.zipWhen(application -> Mono.zip( + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findNewPagesByApplicationId(application.getId(), READ_PAGES) + .collectList()))) .assertNext(tuple -> { Application application = tuple.getT1(); List<NewAction> actionList = tuple.getT2().getT1(); @@ -486,47 +529,54 @@ public void test4_validForkApplication_cancelledMidWay_createValidApplication() pageList.forEach(newPage -> { assertThat(newPage.getDefaultResources()).isNotNull(); assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); - assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); - - newPage.getUnpublishedPage() - .getLayouts() - .forEach(layout -> - layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { - dslActionDTOS.forEach(actionDTO -> { - assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); - }); - }) - ); + assertThat(newPage.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); + + newPage.getUnpublishedPage().getLayouts().forEach(layout -> layout.getLayoutOnLoadActions() + .forEach(dslActionDTOS -> { + dslActionDTOS.forEach(actionDTO -> { + assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); + }); + })); }); assertThat(actionList).hasSize(2); actionList.forEach(newAction -> { assertThat(newAction.getDefaultResources()).isNotNull(); - assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); - assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + assertThat(newAction.getDefaultResources().getActionId()) + .isEqualTo(newAction.getId()); + assertThat(newAction.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); ActionDTO action = newAction.getUnpublishedAction(); assertThat(action.getDefaultResources()).isNotNull(); - assertThat(action.getDefaultResources().getPageId()).isEqualTo(application.getPages().get(0).getId()); + assertThat(action.getDefaultResources().getPageId()) + .isEqualTo(application.getPages().get(0).getId()); if (!StringUtils.isEmpty(action.getDefaultResources().getCollectionId())) { - assertThat(action.getDefaultResources().getCollectionId()).isEqualTo(action.getCollectionId()); + assertThat(action.getDefaultResources().getCollectionId()) + .isEqualTo(action.getCollectionId()); } }); assertThat(actionCollectionList).hasSize(1); actionCollectionList.forEach(actionCollection -> { assertThat(actionCollection.getDefaultResources()).isNotNull(); - assertThat(actionCollection.getDefaultResources().getCollectionId()).isEqualTo(actionCollection.getId()); - assertThat(actionCollection.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + assertThat(actionCollection.getDefaultResources().getCollectionId()) + .isEqualTo(actionCollection.getId()); + assertThat(actionCollection.getDefaultResources().getApplicationId()) + .isEqualTo(application.getId()); ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); assertThat(unpublishedCollection.getDefaultToBranchedActionIdsMap()) .hasSize(1); - unpublishedCollection.getDefaultToBranchedActionIdsMap().keySet() - .forEach(key -> - assertThat(key).isEqualTo(unpublishedCollection.getDefaultToBranchedActionIdsMap().get(key)) - ); + unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .keySet() + .forEach(key -> assertThat(key) + .isEqualTo(unpublishedCollection + .getDefaultToBranchedActionIdsMap() + .get(key))); assertThat(unpublishedCollection.getDefaultResources()).isNotNull(); assertThat(unpublishedCollection.getDefaultResources().getPageId()) @@ -534,17 +584,19 @@ public void test4_validForkApplication_cancelledMidWay_createValidApplication() }); }) .verifyComplete(); - } @Test @WithUserDetails("api_user") public void forkApplicationToWorkspace_WhenAppHasUnsavedThemeCustomization_ForkedWithCustomizations() { - // Fork application is currently a slow API because it needs to create application, clone all the pages, and then + // Fork application is currently a slow API because it needs to create application, clone all the pages, and + // then // copy all the actions and collections. This process may take time and since some of the test cases in - // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this temporarily, + // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this + // temporarily, // synchronous block() is being used until it is fixed. - // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the timeoutException. + // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the + // timeoutException. String uniqueString = UUID.randomUUID().toString(); Workspace srcWorkspace = new Workspace(); srcWorkspace.setName("ws_" + uniqueString); @@ -564,17 +616,23 @@ public void forkApplicationToWorkspace_WhenAppHasUnsavedThemeCustomization_Forke theme.setDisplayName("theme_" + uniqueString); themeService.updateTheme(createdSrcApplication.getId(), null, theme).block(); - createdSrcApplication = applicationService.findById(srcApplication.getId()).block(); + createdSrcApplication = + applicationService.findById(srcApplication.getId()).block(); Workspace destWorkspace = new Workspace(); destWorkspace.setName("ws_dest_" + uniqueString); Workspace createdDestWorkspace = workspaceService.create(destWorkspace).block(); Application forkedApplication = applicationForkingService - .forkApplicationToWorkspaceWithEnvironment(createdSrcApplication.getId(), createdDestWorkspace.getId(), createdSrcDefaultEnvironmentId) + .forkApplicationToWorkspaceWithEnvironment( + createdSrcApplication.getId(), createdDestWorkspace.getId(), createdSrcDefaultEnvironmentId) .block(); - Theme forkedApplicationEditModeTheme = themeService.getApplicationTheme(forkedApplication.getId(), ApplicationMode.EDIT, null).block(); - Theme forkedApplicationPublishedModeTheme = themeService.getApplicationTheme(forkedApplication.getId(), ApplicationMode.PUBLISHED, null).block(); + Theme forkedApplicationEditModeTheme = themeService + .getApplicationTheme(forkedApplication.getId(), ApplicationMode.EDIT, null) + .block(); + Theme forkedApplicationPublishedModeTheme = themeService + .getApplicationTheme(forkedApplication.getId(), ApplicationMode.PUBLISHED, null) + .block(); final Mono<Tuple4<Theme, Theme, Application, Application>> tuple4Mono = Mono.zip( Mono.just(forkedApplicationEditModeTheme), @@ -582,46 +640,52 @@ public void forkApplicationToWorkspace_WhenAppHasUnsavedThemeCustomization_Forke Mono.just(forkedApplication), Mono.just(createdSrcApplication)); - StepVerifier.create(tuple4Mono).assertNext(objects -> { - Theme editModeTheme = objects.getT1(); - Theme publishedModeTheme = objects.getT2(); - Application forkedApp = objects.getT3(); - Application srcApp = objects.getT4(); - - assertThat(forkedApp.getEditModeThemeId()).isEqualTo(editModeTheme.getId()); - assertThat(forkedApp.getPublishedModeThemeId()).isEqualTo(publishedModeTheme.getId()); - assertThat(forkedApp.getEditModeThemeId()).isNotEqualTo(forkedApp.getPublishedModeThemeId()); - - // published mode should have the custom theme as we publish after forking the app - assertThat(publishedModeTheme.isSystemTheme()).isFalse(); - // published mode theme will have no application id and org id set as the customizations were not saved - assertThat(publishedModeTheme.getWorkspaceId()).isNullOrEmpty(); - assertThat(publishedModeTheme.getApplicationId()).isNullOrEmpty(); - - // edit mode theme should be a custom one - assertThat(editModeTheme.isSystemTheme()).isFalse(); - // edit mode theme will have no application id and org id set as the customizations were not saved - assertThat(editModeTheme.getWorkspaceId()).isNullOrEmpty(); - assertThat(editModeTheme.getApplicationId()).isNullOrEmpty(); - - // forked theme should have the same name as src theme - assertThat(editModeTheme.getDisplayName()).isEqualTo("theme_" + uniqueString); - assertThat(publishedModeTheme.getDisplayName()).isEqualTo("theme_" + uniqueString); - - // forked application should have a new edit mode theme created, should not be same as src app theme - assertThat(srcApp.getEditModeThemeId()).isNotEqualTo(forkedApp.getEditModeThemeId()); - assertThat(srcApp.getPublishedModeThemeId()).isNotEqualTo(forkedApp.getPublishedModeThemeId()); - }).verifyComplete(); + StepVerifier.create(tuple4Mono) + .assertNext(objects -> { + Theme editModeTheme = objects.getT1(); + Theme publishedModeTheme = objects.getT2(); + Application forkedApp = objects.getT3(); + Application srcApp = objects.getT4(); + + assertThat(forkedApp.getEditModeThemeId()).isEqualTo(editModeTheme.getId()); + assertThat(forkedApp.getPublishedModeThemeId()).isEqualTo(publishedModeTheme.getId()); + assertThat(forkedApp.getEditModeThemeId()).isNotEqualTo(forkedApp.getPublishedModeThemeId()); + + // published mode should have the custom theme as we publish after forking the app + assertThat(publishedModeTheme.isSystemTheme()).isFalse(); + // published mode theme will have no application id and org id set as the customizations were not + // saved + assertThat(publishedModeTheme.getWorkspaceId()).isNullOrEmpty(); + assertThat(publishedModeTheme.getApplicationId()).isNullOrEmpty(); + + // edit mode theme should be a custom one + assertThat(editModeTheme.isSystemTheme()).isFalse(); + // edit mode theme will have no application id and org id set as the customizations were not saved + assertThat(editModeTheme.getWorkspaceId()).isNullOrEmpty(); + assertThat(editModeTheme.getApplicationId()).isNullOrEmpty(); + + // forked theme should have the same name as src theme + assertThat(editModeTheme.getDisplayName()).isEqualTo("theme_" + uniqueString); + assertThat(publishedModeTheme.getDisplayName()).isEqualTo("theme_" + uniqueString); + + // forked application should have a new edit mode theme created, should not be same as src app theme + assertThat(srcApp.getEditModeThemeId()).isNotEqualTo(forkedApp.getEditModeThemeId()); + assertThat(srcApp.getPublishedModeThemeId()).isNotEqualTo(forkedApp.getPublishedModeThemeId()); + }) + .verifyComplete(); } @Test @WithUserDetails("api_user") public void forkApplicationToWorkspace_WhenAppHasSystemTheme_SystemThemeSet() { - // Fork application is currently a slow API because it needs to create application, clone all the pages, and then + // Fork application is currently a slow API because it needs to create application, clone all the pages, and + // then // copy all the actions and collections. This process may take time and since some of the test cases in - // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this temporarily, + // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this + // temporarily, // synchronous block() is being used until it is fixed. - // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the timeoutException. + // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the + // timeoutException. String uniqueString = UUID.randomUUID().toString(); Workspace workspace = new Workspace(); workspace.setName("ws_" + uniqueString); @@ -634,50 +698,61 @@ public void forkApplicationToWorkspace_WhenAppHasSystemTheme_SystemThemeSet() { Application application = new Application(); application.setName("app_" + uniqueString); - Application createdSrcApplication = applicationPageService.createApplication(application, createdWorkspace.getId()).block(); + Application createdSrcApplication = applicationPageService + .createApplication(application, createdWorkspace.getId()) + .block(); Workspace destWorkspace = new Workspace(); destWorkspace.setName("ws_dest_" + uniqueString); Workspace createdDestWorkspace = workspaceService.create(destWorkspace).block(); Application forkedApplication = applicationForkingService - .forkApplicationToWorkspaceWithEnvironment(createdSrcApplication.getId(), createdDestWorkspace.getId(), createdSrcDefaultEnvironmentId) + .forkApplicationToWorkspaceWithEnvironment( + createdSrcApplication.getId(), createdDestWorkspace.getId(), createdSrcDefaultEnvironmentId) + .block(); + Theme forkedApplicationTheme = themeService + .getApplicationTheme(forkedApplication.getId(), ApplicationMode.EDIT, null) .block(); - Theme forkedApplicationTheme = themeService.getApplicationTheme(forkedApplication.getId(), ApplicationMode.EDIT, null).block(); - Mono<Tuple3<Theme, Application, Application>> tuple3Mono = Mono.zip(Mono.just(forkedApplicationTheme), Mono.just(forkedApplication), Mono.just(createdSrcApplication)); + Mono<Tuple3<Theme, Application, Application>> tuple3Mono = Mono.zip( + Mono.just(forkedApplicationTheme), Mono.just(forkedApplication), Mono.just(createdSrcApplication)); - StepVerifier.create(tuple3Mono).assertNext(objects -> { - Theme editModeTheme = objects.getT1(); - Application forkedApp = objects.getT2(); - Application srcApp = objects.getT3(); + StepVerifier.create(tuple3Mono) + .assertNext(objects -> { + Theme editModeTheme = objects.getT1(); + Application forkedApp = objects.getT2(); + Application srcApp = objects.getT3(); - // same theme should be set to edit mode and published mode - assertThat(forkedApp.getEditModeThemeId()).isEqualTo(editModeTheme.getId()); - assertThat(forkedApp.getPublishedModeThemeId()).isEqualTo(editModeTheme.getId()); + // same theme should be set to edit mode and published mode + assertThat(forkedApp.getEditModeThemeId()).isEqualTo(editModeTheme.getId()); + assertThat(forkedApp.getPublishedModeThemeId()).isEqualTo(editModeTheme.getId()); - // edit mode theme should be system theme - assertThat(editModeTheme.isSystemTheme()).isTrue(); - // edit mode theme will have no application id and org id set as it's system theme - assertThat(editModeTheme.getWorkspaceId()).isNullOrEmpty(); - assertThat(editModeTheme.getApplicationId()).isNullOrEmpty(); + // edit mode theme should be system theme + assertThat(editModeTheme.isSystemTheme()).isTrue(); + // edit mode theme will have no application id and org id set as it's system theme + assertThat(editModeTheme.getWorkspaceId()).isNullOrEmpty(); + assertThat(editModeTheme.getApplicationId()).isNullOrEmpty(); - // forked theme should be default theme - assertThat(editModeTheme.getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + // forked theme should be default theme + assertThat(editModeTheme.getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); - // forked application should have same theme set - assertThat(srcApp.getEditModeThemeId()).isEqualTo(forkedApp.getEditModeThemeId()); - }).verifyComplete(); + // forked application should have same theme set + assertThat(srcApp.getEditModeThemeId()).isEqualTo(forkedApp.getEditModeThemeId()); + }) + .verifyComplete(); } @Test @WithUserDetails("api_user") public void forkApplicationToWorkspace_WhenAppHasCustomSavedTheme_NewCustomThemeCreated() { - // Fork application is currently a slow API because it needs to create application, clone all the pages, and then + // Fork application is currently a slow API because it needs to create application, clone all the pages, and + // then // copy all the actions and collections. This process may take time and since some of the test cases in - // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this temporarily, + // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this + // temporarily, // synchronous block() is being used until it is fixed. - // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the timeoutException. + // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the + // timeoutException. String uniqueString = UUID.randomUUID().toString(); Workspace workspace = new Workspace(); workspace.setName("ws_" + uniqueString); @@ -689,69 +764,88 @@ public void forkApplicationToWorkspace_WhenAppHasCustomSavedTheme_NewCustomTheme Application application = new Application(); application.setName("app_" + uniqueString); - Application createdSrcApplication = applicationPageService.createApplication(application, createdSrcWorkspace.getId()).block(); + Application createdSrcApplication = applicationPageService + .createApplication(application, createdSrcWorkspace.getId()) + .block(); Theme theme = new Theme(); theme.setDisplayName("theme_" + uniqueString); themeService.updateTheme(createdSrcApplication.getId(), null, theme).block(); - themeService.persistCurrentTheme(createdSrcApplication.getId(), null, theme).block(); - createdSrcApplication = applicationService.findById(createdSrcApplication.getId()).block(); + themeService + .persistCurrentTheme(createdSrcApplication.getId(), null, theme) + .block(); + createdSrcApplication = + applicationService.findById(createdSrcApplication.getId()).block(); Workspace destWorkspace = new Workspace(); destWorkspace.setName("ws_dest_" + uniqueString); Workspace createdDestWorkspace = workspaceService.create(destWorkspace).block(); Application forkedApplication = applicationForkingService - .forkApplicationToWorkspaceWithEnvironment(createdSrcApplication.getId(), createdDestWorkspace.getId(), createdSrcDefaultEnvironmentId) + .forkApplicationToWorkspaceWithEnvironment( + createdSrcApplication.getId(), createdDestWorkspace.getId(), createdSrcDefaultEnvironmentId) .block(); - Theme forkedApplicationEditModeTheme = themeService.getApplicationTheme(forkedApplication.getId(), ApplicationMode.EDIT, null).block(); - Theme forkedApplicationPublishedModeTheme = themeService.getApplicationTheme(forkedApplication.getId(), ApplicationMode.PUBLISHED, null).block(); + Theme forkedApplicationEditModeTheme = themeService + .getApplicationTheme(forkedApplication.getId(), ApplicationMode.EDIT, null) + .block(); + Theme forkedApplicationPublishedModeTheme = themeService + .getApplicationTheme(forkedApplication.getId(), ApplicationMode.PUBLISHED, null) + .block(); - Mono<Tuple4<Theme, Theme, Application, Application>> tuple4Mono = Mono.zip(Mono.just(forkedApplicationEditModeTheme), Mono.just(forkedApplicationPublishedModeTheme), Mono.just(forkedApplication), Mono.just(createdSrcApplication)); + Mono<Tuple4<Theme, Theme, Application, Application>> tuple4Mono = Mono.zip( + Mono.just(forkedApplicationEditModeTheme), + Mono.just(forkedApplicationPublishedModeTheme), + Mono.just(forkedApplication), + Mono.just(createdSrcApplication)); - StepVerifier.create(tuple4Mono).assertNext(objects -> { - Theme editModeTheme = objects.getT1(); - Theme publishedModeTheme = objects.getT2(); - Application forkedApp = objects.getT3(); - Application srcApp = objects.getT4(); + StepVerifier.create(tuple4Mono) + .assertNext(objects -> { + Theme editModeTheme = objects.getT1(); + Theme publishedModeTheme = objects.getT2(); + Application forkedApp = objects.getT3(); + Application srcApp = objects.getT4(); - assertThat(forkedApp.getEditModeThemeId()).isEqualTo(editModeTheme.getId()); - assertThat(forkedApp.getPublishedModeThemeId()).isEqualTo(publishedModeTheme.getId()); - assertThat(forkedApp.getEditModeThemeId()).isNotEqualTo(forkedApp.getPublishedModeThemeId()); + assertThat(forkedApp.getEditModeThemeId()).isEqualTo(editModeTheme.getId()); + assertThat(forkedApp.getPublishedModeThemeId()).isEqualTo(publishedModeTheme.getId()); + assertThat(forkedApp.getEditModeThemeId()).isNotEqualTo(forkedApp.getPublishedModeThemeId()); - // published mode should have the custom theme as we publish after forking the app - assertThat(publishedModeTheme.isSystemTheme()).isFalse(); + // published mode should have the custom theme as we publish after forking the app + assertThat(publishedModeTheme.isSystemTheme()).isFalse(); - // published mode theme will have no application id and org id set as it's a copy - assertThat(publishedModeTheme.getWorkspaceId()).isNullOrEmpty(); - assertThat(publishedModeTheme.getApplicationId()).isNullOrEmpty(); + // published mode theme will have no application id and org id set as it's a copy + assertThat(publishedModeTheme.getWorkspaceId()).isNullOrEmpty(); + assertThat(publishedModeTheme.getApplicationId()).isNullOrEmpty(); - // edit mode theme should be a custom one - assertThat(editModeTheme.isSystemTheme()).isFalse(); + // edit mode theme should be a custom one + assertThat(editModeTheme.isSystemTheme()).isFalse(); - // edit mode theme will have application id and org id set as the customizations were saved - assertThat(editModeTheme.getWorkspaceId()).isNullOrEmpty(); - assertThat(editModeTheme.getApplicationId()).isNullOrEmpty(); + // edit mode theme will have application id and org id set as the customizations were saved + assertThat(editModeTheme.getWorkspaceId()).isNullOrEmpty(); + assertThat(editModeTheme.getApplicationId()).isNullOrEmpty(); - // forked theme should have the same name as src theme - assertThat(editModeTheme.getDisplayName()).isEqualTo("theme_" + uniqueString); - assertThat(publishedModeTheme.getDisplayName()).isEqualTo("theme_" + uniqueString); + // forked theme should have the same name as src theme + assertThat(editModeTheme.getDisplayName()).isEqualTo("theme_" + uniqueString); + assertThat(publishedModeTheme.getDisplayName()).isEqualTo("theme_" + uniqueString); - // forked application should have a new edit mode theme created, should not be same as src app theme - assertThat(srcApp.getEditModeThemeId()).isNotEqualTo(forkedApp.getEditModeThemeId()); - assertThat(srcApp.getPublishedModeThemeId()).isNotEqualTo(forkedApp.getPublishedModeThemeId()); - }).verifyComplete(); + // forked application should have a new edit mode theme created, should not be same as src app theme + assertThat(srcApp.getEditModeThemeId()).isNotEqualTo(forkedApp.getEditModeThemeId()); + assertThat(srcApp.getPublishedModeThemeId()).isNotEqualTo(forkedApp.getPublishedModeThemeId()); + }) + .verifyComplete(); } @Test @WithUserDetails(value = "api_user") public void forkApplication_deletePageAfterBeingPublished_deletedPageIsNotCloned() { - // Fork application is currently a slow API because it needs to create application, clone all the pages, and then + // Fork application is currently a slow API because it needs to create application, clone all the pages, and + // then // copy all the actions and collections. This process may take time and since some of the test cases in - // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this temporarily, + // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this + // temporarily, // synchronous block() is being used until it is fixed. - // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the timeoutException. + // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the + // timeoutException. Workspace targetWorkspace = new Workspace(); targetWorkspace.setName("delete-edit-mode-page-target-org"); targetWorkspace = workspaceService.create(targetWorkspace).block(); @@ -762,28 +856,36 @@ public void forkApplication_deletePageAfterBeingPublished_deletedPageIsNotCloned srcWorkspace.setName("delete-edit-mode-page-src-org"); srcWorkspace = workspaceService.create(srcWorkspace).block(); - String srcDefaultEnvironmentId = workspaceService - .getDefaultEnvironmentId(srcWorkspace.getId()) - .block(); + String srcDefaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(srcWorkspace.getId()).block(); Application application = new Application(); application.setName("delete-edit-mode-page-app"); assert srcWorkspace != null; - final String originalAppId = Objects.requireNonNull(applicationPageService.createApplication(application, srcWorkspace.getId()).block()).getId(); + final String originalAppId = Objects.requireNonNull(applicationPageService + .createApplication(application, srcWorkspace.getId()) + .block()) + .getId(); PageDTO pageDTO = new PageDTO(); pageDTO.setName("delete-edit-mode-page"); pageDTO.setApplicationId(originalAppId); - final String pageId = Objects.requireNonNull(applicationPageService.createPage(pageDTO).block()).getId(); + final String pageId = Objects.requireNonNull( + applicationPageService.createPage(pageDTO).block()) + .getId(); applicationPageService.publish(originalAppId, true).block(); applicationPageService.deleteUnpublishedPage(pageId).block(); Application resultApplication = applicationForkingService - .forkApplicationToWorkspaceWithEnvironment(pageDTO.getApplicationId(), targetWorkspaceId, srcDefaultEnvironmentId) + .forkApplicationToWorkspaceWithEnvironment( + pageDTO.getApplicationId(), targetWorkspaceId, srcDefaultEnvironmentId) .block(); final Mono<Application> resultMono = Mono.just(resultApplication); - StepVerifier.create(resultMono - .zipWhen(application1 -> newPageService.findNewPagesByApplicationId(application1.getId(), READ_PAGES).collectList() - .zipWith(newPageService.findNewPagesByApplicationId(originalAppId, READ_PAGES).collectList()))) + StepVerifier.create(resultMono.zipWhen(application1 -> newPageService + .findNewPagesByApplicationId(application1.getId(), READ_PAGES) + .collectList() + .zipWith(newPageService + .findNewPagesByApplicationId(originalAppId, READ_PAGES) + .collectList()))) .assertNext(tuple -> { Application forkedApplication = tuple.getT1(); List<NewPage> forkedPages = tuple.getT2().getT1(); @@ -792,9 +894,11 @@ public void forkApplication_deletePageAfterBeingPublished_deletedPageIsNotCloned assertThat(forkedApplication).isNotNull(); assertThat(forkedPages).hasSize(1); assertThat(originalPages).hasSize(2); - forkedPages.forEach(newPage -> assertThat(newPage.getUnpublishedPage().getName()).isNotEqualTo(pageDTO.getName())); + forkedPages.forEach(newPage -> + assertThat(newPage.getUnpublishedPage().getName()).isNotEqualTo(pageDTO.getName())); NewPage deletedPage = originalPages.stream() - .filter(newPage -> pageDTO.getName().equals(newPage.getUnpublishedPage().getName())) + .filter(newPage -> pageDTO.getName() + .equals(newPage.getUnpublishedPage().getName())) .findAny() .orElse(null); assert deletedPage != null; @@ -808,18 +912,21 @@ private Flux<ActionDTO> getActionsInWorkspace(Workspace workspace) { .findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) // fetch the unpublished pages .flatMap(application -> newPageService.findByApplicationId(application.getId(), READ_PAGES, false)) - .flatMap(page -> newActionService.getUnpublishedActionsExceptJs(new LinkedMultiValueMap<>( - Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))))); + .flatMap(page -> newActionService.getUnpublishedActionsExceptJs( + new LinkedMultiValueMap<>(Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))))); } @Test @WithUserDetails(value = "api_user") public void forkGitConnectedApplication_defaultBranchUpdated_forkDefaultBranchApplication() { - // Fork application is currently a slow API because it needs to create application, clone all the pages, and then + // Fork application is currently a slow API because it needs to create application, clone all the pages, and + // then // copy all the actions and collections. This process may take time and since some of the test cases in - // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this temporarily, + // ApplicationForkingServiceTests observed failure in the CI due to timeoutException, to unblock this + // temporarily, // synchronous block() is being used until it is fixed. - // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the timeoutException. + // TODO: Investigate working of applicationForkingService.forkApplicationToWorkspace() further and fix the + // timeoutException. String uniqueString = UUID.randomUUID().toString(); Workspace workspace = new Workspace(); workspace.setName("ws_" + uniqueString); @@ -831,7 +938,9 @@ public void forkGitConnectedApplication_defaultBranchUpdated_forkDefaultBranchAp Application application = new Application(); application.setName("app_" + uniqueString); - Application createdSrcApplication = applicationPageService.createApplication(application, createdWorkspace.getId()).block(); + Application createdSrcApplication = applicationPageService + .createApplication(application, createdWorkspace.getId()) + .block(); Theme theme = new Theme(); theme.setDisplayName("theme_" + uniqueString); @@ -853,7 +962,9 @@ public void forkGitConnectedApplication_defaultBranchUpdated_forkDefaultBranchAp // Create a branch application Application branchApp = new Application(); branchApp.setName("app_" + uniqueString); - Application createdBranchApplication = applicationPageService.createApplication(branchApp, createdSrcApplication.getWorkspaceId()).block(); + Application createdBranchApplication = applicationPageService + .createApplication(branchApp, createdSrcApplication.getWorkspaceId()) + .block(); GitApplicationMetadata gitApplicationMetadata1 = new GitApplicationMetadata(); gitApplicationMetadata1.setDefaultApplicationId(createdSrcApplication.getId()); @@ -862,7 +973,8 @@ public void forkGitConnectedApplication_defaultBranchUpdated_forkDefaultBranchAp gitApplicationMetadata1.setIsRepoPrivate(false); gitApplicationMetadata1.setRepoName("testRepo"); createdBranchApplication.setGitApplicationMetadata(gitApplicationMetadata1); - createdBranchApplication = applicationService.save(createdBranchApplication).block(); + createdBranchApplication = + applicationService.save(createdBranchApplication).block(); PageDTO page = new PageDTO(); page.setName("discard-page-test"); @@ -881,11 +993,11 @@ public void forkGitConnectedApplication_defaultBranchUpdated_forkDefaultBranchAp Mono<Application> applicationMono = Mono.just(resultApplication); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(forkedApplication -> { assertThat(forkedApplication.getPages().size()).isEqualTo(1); - }).verifyComplete(); + }) + .verifyComplete(); } @Test @@ -901,25 +1013,26 @@ public void forkApplication_WhenContainsInternalFields_InternalFieldsNotForked() srcWorkspace.setName("fork-internal-fields-src-org"); srcWorkspace = workspaceService.create(srcWorkspace).block(); - String createdSrcDefaultEnvironmentId = workspaceService - .getDefaultEnvironmentId(srcWorkspace.getId()) - .block(); + String createdSrcDefaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(srcWorkspace.getId()).block(); Application application = new Application(); application.setName("fork-internal-fields-app"); assert srcWorkspace != null; - Application srcApp = applicationPageService.createApplication(application, srcWorkspace.getId()).block(); + Application srcApp = applicationPageService + .createApplication(application, srcWorkspace.getId()) + .block(); srcApp.setForkWithConfiguration(true); srcApp.setExportWithConfiguration(true); srcApp.setForkingEnabled(true); Application resultApplication = applicationForkingService - .forkApplicationToWorkspaceWithEnvironment(srcApp.getId(), targetWorkspaceId, createdSrcDefaultEnvironmentId) + .forkApplicationToWorkspaceWithEnvironment( + srcApp.getId(), targetWorkspaceId, createdSrcDefaultEnvironmentId) .block(); final Mono<Application> resultMono = Mono.just(resultApplication); StepVerifier.create(resultMono) .assertNext(forkedApplication -> { - assertThat(forkedApplication).isNotNull(); assertThat(forkedApplication.getForkWithConfiguration()).isNull(); assertThat(forkedApplication.getExportWithConfiguration()).isNull(); @@ -928,7 +1041,8 @@ public void forkApplication_WhenContainsInternalFields_InternalFieldsNotForked() .verifyComplete(); } - private Mono<Tuple2<Application, String>> forkApplicationSetup(Boolean forkWithConfiguration, Boolean connectDatasourceToAction) { + private Mono<Tuple2<Application, String>> forkApplicationSetup( + Boolean forkWithConfiguration, Boolean connectDatasourceToAction) { Workspace targetWorkspace = new Workspace(); targetWorkspace.setName("target-org"); targetWorkspace = workspaceService.create(targetWorkspace).block(); @@ -939,15 +1053,16 @@ private Mono<Tuple2<Application, String>> forkApplicationSetup(Boolean forkWithC srcWorkspace.setName("src-org"); srcWorkspace = workspaceService.create(srcWorkspace).block(); - String srcDefaultEnvironmentId = workspaceService - .getDefaultEnvironmentId(srcWorkspace.getId()) - .block(); + String srcDefaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(srcWorkspace.getId()).block(); Application application = new Application(); application.setName("app1"); application.setForkWithConfiguration(forkWithConfiguration); assert srcWorkspace != null; - Application srcApp = applicationPageService.createApplication(application, srcWorkspace.getId()).block(); + Application srcApp = applicationPageService + .createApplication(application, srcWorkspace.getId()) + .block(); Datasource datasource = new Datasource(); datasource.setName("test db datasource1"); @@ -973,7 +1088,8 @@ private Mono<Tuple2<Application, String>> forkApplicationSetup(Boolean forkWithC storages.put(srcDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); - Plugin installed_plugin = pluginRepository.findByPackageName("installed-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("installed-plugin").block(); datasource.setPluginId(installed_plugin.getId()); Datasource createdDatasource = datasourceService.create(datasource).block(); @@ -996,7 +1112,8 @@ private Mono<Tuple2<Application, String>> forkApplicationSetup(Boolean forkWithC @Test @WithUserDetails(value = "api_user") public void forkApplication_withForkWithConfigurationFalseAndDatasourceUsed_IsPartialImportTrue() { - Tuple2<Application, String> forkApplicationSetupResponse = forkApplicationSetup(false, true).block(); + Tuple2<Application, String> forkApplicationSetupResponse = + forkApplicationSetup(false, true).block(); Application srcApp = forkApplicationSetupResponse.getT1(); String targetWorkspaceId = forkApplicationSetupResponse.getT2(); @@ -1006,12 +1123,8 @@ public void forkApplication_withForkWithConfigurationFalseAndDatasourceUsed_IsPa Mono<ApplicationImportDTO> resultMono = applicationForkingService .forkApplicationToWorkspaceWithEnvironment(srcApp.getId(), targetWorkspaceId, srcDefaultEnvironmentId) - .flatMap(application -> importExportApplicationService - .getApplicationImportDTO( - application.getId(), - application.getWorkspaceId(), - application - )); + .flatMap(application -> importExportApplicationService.getApplicationImportDTO( + application.getId(), application.getWorkspaceId(), application)); StepVerifier.create(resultMono) .assertNext(forkedApplicationImportDTO -> { @@ -1023,13 +1136,13 @@ public void forkApplication_withForkWithConfigurationFalseAndDatasourceUsed_IsPa assertThat(forkedApplication.getForkingEnabled()).isNull(); }) .verifyComplete(); - } @Test @WithUserDetails(value = "api_user") public void forkApplication_withForkWithConfigurationFalseAndDatasourceNotUsed_IsPartialImportFalse() { - Tuple2<Application, String> forkApplicationSetupResponse = forkApplicationSetup(false, false).block(); + Tuple2<Application, String> forkApplicationSetupResponse = + forkApplicationSetup(false, false).block(); Application srcApp = forkApplicationSetupResponse.getT1(); String targetWorkspaceId = forkApplicationSetupResponse.getT2(); @@ -1039,12 +1152,8 @@ public void forkApplication_withForkWithConfigurationFalseAndDatasourceNotUsed_I Mono<ApplicationImportDTO> resultMono = applicationForkingService .forkApplicationToWorkspaceWithEnvironment(srcApp.getId(), targetWorkspaceId, srcDefaultEnvironmentId) - .flatMap(application -> importExportApplicationService - .getApplicationImportDTO( - application.getId(), - application.getWorkspaceId(), - application - )); + .flatMap(application -> importExportApplicationService.getApplicationImportDTO( + application.getId(), application.getWorkspaceId(), application)); StepVerifier.create(resultMono) .assertNext(forkedApplicationImportDTO -> { @@ -1056,13 +1165,13 @@ public void forkApplication_withForkWithConfigurationFalseAndDatasourceNotUsed_I assertThat(forkedApplication.getForkingEnabled()).isNull(); }) .verifyComplete(); - } @Test @WithUserDetails(value = "api_user") public void forkApplication_withForkWithConfigurationTrue_IsPartialImportFalse() { - Tuple2<Application, String> forkApplicationSetupResponse = forkApplicationSetup(true, true).block(); + Tuple2<Application, String> forkApplicationSetupResponse = + forkApplicationSetup(true, true).block(); Application srcApp = forkApplicationSetupResponse.getT1(); String targetWorkspaceId = forkApplicationSetupResponse.getT2(); @@ -1072,12 +1181,8 @@ public void forkApplication_withForkWithConfigurationTrue_IsPartialImportFalse() Mono<ApplicationImportDTO> resultMono = applicationForkingService .forkApplicationToWorkspaceWithEnvironment(srcApp.getId(), targetWorkspaceId, srcDefaultEnvironmentId) - .flatMap(application -> importExportApplicationService - .getApplicationImportDTO( - application.getId(), - application.getWorkspaceId(), - application - )); + .flatMap(application -> importExportApplicationService.getApplicationImportDTO( + application.getId(), application.getWorkspaceId(), application)); StepVerifier.create(resultMono) .assertNext(forkedApplicationImportDTO -> { @@ -1089,7 +1194,6 @@ public void forkApplication_withForkWithConfigurationTrue_IsPartialImportFalse() assertThat(forkedApplication.getForkingEnabled()).isNull(); }) .verifyComplete(); - } private static class WorkspaceData { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/AuthenticationServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/AuthenticationServiceTest.java index 161201005ec9..3f7d848b68cc 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/AuthenticationServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/AuthenticationServiceTest.java @@ -76,21 +76,14 @@ public class AuthenticationServiceTest { @Test @WithUserDetails(value = "api_user") public void testGetAuthorizationCodeURL_missingDatasource() { - Mono<String> authorizationCodeUrlMono = authenticationService - .getAuthorizationCodeURLForGenericOAuth2( - "invalidId", - FieldName.UNUSED_ENVIRONMENT_ID, - "irrelevantPageId", - null); - - StepVerifier - .create(authorizationCodeUrlMono) - .expectErrorMatches(throwable -> - throwable instanceof AppsmithException && - ((AppsmithException) throwable).getError().equals(AppsmithError.NO_RESOURCE_FOUND) && - throwable.getMessage().equalsIgnoreCase("Unable to find datasource invalidId")) - .verify(); + Mono<String> authorizationCodeUrlMono = authenticationService.getAuthorizationCodeURLForGenericOAuth2( + "invalidId", FieldName.UNUSED_ENVIRONMENT_ID, "irrelevantPageId", null); + StepVerifier.create(authorizationCodeUrlMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && ((AppsmithException) throwable).getError().equals(AppsmithError.NO_RESOURCE_FOUND) + && throwable.getMessage().equalsIgnoreCase("Unable to find datasource invalidId")) + .verify(); } @Test @@ -102,9 +95,11 @@ public void testGetAuthorizationCodeURL_invalidDatasourceWithNullAuthentication( assert testWorkspace != null; String workspaceId = testWorkspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mono<Plugin> pluginMono = pluginService.findByName("Installed Plugin Name"); Datasource datasource = new Datasource(); @@ -125,46 +120,45 @@ public void testGetAuthorizationCodeURL_invalidDatasourceWithNullAuthentication( .flatMap(datasourceService::create) .cache(); - Mono<String> authorizationCodeUrlMono = datasourceMono.map(BaseDomain::getId) + Mono<String> authorizationCodeUrlMono = datasourceMono + .map(BaseDomain::getId) .flatMap(datasourceId -> authenticationService.getAuthorizationCodeURLForGenericOAuth2( - datasourceId, - defaultEnvironmentId, - "irrelevantPageId", - null)); - - StepVerifier - .create(authorizationCodeUrlMono) - .expectErrorMatches(throwable -> - throwable instanceof AppsmithException && - ((AppsmithException) throwable).getError().equals(AppsmithError.INVALID_PARAMETER) && - throwable.getMessage().equalsIgnoreCase("Please enter a valid parameter authentication.")) + datasourceId, defaultEnvironmentId, "irrelevantPageId", null)); + + StepVerifier.create(authorizationCodeUrlMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && ((AppsmithException) throwable).getError().equals(AppsmithError.INVALID_PARAMETER) + && throwable.getMessage().equalsIgnoreCase("Please enter a valid parameter authentication.")) .verify(); } - @Test @WithUserDetails(value = "api_user") public void testGetAuthorizationCodeURL_validDatasource() { LinkedMultiValueMap<String, String> mockHeaders = new LinkedMultiValueMap<>(1); mockHeaders.add(HttpHeaders.REFERER, "https://mock.origin.com/source/uri"); - MockServerHttpRequest httpRequest = MockServerHttpRequest.get("").headers(mockHeaders).build(); + MockServerHttpRequest httpRequest = + MockServerHttpRequest.get("").headers(mockHeaders).build(); Workspace testWorkspace = new Workspace(); testWorkspace.setName("Another Test Workspace"); testWorkspace = workspaceService.create(testWorkspace).block(); assert testWorkspace != null; String workspaceId = testWorkspace.getId(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); PageDTO testPage = new PageDTO(); testPage.setName("PageServiceTest TestApp"); Application newApp = new Application(); newApp.setName(UUID.randomUUID().toString()); - Application application = applicationPageService.createApplication(newApp, workspaceId).block(); + Application application = + applicationPageService.createApplication(newApp, workspaceId).block(); testPage.setApplicationId(application.getId()); @@ -172,9 +166,15 @@ public void testGetAuthorizationCodeURL_validDatasource() { Mono<Plugin> pluginMono = pluginService.findByName("Installed Plugin Name"); // install plugin - pluginMono.flatMap(plugin -> { - return pluginService.installPlugin(PluginWorkspaceDTO.builder().pluginId(plugin.getId()).workspaceId(workspaceId).status(WorkspacePluginStatus.FREE).build()); - }).block(); + pluginMono + .flatMap(plugin -> { + return pluginService.installPlugin(PluginWorkspaceDTO.builder() + .pluginId(plugin.getId()) + .workspaceId(workspaceId) + .status(WorkspacePluginStatus.FREE) + .build()); + }) + .block(); Datasource datasource = new Datasource(); datasource.setName("Valid datasource for OAuth2"); datasource.setWorkspaceId(workspaceId); @@ -204,21 +204,23 @@ public void testGetAuthorizationCodeURL_validDatasource() { final String datasourceId1 = datasourceMono.map(BaseDomain::getId).block(); Mono<String> authorizationCodeUrlMono = authenticationService.getAuthorizationCodeURLForGenericOAuth2( - datasourceId1, - defaultEnvironmentId, - pageDto.getId(), - httpRequest); + datasourceId1, defaultEnvironmentId, pageDto.getId(), httpRequest); - StepVerifier - .create(authorizationCodeUrlMono) + StepVerifier.create(authorizationCodeUrlMono) .assertNext(url -> { - assertThat(url).matches(Pattern.compile("AuthorizationURL" + - "\\?client_id=ClientId" + - "&response_type=code" + - "&redirect_uri=https://mock.origin.com/api/v1/datasources/authorize" + - "&state=" + String.join(",", pageDto.getId(), datasourceId1, defaultEnvironmentId, "https://mock.origin.com") + - "&scope=Scope\\d%20Scope\\d" + - "&key=value")); + assertThat(url) + .matches(Pattern.compile("AuthorizationURL" + "\\?client_id=ClientId" + + "&response_type=code" + + "&redirect_uri=https://mock.origin.com/api/v1/datasources/authorize" + + "&state=" + + String.join( + ",", + pageDto.getId(), + datasourceId1, + defaultEnvironmentId, + "https://mock.origin.com") + + "&scope=Scope\\d%20Scope\\d" + + "&key=value")); }) .verifyComplete(); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/CreateDBTablePageSolutionTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/CreateDBTablePageSolutionTests.java index 2097c93cb532..697e0e873d37 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/CreateDBTablePageSolutionTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/CreateDBTablePageSolutionTests.java @@ -69,8 +69,8 @@ public class CreateDBTablePageSolutionTests { // Regex to break string in separate words - final static String specialCharactersRegex = "[^a-zA-Z0-9,;(){}*_]+"; - private final static String DATA = "data"; + static final String specialCharactersRegex = "[^a-zA-Z0-9,;(){}*_]+"; + private static final String DATA = "data"; private static final Datasource testDatasource = new Datasource(); private static final DatasourceStorageStructure testDatasourceStructure = new DatasourceStorageStructure(); private static Workspace testWorkspace; @@ -84,113 +84,126 @@ public class CreateDBTablePageSolutionTests { private final String UPDATE_QUERY = "UpdateQuery"; private final String INSERT_QUERY = "InsertQuery"; private final Map<String, String> actionNameToBodyMap = Map.of( - "DeleteQuery", "DELETE FROM sampleTable\n" + - " WHERE \"id\" = {{data_table.triggeredRow.id}};", - - "InsertQuery", "INSERT INTO sampleTable (\n" + - "\t\"field1.something\", \n" + - "\t\"field2\",\n" + - "\t\"field3\", \n" + - "\t\"field4\"\n" + - ")\n" + - "VALUES (\n" + - "\t\t\t\t{{insert_form.formData.field1.something}}, \n" + - "\t\t\t\t{{insert_form.formData.field2}}, \n" + - "\t\t\t\t{{insert_form.formData.field3}}, \n" + - "\t\t\t\t{{insert_form.formData.field4}}\n" + - ");", - - "SelectQuery", "SELECT * FROM sampleTable\n" + - "WHERE \"field1.something\" like '%{{data_table.searchText || \"\"}}%'\n" + - "ORDER BY \"{{data_table.sortOrder.column || 'id'}}\" {{data_table.sortOrder.order || 'ASC'}}\n" + - "LIMIT {{data_table.pageSize}}" + - "OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}};", - - "UpdateQuery", "UPDATE sampleTable SET\n" + - "\t\t\"field1.something\" = '{{update_form.fieldState.field1.something.isVisible ? update_form.formData.field1.something : update_form.sourceData.field1.something}}',\n" + - " \"field2\" = '{{update_form.fieldState.field2.isVisible ? update_form.formData.field2 : update_form.sourceData.field2}}',\n" + - " \"field3\" = '{{update_form.fieldState.field3.isVisible ? update_form.formData.field3 : update_form.sourceData.field3}}',\n" + - "\t\t\"field4\" = '{{update_form.fieldState.field4.isVisible ? update_form.formData.field4 : update_form.sourceData.field4}}'\n" + - " WHERE \"id\" = {{data_table.selectedRow.id}};", - - "UpdateActionWithLessColumns", "UPDATE limitedColumnTable SET\n" + - "\t\t\"field1.something\" = '{{update_form.fieldState.field1.something.isVisible ? update_form.formData.field1.something : update_form.sourceData.field1.something}}'\n" + - " WHERE \"id\" = {{data_table.selectedRow.id}};", - - "InsertActionWithLessColumns", "INSERT INTO limitedColumnTable (\n" + - "\t\"field1.something\" \n" + - ")\n" + - "VALUES (\n" + - "\t\t\t\t{{insert_form.formData.field1.something}} \n" + - ");" - ); + "DeleteQuery", "DELETE FROM sampleTable\n" + " WHERE \"id\" = {{data_table.triggeredRow.id}};", + "InsertQuery", + "INSERT INTO sampleTable (\n" + "\t\"field1.something\", \n" + + "\t\"field2\",\n" + + "\t\"field3\", \n" + + "\t\"field4\"\n" + + ")\n" + + "VALUES (\n" + + "\t\t\t\t{{insert_form.formData.field1.something}}, \n" + + "\t\t\t\t{{insert_form.formData.field2}}, \n" + + "\t\t\t\t{{insert_form.formData.field3}}, \n" + + "\t\t\t\t{{insert_form.formData.field4}}\n" + + ");", + "SelectQuery", + "SELECT * FROM sampleTable\n" + + "WHERE \"field1.something\" like '%{{data_table.searchText || \"\"}}%'\n" + + "ORDER BY \"{{data_table.sortOrder.column || 'id'}}\" {{data_table.sortOrder.order || 'ASC'}}\n" + + "LIMIT {{data_table.pageSize}}" + + "OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}};", + "UpdateQuery", + "UPDATE sampleTable SET\n" + + "\t\t\"field1.something\" = '{{update_form.fieldState.field1.something.isVisible ? update_form.formData.field1.something : update_form.sourceData.field1.something}}',\n" + + " \"field2\" = '{{update_form.fieldState.field2.isVisible ? update_form.formData.field2 : update_form.sourceData.field2}}',\n" + + " \"field3\" = '{{update_form.fieldState.field3.isVisible ? update_form.formData.field3 : update_form.sourceData.field3}}',\n" + + "\t\t\"field4\" = '{{update_form.fieldState.field4.isVisible ? update_form.formData.field4 : update_form.sourceData.field4}}'\n" + + " WHERE \"id\" = {{data_table.selectedRow.id}};", + "UpdateActionWithLessColumns", + "UPDATE limitedColumnTable SET\n" + + "\t\t\"field1.something\" = '{{update_form.fieldState.field1.something.isVisible ? update_form.formData.field1.something : update_form.sourceData.field1.something}}'\n" + + " WHERE \"id\" = {{data_table.selectedRow.id}};", + "InsertActionWithLessColumns", + "INSERT INTO limitedColumnTable (\n" + "\t\"field1.something\" \n" + + ")\n" + + "VALUES (\n" + + "\t\t\t\t{{insert_form.formData.field1.something}} \n" + + ");"); + @Autowired CreateDBTablePageSolution solution; + @Autowired NewActionService newActionService; + @Autowired NewPageService newPageService; + @Autowired WorkspaceService workspaceService; + @Autowired DatasourceService datasourceService; + @Autowired DatasourceStructureService datasourceStructureService; + @Autowired ApplicationPageService applicationPageService; + @Autowired PluginRepository pluginRepository; + @Autowired ImportExportApplicationService importExportApplicationService; + @Autowired ApplicationService applicationService; + DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); + @MockBean private PluginExecutorHelper pluginExecutorHelper; + private final CRUDPageResourceDTO resource = new CRUDPageResourceDTO(); @BeforeEach @WithUserDetails(value = "api_user") public void setup() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); - Mockito.when(pluginExecutorHelper.getPluginExecutorFromPackageName(Mockito.anyString())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutorFromPackageName(Mockito.anyString())) + .thenReturn(Mono.just(new MockPluginExecutor())); if (testWorkspace == null) { Workspace workspace = new Workspace(); workspace.setName("Create-DB-Table-Page-Org"); testWorkspace = workspaceService.create(workspace).block(); - testDefaultEnvironmentId = workspaceService.getDefaultEnvironmentId(testWorkspace.getId()).block(); + testDefaultEnvironmentId = workspaceService + .getDefaultEnvironmentId(testWorkspace.getId()) + .block(); } if (testApp == null) { Application testApplication = new Application(); testApplication.setName("DB-Table-Page-Test-Application"); testApplication.setWorkspaceId(testWorkspace.getId()); - testApp = applicationPageService.createApplication(testApplication, testWorkspace.getId()).block(); + testApp = applicationPageService + .createApplication(testApplication, testWorkspace.getId()) + .block(); } if (StringUtils.isEmpty(testDatasource.getId())) { postgreSQLPlugin = pluginRepository.findByName("PostgreSQL").block(); - // This datasource structure includes only 1 table with 2 columns. This is to test the scenario where template table - // have more number of columns than the user provided table which leads to deleting the column names from action configuration + // This datasource structure includes only 1 table with 2 columns. This is to test the scenario where + // template table + // have more number of columns than the user provided table which leads to deleting the column names from + // action configuration List<Column> limitedColumns = List.of( - new Column("id", "type1", null, true), - new Column("field1.something", "VARCHAR(23)", null, false) - ); + new Column("id", "type1", null, true), new Column("field1.something", "VARCHAR(23)", null, false)); List<Key> keys = List.of(new DatasourceStructure.PrimaryKey("pKey", List.of("id"))); List<Column> columns = List.of( new Column("id", "type1", null, true), new Column("field1.something", "VARCHAR(23)", null, false), new Column("field2", "type3", null, false), new Column("field3", "type4", null, false), - new Column("field4", "type5", null, false) - ); + new Column("field4", "type5", null, false)); List<Table> tables = List.of( new Table(TableType.TABLE, "", "sampleTable", columns, keys, new ArrayList<>()), - new Table(TableType.TABLE, "", "limitedColumnTable", limitedColumns, keys, new ArrayList<>()) - ); + new Table(TableType.TABLE, "", "limitedColumnTable", limitedColumns, keys, new ArrayList<>())); structure.setTables(tables); testDatasource.setPluginId(postgreSQLPlugin.getId()); testDatasource.setWorkspaceId(testWorkspace.getId()); @@ -218,23 +231,19 @@ Mono<List<NewAction>> getActions(String pageId) { return newActionService.findByPageId(pageId).collectList(); } - @Test @WithUserDetails(value = "api_user") public void createPageWithInvalidApplicationIdTest() { Mono<CRUDPageResponseDTO> resultMono = solution.createPageFromDBTable( - testApp.getPages().get(0).getId(), - resource, - testDefaultEnvironmentId, - ""); + testApp.getPages().get(0).getId(), resource, testDefaultEnvironmentId, ""); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.APPLICATION_ID))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.APPLICATION_ID))) .verify(); - } @Test @@ -247,38 +256,34 @@ public void createPageWithInvalidDatasourceTest() { invalidDatasource.setDatasourceConfiguration(new DatasourceConfiguration()); resource.setDatasourceId(invalidDatasource.getId()); - Mono<CRUDPageResponseDTO> resultMono = datasourceService.create(invalidDatasource) + Mono<CRUDPageResponseDTO> resultMono = datasourceService + .create(invalidDatasource) .flatMap(datasource -> { resource.setApplicationId(testApp.getId()); resource.setDatasourceId(datasource.getId()); return solution.createPageFromDBTable( - testApp.getPages().get(0).getId(), - resource, - testDefaultEnvironmentId, - null); + testApp.getPages().get(0).getId(), resource, testDefaultEnvironmentId, null); }); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PLUGIN_ID))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.PLUGIN_ID))) .verify(); - } @Test @WithUserDetails(value = "api_user") public void createPageWithInvalidRequestBodyTest() { Mono<CRUDPageResponseDTO> resultMono = solution.createPageFromDBTable( - testApp.getPages().get(0).getId(), - new CRUDPageResourceDTO(), - testDefaultEnvironmentId, - ""); + testApp.getPages().get(0).getId(), new CRUDPageResourceDTO(), testDefaultEnvironmentId, ""); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage("tableName and datasourceId"))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage("tableName and datasourceId"))) .verify(); } @@ -287,16 +292,15 @@ public void createPageWithInvalidRequestBodyTest() { public void createPage_withInvalidBranchName_throwException() { final String pageId = testApp.getPages().get(0).getId(); resource.setApplicationId(testApp.getId()); - Mono<CRUDPageResponseDTO> resultMono = solution.createPageFromDBTable( - pageId, - resource, - testDefaultEnvironmentId, - "invalidBranch"); - - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PAGE, pageId + ", " + "invalidBranch"))) + Mono<CRUDPageResponseDTO> resultMono = + solution.createPageFromDBTable(pageId, resource, testDefaultEnvironmentId, "invalidBranch"); + + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.PAGE, pageId + ", " + "invalidBranch"))) .verify(); } @@ -305,14 +309,10 @@ public void createPage_withInvalidBranchName_throwException() { public void createPageWithNullPageId() { resource.setApplicationId(testApp.getId()); - Mono<CRUDPageResponseDTO> resultMono = solution.createPageFromDBTable( - null, - resource, - testDefaultEnvironmentId, - null); + Mono<CRUDPageResponseDTO> resultMono = + solution.createPageFromDBTable(null, resource, testDefaultEnvironmentId, null); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(crudPage -> { PageDTO page = crudPage.getPage(); Layout layout = page.getLayouts().get(0); @@ -338,15 +338,19 @@ public void createPage_withValidBranch_validDefaultIds() { GitApplicationMetadata gitData = new GitApplicationMetadata(); gitData.setBranchName("crudTestBranch"); gitConnectedApp.setGitApplicationMetadata(gitData); - applicationPageService.createApplication(gitConnectedApp, testWorkspace.getId()) + applicationPageService + .createApplication(gitConnectedApp, testWorkspace.getId()) .flatMap(application -> { application.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); gitData.setDefaultApplicationId(application.getId()); - return applicationService.save(application) - .zipWhen(application1 -> importExportApplicationService.exportApplicationById(application1.getId(), gitData.getBranchName())); + return applicationService + .save(application) + .zipWhen(application1 -> importExportApplicationService.exportApplicationById( + application1.getId(), gitData.getBranchName())); }) // Assign the branchName to all the resources connected to the application - .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit(testWorkspace.getId(), tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) + .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit( + testWorkspace.getId(), tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) .block(); resource.setApplicationId(gitData.getDefaultApplicationId()); @@ -354,17 +358,14 @@ public void createPage_withValidBranch_validDefaultIds() { newPage.setApplicationId(gitData.getDefaultApplicationId()); newPage.setName("crud-admin-page-with-git-connected-app"); - Mono<NewPage> resultMono = applicationPageService.createPageWithBranchName(newPage, gitData.getBranchName()) + Mono<NewPage> resultMono = applicationPageService + .createPageWithBranchName(newPage, gitData.getBranchName()) .flatMap(savedPage -> solution.createPageFromDBTable( - savedPage.getId(), - resource, - testDefaultEnvironmentId, - gitData.getBranchName())) - .flatMap(crudPageResponseDTO -> - newPageService.findByBranchNameAndDefaultPageId(gitData.getBranchName(), crudPageResponseDTO.getPage().getId(), READ_PAGES)); + savedPage.getId(), resource, testDefaultEnvironmentId, gitData.getBranchName())) + .flatMap(crudPageResponseDTO -> newPageService.findByBranchNameAndDefaultPageId( + gitData.getBranchName(), crudPageResponseDTO.getPage().getId(), READ_PAGES)); - StepVerifier - .create(resultMono.zipWhen(newPage1 -> getActions(newPage1.getId()))) + StepVerifier.create(resultMono.zipWhen(newPage1 -> getActions(newPage1.getId()))) .assertNext(tuple -> { NewPage newPage1 = tuple.getT1(); List<NewAction> actionList = tuple.getT2(); @@ -376,16 +377,21 @@ public void createPage_withValidBranch_validDefaultIds() { assertThat(newPage1.getDefaultResources()).isNotNull(); assertThat(newPage1.getDefaultResources().getBranchName()).isEqualTo(gitData.getBranchName()); assertThat(newPage1.getDefaultResources().getPageId()).isEqualTo(newPage1.getId()); - assertThat(newPage1.getDefaultResources().getApplicationId()).isEqualTo(newPage1.getApplicationId()); + assertThat(newPage1.getDefaultResources().getApplicationId()) + .isEqualTo(newPage1.getApplicationId()); assertThat(actionList).hasSize(4); DefaultResources newActionResources = actionList.get(0).getDefaultResources(); - DefaultResources actionDTOResources = actionList.get(0).getUnpublishedAction().getDefaultResources(); - assertThat(newActionResources.getActionId()).isEqualTo(actionList.get(0).getId()); - assertThat(newActionResources.getApplicationId()).isEqualTo(newPage1.getDefaultResources().getApplicationId()); + DefaultResources actionDTOResources = + actionList.get(0).getUnpublishedAction().getDefaultResources(); + assertThat(newActionResources.getActionId()) + .isEqualTo(actionList.get(0).getId()); + assertThat(newActionResources.getApplicationId()) + .isEqualTo(newPage1.getDefaultResources().getApplicationId()); assertThat(newActionResources.getPageId()).isNull(); assertThat(newActionResources.getBranchName()).isEqualTo(gitData.getBranchName()); - assertThat(actionDTOResources.getPageId()).isEqualTo(newPage1.getDefaultResources().getPageId()); + assertThat(actionDTOResources.getPageId()) + .isEqualTo(newPage1.getDefaultResources().getPageId()); }) .verifyComplete(); } @@ -399,16 +405,13 @@ public void createPageWithValidPageIdForPostgresqlDS() { newPage.setApplicationId(testApp.getId()); newPage.setName("crud-admin-page"); - Mono<PageDTO> resultMono = applicationPageService.createPage(newPage) - .flatMap(savedPage -> solution.createPageFromDBTable( - savedPage.getId(), - resource, - testDefaultEnvironmentId, - "")) + Mono<PageDTO> resultMono = applicationPageService + .createPage(newPage) + .flatMap(savedPage -> + solution.createPageFromDBTable(savedPage.getId(), resource, testDefaultEnvironmentId, "")) .map(crudPageResponseDTO -> crudPageResponseDTO.getPage()); - StepVerifier - .create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) + StepVerifier.create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) .assertNext(tuple -> { PageDTO page = tuple.getT1(); List<NewAction> actions = tuple.getT2(); @@ -430,11 +433,16 @@ public void createPageWithValidPageIdForPostgresqlDS() { ActionConfiguration actionConfiguration = unpublishedAction.getActionConfiguration(); String actionBody = actionConfiguration.getBody().replaceAll(specialCharactersRegex, ""); String templateActionBody = actionNameToBodyMap - .get(action.getUnpublishedAction().getName()).replaceAll(specialCharactersRegex, "") + .get(action.getUnpublishedAction().getName()) + .replaceAll(specialCharactersRegex, "") .replace("like", "ilike"); assertThat(actionBody).isEqualTo(templateActionBody); if (!StringUtils.equals(unpublishedAction.getName(), SELECT_QUERY)) { - assertThat(actionConfiguration.getPluginSpecifiedTemplates().get(0).getValue()).isEqualTo(Boolean.TRUE); + assertThat(actionConfiguration + .getPluginSpecifiedTemplates() + .get(0) + .getValue()) + .isEqualTo(Boolean.TRUE); } } }) @@ -446,22 +454,21 @@ public void createPageWithValidPageIdForPostgresqlDS() { public void createPageWithLessColumnsComparedToTemplateForPostgres() { CRUDPageResourceDTO resourceDTO = new CRUDPageResourceDTO(); - resourceDTO.setTableName(testDatasourceStructure.getStructure().getTables().get(1).getName()); + resourceDTO.setTableName( + testDatasourceStructure.getStructure().getTables().get(1).getName()); resourceDTO.setDatasourceId(testDatasource.getId()); resourceDTO.setApplicationId(testApp.getId()); PageDTO newPage = new PageDTO(); newPage.setApplicationId(testApp.getId()); newPage.setName("crud-admin-page-postgres-with-less-columns"); - Mono<CRUDPageResponseDTO> resultMono = applicationPageService.createPage(newPage) - .flatMap(savedPage -> solution.createPageFromDBTable( - savedPage.getId(), - resourceDTO, - testDefaultEnvironmentId, - "")); + Mono<CRUDPageResponseDTO> resultMono = applicationPageService + .createPage(newPage) + .flatMap(savedPage -> + solution.createPageFromDBTable(savedPage.getId(), resourceDTO, testDefaultEnvironmentId, "")); - StepVerifier - .create(resultMono.zipWhen(crudPageResponseDTO -> getActions(crudPageResponseDTO.getPage().getId()))) + StepVerifier.create(resultMono.zipWhen(crudPageResponseDTO -> + getActions(crudPageResponseDTO.getPage().getId()))) .assertNext(tuple -> { CRUDPageResponseDTO crudPageResponseDTO = tuple.getT1(); PageDTO page = crudPageResponseDTO.getPage(); @@ -478,12 +485,14 @@ public void createPageWithLessColumnsComparedToTemplateForPostgres() { assertThat(actions).hasSize(4); for (NewAction action : actions) { - ActionConfiguration actionConfiguration = action.getUnpublishedAction().getActionConfiguration(); + ActionConfiguration actionConfiguration = + action.getUnpublishedAction().getActionConfiguration(); String actionBody = actionConfiguration.getBody().replaceAll(specialCharactersRegex, ""); String actionName; if (StringUtils.equals(action.getUnpublishedAction().getName(), UPDATE_QUERY)) { actionName = "UpdateActionWithLessColumns"; - } else if (StringUtils.equals(action.getUnpublishedAction().getName(), INSERT_QUERY)) { + } else if (StringUtils.equals( + action.getUnpublishedAction().getName(), INSERT_QUERY)) { actionName = "InsertActionWithLessColumns"; } else { actionName = action.getUnpublishedAction().getName(); @@ -493,7 +502,9 @@ public void createPageWithLessColumnsComparedToTemplateForPostgres() { .get(actionName) .replaceAll(specialCharactersRegex, "") .replace("like", "ilike") - .replace(structure.getTables().get(0).getName(), structure.getTables().get(1).getName()); + .replace( + structure.getTables().get(0).getName(), + structure.getTables().get(1).getName()); assertThat(actionBody).isEqualTo(templateActionBody); } assertThat(crudPageResponseDTO.getSuccessMessage()).containsIgnoringCase("TABLE"); @@ -507,7 +518,8 @@ public void createPageWithLessColumnsComparedToTemplateForPostgres() { public void createPageWithLessColumnsComparedToTemplateForSql() { CRUDPageResourceDTO resourceDTO = new CRUDPageResourceDTO(); - resourceDTO.setTableName(testDatasourceStructure.getStructure().getTables().get(1).getName()); + resourceDTO.setTableName( + testDatasourceStructure.getStructure().getTables().get(1).getName()); resourceDTO.setDatasourceId(testDatasource.getId()); resourceDTO.setApplicationId(testApp.getId()); PageDTO newPage = new PageDTO(); @@ -515,7 +527,8 @@ public void createPageWithLessColumnsComparedToTemplateForSql() { newPage.setName("crud-admin-page-mysql"); StringBuilder pluginName = new StringBuilder(); - Mono<Datasource> datasourceMono = pluginRepository.findByName("MySQL") + Mono<Datasource> datasourceMono = pluginRepository + .findByName("MySQL") .flatMap(plugin -> { pluginName.append(plugin.getName()); Datasource datasource = new Datasource(); @@ -537,7 +550,8 @@ public void createPageWithLessColumnsComparedToTemplateForSql() { datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); datasourceStorageStructure.setStructure(structure); - return datasourceStructureService.save(datasourceStorageStructure) + return datasourceStructureService + .save(datasourceStorageStructure) .thenReturn(datasource); }); @@ -546,14 +560,11 @@ public void createPageWithLessColumnsComparedToTemplateForSql() { resourceDTO.setDatasourceId(datasource1.getId()); return applicationPageService.createPage(newPage); }) - .flatMap(savedPage -> solution.createPageFromDBTable( - savedPage.getId(), - resourceDTO, - testDefaultEnvironmentId, - null)); + .flatMap(savedPage -> + solution.createPageFromDBTable(savedPage.getId(), resourceDTO, testDefaultEnvironmentId, null)); - StepVerifier - .create(resultMono.zipWhen(crudPageResponseDTO -> getActions(crudPageResponseDTO.getPage().getId()))) + StepVerifier.create(resultMono.zipWhen(crudPageResponseDTO -> + getActions(crudPageResponseDTO.getPage().getId()))) .assertNext(tuple -> { CRUDPageResponseDTO crudPageResponseDTO = tuple.getT1(); PageDTO page = crudPageResponseDTO.getPage(); @@ -570,12 +581,14 @@ public void createPageWithLessColumnsComparedToTemplateForSql() { assertThat(actions).hasSize(4); for (NewAction action : actions) { - ActionConfiguration actionConfiguration = action.getUnpublishedAction().getActionConfiguration(); + ActionConfiguration actionConfiguration = + action.getUnpublishedAction().getActionConfiguration(); String actionBody = actionConfiguration.getBody().replaceAll(specialCharactersRegex, ""); String actionName; if (StringUtils.equals(action.getUnpublishedAction().getName(), UPDATE_QUERY)) { actionName = "UpdateActionWithLessColumns"; - } else if (StringUtils.equals(action.getUnpublishedAction().getName(), INSERT_QUERY)) { + } else if (StringUtils.equals( + action.getUnpublishedAction().getName(), INSERT_QUERY)) { actionName = "InsertActionWithLessColumns"; } else { actionName = action.getUnpublishedAction().getName(); @@ -584,7 +597,9 @@ public void createPageWithLessColumnsComparedToTemplateForSql() { String templateActionBody = actionNameToBodyMap .get(actionName) .replaceAll(specialCharactersRegex, "") - .replace(structure.getTables().get(0).getName(), structure.getTables().get(1).getName()); + .replace( + structure.getTables().get(0).getName(), + structure.getTables().get(1).getName()); assertThat(actionBody).isEqualTo(templateActionBody); } assertThat(crudPageResponseDTO.getSuccessMessage()).containsIgnoringCase(pluginName); @@ -604,44 +619,40 @@ public void createPageWithValidPageIdForMySqlDS() { newPage.setName("crud-admin-page-mysql"); StringBuilder pluginName = new StringBuilder(); - Mono<Datasource> datasourceMono = pluginRepository.findByName("MySQL") - .flatMap(plugin -> { - pluginName.append(plugin.getName()); - Datasource datasource = new Datasource(); - datasource.setPluginId(plugin.getId()); - datasource.setWorkspaceId(testWorkspace.getId()); - datasource.setName("MySql-CRUD-Page-Table-DS"); - datasource.setDatasourceConfiguration(datasourceConfiguration); - DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, testDefaultEnvironmentId); - HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); - datasource.setDatasourceStorages(storages); + Mono<Datasource> datasourceMono = pluginRepository.findByName("MySQL").flatMap(plugin -> { + pluginName.append(plugin.getName()); + Datasource datasource = new Datasource(); + datasource.setPluginId(plugin.getId()); + datasource.setWorkspaceId(testWorkspace.getId()); + datasource.setName("MySql-CRUD-Page-Table-DS"); + datasource.setDatasourceConfiguration(datasourceConfiguration); + DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, testDefaultEnvironmentId); + HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); + storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); + datasource.setDatasourceStorages(storages); - return datasourceService.create(datasource) - .flatMap(datasource1 -> { - DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); - datasourceStorageStructure.setDatasourceId(datasource1.getId()); - datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); - datasourceStorageStructure.setStructure(structure); + return datasourceService.create(datasource).flatMap(datasource1 -> { + DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); + datasourceStorageStructure.setDatasourceId(datasource1.getId()); + datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); + datasourceStorageStructure.setStructure(structure); - return datasourceStructureService.save(datasourceStorageStructure) - .thenReturn(datasource1); - }); - }); + return datasourceStructureService + .save(datasourceStorageStructure) + .thenReturn(datasource1); + }); + }); Mono<CRUDPageResponseDTO> resultMono = datasourceMono .flatMap(datasource1 -> { resource.setDatasourceId(datasource1.getId()); return applicationPageService.createPage(newPage); }) - .flatMap(savedPage -> solution.createPageFromDBTable( - savedPage.getId(), - resource, - testDefaultEnvironmentId, - null)); + .flatMap(savedPage -> + solution.createPageFromDBTable(savedPage.getId(), resource, testDefaultEnvironmentId, null)); - StepVerifier - .create(resultMono.zipWhen(crudPageResponseDTO -> getActions(crudPageResponseDTO.getPage().getId()))) + StepVerifier.create(resultMono.zipWhen(crudPageResponseDTO -> + getActions(crudPageResponseDTO.getPage().getId()))) .assertNext(tuple -> { CRUDPageResponseDTO crudPageResponseDTO = tuple.getT1(); PageDTO page = crudPageResponseDTO.getPage(); @@ -658,16 +669,20 @@ public void createPageWithValidPageIdForMySqlDS() { assertThat(actions).hasSize(4); for (NewAction action : actions) { - ActionConfiguration actionConfiguration = action.getUnpublishedAction().getActionConfiguration(); + ActionConfiguration actionConfiguration = + action.getUnpublishedAction().getActionConfiguration(); String actionBody = actionConfiguration.getBody().replaceAll(specialCharactersRegex, ""); String templateActionBody = actionNameToBodyMap - .get(action.getUnpublishedAction().getName()).replaceAll(specialCharactersRegex, ""); + .get(action.getUnpublishedAction().getName()) + .replaceAll(specialCharactersRegex, ""); assertThat(actionBody).isEqualTo(templateActionBody); if (SELECT_QUERY.equals(action.getUnpublishedAction().getName())) { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isTrue(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isTrue(); } else { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isFalse(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isFalse(); } } assertThat(crudPageResponseDTO.getSuccessMessage()).containsIgnoringCase(pluginName); @@ -686,7 +701,8 @@ public void createPageWithValidPageIdForRedshiftDS() { newPage.setApplicationId(testApp.getId()); newPage.setName("crud-admin-page-redshift"); - Mono<Datasource> datasourceMono = pluginRepository.findByName("Redshift") + Mono<Datasource> datasourceMono = pluginRepository + .findByName("Redshift") .flatMap(plugin -> { Datasource datasource = new Datasource(); datasource.setPluginId(plugin.getId()); @@ -698,16 +714,16 @@ public void createPageWithValidPageIdForRedshiftDS() { storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); - return datasourceService.create(datasource) - .flatMap(datasource1 -> { - DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); - datasourceStorageStructure.setDatasourceId(datasource1.getId()); - datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); - datasourceStorageStructure.setStructure(structure); + return datasourceService.create(datasource).flatMap(datasource1 -> { + DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); + datasourceStorageStructure.setDatasourceId(datasource1.getId()); + datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); + datasourceStorageStructure.setStructure(structure); - return datasourceStructureService.save(datasourceStorageStructure) - .thenReturn(datasource1); - }); + return datasourceStructureService + .save(datasourceStorageStructure) + .thenReturn(datasource1); + }); }); Mono<PageDTO> resultMono = datasourceMono @@ -715,15 +731,11 @@ public void createPageWithValidPageIdForRedshiftDS() { resource.setDatasourceId(datasource1.getId()); return applicationPageService.createPage(newPage); }) - .flatMap(savedPage -> solution.createPageFromDBTable( - savedPage.getId(), - resource, - testDefaultEnvironmentId, - "")) + .flatMap(savedPage -> + solution.createPageFromDBTable(savedPage.getId(), resource, testDefaultEnvironmentId, "")) .map(crudPageResponseDTO -> crudPageResponseDTO.getPage()); - StepVerifier - .create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) + StepVerifier.create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) .assertNext(tuple -> { PageDTO page = tuple.getT1(); List<NewAction> actions = tuple.getT2(); @@ -736,23 +748,26 @@ public void createPageWithValidPageIdForRedshiftDS() { assertThat(actions).hasSize(4); for (NewAction action : actions) { - ActionConfiguration actionConfiguration = action.getUnpublishedAction().getActionConfiguration(); + ActionConfiguration actionConfiguration = + action.getUnpublishedAction().getActionConfiguration(); String actionBody = actionConfiguration.getBody().replaceAll(specialCharactersRegex, ""); String templateActionBody = actionNameToBodyMap - .get(action.getUnpublishedAction().getName()).replaceAll(specialCharactersRegex, ""); + .get(action.getUnpublishedAction().getName()) + .replaceAll(specialCharactersRegex, ""); assertThat(actionBody).isEqualTo(templateActionBody); if (SELECT_QUERY.equals(action.getUnpublishedAction().getName())) { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isTrue(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isTrue(); } else { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isFalse(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isFalse(); } } }) .verifyComplete(); } - // TODO this has been disabled as we don't have the getStructure method for mssql-plugin /* @Test @@ -816,7 +831,8 @@ public void createPageWithNullPageIdForSnowflake() { resource.setApplicationId(testApp.getId()); - Mono<Datasource> datasourceMono = pluginRepository.findByName("Snowflake") + Mono<Datasource> datasourceMono = pluginRepository + .findByName("Snowflake") .flatMap(plugin -> { Datasource datasource = new Datasource(); datasource.setPluginId(plugin.getId()); @@ -828,32 +844,26 @@ public void createPageWithNullPageIdForSnowflake() { storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); - return datasourceService.create(datasource) - .flatMap(datasource1 -> { - DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); - datasourceStorageStructure.setDatasourceId(datasource1.getId()); - datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); - datasourceStorageStructure.setStructure(structure); - - return datasourceStructureService.save(datasourceStorageStructure) - .thenReturn(datasource1); - }); + return datasourceService.create(datasource).flatMap(datasource1 -> { + DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); + datasourceStorageStructure.setDatasourceId(datasource1.getId()); + datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); + datasourceStorageStructure.setStructure(structure); + return datasourceStructureService + .save(datasourceStorageStructure) + .thenReturn(datasource1); + }); }); Mono<PageDTO> resultMono = datasourceMono .flatMap(datasource1 -> { resource.setDatasourceId(datasource1.getId()); - return solution.createPageFromDBTable( - null, - resource, - testDefaultEnvironmentId, - ""); + return solution.createPageFromDBTable(null, resource, testDefaultEnvironmentId, ""); }) .map(crudPageResponseDTO -> crudPageResponseDTO.getPage()); - StepVerifier - .create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) + StepVerifier.create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) .assertNext(tuple -> { PageDTO page = tuple.getT1(); List<NewAction> actions = tuple.getT2(); @@ -866,15 +876,19 @@ public void createPageWithNullPageIdForSnowflake() { assertThat(actions).hasSize(4); for (NewAction action : actions) { - ActionConfiguration actionConfiguration = action.getUnpublishedAction().getActionConfiguration(); + ActionConfiguration actionConfiguration = + action.getUnpublishedAction().getActionConfiguration(); String actionBody = actionConfiguration.getBody().replaceAll(specialCharactersRegex, ""); String templateActionBody = actionNameToBodyMap - .get(action.getUnpublishedAction().getName()).replaceAll(specialCharactersRegex, ""); + .get(action.getUnpublishedAction().getName()) + .replaceAll(specialCharactersRegex, ""); assertThat(actionBody).isEqualTo(templateActionBody); if (SELECT_QUERY.equals(action.getUnpublishedAction().getName())) { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isTrue(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isTrue(); } else { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isFalse(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isFalse(); } } }) @@ -888,42 +902,36 @@ public void createPageWithNullPageIdForS3() { resource.setApplicationId(testApp.getId()); StringBuilder pluginName = new StringBuilder(); - Mono<Datasource> datasourceMono = pluginRepository.findByName("S3") - .flatMap(plugin -> { - Datasource datasource = new Datasource(); - datasource.setPluginId(plugin.getId()); - datasource.setWorkspaceId(testWorkspace.getId()); - datasource.setName("S3-CRUD-Page-Table-DS"); - datasource.setDatasourceConfiguration(datasourceConfiguration); - pluginName.append(plugin.getName()); - DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, testDefaultEnvironmentId); - HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); - datasource.setDatasourceStorages(storages); + Mono<Datasource> datasourceMono = pluginRepository.findByName("S3").flatMap(plugin -> { + Datasource datasource = new Datasource(); + datasource.setPluginId(plugin.getId()); + datasource.setWorkspaceId(testWorkspace.getId()); + datasource.setName("S3-CRUD-Page-Table-DS"); + datasource.setDatasourceConfiguration(datasourceConfiguration); + pluginName.append(plugin.getName()); + DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, testDefaultEnvironmentId); + HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); + storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); + datasource.setDatasourceStorages(storages); - return datasourceService.create(datasource) - .flatMap(datasource1 -> { - DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); - datasourceStorageStructure.setDatasourceId(datasource1.getId()); - datasourceStorageStructure.setStructure(structure); + return datasourceService.create(datasource).flatMap(datasource1 -> { + DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); + datasourceStorageStructure.setDatasourceId(datasource1.getId()); + datasourceStorageStructure.setStructure(structure); - return datasourceStructureService.save(datasourceStorageStructure) - .thenReturn(datasource1); - }); - }); + return datasourceStructureService + .save(datasourceStorageStructure) + .thenReturn(datasource1); + }); + }); - Mono<CRUDPageResponseDTO> resultMono = datasourceMono - .flatMap(datasource1 -> { - resource.setDatasourceId(datasource1.getId()); - return solution.createPageFromDBTable( - null, - resource, - testDefaultEnvironmentId, - ""); - }); + Mono<CRUDPageResponseDTO> resultMono = datasourceMono.flatMap(datasource1 -> { + resource.setDatasourceId(datasource1.getId()); + return solution.createPageFromDBTable(null, resource, testDefaultEnvironmentId, ""); + }); - StepVerifier - .create(resultMono.zipWhen(crudPageResponseDTO -> getActions(crudPageResponseDTO.getPage().getId()))) + StepVerifier.create(resultMono.zipWhen(crudPageResponseDTO -> + getActions(crudPageResponseDTO.getPage().getId()))) .assertNext(tuple -> { CRUDPageResponseDTO crudPage = tuple.getT1(); PageDTO page = crudPage.getPage(); @@ -940,12 +948,18 @@ public void createPageWithNullPageIdForS3() { assertThat(actions).hasSize(5); for (NewAction action : actions) { - ActionConfiguration actionConfiguration = action.getUnpublishedAction().getActionConfiguration(); - assertThat(((Map<String, String>) actionConfiguration.getFormData().get("bucket")).get(DATA)) + ActionConfiguration actionConfiguration = + action.getUnpublishedAction().getActionConfiguration(); + assertThat(((Map<String, String>) actionConfiguration + .getFormData() + .get("bucket")) + .get(DATA)) .isEqualTo(resource.getTableName()); if (action.getUnpublishedAction().getName().equals(LIST_QUERY)) { - Map<String, Object> listObject = (Map<String, Object>) actionConfiguration.getFormData().get("list"); - assertThat(((Map<String, Object>) ((Map<String, Object>) listObject.get("where")).get(DATA)).get("condition")) + Map<String, Object> listObject = (Map<String, Object>) + actionConfiguration.getFormData().get("list"); + assertThat(((Map<String, Object>) ((Map<String, Object>) listObject.get("where")).get(DATA)) + .get("condition")) .isEqualTo("AND"); } } @@ -972,7 +986,8 @@ public void createPageWithValidPageIdForGoogleSheet() { newPage.setApplicationId(testApp.getId()); newPage.setName("crud-admin-page-GoogleSheet"); - Mono<Datasource> datasourceMono = pluginRepository.findByName("Google Sheets") + Mono<Datasource> datasourceMono = pluginRepository + .findByName("Google Sheets") .flatMap(plugin -> { Datasource datasource = new Datasource(); datasource.setPluginId(plugin.getId()); @@ -985,15 +1000,15 @@ public void createPageWithValidPageIdForGoogleSheet() { storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); datasource.setDatasourceStorages(storages); - return datasourceService.create(datasource) - .flatMap(datasource1 -> { - DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); - datasourceStorageStructure.setDatasourceId(datasource1.getId()); - datasourceStorageStructure.setStructure(structure); + return datasourceService.create(datasource).flatMap(datasource1 -> { + DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); + datasourceStorageStructure.setDatasourceId(datasource1.getId()); + datasourceStorageStructure.setStructure(structure); - return datasourceStructureService.save(datasourceStorageStructure) - .thenReturn(datasource1); - }); + return datasourceStructureService + .save(datasourceStorageStructure) + .thenReturn(datasource1); + }); }); Mono<PageDTO> resultMono = datasourceMono @@ -1001,15 +1016,11 @@ public void createPageWithValidPageIdForGoogleSheet() { resource.setDatasourceId(datasource1.getId()); return applicationPageService.createPage(newPage); }) - .flatMap(savedPage -> solution.createPageFromDBTable( - savedPage.getId(), - resource, - testDefaultEnvironmentId, - null)) + .flatMap(savedPage -> + solution.createPageFromDBTable(savedPage.getId(), resource, testDefaultEnvironmentId, null)) .map(crudPageResponseDTO -> crudPageResponseDTO.getPage()); - StepVerifier - .create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) + StepVerifier.create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) .assertNext(tuple -> { PageDTO page = tuple.getT1(); List<NewAction> actions = tuple.getT2(); @@ -1021,17 +1032,21 @@ public void createPageWithValidPageIdForGoogleSheet() { assertThat(actions).hasSize(4); for (NewAction action : actions) { - ActionConfiguration actionConfiguration = action.getUnpublishedAction().getActionConfiguration(); + ActionConfiguration actionConfiguration = + action.getUnpublishedAction().getActionConfiguration(); if (SELECT_QUERY.equals(action.getUnpublishedAction().getName())) { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isTrue(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isTrue(); } else { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isFalse(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isFalse(); } List<Property> pluginSpecifiedTemplate = actionConfiguration.getPluginSpecifiedTemplates(); pluginSpecifiedTemplate.forEach(template -> { if (pluginSpecificFields.containsKey(template.getKey())) { - assertThat(template.getValue().toString()).isEqualTo(pluginSpecificFields.get(template.getKey())); + assertThat(template.getValue().toString()) + .isEqualTo(pluginSpecificFields.get(template.getKey())); } }); } @@ -1049,44 +1064,39 @@ public void createPageWithValidPageIdForMongoDB() { newPage.setApplicationId(testApp.getId()); newPage.setName("crud-admin-page-Mongo"); - Mono<Datasource> datasourceMono = pluginRepository.findByName("MongoDB") - .flatMap(plugin -> { - Datasource datasource = new Datasource(); - datasource.setPluginId(plugin.getId()); - datasource.setWorkspaceId(testWorkspace.getId()); - datasource.setName("Mongo-CRUD-Page-Table-DS"); - datasource.setDatasourceConfiguration(datasourceConfiguration); - DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, testDefaultEnvironmentId); - HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); - storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); - datasource.setDatasourceStorages(storages); + Mono<Datasource> datasourceMono = pluginRepository.findByName("MongoDB").flatMap(plugin -> { + Datasource datasource = new Datasource(); + datasource.setPluginId(plugin.getId()); + datasource.setWorkspaceId(testWorkspace.getId()); + datasource.setName("Mongo-CRUD-Page-Table-DS"); + datasource.setDatasourceConfiguration(datasourceConfiguration); + DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, testDefaultEnvironmentId); + HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); + storages.put(testDefaultEnvironmentId, new DatasourceStorageDTO(datasourceStorage)); + datasource.setDatasourceStorages(storages); - return datasourceService.create(datasource) - .flatMap(datasource1 -> { - DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); - datasourceStorageStructure.setDatasourceId(datasource1.getId()); - datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); - datasourceStorageStructure.setStructure(structure); + return datasourceService.create(datasource).flatMap(datasource1 -> { + DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); + datasourceStorageStructure.setDatasourceId(datasource1.getId()); + datasourceStorageStructure.setEnvironmentId(testDefaultEnvironmentId); + datasourceStorageStructure.setStructure(structure); - return datasourceStructureService.save(datasourceStorageStructure) - .thenReturn(datasource1); - }); - }); + return datasourceStructureService + .save(datasourceStorageStructure) + .thenReturn(datasource1); + }); + }); Mono<PageDTO> resultMono = datasourceMono .flatMap(datasource1 -> { resource.setDatasourceId(datasource1.getId()); return applicationPageService.createPage(newPage); }) - .flatMap(savedPage -> solution.createPageFromDBTable( - savedPage.getId(), - resource, - testDefaultEnvironmentId, - null)) + .flatMap(savedPage -> + solution.createPageFromDBTable(savedPage.getId(), resource, testDefaultEnvironmentId, null)) .map(crudPageResponseDTO -> crudPageResponseDTO.getPage()); - StepVerifier - .create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) + StepVerifier.create(resultMono.zipWhen(pageDTO -> getActions(pageDTO.getId()))) .assertNext(tuple -> { PageDTO page = tuple.getT1(); List<NewAction> actions = tuple.getT2(); @@ -1101,56 +1111,82 @@ public void createPageWithValidPageIdForMongoDB() { assertThat(actions).hasSize(4); for (NewAction action : actions) { - ActionConfiguration actionConfiguration = action.getUnpublishedAction().getActionConfiguration(); + ActionConfiguration actionConfiguration = + action.getUnpublishedAction().getActionConfiguration(); if (FIND_QUERY.equals(action.getUnpublishedAction().getName())) { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isTrue(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isTrue(); } else { - assertThat(action.getUnpublishedAction().getExecuteOnLoad()).isFalse(); + assertThat(action.getUnpublishedAction().getExecuteOnLoad()) + .isFalse(); } Map<String, Object> formData = actionConfiguration.getFormData(); - assertThat(((Map<String, Object>) formData.get("collection")).get(DATA)).isEqualTo("sampleTable"); + assertThat(((Map<String, Object>) formData.get("collection")).get(DATA)) + .isEqualTo("sampleTable"); String queryType = ((Map<String, String>) formData.get("command")).get(DATA); if (queryType.equals("UPDATE")) { Map<String, Object> updateMany = (Map<String, Object>) formData.get("updateMany"); - assertThat(((Map<String, String>) updateMany.get("query")).get(DATA).replaceAll(specialCharactersRegex, "")) - .isEqualTo("{ id: ObjectId('{{data_table.selectedRow.id}}') }".replaceAll(specialCharactersRegex, "")); + assertThat(((Map<String, String>) updateMany.get("query")) + .get(DATA) + .replaceAll(specialCharactersRegex, "")) + .isEqualTo("{ id: ObjectId('{{data_table.selectedRow.id}}') }" + .replaceAll(specialCharactersRegex, "")); assertThat(((Map<String, Object>) updateMany.get("update")).get(DATA)) - .isEqualTo("{\n" + - " $set:{{update_form.formData}}\n" + - "}".replaceAll(specialCharactersRegex, "")); - assertThat(((Map<String, Object>) formData.get("smartSubstitution")).get(DATA)).isEqualTo(true); + .isEqualTo("{\n" + " $set:{{update_form.formData}}\n" + + "}".replaceAll(specialCharactersRegex, "")); + assertThat(((Map<String, Object>) formData.get("smartSubstitution")).get(DATA)) + .isEqualTo(true); } else if (queryType.equals("DELETE")) { Map<String, Object> delete = (Map<String, Object>) formData.get("delete"); - assertThat(((Map<String, String>) delete.get("query")).get(DATA).replaceAll(specialCharactersRegex, "")) - .isEqualTo("{ id: ObjectId('{{data_table.triggeredRow.id}}') }".replaceAll(specialCharactersRegex, "")); - assertThat(((Map<String, Object>) formData.get("smartSubstitution")).get(DATA)).isEqualTo(true); + assertThat(((Map<String, String>) delete.get("query")) + .get(DATA) + .replaceAll(specialCharactersRegex, "")) + .isEqualTo("{ id: ObjectId('{{data_table.triggeredRow.id}}') }" + .replaceAll(specialCharactersRegex, "")); + assertThat(((Map<String, Object>) formData.get("smartSubstitution")).get(DATA)) + .isEqualTo(true); } else if (queryType.equals("FIND")) { Map<String, Object> find = (Map<String, Object>) formData.get("find"); - assertThat(((Map<String, Object>) find.get("sort")).get(DATA).toString().replaceAll(specialCharactersRegex, "")) - .isEqualTo("{ \n{{data_table.sortOrder.column || 'field2'}}: {{data_table.sortOrder.order == \"desc\" ? -1 : 1}}}" - .replaceAll(specialCharactersRegex, "")); - - assertThat(((Map<String, Object>) find.get("limit")).get(DATA).toString()).isEqualTo("{{data_table.pageSize}}"); - - assertThat(((Map<String, Object>) find.get("skip")).get(DATA).toString()) + assertThat(((Map<String, Object>) find.get("sort")) + .get(DATA) + .toString() + .replaceAll(specialCharactersRegex, "")) + .isEqualTo( + "{ \n{{data_table.sortOrder.column || 'field2'}}: {{data_table.sortOrder.order == \"desc\" ? -1 : 1}}}" + .replaceAll(specialCharactersRegex, "")); + + assertThat(((Map<String, Object>) find.get("limit")) + .get(DATA) + .toString()) + .isEqualTo("{{data_table.pageSize}}"); + + assertThat(((Map<String, Object>) find.get("skip")) + .get(DATA) + .toString()) .isEqualTo("{{(data_table.pageNo - 1) * data_table.pageSize}}"); - assertThat(((Map<String, Object>) find.get("query")).get(DATA).toString().replaceAll(specialCharactersRegex, "")) - .isEqualTo("{ field1.something: /{{data_table.searchText||\"\"}}/i }".replaceAll(specialCharactersRegex, "")); + assertThat(((Map<String, Object>) find.get("query")) + .get(DATA) + .toString() + .replaceAll(specialCharactersRegex, "")) + .isEqualTo("{ field1.something: /{{data_table.searchText||\"\"}}/i }" + .replaceAll(specialCharactersRegex, "")); - assertThat(((Map<String, Object>) formData.get("smartSubstitution")).get(DATA)).isEqualTo(false); + assertThat(((Map<String, Object>) formData.get("smartSubstitution")).get(DATA)) + .isEqualTo(false); } else if (queryType.equals("INSERT")) { Map<String, Object> insert = (Map<String, Object>) formData.get("insert"); - assertThat(((Map<String, Object>) insert.get("documents")).get(DATA)).isEqualTo("{{insert_form.formData}}"); - assertThat(((Map<String, Object>) formData.get("smartSubstitution")).get(DATA)).isEqualTo(true); + assertThat(((Map<String, Object>) insert.get("documents")).get(DATA)) + .isEqualTo("{{insert_form.formData}}"); + assertThat(((Map<String, Object>) formData.get("smartSubstitution")).get(DATA)) + .isEqualTo(true); } } }) .verifyComplete(); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/DatasourceStructureSolutionTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/DatasourceStructureSolutionTest.java index 482e71b7eb45..66370b254ec3 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/DatasourceStructureSolutionTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/DatasourceStructureSolutionTest.java @@ -1,6 +1,5 @@ package com.appsmith.server.solutions; - import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceConfiguration; @@ -99,9 +98,11 @@ public void setup() { toCreate.setName("DatasourceServiceTest"); if (!StringUtils.hasLength(workspaceId)) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) @@ -124,7 +125,7 @@ private Datasource createDatasourceObject(String name, String workspaceId, Strin } private DatasourceStorageDTO generateSampleDatasourceStorageDTO() { - DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); + DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); Endpoint endpoint = new Endpoint("https://sample.endpoint", 5432L); DBAuth dbAuth = new DBAuth(); dbAuth.setPassword("password"); @@ -142,28 +143,28 @@ private DatasourceStorageDTO generateSampleDatasourceStorageDTO() { private DatasourceStructure generateDatasourceStructureObject() { DatasourceStructure.Column[] table1Columns = { - new DatasourceStructure.Column("_id1", "ObjectId", null, true), - new DatasourceStructure.Column("age1", "Integer", null, false), - new DatasourceStructure.Column("dob1", "Date", null, false), - new DatasourceStructure.Column("gender1", "String", null, false), - new DatasourceStructure.Column("luckyNumber1", "Long", null, false), - new DatasourceStructure.Column("name1", "String", null, false), - new DatasourceStructure.Column("netWorth1", "BigDecimal", null, false), - new DatasourceStructure.Column("updatedByCommand1", "Object", null, false), + new DatasourceStructure.Column("_id1", "ObjectId", null, true), + new DatasourceStructure.Column("age1", "Integer", null, false), + new DatasourceStructure.Column("dob1", "Date", null, false), + new DatasourceStructure.Column("gender1", "String", null, false), + new DatasourceStructure.Column("luckyNumber1", "Long", null, false), + new DatasourceStructure.Column("name1", "String", null, false), + new DatasourceStructure.Column("netWorth1", "BigDecimal", null, false), + new DatasourceStructure.Column("updatedByCommand1", "Object", null, false), }; DatasourceStructure.Table table1 = new DatasourceStructure.Table(TABLE, null, "Table1", List.of(table1Columns), null, null); DatasourceStructure.Column[] table2Columns = { - new DatasourceStructure.Column("_id2", "ObjectId", null, true), - new DatasourceStructure.Column("age2", "Integer", null, false), - new DatasourceStructure.Column("dob2", "Date", null, false), - new DatasourceStructure.Column("gender2", "String", null, false), - new DatasourceStructure.Column("luckyNumber2", "Long", null, false), - new DatasourceStructure.Column("name2", "String", null, false), - new DatasourceStructure.Column("netWorth2", "BigDecimal", null, false), - new DatasourceStructure.Column("updatedByCommand2", "Object", null, false), + new DatasourceStructure.Column("_id2", "ObjectId", null, true), + new DatasourceStructure.Column("age2", "Integer", null, false), + new DatasourceStructure.Column("dob2", "Date", null, false), + new DatasourceStructure.Column("gender2", "String", null, false), + new DatasourceStructure.Column("luckyNumber2", "Long", null, false), + new DatasourceStructure.Column("name2", "String", null, false), + new DatasourceStructure.Column("netWorth2", "BigDecimal", null, false), + new DatasourceStructure.Column("updatedByCommand2", "Object", null, false), }; DatasourceStructure.Table table2 = @@ -176,37 +177,40 @@ private DatasourceStructure generateDatasourceStructureObject() { @WithUserDetails(value = "api_user") public void verifyGenerateNewStructureWhenNotPresent() { doReturn(Mono.just(generateDatasourceStructureObject())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); Mono<DatasourceStructure> datasourceStructureMono = datasourceStructureSolution.getStructure(datasourceId, Boolean.FALSE, defaultEnvironmentId); - StepVerifier - .create(datasourceStructureMono) - .assertNext(datasourceStructure -> { - assertThat(datasourceStructure.getTables().size()).isEqualTo(2); - assertThat(datasourceStructure.getTables().get(0).getName()).isEqualTo("Table1"); - assertThat(datasourceStructure.getTables().get(1).getName()).isEqualTo("Table2"); - }) - .verifyComplete(); + StepVerifier.create(datasourceStructureMono) + .assertNext(datasourceStructure -> { + assertThat(datasourceStructure.getTables().size()).isEqualTo(2); + assertThat(datasourceStructure.getTables().get(0).getName()).isEqualTo("Table1"); + assertThat(datasourceStructure.getTables().get(1).getName()).isEqualTo("Table2"); + }) + .verifyComplete(); } @Test @WithUserDetails(value = "api_user") public void verifyUseCachedStructureWhenStructurePresent() { doReturn(Mono.just(generateDatasourceStructureObject())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); - datasourceStructureSolution.getStructure(datasourceId, Boolean.TRUE, defaultEnvironmentId).block(); + datasourceStructureSolution + .getStructure(datasourceId, Boolean.TRUE, defaultEnvironmentId) + .block(); doReturn(Mono.just(new DatasourceStructure())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); Mono<DatasourceStructure> datasourceStructureMono = datasourceStructureSolution.getStructure(datasourceId, Boolean.FALSE, defaultEnvironmentId); - StepVerifier - .create(datasourceStructureMono) + StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { assertThat(datasourceStructure.getTables().size()).isEqualTo(2); assertThat(datasourceStructure.getTables().get(0).getName()).isEqualTo("Table1"); @@ -219,18 +223,21 @@ public void verifyUseCachedStructureWhenStructurePresent() { @WithUserDetails(value = "api_user") public void verifyUseNewStructureWhenIgnoreCacheSetTrue() { doReturn(Mono.just(new DatasourceStructure())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); - datasourceStructureSolution.getStructure(datasourceId, Boolean.TRUE, defaultEnvironmentId).block(); + datasourceStructureSolution + .getStructure(datasourceId, Boolean.TRUE, defaultEnvironmentId) + .block(); doReturn(Mono.just(generateDatasourceStructureObject())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); Mono<DatasourceStructure> datasourceStructureMono = datasourceStructureSolution.getStructure(datasourceId, Boolean.TRUE, defaultEnvironmentId); - StepVerifier - .create(datasourceStructureMono) + StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { assertThat(datasourceStructure.getTables().size()).isEqualTo(2); assertThat(datasourceStructure.getTables().get(0).getName()).isEqualTo("Table1"); @@ -243,15 +250,17 @@ public void verifyUseNewStructureWhenIgnoreCacheSetTrue() { @WithUserDetails(value = "api_user") public void verifyDatasourceStorageStructureGettingSaved() { doReturn(Mono.just(generateDatasourceStructureObject())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); - datasourceStructureSolution.getStructure(datasourceId, Boolean.TRUE, defaultEnvironmentId).block(); + datasourceStructureSolution + .getStructure(datasourceId, Boolean.TRUE, defaultEnvironmentId) + .block(); Mono<DatasourceStorageStructure> datasourceStorageStructureMono = datasourceStructureService.getByDatasourceIdAndEnvironmentId(datasourceId, defaultEnvironmentId); - StepVerifier - .create(datasourceStorageStructureMono) + StepVerifier.create(datasourceStorageStructureMono) .assertNext(datasourceStorageStructure -> { assertThat(datasourceStorageStructure.getDatasourceId()).isEqualTo(datasourceId); assertThat(datasourceStorageStructure.getEnvironmentId()).isEqualTo(defaultEnvironmentId); @@ -268,13 +277,13 @@ public void verifyDatasourceStorageStructureGettingSaved() { @WithUserDetails(value = "api_user") public void verifyCaseWhereNoEnvironmentProvided() { doReturn(Mono.just(generateDatasourceStructureObject())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); Mono<DatasourceStructure> datasourceStructureMono = datasourceStructureSolution.getStructure(datasourceId, Boolean.FALSE, null); - StepVerifier - .create(datasourceStructureMono) + StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { assertThat(datasourceStructure.getTables().size()).isEqualTo(2); assertThat(datasourceStructure.getTables().get(0).getName()).isEqualTo("Table1"); @@ -287,21 +296,24 @@ public void verifyCaseWhereNoEnvironmentProvided() { @WithUserDetails(value = "api_user") public void verifyUseCachedStructureWhenStructurePresentWithNoEnvironment() { doReturn(Mono.just(generateDatasourceStructureObject())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); // Null defaults to default environment - datasourceStructureSolution.getStructure(datasourceId, Boolean.TRUE, null).block(); + datasourceStructureSolution + .getStructure(datasourceId, Boolean.TRUE, null) + .block(); doReturn(Mono.just(new DatasourceStructure())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); // Null defaults to default environment // will work as expected Mono<DatasourceStructure> datasourceStructureMono = datasourceStructureSolution.getStructure(datasourceId, Boolean.FALSE, null); - StepVerifier - .create(datasourceStructureMono) + StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { assertThat(datasourceStructure.getTables().size()).isEqualTo(2); assertThat(datasourceStructure.getTables().get(0).getName()).isEqualTo("Table1"); @@ -319,7 +331,7 @@ public void verifyEmptyStructureForPluginsWithNoGetStructureImplementation() { oAuth2.setClientId("clientId"); oAuth2.setClientSecret("clientSecret"); - DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); + DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setUrl("https://mock.codes"); datasourceConfiguration.setAuthentication(oAuth2); @@ -337,8 +349,7 @@ public void verifyEmptyStructureForPluginsWithNoGetStructureImplementation() { Mono<DatasourceStructure> datasourceStructureMono = datasourceStructureSolution.getStructure(savedDatasource.getId(), Boolean.FALSE, null); - StepVerifier - .create(datasourceStructureMono) + StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { assertThat(datasourceStructure.getTables()).isNull(); assertThat(datasourceStructure.getError()).isNull(); @@ -350,20 +361,22 @@ public void verifyEmptyStructureForPluginsWithNoGetStructureImplementation() { @WithUserDetails(value = "api_user") public void verifyDatasourceStorageStructureEntriesWithTwoEnvironmentId() { doReturn(Mono.just(generateDatasourceStructureObject())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); // creating an entry with environmentId as randomId and then - datasourceStructureService. - saveStructure(datasourceId, "randomId", generateDatasourceStructureObject()) + datasourceStructureService + .saveStructure(datasourceId, "randomId", generateDatasourceStructureObject()) .block(); - datasourceStructureSolution.getStructure(datasourceId, Boolean.FALSE, defaultEnvironmentId).block(); + datasourceStructureSolution + .getStructure(datasourceId, Boolean.FALSE, defaultEnvironmentId) + .block(); Mono<DatasourceStorageStructure> datasourceStorageStructureMono = datasourceStructureService.getByDatasourceIdAndEnvironmentId(datasourceId, defaultEnvironmentId); - StepVerifier - .create(datasourceStorageStructureMono) + StepVerifier.create(datasourceStorageStructureMono) .assertNext(datasourceStorageStructure -> { assertThat(datasourceStorageStructure.getDatasourceId()).isEqualTo(datasourceId); assertThat(datasourceStorageStructure.getEnvironmentId()).isEqualTo(defaultEnvironmentId); @@ -373,8 +386,7 @@ public void verifyDatasourceStorageStructureEntriesWithTwoEnvironmentId() { Mono<DatasourceStorageStructure> datasourceStorageStructureMonoWithRandomEnvironmentId = datasourceStructureService.getByDatasourceIdAndEnvironmentId(datasourceId, "randomId"); - StepVerifier - .create(datasourceStorageStructureMonoWithRandomEnvironmentId) + StepVerifier.create(datasourceStorageStructureMonoWithRandomEnvironmentId) .assertNext(datasourceStorageStructure -> { assertThat(datasourceStorageStructure.getDatasourceId()).isEqualTo(datasourceId); assertThat(datasourceStorageStructure.getEnvironmentId()).isEqualTo("randomId"); @@ -386,26 +398,26 @@ public void verifyDatasourceStorageStructureEntriesWithTwoEnvironmentId() { @WithUserDetails(value = "api_user") public void verifyDuplicateKeyErrorOnSave() { doReturn(Mono.just(generateDatasourceStructureObject())) - .when(datasourceContextService).retryOnce(any(), any()); + .when(datasourceContextService) + .retryOnce(any(), any()); - datasourceStructureSolution.getStructure(datasourceId, Boolean.FALSE, defaultEnvironmentId).block(); + datasourceStructureSolution + .getStructure(datasourceId, Boolean.FALSE, defaultEnvironmentId) + .block(); DatasourceStorageStructure datasourceStorageStructure = new DatasourceStorageStructure(); datasourceStorageStructure.setDatasourceId(datasourceId); datasourceStorageStructure.setEnvironmentId(defaultEnvironmentId); datasourceStorageStructure.setStructure(new DatasourceStructure()); - Mono<DatasourceStorageStructure> datasourceStorageStructureMono = + Mono<DatasourceStorageStructure> datasourceStorageStructureMono = datasourceStructureService.save(datasourceStorageStructure); - StepVerifier - .create(datasourceStorageStructureMono) - .verifyErrorSatisfies(error -> { - assertThat(error).isInstanceOf(DuplicateKeyException.class); - }); + StepVerifier.create(datasourceStorageStructureMono).verifyErrorSatisfies(error -> { + assertThat(error).isInstanceOf(DuplicateKeyException.class); + }); } - @Test @WithUserDetails(value = "api_user") public void verifyEmptyDatasourceStructureObjectIfDatasourceIsInvalid() { @@ -416,19 +428,17 @@ public void verifyEmptyDatasourceStructureObjectIfDatasourceIsInvalid() { datasourceStorage.getInvalids().add("random invalid"); doReturn(Mono.just(datasourceStorage)) - .when(datasourceStorageService).findByDatasourceAndEnvironmentId(any(), any()); + .when(datasourceStorageService) + .findByDatasourceAndEnvironmentId(any(), any()); Mono<DatasourceStructure> datasourceStructureMono = datasourceStructureSolution.getStructure(datasourceId, Boolean.FALSE, defaultEnvironmentId); - StepVerifier - .create(datasourceStructureMono) + StepVerifier.create(datasourceStructureMono) .assertNext(datasourceStructure -> { assertThat(datasourceStructure.getTables()).isNull(); assertThat(datasourceStructure.getError()).isNull(); }) .verifyComplete(); - } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/DatasourceTriggerSolutionTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/DatasourceTriggerSolutionTest.java index 6bee37bae5b2..e21cb13bc7fd 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/DatasourceTriggerSolutionTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/DatasourceTriggerSolutionTest.java @@ -9,7 +9,6 @@ import com.appsmith.external.models.TriggerRequestDTO; import com.appsmith.external.models.TriggerResultDTO; import com.appsmith.external.plugins.PluginExecutor; -import com.appsmith.server.constants.FieldName; import com.appsmith.server.domains.Plugin; import com.appsmith.server.domains.Workspace; import com.appsmith.server.helpers.MockPluginExecutor; @@ -81,17 +80,20 @@ public class DatasourceTriggerSolutionTest { @BeforeEach @WithUserDetails(value = "api_user") public void setup() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Workspace workspace = new Workspace(); workspace.setName("Datasource Trigger Test Workspace"); Workspace savedWorkspace = workspaceService.create(workspace).block(); workspaceId = savedWorkspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); Datasource datasource = new Datasource(); datasource.setName("Datasource Trigger Database"); datasource.setWorkspaceId(workspaceId); - Plugin installed_plugin = pluginService.findByName("Installed Plugin Name").block(); + Plugin installed_plugin = + pluginService.findByName("Installed Plugin Name").block(); datasource.setPluginId(installed_plugin.getId()); DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setUrl("http://test.com"); @@ -108,80 +110,72 @@ public void setup() { @Test @WithUserDetails(value = "api_user") public void datasourceTriggerTest() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); DatasourceStructure.Column[] table1Columns = { - new DatasourceStructure.Column("_id1", "ObjectId", null, true), - new DatasourceStructure.Column("age1", "Integer", null, false), - new DatasourceStructure.Column("dob1", "Date", null, false), - new DatasourceStructure.Column("gender1", "String", null, false), - new DatasourceStructure.Column("luckyNumber1", "Long", null, false), - new DatasourceStructure.Column("name1", "String", null, false), - new DatasourceStructure.Column("netWorth1", "BigDecimal", null, false), - new DatasourceStructure.Column("updatedByCommand1", "Object", null, false), + new DatasourceStructure.Column("_id1", "ObjectId", null, true), + new DatasourceStructure.Column("age1", "Integer", null, false), + new DatasourceStructure.Column("dob1", "Date", null, false), + new DatasourceStructure.Column("gender1", "String", null, false), + new DatasourceStructure.Column("luckyNumber1", "Long", null, false), + new DatasourceStructure.Column("name1", "String", null, false), + new DatasourceStructure.Column("netWorth1", "BigDecimal", null, false), + new DatasourceStructure.Column("updatedByCommand1", "Object", null, false), }; - DatasourceStructure.Table table1 = new DatasourceStructure.Table(TABLE, null, "Table1", List.of(table1Columns), null, null); + DatasourceStructure.Table table1 = + new DatasourceStructure.Table(TABLE, null, "Table1", List.of(table1Columns), null, null); DatasourceStructure.Column[] table2Columns = { - new DatasourceStructure.Column("_id2", "ObjectId", null, true), - new DatasourceStructure.Column("age2", "Integer", null, false), - new DatasourceStructure.Column("dob2", "Date", null, false), - new DatasourceStructure.Column("gender2", "String", null, false), - new DatasourceStructure.Column("luckyNumber2", "Long", null, false), - new DatasourceStructure.Column("name2", "String", null, false), - new DatasourceStructure.Column("netWorth2", "BigDecimal", null, false), - new DatasourceStructure.Column("updatedByCommand2", "Object", null, false), + new DatasourceStructure.Column("_id2", "ObjectId", null, true), + new DatasourceStructure.Column("age2", "Integer", null, false), + new DatasourceStructure.Column("dob2", "Date", null, false), + new DatasourceStructure.Column("gender2", "String", null, false), + new DatasourceStructure.Column("luckyNumber2", "Long", null, false), + new DatasourceStructure.Column("name2", "String", null, false), + new DatasourceStructure.Column("netWorth2", "BigDecimal", null, false), + new DatasourceStructure.Column("updatedByCommand2", "Object", null, false), }; - DatasourceStructure.Table table2 = new DatasourceStructure.Table(TABLE, null, "Table2", List.of(table2Columns), null, null); + DatasourceStructure.Table table2 = + new DatasourceStructure.Table(TABLE, null, "Table2", List.of(table2Columns), null, null); DatasourceStructure testStructure = new DatasourceStructure(List.of(table1, table2)); - Mockito - .when(datasourceStructureSolution - .getStructure( - Mockito.anyString(), - Mockito.anyBoolean(), Mockito.any())) + Mockito.when(datasourceStructureSolution.getStructure(Mockito.anyString(), Mockito.anyBoolean(), Mockito.any())) .thenReturn(Mono.just(testStructure)); - Datasource datasource = datasourceService.findById(datasourceId, datasourcePermission.getReadPermission()).block(); + Datasource datasource = datasourceService + .findById(datasourceId, datasourcePermission.getReadPermission()) + .block(); Mockito.doReturn(Mono.just(Boolean.TRUE)).when(featureFlagService).check(Mockito.any()); Mono<TriggerResultDTO> tableNameMono = datasourceTriggerSolution.trigger( datasourceId, - null, new TriggerRequestDTO( - "ENTITY_SELECTOR", - Map.of(), - ClientDataDisplayType.DROP_DOWN)); + null, + new TriggerRequestDTO("ENTITY_SELECTOR", Map.of(), ClientDataDisplayType.DROP_DOWN)); Mono<TriggerResultDTO> columnNamesMono = datasourceTriggerSolution.trigger( datasourceId, - null, new TriggerRequestDTO( - "ENTITY_SELECTOR", - Map.of("tableName", "Table1"), - ClientDataDisplayType.DROP_DOWN)); + null, + new TriggerRequestDTO( + "ENTITY_SELECTOR", Map.of("tableName", "Table1"), ClientDataDisplayType.DROP_DOWN)); StepVerifier.create(tableNameMono) .assertNext(tablesResult -> { - List tables = (List) tablesResult.getTrigger(); assertEquals(2, tables.size()); - }) .verifyComplete(); StepVerifier.create(columnNamesMono) .assertNext(columnsResult -> { - List columns = (List) columnsResult.getTrigger(); assertEquals(8, columns.size()); - }) .verifyComplete(); - } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EnvManagerTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EnvManagerTest.java index bab3ca1b3b4d..82e8c6216112 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EnvManagerTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EnvManagerTest.java @@ -44,40 +44,56 @@ @Slf4j public class EnvManagerTest { EnvManager envManager; + @MockBean private SessionUserService sessionUserService; + @MockBean private UserService userService; + @MockBean private AnalyticsService analyticsService; + @MockBean private UserRepository userRepository; + @MockBean private EmailSender emailSender; + @MockBean private CommonConfig commonConfig; + @MockBean private EmailConfig emailConfig; + @MockBean private JavaMailSender javaMailSender; + @MockBean private GoogleRecaptchaConfig googleRecaptchaConfig; + @MockBean private FileUtils fileUtils; + @MockBean private ConfigService configService; + @MockBean private PermissionGroupService permissionGroupService; + @MockBean private UserUtils userUtils; + @MockBean private TenantService tenantService; + @MockBean private ObjectMapper objectMapper; @BeforeEach public void setup() { - envManager = new EnvManagerImpl(sessionUserService, + envManager = new EnvManagerImpl( + sessionUserService, userService, analyticsService, userRepository, @@ -96,214 +112,181 @@ public void setup() { @Test public void simpleSample() { - final String content = "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL='second value'\n\nAPPSMITH_INSTANCE_NAME='third value'"; - - assertThat(envManager.transformEnvContent( - content, - Map.of("APPSMITH_MONGODB_URI", "new first value") - )).containsExactly( - "APPSMITH_MONGODB_URI='new first value'", - "APPSMITH_REDIS_URL='second value'", - "", - "APPSMITH_INSTANCE_NAME='third value'" - ); - - assertThat(envManager.transformEnvContent( - content, - Map.of("APPSMITH_REDIS_URL", "new second value") - )).containsExactly( - "APPSMITH_MONGODB_URI='first value'", - "APPSMITH_REDIS_URL='new second value'", - "", - "APPSMITH_INSTANCE_NAME='third value'" - ); + final String content = + "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL='second value'\n\nAPPSMITH_INSTANCE_NAME='third value'"; + + assertThat(envManager.transformEnvContent(content, Map.of("APPSMITH_MONGODB_URI", "new first value"))) + .containsExactly( + "APPSMITH_MONGODB_URI='new first value'", + "APPSMITH_REDIS_URL='second value'", + "", + "APPSMITH_INSTANCE_NAME='third value'"); + + assertThat(envManager.transformEnvContent(content, Map.of("APPSMITH_REDIS_URL", "new second value"))) + .containsExactly( + "APPSMITH_MONGODB_URI='first value'", + "APPSMITH_REDIS_URL='new second value'", + "", + "APPSMITH_INSTANCE_NAME='third value'"); + + assertThat(envManager.transformEnvContent(content, Map.of("APPSMITH_INSTANCE_NAME", "new third value"))) + .containsExactly( + "APPSMITH_MONGODB_URI='first value'", + "APPSMITH_REDIS_URL='second value'", + "", + "APPSMITH_INSTANCE_NAME='new third value'"); assertThat(envManager.transformEnvContent( - content, - Map.of("APPSMITH_INSTANCE_NAME", "new third value") - )).containsExactly( - "APPSMITH_MONGODB_URI='first value'", - "APPSMITH_REDIS_URL='second value'", - "", - "APPSMITH_INSTANCE_NAME='new third value'" - ); - - assertThat(envManager.transformEnvContent( - content, - Map.of( - "APPSMITH_MONGODB_URI", "new first value", - "APPSMITH_INSTANCE_NAME", "new third value" - ) - )).containsExactly( - "APPSMITH_MONGODB_URI='new first value'", - "APPSMITH_REDIS_URL='second value'", - "", - "APPSMITH_INSTANCE_NAME='new third value'" - ); - + content, + Map.of( + "APPSMITH_MONGODB_URI", "new first value", + "APPSMITH_INSTANCE_NAME", "new third value"))) + .containsExactly( + "APPSMITH_MONGODB_URI='new first value'", + "APPSMITH_REDIS_URL='second value'", + "", + "APPSMITH_INSTANCE_NAME='new third value'"); } @Test public void emptyValues() { - final String content = "APPSMITH_MONGODB_URI=first value\nAPPSMITH_REDIS_URL=\n\nAPPSMITH_INSTANCE_NAME=third value"; - - assertThat(envManager.transformEnvContent( - content, - Map.of("APPSMITH_REDIS_URL", "new second value") - )).containsExactly( - "APPSMITH_MONGODB_URI=first value", - "APPSMITH_REDIS_URL='new second value'", - "", - "APPSMITH_INSTANCE_NAME=third value" - ); - - assertThat(envManager.transformEnvContent( - content, - Map.of("APPSMITH_REDIS_URL", "") - )).containsExactly( - "APPSMITH_MONGODB_URI=first value", - "APPSMITH_REDIS_URL=", - "", - "APPSMITH_INSTANCE_NAME=third value" - ); - + final String content = + "APPSMITH_MONGODB_URI=first value\nAPPSMITH_REDIS_URL=\n\nAPPSMITH_INSTANCE_NAME=third value"; + + assertThat(envManager.transformEnvContent(content, Map.of("APPSMITH_REDIS_URL", "new second value"))) + .containsExactly( + "APPSMITH_MONGODB_URI=first value", + "APPSMITH_REDIS_URL='new second value'", + "", + "APPSMITH_INSTANCE_NAME=third value"); + + assertThat(envManager.transformEnvContent(content, Map.of("APPSMITH_REDIS_URL", ""))) + .containsExactly( + "APPSMITH_MONGODB_URI=first value", + "APPSMITH_REDIS_URL=", + "", + "APPSMITH_INSTANCE_NAME=third value"); } @Test public void quotedValues() { - final String content = "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL=\"quoted value\"\n\nAPPSMITH_INSTANCE_NAME='third value'"; - - assertThat(envManager.transformEnvContent( - content, - Map.of( - "APPSMITH_MONGODB_URI", "new first value", - "APPSMITH_REDIS_URL", "new second value" - ) - )).containsExactly( - "APPSMITH_MONGODB_URI='new first value'", - "APPSMITH_REDIS_URL='new second value'", - "", - "APPSMITH_INSTANCE_NAME='third value'" - ); + final String content = + "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL=\"quoted value\"\n\nAPPSMITH_INSTANCE_NAME='third value'"; assertThat(envManager.transformEnvContent( - content, - Map.of("APPSMITH_REDIS_URL", "") - )).containsExactly( - "APPSMITH_MONGODB_URI='first value'", - "APPSMITH_REDIS_URL=", - "", - "APPSMITH_INSTANCE_NAME='third value'" - ); + content, + Map.of( + "APPSMITH_MONGODB_URI", "new first value", + "APPSMITH_REDIS_URL", "new second value"))) + .containsExactly( + "APPSMITH_MONGODB_URI='new first value'", + "APPSMITH_REDIS_URL='new second value'", + "", + "APPSMITH_INSTANCE_NAME='third value'"); + + assertThat(envManager.transformEnvContent(content, Map.of("APPSMITH_REDIS_URL", ""))) + .containsExactly( + "APPSMITH_MONGODB_URI='first value'", + "APPSMITH_REDIS_URL=", + "", + "APPSMITH_INSTANCE_NAME='third value'"); assertThat(envManager.transformEnvContent( - content, - Map.of( - "APPSMITH_INSTANCE_NAME", "Sponge-bob's Instance", - "APPSMITH_REDIS_URL", "value with \" char in it" - ) - )).containsExactly( - "APPSMITH_MONGODB_URI='first value'", - "APPSMITH_REDIS_URL='value with \" char in it'", - "", - "APPSMITH_INSTANCE_NAME='Sponge-bob'\"'\"'s Instance'" - ); - + content, + Map.of( + "APPSMITH_INSTANCE_NAME", "Sponge-bob's Instance", + "APPSMITH_REDIS_URL", "value with \" char in it"))) + .containsExactly( + "APPSMITH_MONGODB_URI='first value'", + "APPSMITH_REDIS_URL='value with \" char in it'", + "", + "APPSMITH_INSTANCE_NAME='Sponge-bob'\"'\"'s Instance'"); } @Test public void parseEmptyValues() { - assertThat(envManager.parseToMap( - "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL=\n\nAPPSMITH_INSTANCE_NAME='third value'" - )).containsExactlyInAnyOrderEntriesOf(Map.of( - "APPSMITH_MONGODB_URI", "first value", - "APPSMITH_REDIS_URL", "", - "APPSMITH_INSTANCE_NAME", "third value" - )); - + assertThat( + envManager.parseToMap( + "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL=\n\nAPPSMITH_INSTANCE_NAME='third value'")) + .containsExactlyInAnyOrderEntriesOf(Map.of( + "APPSMITH_MONGODB_URI", "first value", + "APPSMITH_REDIS_URL", "", + "APPSMITH_INSTANCE_NAME", "third value")); } @Test public void parseQuotedValues() { - assertThat(envManager.parseToMap( - "APPSMITH_MONGODB_URI=first\nAPPSMITH_REDIS_URL=\"quoted value\"\n\nAPPSMITH_INSTANCE_NAME='third value'" - )).containsExactlyInAnyOrderEntriesOf(Map.of( - "APPSMITH_MONGODB_URI", "first", - "APPSMITH_REDIS_URL", "quoted value", - "APPSMITH_INSTANCE_NAME", "third value" - )); - - assertThat(envManager.parseToMap( - "APPSMITH_INSTANCE_NAME=\"Sponge-bob's Instance\"" - )).containsExactlyInAnyOrderEntriesOf(Map.of( - "APPSMITH_INSTANCE_NAME", "Sponge-bob's Instance" - )); + assertThat( + envManager.parseToMap( + "APPSMITH_MONGODB_URI=first\nAPPSMITH_REDIS_URL=\"quoted value\"\n\nAPPSMITH_INSTANCE_NAME='third value'")) + .containsExactlyInAnyOrderEntriesOf(Map.of( + "APPSMITH_MONGODB_URI", "first", + "APPSMITH_REDIS_URL", "quoted value", + "APPSMITH_INSTANCE_NAME", "third value")); + assertThat(envManager.parseToMap("APPSMITH_INSTANCE_NAME=\"Sponge-bob's Instance\"")) + .containsExactlyInAnyOrderEntriesOf(Map.of("APPSMITH_INSTANCE_NAME", "Sponge-bob's Instance")); } @Test public void parseTestWithEscapes() { assertThat(envManager.parseToMap( - "APPSMITH_ALLOWED_FRAME_ANCESTORS=\"'\"'none'\"'\"\nAPPSMITH_REDIS_URL='second\" value'\n" - )).containsExactlyInAnyOrderEntriesOf(Map.of( - "APPSMITH_ALLOWED_FRAME_ANCESTORS", "'none'", - "APPSMITH_REDIS_URL", "second\" value" - )); + "APPSMITH_ALLOWED_FRAME_ANCESTORS=\"'\"'none'\"'\"\nAPPSMITH_REDIS_URL='second\" value'\n")) + .containsExactlyInAnyOrderEntriesOf(Map.of( + "APPSMITH_ALLOWED_FRAME_ANCESTORS", "'none'", + "APPSMITH_REDIS_URL", "second\" value")); } @Test public void disallowedVariable() { - final String content = "APPSMITH_MONGODB_URI=first value\nDISALLOWED_NASTY_STUFF=\"quoted value\"\n\nAPPSMITH_INSTANCE_NAME=third value"; + final String content = + "APPSMITH_MONGODB_URI=first value\nDISALLOWED_NASTY_STUFF=\"quoted value\"\n\nAPPSMITH_INSTANCE_NAME=third value"; assertThatThrownBy(() -> envManager.transformEnvContent( - content, - Map.of( - "APPSMITH_MONGODB_URI", "new first value", - "DISALLOWED_NASTY_STUFF", "new second value" - ) - )) + content, + Map.of( + "APPSMITH_MONGODB_URI", "new first value", + "DISALLOWED_NASTY_STUFF", "new second value"))) .matches(value -> value instanceof AppsmithException && AppsmithError.GENERIC_BAD_REQUEST.equals(((AppsmithException) value).getError())); } @Test public void addNewVariable() { - final String content = "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL='quoted value'\n\nAPPSMITH_INSTANCE_NAME='third value'"; + final String content = + "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL='quoted value'\n\nAPPSMITH_INSTANCE_NAME='third value'"; assertThat(envManager.transformEnvContent( - content, - Map.of( - "APPSMITH_MONGODB_URI", "new first value", - "APPSMITH_DISABLE_TELEMETRY", "false" - ) - )).containsExactly( - "APPSMITH_MONGODB_URI='new first value'", - "APPSMITH_REDIS_URL='quoted value'", - "", - "APPSMITH_INSTANCE_NAME='third value'", - "APPSMITH_DISABLE_TELEMETRY=false" - ); + content, + Map.of( + "APPSMITH_MONGODB_URI", "new first value", + "APPSMITH_DISABLE_TELEMETRY", "false"))) + .containsExactly( + "APPSMITH_MONGODB_URI='new first value'", + "APPSMITH_REDIS_URL='quoted value'", + "", + "APPSMITH_INSTANCE_NAME='third value'", + "APPSMITH_DISABLE_TELEMETRY=false"); } @Test public void setValueWithQuotes() { - final String content = "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL='quoted value'\n\nAPPSMITH_INSTANCE_NAME='third value'"; + final String content = + "APPSMITH_MONGODB_URI='first value'\nAPPSMITH_REDIS_URL='quoted value'\n\nAPPSMITH_INSTANCE_NAME='third value'"; assertThat(envManager.transformEnvContent( - content, - Map.of( - "APPSMITH_MONGODB_URI", "'just quotes'", - "APPSMITH_DISABLE_TELEMETRY", "some quotes 'inside' it" - ) - )).containsExactly( - "APPSMITH_MONGODB_URI=\"'\"'just quotes'\"'\"", - "APPSMITH_REDIS_URL='quoted value'", - "", - "APPSMITH_INSTANCE_NAME='third value'", - "APPSMITH_DISABLE_TELEMETRY='some quotes '\"'\"'inside'\"'\"' it'" - ); + content, + Map.of( + "APPSMITH_MONGODB_URI", "'just quotes'", + "APPSMITH_DISABLE_TELEMETRY", "some quotes 'inside' it"))) + .containsExactly( + "APPSMITH_MONGODB_URI=\"'\"'just quotes'\"'\"", + "APPSMITH_REDIS_URL='quoted value'", + "", + "APPSMITH_INSTANCE_NAME='third value'", + "APPSMITH_DISABLE_TELEMETRY='some quotes '\"'\"'inside'\"'\"' it'"); } @Test @@ -345,8 +328,7 @@ public void download_UserIsSuperUser_ReturnsZip() throws IOException { Mockito.when(exchange.getResponse()).thenReturn(response); Mockito.when(response.writeWith(any())).thenReturn(Mono.empty()); - StepVerifier.create(envManager.download(exchange)) - .verifyComplete(); + StepVerifier.create(envManager.download(exchange)).verifyComplete(); assertThat(headers.getContentType().toString()).isEqualTo("application/zip"); assertThat(headers.getContentDisposition().toString()).containsIgnoringCase("appsmith-config.zip"); @@ -376,7 +358,6 @@ public void setEnv_AndGetAll() { Mockito.when(envManagerInner.getAll()).thenReturn(Mono.just(envs)); Mockito.when(envManagerInner.getAllNonEmpty()).thenCallRealMethod(); - Mono<Map<String, String>> envMono = envManagerInner.getAllNonEmpty(); StepVerifier.create(envMono) diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ExampleApplicationsAreMarked.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ExampleApplicationsAreMarked.java index 6189714aaf48..4cd65d960d82 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ExampleApplicationsAreMarked.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ExampleApplicationsAreMarked.java @@ -60,11 +60,8 @@ public class ExampleApplicationsAreMarked { public void exampleApplicationsAreMarked() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace 3"); - final Mono<List<Application>> resultMono = Mono - .zip( - workspaceService.create(newWorkspace), - sessionUserService.getCurrentUser() - ) + final Mono<List<Application>> resultMono = Mono.zip( + workspaceService.create(newWorkspace), sessionUserService.getCurrentUser()) .flatMap(tuple -> { final Workspace workspace = tuple.getT1(); @@ -92,15 +89,14 @@ public void exampleApplicationsAreMarked() { app4.setWorkspaceId(workspace.getId()); app4.setIsPublic(false); - Mockito.when(configService.getTemplateApplications()).thenReturn(Flux.fromIterable(List.of(app1, app2, app3))); + Mockito.when(configService.getTemplateApplications()) + .thenReturn(Flux.fromIterable(List.of(app1, app2, app3))); - return Mono - .when( + return Mono.when( applicationPageService.createApplication(app1), applicationPageService.createApplication(app2), applicationPageService.createApplication(app3), - applicationPageService.createApplication(app4) - ) + applicationPageService.createApplication(app4)) .thenReturn(workspace.getId()); }) .flatMapMany(workspaceId -> applicationService.findByWorkspaceId(workspaceId, READ_APPLICATIONS)) @@ -109,9 +105,9 @@ public void exampleApplicationsAreMarked() { StepVerifier.create(resultMono) .assertNext(applications -> { assertThat(applications).hasSize(4); - assertThat(applications.stream().filter(Application::isAppIsExample)).hasSize(3); + assertThat(applications.stream().filter(Application::isAppIsExample)) + .hasSize(3); }) .verifyComplete(); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ForkExamplesWorkspaceServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ForkExamplesWorkspaceServiceTests.java index bff68fbad864..0b0252167d24 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ForkExamplesWorkspaceServiceTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ForkExamplesWorkspaceServiceTests.java @@ -93,26 +93,37 @@ public class ForkExamplesWorkspaceServiceTests { @MockBean PluginExecutor pluginExecutor; + @Autowired private ForkExamplesWorkspace forkExamplesWorkspace; + @Autowired private ApplicationService applicationService; + @Autowired private DatasourceService datasourceService; + @Autowired private WorkspaceService workspaceService; + @Autowired private ApplicationPageService applicationPageService; + @Autowired private SessionUserService sessionUserService; + @Autowired private NewActionService newActionService; + @Autowired private ActionCollectionService actionCollectionService; + @Autowired private PluginRepository pluginRepository; + @MockBean private PluginExecutorHelper pluginExecutorHelper; + @Autowired private LayoutActionService layoutActionService; @@ -140,27 +151,25 @@ public Mono<WorkspaceData> loadWorkspaceData(Workspace workspace) { final WorkspaceData data = new WorkspaceData(); data.workspace = workspace; - return Mono - .when( + return Mono.when( applicationService .findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) .map(data.applications::add), datasourceService .getAllByWorkspaceIdWithStorages(workspace.getId(), Optional.of(READ_DATASOURCES)) .map(data.datasources::add), - getActionsInWorkspace(workspace) - .map(data.actions::add), - getActionCollectionsInWorkspace(workspace) - .map(data.actionCollections::add), - workspaceService.getDefaultEnvironmentId(workspace.getId()) - .doOnSuccess(signal -> data.defaultEnvironmentId = signal) - ) + getActionsInWorkspace(workspace).map(data.actions::add), + getActionCollectionsInWorkspace(workspace).map(data.actionCollections::add), + workspaceService + .getDefaultEnvironmentId(workspace.getId()) + .doOnSuccess(signal -> data.defaultEnvironmentId = signal)) .thenReturn(data); } @BeforeEach public void setup() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); installedPlugin = pluginRepository.findByPackageName("installed-plugin").block(); } @@ -169,10 +178,11 @@ public void setup() { public void cloneEmptyWorkspace() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); - final Mono<WorkspaceData> resultMono = workspaceService.create(newWorkspace) + final Mono<WorkspaceData> resultMono = workspaceService + .create(newWorkspace) .zipWith(sessionUserService.getCurrentUser()) - .flatMap(tuple -> - forkExamplesWorkspace.forkWorkspaceForUser(tuple.getT1().getId(), tuple.getT2(), Flux.empty(), Flux.empty())) + .flatMap(tuple -> forkExamplesWorkspace.forkWorkspaceForUser( + tuple.getT1().getId(), tuple.getT2(), Flux.empty(), Flux.empty())) .flatMap(this::loadWorkspaceData); StepVerifier.create(resultMono) @@ -195,11 +205,8 @@ public void cloneEmptyWorkspace() { public void cloneWorkspaceWithItsContents() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); - final Mono<WorkspaceData> resultMono = Mono - .zip( - workspaceService.create(newWorkspace), - sessionUserService.getCurrentUser() - ) + final Mono<WorkspaceData> resultMono = Mono.zip( + workspaceService.create(newWorkspace), sessionUserService.getCurrentUser()) .flatMap(tuple -> { final Workspace workspace = tuple.getT1(); Application app1 = new Application(); @@ -210,19 +217,14 @@ public void cloneWorkspaceWithItsContents() { app2.setWorkspaceId(workspace.getId()); app2.setName("2 - private app"); - return Mono - .zip( + return Mono.zip( applicationPageService.createApplication(app1), - applicationPageService.createApplication(app2) - ) - .flatMap(tuple1 -> - forkExamplesWorkspace.forkWorkspaceForUser( - workspace.getId(), - tuple.getT2(), - Flux.fromArray(new Application[]{tuple1.getT1()}), - Flux.empty() - ) - ); + applicationPageService.createApplication(app2)) + .flatMap(tuple1 -> forkExamplesWorkspace.forkWorkspaceForUser( + workspace.getId(), + tuple.getT2(), + Flux.fromArray(new Application[] {tuple1.getT1()}), + Flux.empty())); }) .flatMap(this::loadWorkspaceData); @@ -249,11 +251,8 @@ public void cloneWorkspaceWithItsContents() { public void cloneWorkspaceWithOnlyPublicApplications() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace 2"); - final Mono<WorkspaceData> resultMono = Mono - .zip( - workspaceService.create(newWorkspace), - sessionUserService.getCurrentUser() - ) + final Mono<WorkspaceData> resultMono = Mono.zip( + workspaceService.create(newWorkspace), sessionUserService.getCurrentUser()) .flatMap(tuple -> { final Workspace workspace = tuple.getT1(); @@ -266,24 +265,23 @@ public void cloneWorkspaceWithOnlyPublicApplications() { app2.setName("2 - another public app more"); app2.setIsPublic(true); - return Mono - .zip( + return Mono.zip( applicationPageService.createApplication(app1), - applicationPageService.createApplication(app2).flatMap(application -> { - final PageDTO newPage = new PageDTO(); - newPage.setName("The New Page"); - newPage.setApplicationId(application.getId()); - return applicationPageService.createPage(newPage).thenReturn(application); - }) - ) - .flatMap(tuple1 -> - forkExamplesWorkspace.forkWorkspaceForUser( - workspace.getId(), - tuple.getT2(), - Flux.fromArray(new Application[]{tuple1.getT1(), tuple1.getT2()}), - Flux.empty() - ) - ); + applicationPageService + .createApplication(app2) + .flatMap(application -> { + final PageDTO newPage = new PageDTO(); + newPage.setName("The New Page"); + newPage.setApplicationId(application.getId()); + return applicationPageService + .createPage(newPage) + .thenReturn(application); + })) + .flatMap(tuple1 -> forkExamplesWorkspace.forkWorkspaceForUser( + workspace.getId(), + tuple.getT2(), + Flux.fromArray(new Application[] {tuple1.getT1(), tuple1.getT2()}), + Flux.empty())); }) .flatMap(this::loadWorkspaceData); @@ -295,10 +293,8 @@ public void cloneWorkspaceWithOnlyPublicApplications() { assertThat(data.workspace.getPolicies()).isNotEmpty(); assertThat(data.applications).hasSize(2); - assertThat(map(data.applications, Application::getName)).containsExactlyInAnyOrder( - "1 - public app more", - "2 - another public app more" - ); + assertThat(map(data.applications, Application::getName)) + .containsExactlyInAnyOrder("1 - public app more", "2 - another public app more"); for (final Application app : data.applications) { if ("2 - another public app more".equals(app.getName())) { @@ -320,11 +316,8 @@ public void cloneWorkspaceWithOnlyPublicApplications() { public void cloneWorkspaceWithOnlyPrivateApplications() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace 2"); - final Mono<WorkspaceData> resultMono = Mono - .zip( - workspaceService.create(newWorkspace), - sessionUserService.getCurrentUser() - ) + final Mono<WorkspaceData> resultMono = Mono.zip( + workspaceService.create(newWorkspace), sessionUserService.getCurrentUser()) .flatMap(tuple -> { final Workspace workspace = tuple.getT1(); @@ -337,9 +330,10 @@ public void cloneWorkspaceWithOnlyPrivateApplications() { app2.setName("2 - another private app more"); return Mono.when( - applicationPageService.createApplication(app1), - applicationPageService.createApplication(app2) - ).then(forkExamplesWorkspace.forkWorkspaceForUser(workspace.getId(), tuple.getT2(), Flux.empty(), Flux.empty())); + applicationPageService.createApplication(app1), + applicationPageService.createApplication(app2)) + .then(forkExamplesWorkspace.forkWorkspaceForUser( + workspace.getId(), tuple.getT2(), Flux.empty(), Flux.empty())); }) .flatMap(this::loadWorkspaceData); @@ -368,15 +362,17 @@ public void cloneApplicationMultipleTimes() { Application app1 = new Application(); app1.setName("awesome app"); app1.setWorkspaceId(sourceWorkspace.getId()); - Application sourceApplication = applicationPageService.createApplication(app1).block(); + Application sourceApplication = + applicationPageService.createApplication(app1).block(); final String appId = sourceApplication.getId(); final String appName = sourceApplication.getName(); Workspace newWorkspace = new Workspace(); newWorkspace.setName("Target Org 1"); Workspace targetWorkspace = workspaceService.create(newWorkspace).block(); - String sourceEnvironmentId = workspaceService.getDefaultEnvironmentId(sourceWorkspace.getId()).block(); - + String sourceEnvironmentId = workspaceService + .getDefaultEnvironmentId(sourceWorkspace.getId()) + .block(); Mono<Void> cloneMono = Mono.just(sourceApplication) .map(sourceApplication1 -> { @@ -385,9 +381,7 @@ public void cloneApplicationMultipleTimes() { return sourceApplication1; }) .flatMap(sourceApplication1 -> forkExamplesWorkspace.forkApplications( - targetWorkspace.getId(), - Flux.just(sourceApplication1), - sourceEnvironmentId)) + targetWorkspace.getId(), Flux.just(sourceApplication1), sourceEnvironmentId)) .then(); // Clone this application into the same workspace thrice. Mono<List<String>> resultMono = cloneMono @@ -413,12 +407,12 @@ public void cloneWorkspaceWithOnlyDatasources() { Workspace workspace = workspaceService.create(newWorkspace).block(); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) - .thenReturn(Mono.just(new MockPluginExecutor())).thenReturn(Mono.just(new MockPluginExecutor())); + .thenReturn(Mono.just(new MockPluginExecutor())) + .thenReturn(Mono.just(new MockPluginExecutor())); final Mono<WorkspaceData> resultMono = Mono.zip( workspaceService.getDefaultEnvironmentId(workspace.getId()), sessionUserService.getCurrentUser(), - pluginService.findByPackageName("restapi-plugin").map(Plugin::getId) - ) + pluginService.findByPackageName("restapi-plugin").map(Plugin::getId)) .flatMap(tuple -> { String environmentId = tuple.getT1(); @@ -430,9 +424,7 @@ public void cloneWorkspaceWithOnlyDatasources() { final DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); ds1.setDatasourceConfiguration(datasourceConfiguration); datasourceConfiguration.setUrl("http://example.org/get"); - datasourceConfiguration.setHeaders(List.of( - new Property("X-Answer", "42") - )); + datasourceConfiguration.setHeaders(List.of(new Property("X-Answer", "42"))); DatasourceStorage datasourceStorage1 = new DatasourceStorage(ds1, environmentId); HashMap<String, DatasourceStorageDTO> storages1 = new HashMap<>(); storages1.put(environmentId, new DatasourceStorageDTO(datasourceStorage1)); @@ -451,10 +443,9 @@ public void cloneWorkspaceWithOnlyDatasources() { storages2.put(environmentId, new DatasourceStorageDTO(datasourceStorage2)); ds2.setDatasourceStorages(storages2); - return Mono.when( - datasourceService.create(ds1), - datasourceService.create(ds2) - ).then(forkExamplesWorkspace.forkWorkspaceForUser(workspace.getId(), tuple.getT2(), Flux.empty(), Flux.empty())); + return Mono.when(datasourceService.create(ds1), datasourceService.create(ds2)) + .then(forkExamplesWorkspace.forkWorkspaceForUser( + workspace.getId(), tuple.getT2(), Flux.empty(), Flux.empty())); }) .flatMap(this::loadWorkspaceData); @@ -482,8 +473,7 @@ public void cloneWorkspaceWithOnlyDatasourcesSpecifiedExplicitly() { Workspace workspace = workspaceService.create(newWorkspace).block(); final Mono<WorkspaceData> resultMono = Mono.zip( workspaceService.getDefaultEnvironmentId(workspace.getId()), - sessionUserService.getCurrentUser() - ) + sessionUserService.getCurrentUser()) .flatMap(tuple -> { String environmentId = tuple.getT1(); @@ -494,9 +484,7 @@ public void cloneWorkspaceWithOnlyDatasourcesSpecifiedExplicitly() { final DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); ds1.setDatasourceConfiguration(datasourceConfiguration); datasourceConfiguration.setUrl("http://example.org/get"); - datasourceConfiguration.setHeaders(List.of( - new Property("X-Answer", "42") - )); + datasourceConfiguration.setHeaders(List.of(new Property("X-Answer", "42"))); DatasourceStorage datasourceStorage1 = new DatasourceStorage(ds1, environmentId); HashMap<String, DatasourceStorageDTO> storages1 = new HashMap<>(); storages1.put(environmentId, new DatasourceStorageDTO(datasourceStorage1)); @@ -515,15 +503,9 @@ public void cloneWorkspaceWithOnlyDatasourcesSpecifiedExplicitly() { storages2.put(environmentId, new DatasourceStorageDTO(datasourceStorage2)); ds2.setDatasourceStorages(storages2); - return Mono.zip( - datasourceService.create(ds1), - datasourceService.create(ds2) - ).flatMap(tuple1 -> forkExamplesWorkspace.forkWorkspaceForUser( - workspace.getId(), - tuple.getT2(), - Flux.empty(), - Flux.just(tuple1.getT1()) - )); + return Mono.zip(datasourceService.create(ds1), datasourceService.create(ds2)) + .flatMap(tuple1 -> forkExamplesWorkspace.forkWorkspaceForUser( + workspace.getId(), tuple.getT2(), Flux.empty(), Flux.just(tuple1.getT1()))); }) .flatMap(this::loadWorkspaceData); @@ -554,8 +536,7 @@ public void cloneWorkspaceWithDatasourcesAndApplications() { final Mono<WorkspaceData> resultMono = Mono.zip( workspaceService.getDefaultEnvironmentId(workspace.getId()), sessionUserService.getCurrentUser(), - pluginService.findByPackageName("restapi-plugin").map(Plugin::getId) - ) + pluginService.findByPackageName("restapi-plugin").map(Plugin::getId)) .flatMap(tuple -> { String environmentId = tuple.getT1(); @@ -589,23 +570,19 @@ public void cloneWorkspaceWithDatasourcesAndApplications() { ds2.setDatasourceStorages(storages2); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) - .thenReturn(Mono.just(new MockPluginExecutor())).thenReturn(Mono.just(new MockPluginExecutor())); + .thenReturn(Mono.just(new MockPluginExecutor())) + .thenReturn(Mono.just(new MockPluginExecutor())); - return Mono - .zip( + return Mono.zip( applicationPageService.createApplication(app1), applicationPageService.createApplication(app2), datasourceService.create(ds1), - datasourceService.create(ds2) - ) - .flatMap(tuple1 -> - forkExamplesWorkspace.forkWorkspaceForUser( - workspace.getId(), - tuple.getT2(), - Flux.fromArray(new Application[]{tuple1.getT1(), tuple1.getT2()}), - Flux.empty() - ) - ); + datasourceService.create(ds2)) + .flatMap(tuple1 -> forkExamplesWorkspace.forkWorkspaceForUser( + workspace.getId(), + tuple.getT2(), + Flux.fromArray(new Application[] {tuple1.getT1(), tuple1.getT2()}), + Flux.empty())); }) .flatMap(this::loadWorkspaceData); @@ -617,10 +594,8 @@ public void cloneWorkspaceWithDatasourcesAndApplications() { assertThat(data.workspace.getPolicies()).isNotEmpty(); assertThat(data.applications).hasSize(2); - assertThat(map(data.applications, Application::getName)).containsExactlyInAnyOrder( - "first application", - "second application" - ); + assertThat(map(data.applications, Application::getName)) + .containsExactlyInAnyOrder("first application", "second application"); assertThat(data.datasources).isEmpty(); assertThat(data.actions).isEmpty(); @@ -635,7 +610,8 @@ public void cloneWorkspaceWithDatasourcesAndApplicationsAndActionsAndCollections Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace 2"); final Workspace workspace = workspaceService.create(newWorkspace).block(); - String environmentId = workspaceService.getDefaultEnvironmentId(workspace.getId()).block(); + String environmentId = + workspaceService.getDefaultEnvironmentId(workspace.getId()).block(); final User user = sessionUserService.getCurrentUser().block(); final Application app1 = new Application(); @@ -667,7 +643,8 @@ public void cloneWorkspaceWithDatasourcesAndApplicationsAndActionsAndCollections ds2.setDatasourceStorages(storages2); final Application app = applicationPageService.createApplication(app1).block(); - final Application app2Again = applicationPageService.createApplication(app2).block(); + final Application app2Again = + applicationPageService.createApplication(app2).block(); final Datasource ds1WithId = datasourceService.create(ds1).block(); final Datasource ds2WithId = datasourceService.create(ds2).block(); @@ -725,7 +702,8 @@ public void cloneWorkspaceWithDatasourcesAndApplicationsAndActionsAndCollections Datasource jsDatasource = new Datasource(); jsDatasource.setName("Default Database"); jsDatasource.setWorkspaceId(workspace.getId()); - Plugin installedJsPlugin = pluginRepository.findByPackageName("installed-js-plugin").block(); + Plugin installedJsPlugin = + pluginRepository.findByPackageName("installed-js-plugin").block(); assert installedJsPlugin != null; jsDatasource.setPluginId(installedJsPlugin.getId()); @@ -742,13 +720,18 @@ public void cloneWorkspaceWithDatasourcesAndApplicationsAndActionsAndCollections actionCollectionDTO1.setActions(List.of(action5)); actionCollectionDTO1.setPluginType(PluginType.JS); - applicationPageService.createPage(newPage) + applicationPageService + .createPage(newPage) .flatMap(page -> { newPageAction.setPageId(page.getId()); - return applicationPageService.addPageToApplication(app, page, false) + return applicationPageService + .addPageToApplication(app, page, false) .then(layoutActionService.createSingleAction(newPageAction, Boolean.FALSE)) - .flatMap(savedAction -> layoutActionService.updateSingleAction(savedAction.getId(), savedAction)) - .flatMap(updatedAction -> layoutActionService.updatePageLayoutsByPageId(updatedAction.getPageId()).thenReturn(updatedAction)) + .flatMap(savedAction -> + layoutActionService.updateSingleAction(savedAction.getId(), savedAction)) + .flatMap(updatedAction -> layoutActionService + .updatePageLayoutsByPageId(updatedAction.getPageId()) + .thenReturn(updatedAction)) .then(newPageService.findPageById(page.getId(), READ_PAGES, false)); }) .map(tuple2 -> { @@ -760,11 +743,8 @@ public void cloneWorkspaceWithDatasourcesAndApplicationsAndActionsAndCollections layoutActionService.createSingleAction(action3, Boolean.FALSE).block(); layoutCollectionService.createCollection(actionCollectionDTO1).block(); - final Mono<WorkspaceData> resultMono = forkExamplesWorkspace.forkWorkspaceForUser( - workspace.getId(), - user, - Flux.fromIterable(List.of(app, app2Again)), - Flux.empty()) + final Mono<WorkspaceData> resultMono = forkExamplesWorkspace + .forkWorkspaceForUser(workspace.getId(), user, Flux.fromIterable(List.of(app, app2Again)), Flux.empty()) .doOnError(error -> log.error("Error preparing data for test", error)) .flatMap(this::loadWorkspaceData); @@ -776,39 +756,50 @@ public void cloneWorkspaceWithDatasourcesAndApplicationsAndActionsAndCollections assertThat(data.workspace.getPolicies()).isNotEmpty(); assertThat(data.applications).hasSize(2); - assertThat(map(data.applications, Application::getName)).containsExactlyInAnyOrder( - "first application", - "second application" - ); + assertThat(map(data.applications, Application::getName)) + .containsExactlyInAnyOrder("first application", "second application"); - final Application firstApplication = data.applications.stream().filter(appFirst -> appFirst.getName().equals("first application")).findFirst().orElse(null); + final Application firstApplication = data.applications.stream() + .filter(appFirst -> appFirst.getName().equals("first application")) + .findFirst() + .orElse(null); assert firstApplication != null; - assertThat(firstApplication.getPages().stream().filter(ApplicationPage::isDefault).count()).isEqualTo(1); - final NewPage newPage1 = mongoTemplate.findOne(Query.query(Criteria.where("applicationId").is(firstApplication.getId()).and("unpublishedPage.name").is("A New Page")), NewPage.class); + assertThat(firstApplication.getPages().stream() + .filter(ApplicationPage::isDefault) + .count()) + .isEqualTo(1); + final NewPage newPage1 = mongoTemplate.findOne( + Query.query(Criteria.where("applicationId") + .is(firstApplication.getId()) + .and("unpublishedPage.name") + .is("A New Page")), + NewPage.class); assert newPage1 != null; - final String actionId = newPage1.getUnpublishedPage().getLayouts().get(0).getLayoutOnLoadActions().get(0).iterator().next().getId(); - final NewAction newPageAction1 = mongoTemplate.findOne(Query.query(Criteria.where("id").is(actionId)), NewAction.class); + final String actionId = newPage1.getUnpublishedPage() + .getLayouts() + .get(0) + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next() + .getId(); + final NewAction newPageAction1 = mongoTemplate.findOne( + Query.query(Criteria.where("id").is(actionId)), NewAction.class); assert newPageAction1 != null; assertThat(newPageAction1.getWorkspaceId()).isEqualTo(data.workspace.getId()); assertThat(data.datasources).hasSize(2); - assertThat(map(data.datasources, Datasource::getName)).containsExactlyInAnyOrder( - "ds 1", - "ds 2" - ); + assertThat(map(data.datasources, Datasource::getName)).containsExactlyInAnyOrder("ds 1", "ds 2"); assertThat(data.actions).hasSize(3); - assertThat(getUnpublishedActionName(data.actions)).containsExactlyInAnyOrder( - "newPageAction", - "action1", - "action3" - ); + assertThat(getUnpublishedActionName(data.actions)) + .containsExactlyInAnyOrder("newPageAction", "action1", "action3"); assertThat(data.actionCollections).hasSize(1); - assertThat(data.actionCollections.get(0).getDefaultToBranchedActionIdsMap()).hasSize(1); + assertThat(data.actionCollections.get(0).getDefaultToBranchedActionIdsMap()) + .hasSize(1); assertThat(data.actionCollections.get(0).getActions()).hasSize(1); }) .verifyComplete(); - } @Test @@ -823,8 +814,7 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { final Mono<WorkspaceData> resultMono = Mono.zip( workspaceService.getDefaultEnvironmentId(workspace.getId()), - sessionUserService.getCurrentUser() - ) + sessionUserService.getCurrentUser()) .flatMap(tuple -> { String environmentId = tuple.getT1(); @@ -852,33 +842,20 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { new UploadedFile("caCertFile", "caCert file content"), true, new PEMCertificate( - new UploadedFile( - "pemCertFile", - "pem cert file content" - ), - "pem cert file password" - ) - ), - "default db" - )); - - dc.setEndpoints(List.of( - new Endpoint("host1", 1L), - new Endpoint("host2", 2L) - )); - - final DBAuth auth = new DBAuth( - DBAuth.Type.USERNAME_PASSWORD, - "db username", - "db password", - "db name" - ); + new UploadedFile("pemCertFile", "pem cert file content"), + "pem cert file password")), + "default db")); + + dc.setEndpoints(List.of(new Endpoint("host1", 1L), new Endpoint("host2", 2L))); + + final DBAuth auth = + new DBAuth(DBAuth.Type.USERNAME_PASSWORD, "db username", "db password", "db name"); auth.setCustomAuthenticationParameters(Set.of( new Property("custom auth param 1", "custom auth param value 1"), - new Property("custom auth param 2", "custom auth param value 2") - )); + new Property("custom auth param 2", "custom auth param value 2"))); auth.setIsAuthorized(true); - auth.setAuthenticationResponse(new AuthenticationResponse("token", "refreshToken", Instant.now(), Instant.now(), null, "")); + auth.setAuthenticationResponse(new AuthenticationResponse( + "token", "refreshToken", Instant.now(), Instant.now(), null, "")); dc.setAuthentication(auth); DatasourceStorage datasourceStorage1 = new DatasourceStorage(ds1, environmentId); HashMap<String, DatasourceStorageDTO> storages1 = new HashMap<>(); @@ -906,12 +883,10 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { "header prefix", Set.of( new Property("custom token param 1", "custom token param value 1"), - new Property("custom token param 2", "custom token param value 2") - ), + new Property("custom token param 2", "custom token param value 2")), null, null, - false - )); + false)); DatasourceStorage datasourceStorage2 = new DatasourceStorage(ds2, environmentId); HashMap<String, DatasourceStorageDTO> storages2 = new HashMap<>(); storages2.put(environmentId, new DatasourceStorageDTO(datasourceStorage2)); @@ -926,14 +901,16 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { storages3.put(environmentId, new DatasourceStorageDTO(datasourceStorage3)); ds3.setDatasourceStorages(storages3); - return applicationPageService.createApplication(app1) + return applicationPageService + .createApplication(app1) .flatMap(createdApp -> Mono.zip( Mono.just(createdApp), - newPageRepository.findByApplicationId(createdApp.getId()).collectList(), + newPageRepository + .findByApplicationId(createdApp.getId()) + .collectList(), datasourceService.create(ds1), datasourceService.create(ds2), - datasourceService.create(ds3) - )) + datasourceService.create(ds3))) .flatMap(tuple1 -> { final Application app = tuple1.getT1(); final List<NewPage> pages = tuple1.getT2(); @@ -964,13 +941,10 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { action3.setPluginId(installedPlugin.getId()); return Mono.when( - layoutActionService.createSingleAction(action1, Boolean.FALSE), - layoutActionService.createSingleAction(action2, Boolean.FALSE), - layoutActionService.createSingleAction(action3, Boolean.FALSE) - ).then(Mono.zip( - workspaceService.create(targetOrg), - Mono.just(app) - )); + layoutActionService.createSingleAction(action1, Boolean.FALSE), + layoutActionService.createSingleAction(action2, Boolean.FALSE), + layoutActionService.createSingleAction(action3, Boolean.FALSE)) + .then(Mono.zip(workspaceService.create(targetOrg), Mono.just(app))); }) .flatMap(tuple1 -> { final Workspace targetOrg1 = tuple1.getT1(); @@ -979,14 +953,15 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { Mono<Void> clonerMono = Mono.just(tuple1.getT2()) .map(app -> { - // We reset these values here because the clone method updates them and that just messes with our test. + // We reset these values here because the clone method updates them and that + // just messes with our test. app.setId(originalId); app.setName(originalName); return app; }) .flatMap(app -> forkExamplesWorkspace.forkApplications( targetOrg1.getId(), - Flux.fromArray(new Application[]{app}), + Flux.fromArray(new Application[] {app}), environmentId)) .then(); @@ -1006,15 +981,18 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { assertThat(data.workspace.getName()).isEqualTo("Target Org 2"); assertThat(data.workspace.getPolicies()).isNotEmpty(); - assertThat(map(data.applications, Application::getName)).containsExactlyInAnyOrder( - "that great app", - "that great app (1)", - "that great app (2)" - ); + assertThat(map(data.applications, Application::getName)) + .containsExactlyInAnyOrder("that great app", "that great app (1)", "that great app (2)"); - final Application app1 = data.applications.stream().filter(app -> app.getName().equals("that great app")).findFirst().orElse(null); + final Application app1 = data.applications.stream() + .filter(app -> app.getName().equals("that great app")) + .findFirst() + .orElse(null); assert app1 != null; - assertThat(app1.getPages().stream().filter(ApplicationPage::isDefault).count()).isEqualTo(1); + assertThat(app1.getPages().stream() + .filter(ApplicationPage::isDefault) + .count()) + .isEqualTo(1); final DBAuth a1 = new DBAuth(); a1.setUsername("u1"); @@ -1027,30 +1005,33 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { final OAuth2 o2 = new OAuth2(); o2.setClientId("c1"); assertThat(o1).isEqualTo(o2); - assertThat(map(data.datasources, Datasource::getName)).containsExactlyInAnyOrder( - "datasource 1", - "datasource 2" - ); + assertThat(map(data.datasources, Datasource::getName)) + .containsExactlyInAnyOrder("datasource 1", "datasource 2"); - final Datasource ds1 = data.datasources.stream().filter(ds -> ds.getName().equals("datasource 1")).findFirst().get(); + final Datasource ds1 = data.datasources.stream() + .filter(ds -> ds.getName().equals("datasource 1")) + .findFirst() + .get(); DatasourceStorageDTO storage1 = ds1.getDatasourceStorages().get(data.defaultEnvironmentId); - assertThat(storage1.getDatasourceConfiguration().getAuthentication().getIsAuthorized()).isNull(); - - final Datasource ds2 = data.datasources.stream().filter(ds -> ds.getName().equals("datasource 2")).findFirst().get(); + assertThat(storage1.getDatasourceConfiguration() + .getAuthentication() + .getIsAuthorized()) + .isNull(); + + final Datasource ds2 = data.datasources.stream() + .filter(ds -> ds.getName().equals("datasource 2")) + .findFirst() + .get(); DatasourceStorageDTO storage2 = ds2.getDatasourceStorages().get(data.defaultEnvironmentId); - assertThat(storage2.getDatasourceConfiguration().getAuthentication().getIsAuthorized()).isNull(); - - assertThat(getUnpublishedActionName(data.actions)).containsExactlyInAnyOrder( - "action1", - "action2", - "action3", - "action1", - "action2", - "action3", - "action1", - "action2", - "action3" - ); + assertThat(storage2.getDatasourceConfiguration() + .getAuthentication() + .getIsAuthorized()) + .isNull(); + + assertThat(getUnpublishedActionName(data.actions)) + .containsExactlyInAnyOrder( + "action1", "action2", "action3", "action1", "action2", "action3", "action1", + "action2", "action3"); }) .verifyComplete(); } @@ -1067,8 +1048,7 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { final Mono<WorkspaceData> resultMono = Mono.zip( workspaceService.getDefaultEnvironmentId(workspace.getId()), - sessionUserService.getCurrentUser() - ) + sessionUserService.getCurrentUser()) .flatMap(tuple -> { String environmentId = tuple.getT1(); final Application app1 = new Application(); @@ -1095,33 +1075,20 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { new UploadedFile("caCertFile", "caCert file content"), true, new PEMCertificate( - new UploadedFile( - "pemCertFile", - "pem cert file content" - ), - "pem cert file password" - ) - ), - "default db" - )); - - dc.setEndpoints(List.of( - new Endpoint("host1", 1L), - new Endpoint("host2", 2L) - )); - - final DBAuth auth = new DBAuth( - DBAuth.Type.USERNAME_PASSWORD, - "db username", - "db password", - "db name" - ); + new UploadedFile("pemCertFile", "pem cert file content"), + "pem cert file password")), + "default db")); + + dc.setEndpoints(List.of(new Endpoint("host1", 1L), new Endpoint("host2", 2L))); + + final DBAuth auth = + new DBAuth(DBAuth.Type.USERNAME_PASSWORD, "db username", "db password", "db name"); auth.setCustomAuthenticationParameters(Set.of( new Property("custom auth param 1", "custom auth param value 1"), - new Property("custom auth param 2", "custom auth param value 2") - )); + new Property("custom auth param 2", "custom auth param value 2"))); auth.setIsAuthorized(true); - auth.setAuthenticationResponse(new AuthenticationResponse("token", "refreshToken", Instant.now(), Instant.now(), null, "")); + auth.setAuthenticationResponse(new AuthenticationResponse( + "token", "refreshToken", Instant.now(), Instant.now(), null, "")); dc.setAuthentication(auth); DatasourceStorage datasourceStorage1 = new DatasourceStorage(ds1, environmentId); HashMap<String, DatasourceStorageDTO> storages1 = new HashMap<>(); @@ -1149,12 +1116,10 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { "header prefix", Set.of( new Property("custom token param 1", "custom token param value 1"), - new Property("custom token param 2", "custom token param value 2") - ), + new Property("custom token param 2", "custom token param value 2")), null, null, - false - )); + false)); DatasourceStorage datasourceStorage2 = new DatasourceStorage(ds2, environmentId); HashMap<String, DatasourceStorageDTO> storages2 = new HashMap<>(); storages2.put(environmentId, new DatasourceStorageDTO(datasourceStorage2)); @@ -1169,14 +1134,16 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { storages3.put(environmentId, new DatasourceStorageDTO(datasourceStorage3)); ds3.setDatasourceStorages(storages3); - return applicationPageService.createApplication(app1) + return applicationPageService + .createApplication(app1) .flatMap(createdApp -> Mono.zip( Mono.just(createdApp), - newPageRepository.findByApplicationId(createdApp.getId()).collectList(), + newPageRepository + .findByApplicationId(createdApp.getId()) + .collectList(), datasourceService.create(ds1), datasourceService.create(ds2), - datasourceService.create(ds3) - )) + datasourceService.create(ds3))) .flatMap(tuple1 -> { final Application app = tuple1.getT1(); final List<NewPage> pages = tuple1.getT2(); @@ -1207,13 +1174,10 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { action3.setPluginId(installedPlugin.getId()); return Mono.when( - layoutActionService.createSingleAction(action1, Boolean.FALSE), - layoutActionService.createSingleAction(action2, Boolean.FALSE), - layoutActionService.createSingleAction(action3, Boolean.FALSE) - ).then(Mono.zip( - workspaceService.create(targetOrg), - Mono.just(app) - )); + layoutActionService.createSingleAction(action1, Boolean.FALSE), + layoutActionService.createSingleAction(action2, Boolean.FALSE), + layoutActionService.createSingleAction(action3, Boolean.FALSE)) + .then(Mono.zip(workspaceService.create(targetOrg), Mono.just(app))); }) .flatMap(tuple1 -> { final Workspace targetOrg1 = tuple1.getT1(); @@ -1222,14 +1186,15 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { Mono<Void> clonerMono = Mono.just(tuple1.getT2()) .map(app -> { - // We reset these values here because the clone method updates them and that just messes with our test. + // We reset these values here because the clone method updates them and that + // just messes with our test. app.setId(originalId); app.setName(originalName); return app; }) .flatMap(app -> forkExamplesWorkspace.forkApplications( targetOrg1.getId(), - Flux.fromArray(new Application[]{app}), + Flux.fromArray(new Application[] {app}), environmentId)) .then(); @@ -1249,15 +1214,18 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { assertThat(data.workspace.getName()).isEqualTo("Target Org 2"); assertThat(data.workspace.getPolicies()).isNotEmpty(); - assertThat(map(data.applications, Application::getName)).containsExactlyInAnyOrder( - "that great app", - "that great app (1)", - "that great app (2)" - ); + assertThat(map(data.applications, Application::getName)) + .containsExactlyInAnyOrder("that great app", "that great app (1)", "that great app (2)"); - final Application app1 = data.applications.stream().filter(app -> app.getName().equals("that great app")).findFirst().orElse(null); + final Application app1 = data.applications.stream() + .filter(app -> app.getName().equals("that great app")) + .findFirst() + .orElse(null); assert app1 != null; - assertThat(app1.getPages().stream().filter(ApplicationPage::isDefault).count()).isEqualTo(1); + assertThat(app1.getPages().stream() + .filter(ApplicationPage::isDefault) + .count()) + .isEqualTo(1); final DBAuth a1 = new DBAuth(); a1.setUsername("u1"); @@ -1271,34 +1239,33 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { o2.setClientId("c1"); assertThat(o1).isEqualTo(o2); - assertThat(map(data.datasources, Datasource::getName)).containsExactlyInAnyOrder( - "datasource 1", - "datasource 1 (1)", - "datasource 1 (2)", - "datasource 2", - "datasource 2 (1)", - "datasource 2 (2)" - ); - - final Datasource ds1 = data.datasources.stream().filter(ds -> ds.getName().equals("datasource 1")).findFirst().get(); + assertThat(map(data.datasources, Datasource::getName)) + .containsExactlyInAnyOrder( + "datasource 1", + "datasource 1 (1)", + "datasource 1 (2)", + "datasource 2", + "datasource 2 (1)", + "datasource 2 (2)"); + + final Datasource ds1 = data.datasources.stream() + .filter(ds -> ds.getName().equals("datasource 1")) + .findFirst() + .get(); DatasourceStorageDTO storage1 = ds1.getDatasourceStorages().get(data.defaultEnvironmentId); assertThat(storage1.getDatasourceConfiguration()).isNull(); - final Datasource ds2 = data.datasources.stream().filter(ds -> ds.getName().equals("datasource 2")).findFirst().get(); + final Datasource ds2 = data.datasources.stream() + .filter(ds -> ds.getName().equals("datasource 2")) + .findFirst() + .get(); DatasourceStorageDTO storage2 = ds2.getDatasourceStorages().get(data.defaultEnvironmentId); assertThat(storage2.getDatasourceConfiguration()).isNull(); - assertThat(getUnpublishedActionName(data.actions)).containsExactlyInAnyOrder( - "action1", - "action2", - "action3", - "action1", - "action2", - "action3", - "action1", - "action2", - "action3" - ); + assertThat(getUnpublishedActionName(data.actions)) + .containsExactlyInAnyOrder( + "action1", "action2", "action3", "action1", "action2", "action3", "action1", + "action2", "action3"); }) .verifyComplete(); } @@ -1320,8 +1287,8 @@ private Flux<ActionDTO> getActionsInWorkspace(Workspace workspace) { .findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) // fetch the unpublished pages .flatMap(application -> newPageService.findByApplicationId(application.getId(), READ_PAGES, false)) - .flatMap(page -> newActionService.getUnpublishedActionsExceptJs(new LinkedMultiValueMap<>( - Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))))); + .flatMap(page -> newActionService.getUnpublishedActionsExceptJs( + new LinkedMultiValueMap<>(Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))))); } private Flux<ActionCollectionDTO> getActionCollectionsInWorkspace(Workspace workspace) { @@ -1329,8 +1296,9 @@ private Flux<ActionCollectionDTO> getActionCollectionsInWorkspace(Workspace work .findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) // fetch the unpublished pages .flatMap(application -> newPageService.findByApplicationId(application.getId(), READ_PAGES, false)) - .flatMap(page -> actionCollectionService.getPopulatedActionCollectionsByViewMode(new LinkedMultiValueMap<>( - Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))), false)); + .flatMap(page -> actionCollectionService.getPopulatedActionCollectionsByViewMode( + new LinkedMultiValueMap<>(Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))), + false)); } private static class WorkspaceData { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java index 81b1bee20c80..e80594d6c56d 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java @@ -138,40 +138,58 @@ public class ImportExportApplicationServiceTests { private static Plugin installedJsPlugin; private static Boolean isSetupDone = false; private static String exportWithConfigurationAppId; + @Autowired ImportExportApplicationService importExportApplicationService; + @Autowired Gson gson; + @Autowired ApplicationPageService applicationPageService; + @Autowired PluginRepository pluginRepository; + @Autowired ApplicationRepository applicationRepository; + @Autowired DatasourceService datasourceService; + @Autowired NewPageService newPageService; + @Autowired NewActionService newActionService; + @Autowired WorkspaceService workspaceService; + @Autowired LayoutActionService layoutActionService; + @Autowired LayoutCollectionService layoutCollectionService; + @Autowired ActionCollectionService actionCollectionService; + @MockBean PluginExecutorHelper pluginExecutorHelper; + @Autowired ThemeRepository themeRepository; + @Autowired ApplicationService applicationService; + @Autowired PermissionGroupRepository permissionGroupRepository; + @Autowired PermissionGroupService permissionGroupService; + @Autowired CustomJSLibService customJSLibService; @@ -180,8 +198,7 @@ public class ImportExportApplicationServiceTests { @BeforeEach public void setup() { - Mockito - .when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) .thenReturn(Mono.just(new MockPluginExecutor())); if (Boolean.TRUE.equals(isSetupDone)) { @@ -192,7 +209,8 @@ public void setup() { workspace.setName("Import-Export-Test-Workspace"); Workspace savedWorkspace = workspaceService.create(workspace).block(); workspaceId = savedWorkspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); Application testApplication = new Application(); testApplication.setName("Export-Application-Test-Application"); @@ -202,7 +220,9 @@ public void setup() { testApplication.setModifiedBy("some-user"); testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - Application savedApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + Application savedApplication = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); testAppId = savedApplication.getId(); Datasource ds1 = new Datasource(); @@ -211,9 +231,7 @@ public void setup() { ds1.setPluginId(installedPlugin.getId()); final DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setUrl("http://example.org/get"); - datasourceConfiguration.setHeaders(List.of( - new Property("X-Answer", "42") - )); + datasourceConfiguration.setHeaders(List.of(new Property("X-Answer", "42"))); ds1.setDatasourceConfiguration(datasourceConfiguration); DatasourceStorage datasourceStorage1 = new DatasourceStorage(ds1, defaultEnvironmentId); HashMap<String, DatasourceStorageDTO> storages1 = new HashMap<>(); @@ -236,7 +254,8 @@ public void setup() { jsDatasource = new Datasource(); jsDatasource.setName("Default JS datasource"); jsDatasource.setWorkspaceId(workspaceId); - installedJsPlugin = pluginRepository.findByPackageName("installed-js-plugin").block(); + installedJsPlugin = + pluginRepository.findByPackageName("installed-js-plugin").block(); assert installedJsPlugin != null; jsDatasource.setPluginId(installedJsPlugin.getId()); @@ -251,36 +270,32 @@ private Flux<ActionDTO> getActionsInApplication(Application application) { return newPageService // fetch the unpublished pages .findByApplicationId(application.getId(), READ_PAGES, false) - .flatMap(page -> newActionService.getUnpublishedActions(new LinkedMultiValueMap<>( - Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))), "")); + .flatMap(page -> newActionService.getUnpublishedActions( + new LinkedMultiValueMap<>(Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))), + "")); } private FilePart createFilePart(String filePath) { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read( - new ClassPathResource(filePath), - new DefaultDataBufferFactory(), - 4096) + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource(filePath), new DefaultDataBufferFactory(), 4096) .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.APPLICATION_JSON); return filepart; - } private Mono<ApplicationJson> createAppJson(String filePath) { FilePart filePart = createFilePart(filePath); - Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()) - .map(dataBuffer -> { - byte[] data = new byte[dataBuffer.readableByteCount()]; - dataBuffer.read(data); - DataBufferUtils.release(dataBuffer); - return new String(data); - }); + Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()).map(dataBuffer -> { + byte[] data = new byte[dataBuffer.readableByteCount()]; + dataBuffer.read(data); + DataBufferUtils.release(dataBuffer); + return new String(data); + }); return stringifiedFile .map(data -> { @@ -300,10 +315,11 @@ private Workspace createTemplateWorkspace() { public void exportApplicationWithNullApplicationIdTest() { Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById(null, ""); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.APPLICATION_ID))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.APPLICATION_ID))) .verify(); } @@ -314,7 +330,9 @@ public void exportPublicApplicationTest() { Application application = new Application(); application.setName("exportPublicApplicationTest-Test"); - Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -322,13 +340,14 @@ public void exportPublicApplicationTest() { applicationAccessDTO.setPublicAccess(true); // Make the application public - applicationService.changeViewAccess(createdApplication.getId(), applicationAccessDTO).block(); + applicationService + .changeViewAccess(createdApplication.getId(), applicationAccessDTO) + .block(); Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById(createdApplication.getId(), ""); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(applicationJson -> { Application exportedApplication = applicationJson.getExportedApplication(); assertThat(exportedApplication).isNotNull(); @@ -344,10 +363,12 @@ public void exportPublicApplicationTest() { public void exportApplication_withInvalidApplicationId_throwNoResourceFoundException() { Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById("invalidAppId", ""); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION_ID, "invalidAppId"))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.APPLICATION_ID, "invalidAppId"))) .verify(); } @@ -356,8 +377,7 @@ public void exportApplication_withInvalidApplicationId_throwNoResourceFoundExcep public void exportApplicationById_WhenContainsInternalFields_InternalFieldsNotExported() { Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById(testAppId, ""); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(applicationJson -> { Application exportedApplication = applicationJson.getExportedApplication(); assertThat(exportedApplication.getModifiedBy()).isNull(); @@ -381,9 +401,9 @@ public void createExportAppJsonWithDatasourceButWithoutActionsTest() { Application testApplication = new Application(); testApplication.setName("Another Export Application"); - final Mono<ApplicationJson> resultMono = workspaceService.getById(workspaceId) + final Mono<ApplicationJson> resultMono = workspaceService + .getById(workspaceId) .flatMap(workspace -> { - final Datasource ds1 = datasourceMap.get("DS1"); ds1.setWorkspaceId(workspace.getId()); @@ -396,7 +416,6 @@ public void createExportAppJsonWithDatasourceButWithoutActionsTest() { StepVerifier.create(resultMono) .assertNext(applicationJson -> { - assertThat(applicationJson.getPageList()).hasSize(1); assertThat(applicationJson.getActionList()).isEmpty(); assertThat(applicationJson.getDatasourceList()).isEmpty(); @@ -413,14 +432,16 @@ public void createExportAppJsonWithActionAndActionCollectionTest() { Application testApplication = new Application(); testApplication.setName("ApplicationWithActionCollectionAndDatasource"); - testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + testApplication = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); assert testApplication != null; final String appName = testApplication.getName(); final Mono<ApplicationJson> resultMono = Mono.zip( Mono.just(testApplication), - newPageService.findPageById(testApplication.getPages().get(0).getId(), READ_PAGES, false) - ) + newPageService.findPageById( + testApplication.getPages().get(0).getId(), READ_PAGES, false)) .flatMap(tuple -> { Application testApp = tuple.getT1(); PageDTO testPage = tuple.getT2(); @@ -429,8 +450,8 @@ public void createExportAppJsonWithActionAndActionCollectionTest() { ObjectMapper objectMapper = new ObjectMapper(); JSONObject dsl = new JSONObject(); try { - dsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + dsl = new JSONObject(objectMapper.readValue( + DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); } catch (JsonProcessingException e) { e.printStackTrace(); } @@ -493,30 +514,30 @@ public void createExportAppJsonWithActionAndActionCollectionTest() { actionCollectionDTO1.setActions(List.of(action1)); actionCollectionDTO1.setPluginType(PluginType.JS); - return layoutCollectionService.createCollection(actionCollectionDTO1) + return layoutCollectionService + .createCollection(actionCollectionDTO1) .then(layoutActionService.createSingleAction(action, Boolean.FALSE)) .then(layoutActionService.createSingleAction(action2, Boolean.FALSE)) - .then(layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout)) + .then(layoutActionService.updateLayout( + testPage.getId(), testPage.getApplicationId(), layout.getId(), layout)) .then(importExportApplicationService.exportApplicationById(testApp.getId(), "")); }) .cache(); - Mono<List<NewAction>> actionListMono = resultMono - .then(newActionService - .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null).collectList()); + Mono<List<NewAction>> actionListMono = resultMono.then(newActionService + .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null) + .collectList()); - Mono<List<ActionCollection>> collectionListMono = resultMono.then( - actionCollectionService - .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null).collectList()); + Mono<List<ActionCollection>> collectionListMono = resultMono.then(actionCollectionService + .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null) + .collectList()); - Mono<List<NewPage>> pageListMono = resultMono.then( - newPageService - .findNewPagesByApplicationId(testApplication.getId(), READ_PAGES).collectList()); + Mono<List<NewPage>> pageListMono = resultMono.then(newPageService + .findNewPagesByApplicationId(testApplication.getId(), READ_PAGES) + .collectList()); - StepVerifier - .create(Mono.zip(resultMono, actionListMono, collectionListMono, pageListMono)) + StepVerifier.create(Mono.zip(resultMono, actionListMono, collectionListMono, pageListMono)) .assertNext(tuple -> { - ApplicationJson applicationJson = tuple.getT1(); List<NewAction> DBActions = tuple.getT2(); List<ActionCollection> DBCollections = tuple.getT3(); @@ -528,62 +549,77 @@ public void createExportAppJsonWithActionAndActionCollectionTest() { List<ActionCollection> actionCollectionList = applicationJson.getActionCollectionList(); List<DatasourceStorage> datasourceList = applicationJson.getDatasourceList(); - List<String> exportedCollectionIds = actionCollectionList.stream().map(ActionCollection::getId).collect(Collectors.toList()); - List<String> exportedActionIds = actionList.stream().map(NewAction::getId).collect(Collectors.toList()); - List<String> DBCollectionIds = DBCollections.stream().map(ActionCollection::getId).collect(Collectors.toList()); - List<String> DBActionIds = DBActions.stream().map(NewAction::getId).collect(Collectors.toList()); + List<String> exportedCollectionIds = actionCollectionList.stream() + .map(ActionCollection::getId) + .collect(Collectors.toList()); + List<String> exportedActionIds = + actionList.stream().map(NewAction::getId).collect(Collectors.toList()); + List<String> DBCollectionIds = + DBCollections.stream().map(ActionCollection::getId).collect(Collectors.toList()); + List<String> DBActionIds = + DBActions.stream().map(NewAction::getId).collect(Collectors.toList()); List<String> DBOnLayoutLoadActionIds = new ArrayList<>(); List<String> exportedOnLayoutLoadActionIds = new ArrayList<>(); assertThat(DBPages).hasSize(1); - DBPages.forEach(newPage -> - newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + DBPages.forEach( + newPage -> newPage.getUnpublishedPage().getLayouts().forEach(layout -> { if (layout.getLayoutOnLoadActions() != null) { layout.getLayoutOnLoadActions().forEach(dslActionDTOSet -> { - dslActionDTOSet.forEach(actionDTO -> DBOnLayoutLoadActionIds.add(actionDTO.getId())); + dslActionDTOSet.forEach( + actionDTO -> DBOnLayoutLoadActionIds.add(actionDTO.getId())); }); } - }) - ); - pageList.forEach(newPage -> - newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + })); + pageList.forEach( + newPage -> newPage.getUnpublishedPage().getLayouts().forEach(layout -> { if (layout.getLayoutOnLoadActions() != null) { layout.getLayoutOnLoadActions().forEach(dslActionDTOSet -> { - dslActionDTOSet.forEach(actionDTO -> exportedOnLayoutLoadActionIds.add(actionDTO.getId())); + dslActionDTOSet.forEach( + actionDTO -> exportedOnLayoutLoadActionIds.add(actionDTO.getId())); }); } - }) - ); + })); NewPage defaultPage = pageList.get(0); // Check if the mongo escaped widget names are carried to exported file from DB - Layout pageLayout = DBPages.get(0).getUnpublishedPage().getLayouts().get(0); + Layout pageLayout = + DBPages.get(0).getUnpublishedPage().getLayouts().get(0); Set<String> mongoEscapedWidgets = pageLayout.getMongoEscapedWidgetNames(); Set<String> expectedMongoEscapedWidgets = Set.of("Table1"); assertThat(mongoEscapedWidgets).isEqualTo(expectedMongoEscapedWidgets); - pageLayout = pageList.get(0).getUnpublishedPage().getLayouts().get(0); + pageLayout = + pageList.get(0).getUnpublishedPage().getLayouts().get(0); Set<String> exportedMongoEscapedWidgets = pageLayout.getMongoEscapedWidgetNames(); assertThat(exportedMongoEscapedWidgets).isEqualTo(expectedMongoEscapedWidgets); - assertThat(exportedApp.getName()).isEqualTo(appName); assertThat(exportedApp.getWorkspaceId()).isNull(); assertThat(exportedApp.getPages()).hasSize(1); - assertThat(exportedApp.getPages().get(0).getId()).isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(exportedApp.getPages().get(0).getId()) + .isEqualTo(defaultPage.getUnpublishedPage().getName()); assertThat(exportedApp.getPolicies()).isNull(); assertThat(pageList).hasSize(1); assertThat(defaultPage.getApplicationId()).isNull(); - assertThat(defaultPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull(); + assertThat(defaultPage + .getUnpublishedPage() + .getLayouts() + .get(0) + .getDsl()) + .isNotNull(); assertThat(defaultPage.getId()).isNull(); assertThat(defaultPage.getPolicies()).isNull(); assertThat(actionList.isEmpty()).isFalse(); assertThat(actionList).hasSize(3); - NewAction validAction = actionList.stream().filter(action -> action.getId().equals("Page1_validAction")).findFirst().get(); + NewAction validAction = actionList.stream() + .filter(action -> action.getId().equals("Page1_validAction")) + .findFirst() + .get(); assertThat(validAction.getApplicationId()).isNull(); assertThat(validAction.getPluginId()).isEqualTo(installedPlugin.getPackageName()); assertThat(validAction.getPluginType()).isEqualTo(PluginType.API); @@ -591,10 +627,16 @@ public void createExportAppJsonWithActionAndActionCollectionTest() { assertThat(validAction.getPolicies()).isNull(); assertThat(validAction.getId()).isNotNull(); ActionDTO unpublishedAction = validAction.getUnpublishedAction(); - assertThat(unpublishedAction.getPageId()).isEqualTo(defaultPage.getUnpublishedPage().getName()); - assertThat(unpublishedAction.getDatasource().getPluginId()).isEqualTo(installedPlugin.getPackageName()); + assertThat(unpublishedAction.getPageId()) + .isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(unpublishedAction.getDatasource().getPluginId()) + .isEqualTo(installedPlugin.getPackageName()); - NewAction testAction1 = actionList.stream().filter(action -> action.getUnpublishedAction().getName().equals("testAction1")).findFirst().get(); + NewAction testAction1 = actionList.stream() + .filter(action -> + action.getUnpublishedAction().getName().equals("testAction1")) + .findFirst() + .get(); assertThat(testAction1.getId()).isEqualTo("Page1_testCollection1.testAction1"); assertThat(actionCollectionList.isEmpty()).isFalse(); @@ -604,10 +646,12 @@ public void createExportAppJsonWithActionAndActionCollectionTest() { assertThat(actionCollection.getWorkspaceId()).isNull(); assertThat(actionCollection.getPolicies()).isNull(); assertThat(actionCollection.getId()).isNotNull(); - assertThat(actionCollection.getUnpublishedCollection().getPluginType()).isEqualTo(PluginType.JS); + assertThat(actionCollection.getUnpublishedCollection().getPluginType()) + .isEqualTo(PluginType.JS); assertThat(actionCollection.getUnpublishedCollection().getPageId()) .isEqualTo(defaultPage.getUnpublishedPage().getName()); - assertThat(actionCollection.getUnpublishedCollection().getPluginId()).isEqualTo(installedJsPlugin.getPackageName()); + assertThat(actionCollection.getUnpublishedCollection().getPluginId()) + .isEqualTo(installedJsPlugin.getPackageName()); assertThat(datasourceList).hasSize(1); DatasourceStorage datasource = datasourceList.get(0); @@ -617,18 +661,27 @@ public void createExportAppJsonWithActionAndActionCollectionTest() { assertThat(datasource.getDatasourceConfiguration()).isNull(); assertThat(applicationJson.getInvisibleActionFields()).isNull(); - NewAction validAction2 = actionList.stream().filter(action -> action.getId().equals("Page1_validAction2")).findFirst().get(); + NewAction validAction2 = actionList.stream() + .filter(action -> action.getId().equals("Page1_validAction2")) + .findFirst() + .get(); assertEquals(true, validAction2.getUnpublishedAction().getUserSetOnLoad()); - assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull(); - assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull(); + assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()) + .isNull(); + assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()) + .isNull(); assertThat(applicationJson.getEditModeTheme()).isNotNull(); - assertThat(applicationJson.getEditModeTheme().isSystemTheme()).isTrue(); - assertThat(applicationJson.getEditModeTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + assertThat(applicationJson.getEditModeTheme().isSystemTheme()) + .isTrue(); + assertThat(applicationJson.getEditModeTheme().getName()) + .isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); assertThat(applicationJson.getPublishedTheme()).isNotNull(); - assertThat(applicationJson.getPublishedTheme().isSystemTheme()).isTrue(); - assertThat(applicationJson.getPublishedTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + assertThat(applicationJson.getPublishedTheme().isSystemTheme()) + .isTrue(); + assertThat(applicationJson.getPublishedTheme().getName()) + .isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); assertThat(exportedCollectionIds).isNotEmpty(); assertThat(exportedCollectionIds).doesNotContain(String.valueOf(DBCollectionIds)); @@ -647,13 +700,11 @@ public void createExportAppJsonWithActionAndActionCollectionTest() { public void createExportAppJsonForGitTest() { StringBuilder pageName = new StringBuilder(); - final Mono<ApplicationJson> resultMono = applicationRepository.findById(testAppId) + final Mono<ApplicationJson> resultMono = applicationRepository + .findById(testAppId) .flatMap(testApp -> { final String pageId = testApp.getPages().get(0).getId(); - return Mono.zip( - Mono.just(testApp), - newPageService.findPageById(pageId, READ_PAGES, false) - ); + return Mono.zip(Mono.just(testApp), newPageService.findPageById(pageId, READ_PAGES, false)); }) .flatMap(tuple -> { Datasource ds1 = datasourceMap.get("DS1"); @@ -676,14 +727,14 @@ public void createExportAppJsonForGitTest() { action.setActionConfiguration(actionConfiguration); action.setDatasource(ds1); - return layoutActionService.createAction(action) - .then(importExportApplicationService.exportApplicationById(testApp.getId(), SerialiseApplicationObjective.VERSION_CONTROL)); + return layoutActionService + .createAction(action) + .then(importExportApplicationService.exportApplicationById( + testApp.getId(), SerialiseApplicationObjective.VERSION_CONTROL)); }); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(applicationJson -> { - Application exportedApp = applicationJson.getExportedApplication(); List<NewPage> pageList = applicationJson.getPageList(); List<NewAction> actionList = applicationJson.getActionList(); @@ -705,7 +756,8 @@ public void createExportAppJsonForGitTest() { assertThat(pageList).hasSize(1); assertThat(newPage.getApplicationId()).isNull(); - assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull(); + assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getDsl()) + .isNotNull(); assertThat(newPage.getId()).isNull(); assertThat(newPage.getPolicies()).isNull(); @@ -727,8 +779,10 @@ public void createExportAppJsonForGitTest() { assertThat(datasource.getPluginId()).isEqualTo(installedPlugin.getPackageName()); assertThat(datasource.getDatasourceConfiguration()).isNull(); - assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull(); - assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull(); + assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()) + .isNull(); + assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()) + .isNull(); }) .verifyComplete(); } @@ -737,17 +791,19 @@ public void createExportAppJsonForGitTest() { @WithUserDetails(value = "api_user") public void importApplicationFromInvalidFileTest() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), new DefaultDataBufferFactory(), 4096) + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), + new DefaultDataBufferFactory(), + 4096) .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); - Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filepart); + Mono<ApplicationImportDTO> resultMono = + importExportApplicationService.extractFileAndSaveApplication(workspaceId, filepart); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .expectErrorMatches(error -> error instanceof AppsmithException) .verify(); } @@ -757,13 +813,14 @@ public void importApplicationFromInvalidFileTest() { public void importApplicationWithNullWorkspaceIdTest() { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Mono<ApplicationImportDTO> resultMono = importExportApplicationService - .extractFileAndSaveApplication(null, filepart); + Mono<ApplicationImportDTO> resultMono = + importExportApplicationService.extractFileAndSaveApplication(null, filepart); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.WORKSPACE_ID))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.WORKSPACE_ID))) .verify(); } @@ -772,12 +829,14 @@ public void importApplicationWithNullWorkspaceIdTest() { public void importApplicationFromInvalidJsonFileWithoutPagesTest() { FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-json-without-pages.json"); - Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); + Mono<ApplicationImportDTO> resultMono = + importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PAGES, INVALID_JSON_FILE))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PAGES, INVALID_JSON_FILE))) .verify(); } @@ -786,12 +845,15 @@ public void importApplicationFromInvalidJsonFileWithoutPagesTest() { public void importApplicationFromInvalidJsonFileWithoutApplicationTest() { FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-json-without-app.json"); - Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); + Mono<ApplicationImportDTO> resultMono = + importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, INVALID_JSON_FILE))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage( + FieldName.APPLICATION, INVALID_JSON_FILE))) .verify(); } @@ -804,17 +866,14 @@ public void importApplicationFromValidJsonFileTest() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); - Mono<Workspace> workspaceMono = workspaceService - .create(newWorkspace).cache(); + Mono<Workspace> workspaceMono = workspaceService.create(newWorkspace).cache(); String environmentId = workspaceMono .flatMap(workspace -> workspaceService.getDefaultEnvironmentId(workspace.getId())) .block(); - final Mono<ApplicationImportDTO> resultMono = workspaceMono - .flatMap(workspace -> importExportApplicationService - .extractFileAndSaveApplication(workspace.getId(), filePart) - ); + final Mono<ApplicationImportDTO> resultMono = workspaceMono.flatMap( + workspace -> importExportApplicationService.extractFileAndSaveApplication(workspace.getId(), filePart)); List<PermissionGroup> permissionGroups = workspaceMono .flatMapMany(savedWorkspace -> { @@ -826,41 +885,52 @@ public void importApplicationFromValidJsonFileTest() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - StepVerifier - .create(resultMono - .flatMap(applicationImportDTO -> { - Application application = applicationImportDTO.getApplication(); - return Mono.zip( - Mono.just(applicationImportDTO), - datasourceService.getAllByWorkspaceIdWithStorages(application.getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)).collectList(), - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), - false, MANAGE_ACTIONS, null).collectList(), - customJSLibService.getAllJSLibsInApplication(application.getId(), null, false) - ); - })) + StepVerifier.create(resultMono.flatMap(applicationImportDTO -> { + Application application = applicationImportDTO.getApplication(); + return Mono.zip( + Mono.just(applicationImportDTO), + datasourceService + .getAllByWorkspaceIdWithStorages( + application.getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)) + .collectList(), + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null) + .collectList(), + customJSLibService.getAllJSLibsInApplication(application.getId(), null, false)); + })) .assertNext(tuple -> { final Application application = tuple.getT1().getApplication(); - final List<Datasource> unConfiguredDatasourceList = tuple.getT1().getUnConfiguredDatasourceList(); + final List<Datasource> unConfiguredDatasourceList = + tuple.getT1().getUnConfiguredDatasourceList(); final boolean isPartialImport = tuple.getT1().getIsPartialImport(); final List<Datasource> datasourceList = tuple.getT2(); final List<NewAction> actionList = tuple.getT3(); @@ -870,8 +940,8 @@ public void importApplicationFromValidJsonFileTest() { assertEquals(1, importedJSLibList.size()); CustomJSLib importedJSLib = (CustomJSLib) importedJSLibList.toArray()[0]; - CustomJSLib expectedJSLib = new CustomJSLib("TestLib", Set.of("accessor1"), "url", "docsUrl", "1" + - ".0", "defs_string"); + CustomJSLib expectedJSLib = new CustomJSLib( + "TestLib", Set.of("accessor1"), "url", "docsUrl", "1" + ".0", "defs_string"); assertEquals(expectedJSLib.getName(), importedJSLib.getName()); assertEquals(expectedJSLib.getAccessor(), importedJSLib.getAccessor()); assertEquals(expectedJSLib.getUrl(), importedJSLib.getUrl()); @@ -879,7 +949,8 @@ public void importApplicationFromValidJsonFileTest() { assertEquals(expectedJSLib.getVersion(), importedJSLib.getVersion()); assertEquals(expectedJSLib.getDefs(), importedJSLib.getDefs()); assertEquals(1, application.getUnpublishedCustomJSLibs().size()); - assertEquals(getDTOFromCustomJSLib(expectedJSLib), + assertEquals( + getDTOFromCustomJSLib(expectedJSLib), application.getUnpublishedCustomJSLibs().toArray()[0]); assertThat(application.getName()).isEqualTo("valid_application"); @@ -897,7 +968,8 @@ public void importApplicationFromValidJsonFileTest() { assertThat(datasourceList).isNotEmpty(); datasourceList.forEach(datasource -> { assertThat(datasource.getWorkspaceId()).isEqualTo(application.getWorkspaceId()); - DatasourceStorageDTO storageDTO = datasource.getDatasourceStorages().get(environmentId); + DatasourceStorageDTO storageDTO = + datasource.getDatasourceStorages().get(environmentId); assertThat(storageDTO.getDatasourceConfiguration()).isNotNull(); }); @@ -905,7 +977,8 @@ public void importApplicationFromValidJsonFileTest() { assertThat(actionList).isNotEmpty(); actionList.forEach(newAction -> { ActionDTO actionDTO = newAction.getUnpublishedAction(); - assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName()); + assertThat(actionDTO.getPageId()) + .isNotEqualTo(pageList.get(0).getName()); if (StringUtils.equals(actionDTO.getName(), "api_wo_auth")) { ActionDTO publishedAction = newAction.getPublishedAction(); assertThat(publishedAction).isNotNull(); @@ -924,8 +997,10 @@ public void importApplicationFromValidJsonFileTest() { assertThat(actionCollectionList).isNotEmpty(); actionCollectionList.forEach(actionCollection -> { - assertThat(actionCollection.getUnpublishedCollection().getPageId()).isNotEqualTo(pageList.get(0).getName()); - if (StringUtils.equals(actionCollection.getUnpublishedCollection().getName(), "JSObject2")) { + assertThat(actionCollection.getUnpublishedCollection().getPageId()) + .isNotEqualTo(pageList.get(0).getName()); + if (StringUtils.equals( + actionCollection.getUnpublishedCollection().getName(), "JSObject2")) { // Check if this action collection is not attached to any action assertThat(collectionIdInAction).doesNotContain(actionCollection.getId()); } else { @@ -935,18 +1010,20 @@ public void importApplicationFromValidJsonFileTest() { assertThat(pageList).hasSize(2); - ApplicationPage defaultAppPage = application.getPages() - .stream() + ApplicationPage defaultAppPage = application.getPages().stream() .filter(ApplicationPage::getIsDefault) .findFirst() .orElse(null); assertThat(defaultAppPage).isNotNull(); PageDTO defaultPageDTO = pageList.stream() - .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())) + .findFirst() + .orElse(null); assertThat(defaultPageDTO).isNotNull(); - assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()).isNotEmpty(); + assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()) + .isNotEmpty(); }) .verifyComplete(); } @@ -967,17 +1044,17 @@ public void importFromValidJson_cancelledMidway_importSuccess() { .subscribe(); // Wait for import to complete - Mono<Application> importedAppFromDbMono = Mono.just(newWorkspace) - .flatMap(workspace -> { - try { - // Before fetching the imported application, sleep for 5 seconds to ensure that the import completes - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return applicationRepository.findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) - .next(); - }); + Mono<Application> importedAppFromDbMono = Mono.just(newWorkspace).flatMap(workspace -> { + try { + // Before fetching the imported application, sleep for 5 seconds to ensure that the import completes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationRepository + .findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) + .next(); + }); StepVerifier.create(importedAppFromDbMono) .assertNext(application -> { @@ -989,26 +1066,23 @@ public void importFromValidJson_cancelledMidway_importSuccess() { @Test @WithUserDetails(value = "api_user") public void importApplicationInWorkspace_WhenCustomizedThemes_ThemesCreated() { - FilePart filePart = createFilePart( - "test_assets/ImportExportServiceTest/valid-application-with-custom-themes.json" - ); + FilePart filePart = + createFilePart("test_assets/ImportExportServiceTest/valid-application-with-custom-themes.json"); Workspace newWorkspace = new Workspace(); newWorkspace.setName("Import theme test org"); final Mono<ApplicationImportDTO> resultMono = workspaceService .create(newWorkspace) - .flatMap(workspace -> importExportApplicationService - .extractFileAndSaveApplication(workspace.getId(), filePart) - ); - - StepVerifier - .create(resultMono - .flatMap(applicationImportDTO -> Mono.zip( - Mono.just(applicationImportDTO), - themeRepository.findById(applicationImportDTO.getApplication().getEditModeThemeId()), - themeRepository.findById(applicationImportDTO.getApplication().getPublishedModeThemeId()) - ))) + .flatMap(workspace -> + importExportApplicationService.extractFileAndSaveApplication(workspace.getId(), filePart)); + + StepVerifier.create(resultMono.flatMap(applicationImportDTO -> Mono.zip( + Mono.just(applicationImportDTO), + themeRepository.findById( + applicationImportDTO.getApplication().getEditModeThemeId()), + themeRepository.findById( + applicationImportDTO.getApplication().getPublishedModeThemeId())))) .assertNext(tuple -> { final Application application = tuple.getT1().getApplication(); Theme editTheme = tuple.getT2(); @@ -1031,18 +1105,16 @@ public void importApplicationInWorkspace_WhenCustomizedThemes_ThemesCreated() { @WithUserDetails(value = "api_user") public void importApplication_withoutActionCollection_succeedsWithoutError() { - FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); + FilePart filePart = + createFilePart("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); - Mono<Workspace> workspaceMono = workspaceService - .create(newWorkspace).cache(); + Mono<Workspace> workspaceMono = workspaceService.create(newWorkspace).cache(); - final Mono<ApplicationImportDTO> resultMono = workspaceMono - .flatMap(workspace -> importExportApplicationService - .extractFileAndSaveApplication(workspace.getId(), filePart) - ); + final Mono<ApplicationImportDTO> resultMono = workspaceMono.flatMap( + workspace -> importExportApplicationService.extractFileAndSaveApplication(workspace.getId(), filePart)); List<PermissionGroup> permissionGroups = workspaceMono .flatMapMany(savedWorkspace -> { @@ -1054,35 +1126,48 @@ public void importApplication_withoutActionCollection_succeedsWithoutError() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - StepVerifier - .create(resultMono - .flatMap(applicationImportDTO -> Mono.zip( - Mono.just(applicationImportDTO), - datasourceService.getAllByWorkspaceIdWithStorages(applicationImportDTO.getApplication().getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)).collectList(), - getActionsInApplication(applicationImportDTO.getApplication()).collectList(), - newPageService.findByApplicationId(applicationImportDTO.getApplication().getId(), MANAGE_PAGES, false).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(applicationImportDTO.getApplication().getId(), false - , MANAGE_ACTIONS, null).collectList(), - workspaceMono.flatMap(workspace -> workspaceService.getDefaultEnvironmentId(workspace.getId())) - ))) + StepVerifier.create(resultMono.flatMap(applicationImportDTO -> Mono.zip( + Mono.just(applicationImportDTO), + datasourceService + .getAllByWorkspaceIdWithStorages( + applicationImportDTO.getApplication().getWorkspaceId(), + Optional.of(MANAGE_DATASOURCES)) + .collectList(), + getActionsInApplication(applicationImportDTO.getApplication()) + .collectList(), + newPageService + .findByApplicationId( + applicationImportDTO.getApplication().getId(), MANAGE_PAGES, false) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode( + applicationImportDTO.getApplication().getId(), false, MANAGE_ACTIONS, null) + .collectList(), + workspaceMono.flatMap( + workspace -> workspaceService.getDefaultEnvironmentId(workspace.getId()))))) .assertNext(tuple -> { final Application application = tuple.getT1().getApplication(); final List<Datasource> datasourceList = tuple.getT2(); @@ -1102,32 +1187,35 @@ public void importApplication_withoutActionCollection_succeedsWithoutError() { assertThat(datasourceList).isNotEmpty(); datasourceList.forEach(datasource -> { assertThat(datasource.getWorkspaceId()).isEqualTo(application.getWorkspaceId()); - DatasourceStorageDTO storageDTO = datasource.getDatasourceStorages().get(environmentId); + DatasourceStorageDTO storageDTO = + datasource.getDatasourceStorages().get(environmentId); assertThat(storageDTO.getDatasourceConfiguration()).isNotNull(); }); assertThat(actionDTOS).isNotEmpty(); actionDTOS.forEach(actionDTO -> { - assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName()); - + assertThat(actionDTO.getPageId()) + .isNotEqualTo(pageList.get(0).getName()); }); assertThat(actionCollectionList).isEmpty(); assertThat(pageList).hasSize(2); - ApplicationPage defaultAppPage = application.getPages() - .stream() + ApplicationPage defaultAppPage = application.getPages().stream() .filter(ApplicationPage::getIsDefault) .findFirst() .orElse(null); assertThat(defaultAppPage).isNotNull(); PageDTO defaultPageDTO = pageList.stream() - .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())) + .findFirst() + .orElse(null); assertThat(defaultPageDTO).isNotNull(); - assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()).isNotEmpty(); + assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()) + .isNotEmpty(); }) .verifyComplete(); } @@ -1140,16 +1228,17 @@ public void importApplication_WithoutThemes_LegacyThemesAssigned() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); - final Mono<ApplicationImportDTO> resultMono = workspaceService.create(newWorkspace) - .flatMap(workspace -> importExportApplicationService - .extractFileAndSaveApplication(workspace.getId(), filePart) - ); + final Mono<ApplicationImportDTO> resultMono = workspaceService + .create(newWorkspace) + .flatMap(workspace -> + importExportApplicationService.extractFileAndSaveApplication(workspace.getId(), filePart)); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(applicationImportDTO -> { - assertThat(applicationImportDTO.getApplication().getEditModeThemeId()).isNotEmpty(); - assertThat(applicationImportDTO.getApplication().getPublishedModeThemeId()).isNotEmpty(); + assertThat(applicationImportDTO.getApplication().getEditModeThemeId()) + .isNotEmpty(); + assertThat(applicationImportDTO.getApplication().getPublishedModeThemeId()) + .isNotEmpty(); }) .verifyComplete(); } @@ -1158,27 +1247,34 @@ public void importApplication_WithoutThemes_LegacyThemesAssigned() { @WithUserDetails(value = "api_user") public void importApplication_withoutPageIdInActionCollection_succeeds() { - FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-application-without-pageId-action-collection.json"); + FilePart filePart = createFilePart( + "test_assets/ImportExportServiceTest/invalid-application-without-pageId-action-collection.json"); Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); final Mono<ApplicationImportDTO> resultMono = workspaceService .create(newWorkspace) - .flatMap(workspace -> importExportApplicationService - .extractFileAndSaveApplication(workspace.getId(), filePart) - ); - - StepVerifier - .create(resultMono - .flatMap(applicationImportDTO -> Mono.zip( - Mono.just(applicationImportDTO), - datasourceService.getAllByWorkspaceIdWithStorages(applicationImportDTO.getApplication().getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)).collectList(), - getActionsInApplication(applicationImportDTO.getApplication()).collectList(), - newPageService.findByApplicationId(applicationImportDTO.getApplication().getId(), MANAGE_PAGES, false).collectList(), - actionCollectionService - .findAllByApplicationIdAndViewMode(applicationImportDTO.getApplication().getId(), false, MANAGE_ACTIONS, null).collectList() - ))) + .flatMap(workspace -> + importExportApplicationService.extractFileAndSaveApplication(workspace.getId(), filePart)); + + StepVerifier.create(resultMono.flatMap(applicationImportDTO -> Mono.zip( + Mono.just(applicationImportDTO), + datasourceService + .getAllByWorkspaceIdWithStorages( + applicationImportDTO.getApplication().getWorkspaceId(), + Optional.of(MANAGE_DATASOURCES)) + .collectList(), + getActionsInApplication(applicationImportDTO.getApplication()) + .collectList(), + newPageService + .findByApplicationId( + applicationImportDTO.getApplication().getId(), MANAGE_PAGES, false) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode( + applicationImportDTO.getApplication().getId(), false, MANAGE_ACTIONS, null) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1().getApplication(); final List<Datasource> datasourceList = tuple.getT2(); @@ -1186,13 +1282,12 @@ public void importApplication_withoutPageIdInActionCollection_succeeds() { final List<PageDTO> pageList = tuple.getT4(); final List<ActionCollection> actionCollectionList = tuple.getT5(); - assertThat(datasourceList).isNotEmpty(); assertThat(actionDTOS).hasSize(1); actionDTOS.forEach(actionDTO -> { - assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName()); - + assertThat(actionDTO.getPageId()) + .isNotEqualTo(pageList.get(0).getName()); }); assertThat(actionCollectionList).isEmpty(); @@ -1214,13 +1309,17 @@ public void exportImportApplication_importWithBranchName_updateApplicationResour gitData.setBranchName("testBranch"); testApplication.setGitApplicationMetadata(gitData); - Application savedApplication = applicationPageService.createApplication(testApplication, workspaceId) + Application savedApplication = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); + }) + .block(); - Mono<Application> result = newPageService.findNewPagesByApplicationId(savedApplication.getId(), READ_PAGES).collectList() + Mono<Application> result = newPageService + .findNewPagesByApplicationId(savedApplication.getId(), READ_PAGES) + .collectList() .flatMap(newPages -> { NewPage newPage = newPages.get(0); @@ -1232,25 +1331,32 @@ public void exportImportApplication_importWithBranchName_updateApplicationResour actionConfiguration.setHttpMethod(HttpMethod.GET); action.setActionConfiguration(actionConfiguration); action.setDatasource(datasourceMap.get("DS1")); - return layoutActionService.createAction(action) + return layoutActionService + .createAction(action) .flatMap(createdAction -> newActionService.findById(createdAction.getId(), READ_ACTIONS)); }) - .then(importExportApplicationService.exportApplicationById(savedApplication.getId(), SerialiseApplicationObjective.VERSION_CONTROL) - .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, applicationJson, savedApplication.getId(), gitData.getBranchName()))) + .then(importExportApplicationService + .exportApplicationById(savedApplication.getId(), SerialiseApplicationObjective.VERSION_CONTROL) + .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, applicationJson, savedApplication.getId(), gitData.getBranchName()))) .cache(); - Mono<List<NewPage>> updatedPagesMono = result.then(newPageService.findNewPagesByApplicationId(savedApplication.getId(), READ_PAGES).collectList()); + Mono<List<NewPage>> updatedPagesMono = result.then(newPageService + .findNewPagesByApplicationId(savedApplication.getId(), READ_PAGES) + .collectList()); - Mono<List<NewAction>> updatedActionsMono = result.then(newActionService.findAllByApplicationIdAndViewMode(savedApplication.getId(), false, READ_PAGES, null).collectList()); + Mono<List<NewAction>> updatedActionsMono = result.then(newActionService + .findAllByApplicationIdAndViewMode(savedApplication.getId(), false, READ_PAGES, null) + .collectList()); - StepVerifier - .create(Mono.zip(result, updatedPagesMono, updatedActionsMono)) + StepVerifier.create(Mono.zip(result, updatedPagesMono, updatedActionsMono)) .assertNext(tuple -> { Application application = tuple.getT1(); List<NewPage> pageList = tuple.getT2(); List<NewAction> actionList = tuple.getT3(); - final String branchName = application.getGitApplicationMetadata().getBranchName(); + final String branchName = + application.getGitApplicationMetadata().getBranchName(); pageList.forEach(page -> { assertThat(page.getDefaultResources()).isNotNull(); assertThat(page.getDefaultResources().getBranchName()).isEqualTo(branchName); @@ -1268,30 +1374,28 @@ public void exportImportApplication_importWithBranchName_updateApplicationResour @WithUserDetails(value = "api_user") public void importApplication_incompatibleJsonFile_throwException() { FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/incompatible_version.json"); - Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); + Mono<ApplicationImportDTO> resultMono = + importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.INCOMPATIBLE_IMPORTED_JSON.getMessage())) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INCOMPATIBLE_IMPORTED_JSON.getMessage())) .verify(); } @Test @WithUserDetails(value = "api_user") public void importApplication_withUnConfiguredDatasources_Success() { - FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application-with-un-configured-datasource.json"); + FilePart filePart = createFilePart( + "test_assets/ImportExportServiceTest/valid-application-with-un-configured-datasource.json"); Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); - Mono<Workspace> workspaceMono = workspaceService - .create(newWorkspace).cache(); + Mono<Workspace> workspaceMono = workspaceService.create(newWorkspace).cache(); - final Mono<ApplicationImportDTO> resultMono = workspaceMono - .flatMap(workspace -> importExportApplicationService - .extractFileAndSaveApplication(workspace.getId(), filePart) - ); + final Mono<ApplicationImportDTO> resultMono = workspaceMono.flatMap( + workspace -> importExportApplicationService.extractFileAndSaveApplication(workspace.getId(), filePart)); List<PermissionGroup> permissionGroups = workspaceMono .flatMapMany(savedWorkspace -> { @@ -1303,39 +1407,51 @@ public void importApplication_withUnConfiguredDatasources_Success() { PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - StepVerifier - .create(resultMono - .flatMap(applicationImportDTO -> { - Application application = applicationImportDTO.getApplication(); - return Mono.zip( - Mono.just(applicationImportDTO), - datasourceService.getAllByWorkspaceIdWithStorages(application.getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)).collectList(), - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null).collectList() - ); - })) + StepVerifier.create(resultMono.flatMap(applicationImportDTO -> { + Application application = applicationImportDTO.getApplication(); + return Mono.zip( + Mono.just(applicationImportDTO), + datasourceService + .getAllByWorkspaceIdWithStorages( + application.getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)) + .collectList(), + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null) + .collectList()); + })) .assertNext(tuple -> { final Application application = tuple.getT1().getApplication(); - final List<Datasource> unConfiguredDatasourceList = tuple.getT1().getUnConfiguredDatasourceList(); + final List<Datasource> unConfiguredDatasourceList = + tuple.getT1().getUnConfiguredDatasourceList(); final boolean isPartialImport = tuple.getT1().getIsPartialImport(); final List<Datasource> datasourceList = tuple.getT2(); final List<NewAction> actionList = tuple.getT3(); @@ -1355,14 +1471,17 @@ public void importApplication_withUnConfiguredDatasources_Success() { assertThat(unConfiguredDatasourceList.size()).isNotEqualTo(0); assertThat(datasourceList).isNotEmpty(); - List<String> datasourceNames = unConfiguredDatasourceList.stream().map(Datasource::getName).collect(Collectors.toList()); + List<String> datasourceNames = unConfiguredDatasourceList.stream() + .map(Datasource::getName) + .collect(Collectors.toList()); assertThat(datasourceNames).contains("mongoDatasource", "postgresTest"); List<String> collectionIdInAction = new ArrayList<>(); assertThat(actionList).isNotEmpty(); actionList.forEach(newAction -> { ActionDTO actionDTO = newAction.getUnpublishedAction(); - assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName()); + assertThat(actionDTO.getPageId()) + .isNotEqualTo(pageList.get(0).getName()); if (!StringUtils.isEmpty(actionDTO.getCollectionId())) { collectionIdInAction.add(actionDTO.getCollectionId()); } @@ -1372,15 +1491,16 @@ public void importApplication_withUnConfiguredDatasources_Success() { assertThat(pageList).hasSize(1); - ApplicationPage defaultAppPage = application.getPages() - .stream() + ApplicationPage defaultAppPage = application.getPages().stream() .filter(ApplicationPage::getIsDefault) .findFirst() .orElse(null); assertThat(defaultAppPage).isNotNull(); PageDTO defaultPageDTO = pageList.stream() - .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())) + .findFirst() + .orElse(null); assertThat(defaultPageDTO).isNotNull(); }) @@ -1399,12 +1519,17 @@ public void importApplicationIntoWorkspace_pageRemovedAndUpdatedDefaultPageNameI gitData.setBranchName("master"); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication, workspaceId) + Application application = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); - String gitSyncIdBeforeImport = newPageService.findById(application.getPages().get(0).getId(), MANAGE_PAGES).block().getGitSyncId(); + }) + .block(); + String gitSyncIdBeforeImport = newPageService + .findById(application.getPages().get(0).getId(), MANAGE_PAGES) + .block() + .getGitSyncId(); PageDTO page = new PageDTO(); page.setName("Page 2"); @@ -1412,28 +1537,32 @@ public void importApplicationIntoWorkspace_pageRemovedAndUpdatedDefaultPageNameI PageDTO savedPage = applicationPageService.createPage(page).block(); assert application.getId() != null; - Set<String> applicationPageIdsBeforeImport = Objects.requireNonNull(applicationRepository.findById(application.getId()).block()) - .getPages() - .stream() - .map(ApplicationPage::getId) - .collect(Collectors.toSet()); + Set<String> applicationPageIdsBeforeImport = + Objects.requireNonNull(applicationRepository + .findById(application.getId()) + .block()) + .getPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toSet()); - ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application-with-page-removed.json").block(); + ApplicationJson applicationJson = createAppJson( + "test_assets/ImportExportServiceTest/valid-application-with-page-removed.json") + .block(); applicationJson.getPageList().get(0).setGitSyncId(gitSyncIdBeforeImport); - Application importedApplication = importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, applicationJson, application.getId(), "master").block(); + Application importedApplication = importExportApplicationService + .importApplicationInWorkspaceFromGit(workspaceId, applicationJson, application.getId(), "master") + .block(); assert importedApplication != null; - Mono<List<NewPage>> pageList = Flux.fromIterable( - importedApplication - .getPages() - .stream() + Mono<List<NewPage>> pageList = Flux.fromIterable(importedApplication.getPages().stream() .map(ApplicationPage::getId) - .collect(Collectors.toList()) - ).flatMap(s -> newPageService.findById(s, MANAGE_PAGES)).collectList(); + .collect(Collectors.toList())) + .flatMap(s -> newPageService.findById(s, MANAGE_PAGES)) + .collectList(); - StepVerifier - .create(pageList) + StepVerifier.create(pageList) .assertNext(newPages -> { // Check before import we had both the pages assertThat(applicationPageIdsBeforeImport).hasSize(2); @@ -1441,10 +1570,10 @@ public void importApplicationIntoWorkspace_pageRemovedAndUpdatedDefaultPageNameI assertThat(newPages.size()).isEqualTo(1); assertThat(importedApplication.getPages().size()).isEqualTo(1); - assertThat(importedApplication.getPages().get(0).getId()).isEqualTo(newPages.get(0).getId()); + assertThat(importedApplication.getPages().get(0).getId()) + .isEqualTo(newPages.get(0).getId()); assertThat(newPages.get(0).getPublishedPage().getName()).isEqualTo("importedPage"); assertThat(newPages.get(0).getGitSyncId()).isEqualTo(gitSyncIdBeforeImport); - }) .verifyComplete(); } @@ -1463,46 +1592,57 @@ public void importApplicationIntoWorkspace_pageAddedInBranchApplication_Success( gitData.setBranchName("master"); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication, workspaceId) + Application application = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); + }) + .block(); - String gitSyncIdBeforeImport = newPageService.findById(application.getPages().get(0).getId(), MANAGE_PAGES).block().getGitSyncId(); + String gitSyncIdBeforeImport = newPageService + .findById(application.getPages().get(0).getId(), MANAGE_PAGES) + .block() + .getGitSyncId(); assert application.getId() != null; - Set<String> applicationPageIdsBeforeImport = Objects.requireNonNull(applicationRepository.findById(application.getId()).block()) - .getPages() - .stream() - .map(ApplicationPage::getId) - .collect(Collectors.toSet()); + Set<String> applicationPageIdsBeforeImport = + Objects.requireNonNull(applicationRepository + .findById(application.getId()) + .block()) + .getPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toSet()); - ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application-with-page-added.json").block(); + ApplicationJson applicationJson = createAppJson( + "test_assets/ImportExportServiceTest/valid-application-with-page-added.json") + .block(); applicationJson.getPageList().get(0).setGitSyncId(gitSyncIdBeforeImport); - Application applicationMono = importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, applicationJson, application.getId(), "master").block(); + Application applicationMono = importExportApplicationService + .importApplicationInWorkspaceFromGit(workspaceId, applicationJson, application.getId(), "master") + .block(); - Mono<List<NewPage>> pageList = Flux.fromIterable( - applicationMono.getPages() - .stream() + Mono<List<NewPage>> pageList = Flux.fromIterable(applicationMono.getPages().stream() .map(ApplicationPage::getId) - .collect(Collectors.toList()) - ).flatMap(s -> newPageService.findById(s, MANAGE_PAGES)).collectList(); + .collect(Collectors.toList())) + .flatMap(s -> newPageService.findById(s, MANAGE_PAGES)) + .collectList(); - StepVerifier - .create(pageList) + StepVerifier.create(pageList) .assertNext(newPages -> { // Check before import we had both the pages assertThat(applicationPageIdsBeforeImport).hasSize(1); assertThat(newPages.size()).isEqualTo(3); - List<String> pageNames = newPages.stream().map(newPage -> newPage.getUnpublishedPage().getName()).collect(Collectors.toList()); + List<String> pageNames = newPages.stream() + .map(newPage -> newPage.getUnpublishedPage().getName()) + .collect(Collectors.toList()); assertThat(pageNames).contains("Page1"); assertThat(pageNames).contains("Page2"); assertThat(pageNames).contains("Page3"); }) .verifyComplete(); - } @Test @@ -1524,18 +1664,22 @@ public void importUpdatedApplicationIntoWorkspaceFromFile_publicApplication_visi PermissionGroup adminPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup developerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); PermissionGroup viewerPermissionGroup = permissionGroups.stream() .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) - .findFirst().get(); + .findFirst() + .get(); Application testApplication = new Application(); - testApplication.setName("importUpdatedApplicationIntoWorkspaceFromFile_publicApplication_visibilityFlagNotReset"); + testApplication.setName( + "importUpdatedApplicationIntoWorkspaceFromFile_publicApplication_visibilityFlagNotReset"); testApplication.setWorkspaceId(workspaceId); testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); @@ -1545,30 +1689,41 @@ public void importUpdatedApplicationIntoWorkspaceFromFile_publicApplication_visi gitData.setBranchName("master"); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication, workspaceId) + Application application = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); + }) + .block(); ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); applicationAccessDTO.setPublicAccess(true); - Application newApplication = applicationService.changeViewAccess(application.getId(), "master", applicationAccessDTO).block(); + Application newApplication = applicationService + .changeViewAccess(application.getId(), "master", applicationAccessDTO) + .block(); - PermissionGroup anonymousPermissionGroup = permissionGroupService.getPublicPermissionGroup().block(); + PermissionGroup anonymousPermissionGroup = + permissionGroupService.getPublicPermissionGroup().block(); - Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + Policy manageAppPolicy = Policy.builder() + .permission(MANAGE_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) .build(); - Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), - viewerPermissionGroup.getId(), anonymousPermissionGroup.getId())) + Policy readAppPolicy = Policy.builder() + .permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), + developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), + anonymousPermissionGroup.getId())) .build(); - Mono<Application> applicationMono = importExportApplicationService.exportApplicationById(application.getId(), "master") - .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, applicationJson, application.getId(), "master")); + Mono<Application> applicationMono = importExportApplicationService + .exportApplicationById(application.getId(), "master") + .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, applicationJson, application.getId(), "master")); - StepVerifier - .create(applicationMono) + StepVerifier.create(applicationMono) .assertNext(application1 -> { assertThat(application1.getIsPublic()).isEqualTo(Boolean.TRUE); assertThat(application1.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); @@ -1593,12 +1748,14 @@ public void discardChange_addNewPageAfterImport_addedPageRemoved() { 3. Import the application from same JSON with applicationId 4. Added page should be deleted from DB */ - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); String workspaceId = createTemplateWorkspace().getId(); final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono .flatMap(applicationJson -> { applicationJson.getExportedApplication().setName("discard-change-page-added"); - return importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson); }) .flatMap(application -> { PageDTO page = new PageDTO(); @@ -1609,14 +1766,16 @@ public void discardChange_addNewPageAfterImport_addedPageRemoved() { .flatMap(page -> applicationRepository.findById(page.getApplicationId())) .cache(); List<PageDTO> pageListBefore = resultMonoWithoutDiscardOperation - .flatMap(application -> newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList()).block(); - - StepVerifier - .create(resultMonoWithoutDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() - ))) + .flatMap(application -> newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList()) + .block(); + + StepVerifier.create(resultMonoWithoutDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<PageDTO> pageList = tuple.getT2(); @@ -1632,18 +1791,20 @@ public void discardChange_addNewPageAfterImport_addedPageRemoved() { assertThat(pageList).hasSize(3); - ApplicationPage defaultAppPage = application.getPages() - .stream() + ApplicationPage defaultAppPage = application.getPages().stream() .filter(ApplicationPage::getIsDefault) .findFirst() .orElse(null); assertThat(defaultAppPage).isNotNull(); PageDTO defaultPageDTO = pageList.stream() - .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())) + .findFirst() + .orElse(null); assertThat(defaultPageDTO).isNotNull(); - assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()).isNotEmpty(); + assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()) + .isNotEmpty(); List<String> pageNames = new ArrayList<>(); pageList.forEach(page -> pageNames.add(page.getName())); @@ -1652,30 +1813,26 @@ public void discardChange_addNewPageAfterImport_addedPageRemoved() { .verifyComplete(); // Import the same application again to find if the added page is deleted - final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation - .flatMap(importedApplication -> - applicationJsonMono - .flatMap(applicationJson -> - { - importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); - return applicationService.save(importedApplication) - .then(importExportApplicationService.importApplicationInWorkspaceFromGit( - importedApplication.getWorkspaceId(), - applicationJson, - importedApplication.getId(), - "main") - ); - } - ) - ); - - StepVerifier - .create(resultMonoWithDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() - ))) + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation.flatMap( + importedApplication -> applicationJsonMono.flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication + .getGitApplicationMetadata() + .setDefaultApplicationId(importedApplication.getId()); + return applicationService + .save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspaceFromGit( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main")); + })); + + StepVerifier.create(resultMonoWithDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<PageDTO> pageList = tuple.getT2(); @@ -1685,7 +1842,10 @@ public void discardChange_addNewPageAfterImport_addedPageRemoved() { assertThat(pageList).hasSize(2); for (PageDTO page : pageList) { - PageDTO curentPage = pageListBefore.stream().filter(pageDTO -> pageDTO.getId().equals(page.getId())).collect(Collectors.toList()).get(0); + PageDTO curentPage = pageListBefore.stream() + .filter(pageDTO -> pageDTO.getId().equals(page.getId())) + .collect(Collectors.toList()) + .get(0); assertThat(page.getPolicies()).isEqualTo(curentPage.getPolicies()); } @@ -1707,13 +1867,15 @@ public void discardChange_addNewPageAfterImport_addedPageRemoved() { @WithUserDetails(value = "api_user") public void discardChange_addNewActionAfterImport_addedActionRemoved() { - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); String workspaceId = createTemplateWorkspace().getId(); final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono .flatMap(applicationJson -> { applicationJson.getExportedApplication().setName("discard-change-action-added"); - return importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson); }) .flatMap(application -> { ActionDTO action = new ActionDTO(); @@ -1730,14 +1892,12 @@ public void discardChange_addNewActionAfterImport_addedActionRemoved() { .cache(); List<ActionDTO> actionListBefore = resultMonoWithoutDiscardOperation - .flatMap(application -> getActionsInApplication(application).collectList()).block(); - - StepVerifier - .create(resultMonoWithoutDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - getActionsInApplication(application).collectList() - ))) + .flatMap(application -> getActionsInApplication(application).collectList()) + .block(); + + StepVerifier.create(resultMonoWithoutDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + getActionsInApplication(application).collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<ActionDTO> actionList = tuple.getT2(); @@ -1745,7 +1905,6 @@ public void discardChange_addNewActionAfterImport_addedActionRemoved() { assertThat(application.getName()).isEqualTo("discard-change-action-added"); assertThat(application.getWorkspaceId()).isNotNull(); - List<String> actionNames = new ArrayList<>(); actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); assertThat(actionNames).contains("discard-action-test"); @@ -1753,29 +1912,24 @@ public void discardChange_addNewActionAfterImport_addedActionRemoved() { .verifyComplete(); // Import the same application again - final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation - .flatMap(importedApplication -> - applicationJsonMono - .flatMap(applicationJson -> { - importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); - return applicationService.save(importedApplication) - .then(importExportApplicationService.importApplicationInWorkspaceFromGit( - importedApplication.getWorkspaceId(), - applicationJson, - importedApplication.getId(), - "main") - ); - } - ) - ); - - StepVerifier - .create(resultMonoWithDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - getActionsInApplication(application).collectList() - ))) + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation.flatMap( + importedApplication -> applicationJsonMono.flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication + .getGitApplicationMetadata() + .setDefaultApplicationId(importedApplication.getId()); + return applicationService + .save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspaceFromGit( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main")); + })); + + StepVerifier.create(resultMonoWithDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + getActionsInApplication(application).collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<ActionDTO> actionList = tuple.getT2(); @@ -1786,7 +1940,10 @@ public void discardChange_addNewActionAfterImport_addedActionRemoved() { actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); assertThat(actionNames).doesNotContain("discard-action-test"); for (ActionDTO action : actionListBefore) { - ActionDTO currentAction = actionListBefore.stream().filter(actionDTO -> actionDTO.getId().equals(action.getId())).collect(Collectors.toList()).get(0); + ActionDTO currentAction = actionListBefore.stream() + .filter(actionDTO -> actionDTO.getId().equals(action.getId())) + .collect(Collectors.toList()) + .get(0); assertThat(action.getPolicies()).isEqualTo(currentAction.getPolicies()); } }) @@ -1804,12 +1961,14 @@ public void discardChange_addNewActionAfterImport_addedActionRemoved() { @WithUserDetails(value = "api_user") public void discardChange_addNewActionCollectionAfterImport_addedActionCollectionRemoved() { - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); String workspaceId = createTemplateWorkspace().getId(); final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono .flatMap(applicationJson -> { applicationJson.getExportedApplication().setName("discard-change-collection-added"); - return importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson); }) .flatMap(application -> { ActionCollectionDTO actionCollectionDTO1 = new ActionCollectionDTO(); @@ -1832,17 +1991,20 @@ public void discardChange_addNewActionCollectionAfterImport_addedActionCollectio .cache(); List<ActionCollection> actionCollectionListBefore = resultMonoWithoutDiscardOperation - .flatMap(application -> actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList()).block(); + .flatMap(application -> actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList()) + .block(); List<ActionDTO> actionListBefore = resultMonoWithoutDiscardOperation - .flatMap(application -> getActionsInApplication(application).collectList()).block(); - - StepVerifier - .create(resultMonoWithoutDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - getActionsInApplication(application).collectList() - ))) + .flatMap(application -> getActionsInApplication(application).collectList()) + .block(); + + StepVerifier.create(resultMonoWithoutDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + getActionsInApplication(application).collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<ActionCollection> actionCollectionList = tuple.getT2(); @@ -1852,7 +2014,8 @@ public void discardChange_addNewActionCollectionAfterImport_addedActionCollectio assertThat(application.getWorkspaceId()).isNotNull(); List<String> actionCollectionNames = new ArrayList<>(); - actionCollectionList.forEach(actionCollection -> actionCollectionNames.add(actionCollection.getUnpublishedCollection().getName())); + actionCollectionList.forEach(actionCollection -> actionCollectionNames.add( + actionCollection.getUnpublishedCollection().getName())); assertThat(actionCollectionNames).contains("discard-action-collection-test"); List<String> actionNames = new ArrayList<>(); @@ -1862,31 +2025,27 @@ public void discardChange_addNewActionCollectionAfterImport_addedActionCollectio .verifyComplete(); // Import the same application again - final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation - .flatMap(importedApplication -> - applicationJsonMono - .flatMap(applicationJson -> - { - importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); - return applicationService.save(importedApplication) - .then(importExportApplicationService.importApplicationInWorkspaceFromGit( - importedApplication.getWorkspaceId(), - applicationJson, - importedApplication.getId(), - "main") - ); - } - ) - ); - - StepVerifier - .create(resultMonoWithDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), - getActionsInApplication(application).collectList() - ))) + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation.flatMap( + importedApplication -> applicationJsonMono.flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication + .getGitApplicationMetadata() + .setDefaultApplicationId(importedApplication.getId()); + return applicationService + .save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspaceFromGit( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main")); + })); + + StepVerifier.create(resultMonoWithDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList(), + getActionsInApplication(application).collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<ActionCollection> actionCollectionList = tuple.getT2(); @@ -1895,19 +2054,26 @@ public void discardChange_addNewActionCollectionAfterImport_addedActionCollectio assertThat(application.getWorkspaceId()).isNotNull(); List<String> actionCollectionNames = new ArrayList<>(); - actionCollectionList.forEach(actionCollection -> actionCollectionNames.add(actionCollection.getUnpublishedCollection().getName())); + actionCollectionList.forEach(actionCollection -> actionCollectionNames.add( + actionCollection.getUnpublishedCollection().getName())); assertThat(actionCollectionNames).doesNotContain("discard-action-collection-test"); List<String> actionNames = new ArrayList<>(); actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); assertThat(actionNames).doesNotContain("discard-action-collection-test-action"); for (ActionDTO action : actionListBefore) { - ActionDTO currentAction = actionListBefore.stream().filter(actionDTO -> actionDTO.getId().equals(action.getId())).collect(Collectors.toList()).get(0); + ActionDTO currentAction = actionListBefore.stream() + .filter(actionDTO -> actionDTO.getId().equals(action.getId())) + .collect(Collectors.toList()) + .get(0); assertThat(action.getPolicies()).isEqualTo(currentAction.getPolicies()); } for (ActionCollection actionCollection : actionCollectionListBefore) { - ActionCollection currentAction = actionCollectionListBefore.stream().filter(actionDTO -> actionDTO.getId().equals(actionCollection.getId())).collect(Collectors.toList()).get(0); + ActionCollection currentAction = actionCollectionListBefore.stream() + .filter(actionDTO -> actionDTO.getId().equals(actionCollection.getId())) + .collect(Collectors.toList()) + .get(0); assertThat(actionCollection.getPolicies()).isEqualTo(currentAction.getPolicies()); } }) @@ -1925,30 +2091,30 @@ public void discardChange_addNewActionCollectionAfterImport_addedActionCollectio @WithUserDetails(value = "api_user") public void discardChange_removeNewPageAfterImport_removedPageRestored() { - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); String workspaceId = createTemplateWorkspace().getId(); final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono .flatMap(applicationJson -> { applicationJson.getExportedApplication().setName("discard-change-page-removed"); - return importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson); }) .flatMap(application -> { - Optional<ApplicationPage> applicationPage = application - .getPages() - .stream() + Optional<ApplicationPage> applicationPage = application.getPages().stream() .filter(page -> !page.isDefault()) .findFirst(); - return applicationPageService.deleteUnpublishedPage(applicationPage.get().getId()); + return applicationPageService.deleteUnpublishedPage( + applicationPage.get().getId()); }) .flatMap(page -> applicationRepository.findById(page.getApplicationId())) .cache(); - StepVerifier - .create(resultMonoWithoutDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() - ))) + StepVerifier.create(resultMonoWithoutDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<PageDTO> pageList = tuple.getT2(); @@ -1962,30 +2128,26 @@ public void discardChange_removeNewPageAfterImport_removedPageRestored() { .verifyComplete(); // Import the same application again - final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation - .flatMap(importedApplication -> - applicationJsonMono - .flatMap(applicationJson -> - { - importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); - return applicationService.save(importedApplication) - .then(importExportApplicationService.importApplicationInWorkspaceFromGit( - importedApplication.getWorkspaceId(), - applicationJson, - importedApplication.getId(), - "main") - ); - } - ) - ); - - StepVerifier - .create(resultMonoWithDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() - ))) + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation.flatMap( + importedApplication -> applicationJsonMono.flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication + .getGitApplicationMetadata() + .setDefaultApplicationId(importedApplication.getId()); + return applicationService + .save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspaceFromGit( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main")); + })); + + StepVerifier.create(resultMonoWithDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<PageDTO> pageList = tuple.getT2(); @@ -2009,13 +2171,15 @@ public void discardChange_removeNewPageAfterImport_removedPageRestored() { @WithUserDetails(value = "api_user") public void discardChange_removeNewActionAfterImport_removedActionRestored() { - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); String workspaceId = createTemplateWorkspace().getId(); final String[] deletedActionName = new String[1]; final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono .flatMap(applicationJson -> { applicationJson.getExportedApplication().setName("discard-change-action-removed"); - return importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson); }) .flatMap(application -> { return getActionsInApplication(application) @@ -2028,12 +2192,9 @@ public void discardChange_removeNewActionAfterImport_removedActionRestored() { }) .cache(); - StepVerifier - .create(resultMonoWithoutDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - getActionsInApplication(application).collectList() - ))) + StepVerifier.create(resultMonoWithoutDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + getActionsInApplication(application).collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<ActionDTO> actionList = tuple.getT2(); @@ -2048,30 +2209,24 @@ public void discardChange_removeNewActionAfterImport_removedActionRestored() { .verifyComplete(); // Import the same application again - final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation - .flatMap(importedApplication -> - applicationJsonMono - .flatMap(applicationJson -> - { - importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); - return applicationService.save(importedApplication) - .then(importExportApplicationService.importApplicationInWorkspaceFromGit( - importedApplication.getWorkspaceId(), - applicationJson, - importedApplication.getId(), - "main") - ); - } - ) - ); - - StepVerifier - .create(resultMonoWithDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - getActionsInApplication(application).collectList() - ))) + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation.flatMap( + importedApplication -> applicationJsonMono.flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication + .getGitApplicationMetadata() + .setDefaultApplicationId(importedApplication.getId()); + return applicationService + .save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspaceFromGit( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main")); + })); + + StepVerifier.create(resultMonoWithDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + getActionsInApplication(application).collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<ActionDTO> actionList = tuple.getT2(); @@ -2096,31 +2251,36 @@ public void discardChange_removeNewActionAfterImport_removedActionRestored() { @WithUserDetails(value = "api_user") public void discardChange_removeNewActionCollection_removedActionCollectionRestored() { - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); String workspaceId = createTemplateWorkspace().getId(); final String[] deletedActionCollectionNames = new String[1]; final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono .flatMap(applicationJson -> { applicationJson.getExportedApplication().setName("discard-change-collection-removed"); - return importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson); }) .flatMap(application -> { - return actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + return actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) .next() .flatMap(actionCollection -> { - deletedActionCollectionNames[0] = actionCollection.getUnpublishedCollection().getName(); - return actionCollectionService.deleteUnpublishedActionCollection(actionCollection.getId()); + deletedActionCollectionNames[0] = actionCollection + .getUnpublishedCollection() + .getName(); + return actionCollectionService.deleteUnpublishedActionCollection( + actionCollection.getId()); }) .then(applicationPageService.publish(application.getId(), true)); }) .cache(); - StepVerifier - .create(resultMonoWithoutDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() - ))) + StepVerifier.create(resultMonoWithoutDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<ActionCollection> actionCollectionList = tuple.getT2(); @@ -2129,36 +2289,33 @@ public void discardChange_removeNewActionCollection_removedActionCollectionResto assertThat(application.getWorkspaceId()).isNotNull(); List<String> actionCollectionNames = new ArrayList<>(); - actionCollectionList.forEach(actionCollection -> actionCollectionNames.add(actionCollection.getUnpublishedCollection().getName())); + actionCollectionList.forEach(actionCollection -> actionCollectionNames.add( + actionCollection.getUnpublishedCollection().getName())); assertThat(actionCollectionNames).doesNotContain(deletedActionCollectionNames); }) .verifyComplete(); // Import the same application again - final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation - .flatMap(importedApplication -> - applicationJsonMono - .flatMap(applicationJson -> - { - importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); - return applicationService.save(importedApplication) - .then(importExportApplicationService.importApplicationInWorkspaceFromGit( - importedApplication.getWorkspaceId(), - applicationJson, - importedApplication.getId(), - "main") - ); - } - ) - ); - - StepVerifier - .create(resultMonoWithDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() - ))) + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation.flatMap( + importedApplication -> applicationJsonMono.flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication + .getGitApplicationMetadata() + .setDefaultApplicationId(importedApplication.getId()); + return applicationService + .save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspaceFromGit( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main")); + })); + + StepVerifier.create(resultMonoWithDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + actionCollectionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<ActionCollection> actionCollectionList = tuple.getT2(); @@ -2166,7 +2323,8 @@ public void discardChange_removeNewActionCollection_removedActionCollectionResto assertThat(application.getWorkspaceId()).isNotNull(); List<String> actionCollectionNames = new ArrayList<>(); - actionCollectionList.forEach(actionCollection -> actionCollectionNames.add(actionCollection.getUnpublishedCollection().getName())); + actionCollectionList.forEach(actionCollection -> actionCollectionNames.add( + actionCollection.getUnpublishedCollection().getName())); assertThat(actionCollectionNames).contains(deletedActionCollectionNames); }) .verifyComplete(); @@ -2182,12 +2340,14 @@ public void discardChange_removeNewActionCollection_removedActionCollectionResto @Test @WithUserDetails(value = "api_user") public void discardChange_addNavigationSettingAfterImport_addedNavigationSettingRemoved() { - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application-without-navigation-setting.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application-without-navigation-setting.json"); String workspaceId = createTemplateWorkspace().getId(); final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono .flatMap(applicationJson -> { applicationJson.getExportedApplication().setName("discard-change-navsettings-added"); - return importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson); }) .flatMap(application -> { ApplicationDetail applicationDetail = new ApplicationDetail(); @@ -2202,30 +2362,45 @@ public void discardChange_addNavigationSettingAfterImport_addedNavigationSetting StepVerifier.create(resultMonoWithoutDiscardOperation) .assertNext(initialApplication -> { - assertThat(initialApplication.getUnpublishedApplicationDetail()).isNotNull(); - assertThat(initialApplication.getUnpublishedApplicationDetail().getNavigationSetting()).isNotNull(); - assertThat(initialApplication.getUnpublishedApplicationDetail().getNavigationSetting().getOrientation()).isEqualTo("top"); - assertThat(initialApplication.getPublishedApplicationDetail()).isNotNull(); - assertThat(initialApplication.getPublishedApplicationDetail().getNavigationSetting()).isNotNull(); - assertThat(initialApplication.getPublishedApplicationDetail().getNavigationSetting().getOrientation()).isEqualTo("top"); + assertThat(initialApplication.getUnpublishedApplicationDetail()) + .isNotNull(); + assertThat(initialApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting()) + .isNotNull(); + assertThat(initialApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getOrientation()) + .isEqualTo("top"); + assertThat(initialApplication.getPublishedApplicationDetail()) + .isNotNull(); + assertThat(initialApplication + .getPublishedApplicationDetail() + .getNavigationSetting()) + .isNotNull(); + assertThat(initialApplication + .getPublishedApplicationDetail() + .getNavigationSetting() + .getOrientation()) + .isEqualTo("top"); }) .verifyComplete(); // Import the same application again - final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation - .flatMap(importedApplication -> applicationJsonMono - .flatMap(applicationJson -> { - importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); - return applicationService.save(importedApplication) - .then(importExportApplicationService.importApplicationInWorkspaceFromGit( - importedApplication.getWorkspaceId(), - applicationJson, - importedApplication.getId(), - "main") - ); - } - ) - ); + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation.flatMap( + importedApplication -> applicationJsonMono.flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication + .getGitApplicationMetadata() + .setDefaultApplicationId(importedApplication.getId()); + return applicationService + .save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspaceFromGit( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main")); + })); StepVerifier.create(resultMonoWithDiscardOperation) .assertNext(application -> { @@ -2247,12 +2422,14 @@ public void discardChange_addNavigationSettingAfterImport_addedNavigationSetting @WithUserDetails(value = "api_user") public void discardChange_addAppLayoutAfterImport_addedAppLayoutRemoved() { - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application-without-app-layout.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application-without-app-layout.json"); String workspaceId = createTemplateWorkspace().getId(); final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono .flatMap(applicationJson -> { applicationJson.getExportedApplication().setName("discard-change-applayout-added"); - return importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspaceId, applicationJson); }) .flatMap(application -> { application.setUnpublishedAppLayout(new Application.AppLayout(Application.AppLayout.Type.DESKTOP)); @@ -2264,29 +2441,29 @@ public void discardChange_addAppLayoutAfterImport_addedAppLayoutRemoved() { StepVerifier.create(resultMonoWithoutDiscardOperation) .assertNext(initialApplication -> { assertThat(initialApplication.getUnpublishedAppLayout()).isNotNull(); - assertThat(initialApplication.getUnpublishedAppLayout().getType()).isEqualTo(Application.AppLayout.Type.DESKTOP); + assertThat(initialApplication.getUnpublishedAppLayout().getType()) + .isEqualTo(Application.AppLayout.Type.DESKTOP); assertThat(initialApplication.getPublishedAppLayout()).isNotNull(); - assertThat(initialApplication.getPublishedAppLayout().getType()).isEqualTo(Application.AppLayout.Type.DESKTOP); + assertThat(initialApplication.getPublishedAppLayout().getType()) + .isEqualTo(Application.AppLayout.Type.DESKTOP); }) .verifyComplete(); - // Import the same application again - final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation - .flatMap(importedApplication -> applicationJsonMono - .flatMap(applicationJson -> { - importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); - importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); - return applicationService.save(importedApplication) - .then(importExportApplicationService.importApplicationInWorkspaceFromGit( - importedApplication.getWorkspaceId(), - applicationJson, - importedApplication.getId(), - "main") - ); - } - ) - ); + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation.flatMap( + importedApplication -> applicationJsonMono.flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication + .getGitApplicationMetadata() + .setDefaultApplicationId(importedApplication.getId()); + return applicationService + .save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspaceFromGit( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main")); + })); StepVerifier.create(resultMonoWithDiscardOperation) .assertNext(application -> { @@ -2302,27 +2479,25 @@ public void discardChange_addAppLayoutAfterImport_addedAppLayoutRemoved() { public void applySchemaMigration_jsonFileWithFirstVersion_migratedToLatestVersionSuccess() { FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/file-with-v1.json"); - Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()) - .map(dataBuffer -> { - byte[] data = new byte[dataBuffer.readableByteCount()]; - dataBuffer.read(data); - DataBufferUtils.release(dataBuffer); - return new String(data); - }); + Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()).map(dataBuffer -> { + byte[] data = new byte[dataBuffer.readableByteCount()]; + dataBuffer.read(data); + DataBufferUtils.release(dataBuffer); + return new String(data); + }); Mono<ApplicationJson> v1ApplicationMono = stringifiedFile .map(data -> { return gson.fromJson(data, ApplicationJson.class); - }).cache(); + }) + .cache(); - Mono<ApplicationJson> migratedApplicationMono = v1ApplicationMono - .map(applicationJson -> { - ApplicationJson applicationJson1 = new ApplicationJson(); - AppsmithBeanUtils.copyNestedNonNullProperties(applicationJson, applicationJson1); - return JsonSchemaMigration.migrateApplicationToLatestSchema(applicationJson1); - }); + Mono<ApplicationJson> migratedApplicationMono = v1ApplicationMono.map(applicationJson -> { + ApplicationJson applicationJson1 = new ApplicationJson(); + AppsmithBeanUtils.copyNestedNonNullProperties(applicationJson, applicationJson1); + return JsonSchemaMigration.migrateApplicationToLatestSchema(applicationJson1); + }); - StepVerifier - .create(Mono.zip(v1ApplicationMono, migratedApplicationMono)) + StepVerifier.create(Mono.zip(v1ApplicationMono, migratedApplicationMono)) .assertNext(tuple -> { ApplicationJson v1ApplicationJson = tuple.getT1(); ApplicationJson latestApplicationJson = tuple.getT2(); @@ -2330,8 +2505,10 @@ public void applySchemaMigration_jsonFileWithFirstVersion_migratedToLatestVersio assertThat(v1ApplicationJson.getServerSchemaVersion()).isEqualTo(1); assertThat(v1ApplicationJson.getClientSchemaVersion()).isEqualTo(1); - assertThat(latestApplicationJson.getServerSchemaVersion()).isEqualTo(JsonSchemaVersions.serverVersion); - assertThat(latestApplicationJson.getClientSchemaVersion()).isEqualTo(JsonSchemaVersions.clientVersion); + assertThat(latestApplicationJson.getServerSchemaVersion()) + .isEqualTo(JsonSchemaVersions.serverVersion); + assertThat(latestApplicationJson.getClientSchemaVersion()) + .isEqualTo(JsonSchemaVersions.clientVersion); }) .verifyComplete(); } @@ -2350,17 +2527,21 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() Application testApplication = new Application(); testApplication.setName("exportApplication_withCredentialsForSampleApps_SuccessWithDecryptFields"); testApplication.setExportWithConfiguration(true); - testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + testApplication = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); assert testApplication != null; exportWithConfigurationAppId = testApplication.getId(); ApplicationAccessDTO accessDTO = new ApplicationAccessDTO(); accessDTO.setPublicAccess(true); - applicationService.changeViewAccess(exportWithConfigurationAppId, accessDTO).block(); + applicationService + .changeViewAccess(exportWithConfigurationAppId, accessDTO) + .block(); final String appName = testApplication.getName(); final Mono<ApplicationJson> resultMono = Mono.zip( Mono.just(testApplication), - newPageService.findPageById(testApplication.getPages().get(0).getId(), READ_PAGES, false) - ) + newPageService.findPageById( + testApplication.getPages().get(0).getId(), READ_PAGES, false)) .flatMap(tuple -> { Application testApp = tuple.getT1(); PageDTO testPage = tuple.getT2(); @@ -2369,8 +2550,8 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() ObjectMapper objectMapper = new ObjectMapper(); JSONObject dsl = new JSONObject(); try { - dsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { - })); + dsl = new JSONObject(objectMapper.readValue( + DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() {})); } catch (JsonProcessingException e) { e.printStackTrace(); } @@ -2419,30 +2600,30 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() actionCollectionDTO1.setActions(List.of(action1)); actionCollectionDTO1.setPluginType(PluginType.JS); - return layoutCollectionService.createCollection(actionCollectionDTO1) + return layoutCollectionService + .createCollection(actionCollectionDTO1) .then(layoutActionService.createSingleAction(action, Boolean.FALSE)) .then(layoutActionService.createSingleAction(action2, Boolean.FALSE)) - .then(layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout)) + .then(layoutActionService.updateLayout( + testPage.getId(), testPage.getApplicationId(), layout.getId(), layout)) .then(importExportApplicationService.exportApplicationById(testApp.getId(), "")); }) .cache(); - Mono<List<NewAction>> actionListMono = resultMono - .then(newActionService - .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null).collectList()); + Mono<List<NewAction>> actionListMono = resultMono.then(newActionService + .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null) + .collectList()); - Mono<List<ActionCollection>> collectionListMono = resultMono.then( - actionCollectionService - .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null).collectList()); + Mono<List<ActionCollection>> collectionListMono = resultMono.then(actionCollectionService + .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null) + .collectList()); - Mono<List<NewPage>> pageListMono = resultMono.then( - newPageService - .findNewPagesByApplicationId(testApplication.getId(), READ_PAGES).collectList()); + Mono<List<NewPage>> pageListMono = resultMono.then(newPageService + .findNewPagesByApplicationId(testApplication.getId(), READ_PAGES) + .collectList()); - StepVerifier - .create(Mono.zip(resultMono, actionListMono, collectionListMono, pageListMono)) + StepVerifier.create(Mono.zip(resultMono, actionListMono, collectionListMono, pageListMono)) .assertNext(tuple -> { - ApplicationJson applicationJson = tuple.getT1(); List<NewAction> DBActions = tuple.getT2(); List<ActionCollection> DBCollections = tuple.getT3(); @@ -2454,32 +2635,37 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() List<ActionCollection> actionCollectionList = applicationJson.getActionCollectionList(); List<DatasourceStorage> datasourceList = applicationJson.getDatasourceList(); - List<String> exportedCollectionIds = actionCollectionList.stream().map(ActionCollection::getId).collect(Collectors.toList()); - List<String> exportedActionIds = actionList.stream().map(NewAction::getId).collect(Collectors.toList()); - List<String> DBCollectionIds = DBCollections.stream().map(ActionCollection::getId).collect(Collectors.toList()); - List<String> DBActionIds = DBActions.stream().map(NewAction::getId).collect(Collectors.toList()); + List<String> exportedCollectionIds = actionCollectionList.stream() + .map(ActionCollection::getId) + .collect(Collectors.toList()); + List<String> exportedActionIds = + actionList.stream().map(NewAction::getId).collect(Collectors.toList()); + List<String> DBCollectionIds = + DBCollections.stream().map(ActionCollection::getId).collect(Collectors.toList()); + List<String> DBActionIds = + DBActions.stream().map(NewAction::getId).collect(Collectors.toList()); List<String> DBOnLayoutLoadActionIds = new ArrayList<>(); List<String> exportedOnLayoutLoadActionIds = new ArrayList<>(); - DBPages.forEach(newPage -> - newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + DBPages.forEach( + newPage -> newPage.getUnpublishedPage().getLayouts().forEach(layout -> { if (layout.getLayoutOnLoadActions() != null) { layout.getLayoutOnLoadActions().forEach(dslActionDTOSet -> { - dslActionDTOSet.forEach(actionDTO -> DBOnLayoutLoadActionIds.add(actionDTO.getId())); + dslActionDTOSet.forEach( + actionDTO -> DBOnLayoutLoadActionIds.add(actionDTO.getId())); }); } - }) - ); + })); - pageList.forEach(newPage -> - newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + pageList.forEach( + newPage -> newPage.getUnpublishedPage().getLayouts().forEach(layout -> { if (layout.getLayoutOnLoadActions() != null) { layout.getLayoutOnLoadActions().forEach(dslActionDTOSet -> { - dslActionDTOSet.forEach(actionDTO -> exportedOnLayoutLoadActionIds.add(actionDTO.getId())); + dslActionDTOSet.forEach( + actionDTO -> exportedOnLayoutLoadActionIds.add(actionDTO.getId())); }); } - }) - ); + })); NewPage defaultPage = pageList.get(0); @@ -2488,7 +2674,8 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() assertThat(exportedApp.getPages()).hasSize(1); ApplicationPage page = exportedApp.getPages().get(0); - assertThat(page.getId()).isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(page.getId()) + .isEqualTo(defaultPage.getUnpublishedPage().getName()); assertThat(page.getIsDefault()).isTrue(); assertThat(page.getDefaultPageId()).isNull(); @@ -2496,13 +2683,21 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() assertThat(pageList).hasSize(1); assertThat(defaultPage.getApplicationId()).isNull(); - assertThat(defaultPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull(); + assertThat(defaultPage + .getUnpublishedPage() + .getLayouts() + .get(0) + .getDsl()) + .isNotNull(); assertThat(defaultPage.getId()).isNull(); assertThat(defaultPage.getPolicies()).isNull(); assertThat(actionList.isEmpty()).isFalse(); assertThat(actionList).hasSize(3); - NewAction validAction = actionList.stream().filter(action -> action.getId().equals("Page1_validAction")).findFirst().get(); + NewAction validAction = actionList.stream() + .filter(action -> action.getId().equals("Page1_validAction")) + .findFirst() + .get(); assertThat(validAction.getApplicationId()).isNull(); assertThat(validAction.getPluginId()).isEqualTo(installedPlugin.getPackageName()); assertThat(validAction.getPluginType()).isEqualTo(PluginType.API); @@ -2510,10 +2705,16 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() assertThat(validAction.getPolicies()).isNull(); assertThat(validAction.getId()).isNotNull(); ActionDTO unpublishedAction = validAction.getUnpublishedAction(); - assertThat(unpublishedAction.getPageId()).isEqualTo(defaultPage.getUnpublishedPage().getName()); - assertThat(unpublishedAction.getDatasource().getPluginId()).isEqualTo(installedPlugin.getPackageName()); + assertThat(unpublishedAction.getPageId()) + .isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(unpublishedAction.getDatasource().getPluginId()) + .isEqualTo(installedPlugin.getPackageName()); - NewAction testAction1 = actionList.stream().filter(action -> action.getUnpublishedAction().getName().equals("testAction1")).findFirst().get(); + NewAction testAction1 = actionList.stream() + .filter(action -> + action.getUnpublishedAction().getName().equals("testAction1")) + .findFirst() + .get(); assertThat(testAction1.getId()).isEqualTo("Page1_testCollection1.testAction1"); assertThat(actionCollectionList.isEmpty()).isFalse(); @@ -2523,10 +2724,12 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() assertThat(actionCollection.getWorkspaceId()).isNull(); assertThat(actionCollection.getPolicies()).isNull(); assertThat(actionCollection.getId()).isNotNull(); - assertThat(actionCollection.getUnpublishedCollection().getPluginType()).isEqualTo(PluginType.JS); + assertThat(actionCollection.getUnpublishedCollection().getPluginType()) + .isEqualTo(PluginType.JS); assertThat(actionCollection.getUnpublishedCollection().getPageId()) .isEqualTo(defaultPage.getUnpublishedPage().getName()); - assertThat(actionCollection.getUnpublishedCollection().getPluginId()).isEqualTo(installedJsPlugin.getPackageName()); + assertThat(actionCollection.getUnpublishedCollection().getPluginId()) + .isEqualTo(installedJsPlugin.getPackageName()); assertThat(datasourceList).hasSize(1); DatasourceStorage datasource = datasourceList.get(0); @@ -2535,7 +2738,8 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() assertThat(datasource.getPluginId()).isEqualTo(installedPlugin.getPackageName()); assertThat(datasource.getDatasourceConfiguration()).isNotNull(); - final Map<String, InvisibleActionFields> invisibleActionFields = applicationJson.getInvisibleActionFields(); + final Map<String, InvisibleActionFields> invisibleActionFields = + applicationJson.getInvisibleActionFields(); assertThat(invisibleActionFields).isNull(); for (NewAction newAction : actionList) { @@ -2546,15 +2750,21 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() } } - assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull(); - assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull(); + assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()) + .isNull(); + assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()) + .isNull(); assertThat(applicationJson.getEditModeTheme()).isNotNull(); - assertThat(applicationJson.getEditModeTheme().isSystemTheme()).isTrue(); - assertThat(applicationJson.getEditModeTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + assertThat(applicationJson.getEditModeTheme().isSystemTheme()) + .isTrue(); + assertThat(applicationJson.getEditModeTheme().getName()) + .isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); assertThat(applicationJson.getPublishedTheme()).isNotNull(); - assertThat(applicationJson.getPublishedTheme().isSystemTheme()).isTrue(); - assertThat(applicationJson.getPublishedTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + assertThat(applicationJson.getPublishedTheme().isSystemTheme()) + .isTrue(); + assertThat(applicationJson.getPublishedTheme().getName()) + .isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); assertThat(exportedCollectionIds).isNotEmpty(); assertThat(exportedCollectionIds).doesNotContain(String.valueOf(DBCollectionIds)); @@ -2576,11 +2786,10 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() @Test @WithUserDetails(value = "[email protected]") public void exportApplication_withReadOnlyAccess_exportedWithDecryptedFields() { - Mono<ApplicationJson> exportApplicationMono = importExportApplicationService - .exportApplicationById(exportWithConfigurationAppId, SerialiseApplicationObjective.SHARE); + Mono<ApplicationJson> exportApplicationMono = importExportApplicationService.exportApplicationById( + exportWithConfigurationAppId, SerialiseApplicationObjective.SHARE); - StepVerifier - .create(exportApplicationMono) + StepVerifier.create(exportApplicationMono) .assertNext(applicationJson -> { assertThat(applicationJson.getExportedApplication()).isNotNull(); assertThat(applicationJson.getDecryptedFields()).isNotNull(); @@ -2590,14 +2799,17 @@ public void exportApplication_withReadOnlyAccess_exportedWithDecryptedFields() { @Test @WithUserDetails(value = "api_user") - public void importApplication_datasourceWithSameNameAndDifferentPlugin_importedWithValidActionsAndSuffixedDatasource() { + public void + importApplication_datasourceWithSameNameAndDifferentPlugin_importedWithValidActionsAndSuffixedDatasource() { - ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json").block(); + ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json") + .block(); Workspace testWorkspace = new Workspace(); testWorkspace.setName("Duplicate datasource with different plugin org"); testWorkspace = workspaceService.create(testWorkspace).block(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(testWorkspace.getId()).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(testWorkspace.getId()).block(); Datasource testDatasource = new Datasource(); // Chose any plugin except for mongo, as json static file has mongo plugin for datasource @@ -2614,15 +2826,18 @@ public void importApplication_datasourceWithSameNameAndDifferentPlugin_importedW datasourceService.create(testDatasource).block(); - final Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson(testWorkspace.getId(), applicationJson); - - StepVerifier - .create(resultMono - .flatMap(application -> Mono.zip( - Mono.just(application), - datasourceService.getAllByWorkspaceIdWithStorages(application.getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)).collectList(), - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() - ))) + final Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson( + testWorkspace.getId(), applicationJson); + + StepVerifier.create(resultMono.flatMap(application -> Mono.zip( + Mono.just(application), + datasourceService + .getAllByWorkspaceIdWithStorages( + application.getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)) + .collectList(), + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<Datasource> datasourceList = tuple.getT2(); @@ -2652,12 +2867,14 @@ public void importApplication_datasourceWithSameNameAndDifferentPlugin_importedW @WithUserDetails(value = "api_user") public void importApplication_datasourceWithSameNameAndPlugin_importedWithValidActionsWithoutSuffixedDatasource() { - ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json").block(); + ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json") + .block(); Workspace testWorkspace = new Workspace(); testWorkspace.setName("Duplicate datasource with same plugin org"); testWorkspace = workspaceService.create(testWorkspace).block(); - String defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(testWorkspace.getId()).block(); + String defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(testWorkspace.getId()).block(); Datasource testDatasource = new Datasource(); // Chose plugin same as mongo, as json static file has mongo plugin for datasource Plugin postgreSQLPlugin = pluginRepository.findByName("MongoDB").block(); @@ -2672,15 +2889,18 @@ public void importApplication_datasourceWithSameNameAndPlugin_importedWithValidA testDatasource.setDatasourceStorages(storages); datasourceService.create(testDatasource).block(); - final Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson(testWorkspace.getId(), applicationJson); - - StepVerifier - .create(resultMono - .flatMap(application -> Mono.zip( - Mono.just(application), - datasourceService.getAllByWorkspaceIdWithStorages(application.getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)).collectList(), - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() - ))) + final Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson( + testWorkspace.getId(), applicationJson); + + StepVerifier.create(resultMono.flatMap(application -> Mono.zip( + Mono.just(application), + datasourceService + .getAllByWorkspaceIdWithStorages( + application.getWorkspaceId(), Optional.of(MANAGE_DATASOURCES)) + .collectList(), + newActionService + .findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<Datasource> datasourceList = tuple.getT2(); @@ -2694,7 +2914,8 @@ public void importApplication_datasourceWithSameNameAndPlugin_importedWithValidA assertThat(datasource.getWorkspaceId()).isEqualTo(application.getWorkspaceId()); datasourceNameList.add(datasource.getName()); }); - // Check that there are no datasources are created with suffix names as datasource's are of same plugin + // Check that there are no datasources are created with suffix names as datasource's are of same + // plugin assertThat(datasourceNameList).contains(datasourceName); assertThat(actionList).isNotEmpty(); @@ -2708,14 +2929,18 @@ public void importApplication_datasourceWithSameNameAndPlugin_importedWithValidA @Test @WithUserDetails(value = "api_user") - public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode() { + public void + exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("template-org-with-ds"); Application testApplication = new Application(); - testApplication.setName("exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode"); + testApplication.setName( + "exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode"); testApplication.setExportWithConfiguration(true); - testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + testApplication = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); assert testApplication != null; PageDTO testPage1 = new PageDTO(); @@ -2729,20 +2954,24 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit testPage2 = applicationPageService.createPage(testPage2).block(); // Set order for the newly created pages - applicationPageService.reorderPage(testApplication.getId(), testPage1.getId(), 0, null).block(); - applicationPageService.reorderPage(testApplication.getId(), testPage2.getId(), 1, null).block(); + applicationPageService + .reorderPage(testApplication.getId(), testPage1.getId(), 0, null) + .block(); + applicationPageService + .reorderPage(testApplication.getId(), testPage2.getId(), 1, null) + .block(); // Deploy the current application applicationPageService.publish(testApplication.getId(), true).block(); - Mono<ApplicationJson> applicationJsonMono = importExportApplicationService.exportApplicationById(testApplication.getId(), "").cache(); + Mono<ApplicationJson> applicationJsonMono = importExportApplicationService + .exportApplicationById(testApplication.getId(), "") + .cache(); - StepVerifier - .create(applicationJsonMono) + StepVerifier.create(applicationJsonMono) .assertNext(applicationJson -> { assertThat(applicationJson.getPageOrder()).isNull(); assertThat(applicationJson.getPublishedPageOrder()).isNull(); - List<String> pageList = applicationJson.getExportedApplication().getPages() - .stream() + List<String> pageList = applicationJson.getExportedApplication().getPages().stream() .map(ApplicationPage::getId) .collect(Collectors.toList()); @@ -2750,10 +2979,10 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit assertThat(pageList.get(1)).isEqualTo("testPage2"); assertThat(pageList.get(2)).isEqualTo("Page1"); - List<String> publishedPageList = applicationJson.getExportedApplication().getPublishedPages() - .stream() - .map(ApplicationPage::getId) - .collect(Collectors.toList()); + List<String> publishedPageList = + applicationJson.getExportedApplication().getPublishedPages().stream() + .map(ApplicationPage::getId) + .collect(Collectors.toList()); assertThat(publishedPageList.get(0)).isEqualTo("testPage1"); assertThat(publishedPageList.get(1)).isEqualTo("testPage2"); @@ -2762,7 +2991,9 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit .verifyComplete(); ApplicationJson applicationJson = applicationJsonMono.block(); - Application application = importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson).block(); + Application application = importExportApplicationService + .importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson) + .block(); // Get the unpublished pages and verify the order List<ApplicationPage> pageDTOS = application.getPages(); @@ -2770,8 +3001,7 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit Mono<NewPage> newPageMono2 = newPageService.findById(pageDTOS.get(1).getId(), MANAGE_PAGES); Mono<NewPage> newPageMono3 = newPageService.findById(pageDTOS.get(2).getId(), MANAGE_PAGES); - StepVerifier - .create(Mono.zip(newPageMono1, newPageMono2, newPageMono3)) + StepVerifier.create(Mono.zip(newPageMono1, newPageMono2, newPageMono3)) .assertNext(objects -> { NewPage newPage1 = objects.getT1(); NewPage newPage2 = objects.getT2(); @@ -2788,12 +3018,14 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit // Get the published pages List<ApplicationPage> publishedPageDTOs = application.getPublishedPages(); - Mono<NewPage> newPublishedPageMono1 = newPageService.findById(publishedPageDTOs.get(0).getId(), MANAGE_PAGES); - Mono<NewPage> newPublishedPageMono2 = newPageService.findById(publishedPageDTOs.get(1).getId(), MANAGE_PAGES); - Mono<NewPage> newPublishedPageMono3 = newPageService.findById(publishedPageDTOs.get(2).getId(), MANAGE_PAGES); - - StepVerifier - .create(Mono.zip(newPublishedPageMono1, newPublishedPageMono2, newPublishedPageMono3)) + Mono<NewPage> newPublishedPageMono1 = + newPageService.findById(publishedPageDTOs.get(0).getId(), MANAGE_PAGES); + Mono<NewPage> newPublishedPageMono2 = + newPageService.findById(publishedPageDTOs.get(1).getId(), MANAGE_PAGES); + Mono<NewPage> newPublishedPageMono3 = + newPageService.findById(publishedPageDTOs.get(2).getId(), MANAGE_PAGES); + + StepVerifier.create(Mono.zip(newPublishedPageMono1, newPublishedPageMono2, newPublishedPageMono3)) .assertNext(objects -> { NewPage newPage1 = objects.getT1(); NewPage newPage2 = objects.getT2(); @@ -2802,25 +3034,30 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit assertThat(newPage2.getPublishedPage().getName()).isEqualTo("testPage2"); assertThat(newPage3.getPublishedPage().getName()).isEqualTo("Page1"); - assertThat(newPage1.getId()).isEqualTo(publishedPageDTOs.get(0).getId()); - assertThat(newPage2.getId()).isEqualTo(publishedPageDTOs.get(1).getId()); - assertThat(newPage3.getId()).isEqualTo(publishedPageDTOs.get(2).getId()); + assertThat(newPage1.getId()) + .isEqualTo(publishedPageDTOs.get(0).getId()); + assertThat(newPage2.getId()) + .isEqualTo(publishedPageDTOs.get(1).getId()); + assertThat(newPage3.getId()) + .isEqualTo(publishedPageDTOs.get(2).getId()); }) .verifyComplete(); - } - @Test @WithUserDetails(value = "api_user") - public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode() { + public void + exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode() { Workspace newWorkspace = new Workspace(); newWorkspace.setName("template-org-with-ds"); Application testApplication = new Application(); - testApplication.setName("exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode"); + testApplication.setName( + "exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode"); testApplication.setExportWithConfiguration(true); - testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + testApplication = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); assert testApplication != null; PageDTO testPage1 = new PageDTO(); @@ -2837,18 +3074,22 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn applicationPageService.publish(testApplication.getId(), true).block(); // Set order for the newly created pages - applicationPageService.reorderPage(testApplication.getId(), testPage1.getId(), 0, null).block(); - applicationPageService.reorderPage(testApplication.getId(), testPage2.getId(), 1, null).block(); + applicationPageService + .reorderPage(testApplication.getId(), testPage1.getId(), 0, null) + .block(); + applicationPageService + .reorderPage(testApplication.getId(), testPage2.getId(), 1, null) + .block(); - Mono<ApplicationJson> applicationJsonMono = importExportApplicationService.exportApplicationById(testApplication.getId(), "").cache(); + Mono<ApplicationJson> applicationJsonMono = importExportApplicationService + .exportApplicationById(testApplication.getId(), "") + .cache(); - StepVerifier - .create(applicationJsonMono) + StepVerifier.create(applicationJsonMono) .assertNext(applicationJson -> { Application exportedApplication = applicationJson.getExportedApplication(); exportedApplication.setViewMode(false); - List<String> pageOrder = exportedApplication.getPages() - .stream() + List<String> pageOrder = exportedApplication.getPages().stream() .map(ApplicationPage::getId) .collect(Collectors.toList()); assertThat(pageOrder.get(0)).isEqualTo("testPage1"); @@ -2856,8 +3097,7 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn assertThat(pageOrder.get(2)).isEqualTo("Page1"); pageOrder.clear(); - pageOrder = exportedApplication.getPublishedPages() - .stream() + pageOrder = exportedApplication.getPublishedPages().stream() .map(ApplicationPage::getId) .collect(Collectors.toList()); assertThat(pageOrder.get(0)).isEqualTo("Page1"); @@ -2867,7 +3107,9 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn .verifyComplete(); ApplicationJson applicationJson = applicationJsonMono.block(); - Application application = importExportApplicationService.importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson).block(); + Application application = importExportApplicationService + .importNewApplicationInWorkspaceFromJson(workspaceId, applicationJson) + .block(); // Get the unpublished pages and verify the order application.setViewMode(false); @@ -2876,8 +3118,7 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn Mono<NewPage> newPageMono2 = newPageService.findById(pageDTOS.get(1).getId(), MANAGE_PAGES); Mono<NewPage> newPageMono3 = newPageService.findById(pageDTOS.get(2).getId(), MANAGE_PAGES); - StepVerifier - .create(Mono.zip(newPageMono1, newPageMono2, newPageMono3)) + StepVerifier.create(Mono.zip(newPageMono1, newPageMono2, newPageMono3)) .assertNext(objects -> { NewPage newPage1 = objects.getT1(); NewPage newPage2 = objects.getT2(); @@ -2894,12 +3135,14 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn // Get the published pages List<ApplicationPage> publishedPageDTOs = application.getPublishedPages(); - Mono<NewPage> newPublishedPageMono1 = newPageService.findById(publishedPageDTOs.get(0).getId(), MANAGE_PAGES); - Mono<NewPage> newPublishedPageMono2 = newPageService.findById(publishedPageDTOs.get(1).getId(), MANAGE_PAGES); - Mono<NewPage> newPublishedPageMono3 = newPageService.findById(publishedPageDTOs.get(2).getId(), MANAGE_PAGES); - - StepVerifier - .create(Mono.zip(newPublishedPageMono1, newPublishedPageMono2, newPublishedPageMono3)) + Mono<NewPage> newPublishedPageMono1 = + newPageService.findById(publishedPageDTOs.get(0).getId(), MANAGE_PAGES); + Mono<NewPage> newPublishedPageMono2 = + newPageService.findById(publishedPageDTOs.get(1).getId(), MANAGE_PAGES); + Mono<NewPage> newPublishedPageMono3 = + newPageService.findById(publishedPageDTOs.get(2).getId(), MANAGE_PAGES); + + StepVerifier.create(Mono.zip(newPublishedPageMono1, newPublishedPageMono2, newPublishedPageMono3)) .assertNext(objects -> { NewPage newPage1 = objects.getT1(); NewPage newPage2 = objects.getT2(); @@ -2908,12 +3151,14 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn assertThat(newPage2.getPublishedPage().getName()).isEqualTo("testPage1"); assertThat(newPage3.getPublishedPage().getName()).isEqualTo("testPage2"); - assertThat(newPage1.getId()).isEqualTo(publishedPageDTOs.get(0).getId()); - assertThat(newPage2.getId()).isEqualTo(publishedPageDTOs.get(1).getId()); - assertThat(newPage3.getId()).isEqualTo(publishedPageDTOs.get(2).getId()); + assertThat(newPage1.getId()) + .isEqualTo(publishedPageDTOs.get(0).getId()); + assertThat(newPage2.getId()) + .isEqualTo(publishedPageDTOs.get(1).getId()); + assertThat(newPage3.getId()) + .isEqualTo(publishedPageDTOs.get(2).getId()); }) .verifyComplete(); - } private ApplicationJson createApplicationJSON(List<String> pageNames) { @@ -2985,7 +3230,8 @@ public void mergeApplicationJsonWithApplication_WhenPageNameConflicts_PageNamesR destApplication.setSlug("my-slug"); destApplication.setIsPublic(false); destApplication.setForkingEnabled(false); - Mono<Application> createAppAndPageMono = applicationPageService.createApplication(destApplication, workspaceId) + Mono<Application> createAppAndPageMono = applicationPageService + .createApplication(destApplication, workspaceId) .flatMap(application -> { PageDTO pageDTO = new PageDTO(); pageDTO.setName("Home"); @@ -2996,36 +3242,49 @@ public void mergeApplicationJsonWithApplication_WhenPageNameConflicts_PageNamesR // let's create an ApplicationJSON which we'll merge with application created by createAppAndPageMono ApplicationJson applicationJson = createApplicationJSON(List.of("Home", "About")); - Mono<Tuple3<ApplicationPagesDTO, List<NewAction>, List<ActionCollection>>> tuple2Mono = createAppAndPageMono.flatMap(application -> - // merge the application json with the application we've created - importExportApplicationService.mergeApplicationJsonWithApplication(application.getWorkspaceId(), application.getId(), null, applicationJson, null) - .thenReturn(application) - ).flatMap(application -> - // fetch the application pages, this should contain pages from application json - Mono.zip( - newPageService.findApplicationPages(application.getId(), null, null, ApplicationMode.EDIT), - newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null).collectList(), - actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null).collectList() - ) - ); - - StepVerifier.create(tuple2Mono).assertNext(objects -> { - ApplicationPagesDTO applicationPagesDTO = objects.getT1(); - List<NewAction> newActionList = objects.getT2(); - List<ActionCollection> actionCollectionList = objects.getT3(); - - assertThat(applicationPagesDTO.getApplication().getName()).isEqualTo(destApplication.getName()); - assertThat(applicationPagesDTO.getApplication().getSlug()).isEqualTo(destApplication.getSlug()); - assertThat(applicationPagesDTO.getApplication().getIsPublic()).isFalse(); - assertThat(applicationPagesDTO.getApplication().getForkingEnabled()).isFalse(); - assertThat(applicationPagesDTO.getPages().size()).isEqualTo(4); - List<String> pageNames = applicationPagesDTO.getPages().stream() - .map(PageNameIdDTO::getName) - .collect(Collectors.toList()); - assertThat(pageNames).contains("Home", "Home2", "About"); - assertThat(newActionList.size()).isEqualTo(2); // we imported two pages and each page has one action - assertThat(actionCollectionList.size()).isEqualTo(2); // we imported two pages and each page has one Collection - }).verifyComplete(); + Mono<Tuple3<ApplicationPagesDTO, List<NewAction>, List<ActionCollection>>> tuple2Mono = createAppAndPageMono + .flatMap(application -> + // merge the application json with the application we've created + importExportApplicationService + .mergeApplicationJsonWithApplication( + application.getWorkspaceId(), application.getId(), null, applicationJson, null) + .thenReturn(application)) + .flatMap(application -> + // fetch the application pages, this should contain pages from application json + Mono.zip( + newPageService.findApplicationPages( + application.getId(), null, null, ApplicationMode.EDIT), + newActionService + .findAllByApplicationIdAndViewMode( + application.getId(), false, MANAGE_ACTIONS, null) + .collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode( + application.getId(), false, MANAGE_ACTIONS, null) + .collectList())); + + StepVerifier.create(tuple2Mono) + .assertNext(objects -> { + ApplicationPagesDTO applicationPagesDTO = objects.getT1(); + List<NewAction> newActionList = objects.getT2(); + List<ActionCollection> actionCollectionList = objects.getT3(); + + assertThat(applicationPagesDTO.getApplication().getName()).isEqualTo(destApplication.getName()); + assertThat(applicationPagesDTO.getApplication().getSlug()).isEqualTo(destApplication.getSlug()); + assertThat(applicationPagesDTO.getApplication().getIsPublic()) + .isFalse(); + assertThat(applicationPagesDTO.getApplication().getForkingEnabled()) + .isFalse(); + assertThat(applicationPagesDTO.getPages().size()).isEqualTo(4); + List<String> pageNames = applicationPagesDTO.getPages().stream() + .map(PageNameIdDTO::getName) + .collect(Collectors.toList()); + assertThat(pageNames).contains("Home", "Home2", "About"); + assertThat(newActionList.size()).isEqualTo(2); // we imported two pages and each page has one action + assertThat(actionCollectionList.size()) + .isEqualTo(2); // we imported two pages and each page has one Collection + }) + .verifyComplete(); } @Test @@ -3035,7 +3294,8 @@ public void mergeApplicationJsonWithApplication_WhenPageListIProvided_OnlyListed Application destApplication = new Application(); destApplication.setName("App_" + uniqueString); - Mono<Application> createAppAndPageMono = applicationPageService.createApplication(destApplication, workspaceId) + Mono<Application> createAppAndPageMono = applicationPageService + .createApplication(destApplication, workspaceId) .flatMap(application -> { PageDTO pageDTO = new PageDTO(); pageDTO.setName("Home"); @@ -3046,23 +3306,31 @@ public void mergeApplicationJsonWithApplication_WhenPageListIProvided_OnlyListed // let's create an ApplicationJSON which we'll merge with application created by createAppAndPageMono ApplicationJson applicationJson = createApplicationJSON(List.of("Profile", "About", "Contact US")); - Mono<ApplicationPagesDTO> applicationPagesDTOMono = createAppAndPageMono.flatMap(application -> - // merge the application json with the application we've created - importExportApplicationService.mergeApplicationJsonWithApplication(application.getWorkspaceId(), application.getId(), null, applicationJson, List.of("About", "Contact US")) - .thenReturn(application) - ).flatMap(application -> - // fetch the application pages, this should contain pages from application json - newPageService.findApplicationPages(application.getId(), null, null, ApplicationMode.EDIT) - ); - - StepVerifier.create(applicationPagesDTOMono).assertNext(applicationPagesDTO -> { - assertThat(applicationPagesDTO.getPages().size()).isEqualTo(4); - List<String> pageNames = applicationPagesDTO.getPages().stream() - .map(PageNameIdDTO::getName) - .collect(Collectors.toList()); - assertThat(pageNames).contains("Home", "About", "Contact US"); - assertThat(pageNames).doesNotContain("Profile"); - }).verifyComplete(); + Mono<ApplicationPagesDTO> applicationPagesDTOMono = createAppAndPageMono + .flatMap(application -> + // merge the application json with the application we've created + importExportApplicationService + .mergeApplicationJsonWithApplication( + application.getWorkspaceId(), + application.getId(), + null, + applicationJson, + List.of("About", "Contact US")) + .thenReturn(application)) + .flatMap(application -> + // fetch the application pages, this should contain pages from application json + newPageService.findApplicationPages(application.getId(), null, null, ApplicationMode.EDIT)); + + StepVerifier.create(applicationPagesDTOMono) + .assertNext(applicationPagesDTO -> { + assertThat(applicationPagesDTO.getPages().size()).isEqualTo(4); + List<String> pageNames = applicationPagesDTO.getPages().stream() + .map(PageNameIdDTO::getName) + .collect(Collectors.toList()); + assertThat(pageNames).contains("Home", "About", "Contact US"); + assertThat(pageNames).doesNotContain("Profile"); + }) + .verifyComplete(); } @Test @@ -3074,19 +3342,26 @@ public void exportApplicationById_WhenThemeDoesNotExist_ExportedWithDefaultTheme String randomId = UUID.randomUUID().toString(); Application testApplication = new Application(); testApplication.setName("Application_" + randomId); - Mono<ApplicationJson> exportedAppJson = applicationPageService.createApplication(testApplication, workspaceId) + Mono<ApplicationJson> exportedAppJson = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { application.setEditModeThemeId("invalid-theme-id"); application.setPublishedModeThemeId("invalid-theme-id"); String branchName = null; - return applicationService.save(application) - .then(importExportApplicationService.exportApplicationById(application.getId(), branchName)); + return applicationService + .save(application) + .then(importExportApplicationService.exportApplicationById( + application.getId(), branchName)); }); - StepVerifier.create(exportedAppJson).assertNext(applicationJson -> { - assertThat(applicationJson.getEditModeTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); - assertThat(applicationJson.getPublishedTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); - }).verifyComplete(); + StepVerifier.create(exportedAppJson) + .assertNext(applicationJson -> { + assertThat(applicationJson.getEditModeTheme().getName()) + .isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + assertThat(applicationJson.getPublishedTheme().getName()) + .isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + }) + .verifyComplete(); } @Test @@ -3096,17 +3371,21 @@ public void importApplication_invalidPluginReferenceForDatasource_throwException Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); - ApplicationJson appJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json").block(); + ApplicationJson appJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json") + .block(); assert appJson != null; final String randomId = UUID.randomUUID().toString(); appJson.getDatasourceList().get(0).setPluginId(randomId); Workspace createdWorkspace = workspaceService.create(newWorkspace).block(); - final Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson(createdWorkspace.getId(), appJson); + final Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson( + createdWorkspace.getId(), appJson); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().contains(AppsmithError.GENERIC_JSON_IMPORT_ERROR.getMessage(createdWorkspace.getId(), ""))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .contains(AppsmithError.GENERIC_JSON_IMPORT_ERROR.getMessage( + createdWorkspace.getId(), ""))) .verify(); } @@ -3114,29 +3393,31 @@ public void importApplication_invalidPluginReferenceForDatasource_throwException @WithUserDetails(value = "api_user") public void importApplication_importSameApplicationTwice_applicationImportedLaterWithSuffixCount() { - Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); + Mono<ApplicationJson> applicationJsonMono = + createAppJson("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); Workspace newWorkspace = new Workspace(); newWorkspace.setName("Template Workspace"); - Mono<Workspace> createWorkspaceMono = workspaceService.create(newWorkspace).cache(); + Mono<Workspace> createWorkspaceMono = + workspaceService.create(newWorkspace).cache(); final Mono<Application> importApplicationMono = createWorkspaceMono .zipWith(applicationJsonMono) .flatMap(tuple -> { Workspace workspace = tuple.getT1(); ApplicationJson applicationJson = tuple.getT2(); - return importExportApplicationService - .importNewApplicationInWorkspaceFromJson(workspace.getId(), applicationJson); + return importExportApplicationService.importNewApplicationInWorkspaceFromJson( + workspace.getId(), applicationJson); }); - StepVerifier - .create(importApplicationMono.zipWhen(application -> importApplicationMono)) + StepVerifier.create(importApplicationMono.zipWhen(application -> importApplicationMono)) .assertNext(tuple -> { Application firstImportedApplication = tuple.getT1(); Application secondImportedApplication = tuple.getT2(); assertThat(firstImportedApplication.getName()).isEqualTo("valid_application"); assertThat(secondImportedApplication.getName()).isEqualTo("valid_application (1)"); - assertThat(firstImportedApplication.getWorkspaceId()).isEqualTo(secondImportedApplication.getWorkspaceId()); + assertThat(firstImportedApplication.getWorkspaceId()) + .isEqualTo(secondImportedApplication.getWorkspaceId()); assertThat(firstImportedApplication.getWorkspaceId()).isNotNull(); }) .verifyComplete(); @@ -3146,33 +3427,36 @@ public void importApplication_importSameApplicationTwice_applicationImportedLate @WithUserDetails(value = "api_user") public void mergeApplication_existingApplication_pageAddedSuccessfully() { - //Create application + // Create application Application application = new Application(); application.setName("mergeApplication_existingApplication_pageAddedSuccessfully"); application.setWorkspaceId(workspaceId); application = applicationPageService.createApplication(application).block(); - Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJson = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); Application finalApplication = application; - Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson - .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( - workspaceId, - finalApplication.getId(), - null, - applicationJson1, - new ArrayList<>()) - ) - .flatMap(application1 -> { - Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES).collectList(); - Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); - Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); - return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); - }); - - - StepVerifier - .create(importedApplication) + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = + applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, finalApplication.getId(), null, applicationJson1, new ArrayList<>())) + .flatMap(application1 -> { + Mono<List<NewPage>> pageList = newPageService + .findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES) + .collectList(); + Mono<List<NewAction>> actionList = newActionService + .findAllByApplicationIdAndViewMode( + application1.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService + .findAllByApplicationIdAndViewMode( + application1.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); + }); + + StepVerifier.create(importedApplication) .assertNext(tuple -> { Application application1 = tuple.getT1(); List<NewPage> pageList = tuple.getT2(); @@ -3180,8 +3464,10 @@ public void mergeApplication_existingApplication_pageAddedSuccessfully() { List<ActionCollection> actionCollectionList = tuple.getT4(); assertThat(application1.getId()).isEqualTo(finalApplication.getId()); - assertThat(finalApplication.getPages().size()).isLessThan(application1.getPages().size()); - assertThat(finalApplication.getPages().size()).isEqualTo(application1.getPublishedPages().size()); + assertThat(finalApplication.getPages().size()) + .isLessThan(application1.getPages().size()); + assertThat(finalApplication.getPages().size()) + .isEqualTo(application1.getPublishedPages().size()); // Verify the pages after merging the template pageList.forEach(newPage -> { @@ -3189,28 +3475,34 @@ public void mergeApplication_existingApplication_pageAddedSuccessfully() { assertThat(newPage.getGitSyncId()).isNotNull(); }); - NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + NewPage page = pageList.stream() + .filter(newPage -> + newPage.getUnpublishedPage().getName().equals("Page12")) + .collect(Collectors.toList()) + .get(0); // Verify the actions after merging the template actionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getName()) + .containsAnyOf("api_wo_auth", "get_users", "run"); assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); }); // Verify the actionCollections after merging the template actionCollectionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); - assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(newAction.getUnpublishedCollection().getName()) + .containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()) + .isEqualTo(page.getId()); }); }) .verifyComplete(); - } @Test @WithUserDetails(value = "api_user") public void mergeApplication_gitConnectedApplication_pageAddedSuccessfully() { - //Create application connected to git + // Create application connected to git Application testApplication = new Application(); testApplication.setName("mergeApplication_gitConnectedApplication_pageAddedSuccessfully"); testApplication.setWorkspaceId(workspaceId); @@ -3223,32 +3515,38 @@ public void mergeApplication_gitConnectedApplication_pageAddedSuccessfully() { gitData.setDefaultBranchName("master"); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication, workspaceId) + Application application = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); + }) + .block(); - Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJson = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); Application finalApplication = application; - Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson - .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( - workspaceId, - finalApplication.getId(), - "master", - applicationJson1, - new ArrayList<>()) - ) - .flatMap(application1 -> { - Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES).collectList(); - Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); - Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); - return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); - }); - - StepVerifier - .create(importedApplication) + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = + applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, finalApplication.getId(), "master", applicationJson1, new ArrayList<>())) + .flatMap(application1 -> { + Mono<List<NewPage>> pageList = newPageService + .findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES) + .collectList(); + Mono<List<NewAction>> actionList = newActionService + .findAllByApplicationIdAndViewMode( + application1.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService + .findAllByApplicationIdAndViewMode( + application1.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); + }); + + StepVerifier.create(importedApplication) .assertNext(tuple -> { Application application1 = tuple.getT1(); List<NewPage> pageList = tuple.getT2(); @@ -3256,8 +3554,10 @@ public void mergeApplication_gitConnectedApplication_pageAddedSuccessfully() { List<ActionCollection> actionCollectionList = tuple.getT4(); assertThat(application1.getId()).isEqualTo(finalApplication.getId()); - assertThat(finalApplication.getPages().size()).isLessThan(application1.getPages().size()); - assertThat(finalApplication.getPages().size()).isEqualTo(application1.getPublishedPages().size()); + assertThat(finalApplication.getPages().size()) + .isLessThan(application1.getPages().size()); + assertThat(finalApplication.getPages().size()) + .isEqualTo(application1.getPublishedPages().size()); // Verify the pages after merging the template pageList.forEach(newPage -> { @@ -3265,28 +3565,34 @@ public void mergeApplication_gitConnectedApplication_pageAddedSuccessfully() { assertThat(newPage.getGitSyncId()).isNotNull(); }); - NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + NewPage page = pageList.stream() + .filter(newPage -> + newPage.getUnpublishedPage().getName().equals("Page12")) + .collect(Collectors.toList()) + .get(0); // Verify the actions after merging the template actionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getName()) + .containsAnyOf("api_wo_auth", "get_users", "run"); assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); }); // Verify the actionCollections after merging the template actionCollectionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); - assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(newAction.getUnpublishedCollection().getName()) + .containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()) + .isEqualTo(page.getId()); }); }) .verifyComplete(); - } @Test @WithUserDetails(value = "api_user") public void mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccessfully() { - //Create application connected to git + // Create application connected to git Application testApplication = new Application(); testApplication.setName("mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccessfully"); testApplication.setWorkspaceId(workspaceId); @@ -3299,11 +3605,13 @@ public void mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccess gitData.setDefaultBranchName("master"); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication, workspaceId) + Application application = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); + }) + .block(); // Create branch for the application testApplication = new Application(); @@ -3318,32 +3626,36 @@ public void mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccess gitData1.setDefaultBranchName("master"); testApplication.setGitApplicationMetadata(gitData1); - Application branchApp = applicationPageService.createApplication(testApplication, workspaceId) + Application branchApp = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application2 -> { application2.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); return applicationService.save(application2); - }).block(); + }) + .block(); - Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJson = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); Application finalApplication = application; - Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson - .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( - workspaceId, - branchApp.getId(), - "feature", - applicationJson1, - new ArrayList<>()) - ) - .flatMap(application2 -> { - Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES).collectList(); - Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); - Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); - return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); - }); - - StepVerifier - .create(importedApplication) + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = + applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, branchApp.getId(), "feature", applicationJson1, new ArrayList<>())) + .flatMap(application2 -> { + Mono<List<NewPage>> pageList = newPageService + .findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES) + .collectList(); + Mono<List<NewAction>> actionList = newActionService + .findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService + .findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); + }); + + StepVerifier.create(importedApplication) .assertNext(tuple -> { Application application3 = tuple.getT1(); List<NewPage> pageList = tuple.getT2(); @@ -3351,8 +3663,10 @@ public void mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccess List<ActionCollection> actionCollectionList = tuple.getT4(); assertThat(application3.getId()).isNotEqualTo(finalApplication.getId()); - assertThat(finalApplication.getPages().size()).isLessThan(application3.getPages().size()); - assertThat(finalApplication.getPages().size()).isEqualTo(application3.getPublishedPages().size()); + assertThat(finalApplication.getPages().size()) + .isLessThan(application3.getPages().size()); + assertThat(finalApplication.getPages().size()) + .isEqualTo(application3.getPublishedPages().size()); // Verify the pages after merging the template pageList.forEach(newPage -> { @@ -3360,29 +3674,36 @@ public void mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccess assertThat(newPage.getGitSyncId()).isNotNull(); }); - NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + NewPage page = pageList.stream() + .filter(newPage -> + newPage.getUnpublishedPage().getName().equals("Page12")) + .collect(Collectors.toList()) + .get(0); // Verify the actions after merging the template actionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getName()) + .containsAnyOf("api_wo_auth", "get_users", "run"); assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); }); // Verify the actionCollections after merging the template actionCollectionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); - assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(newAction.getUnpublishedCollection().getName()) + .containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()) + .isEqualTo(page.getId()); }); }) .verifyComplete(); - } @Test @WithUserDetails(value = "api_user") public void mergeApplication_gitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully() { - //Create application connected to git + // Create application connected to git Application testApplication = new Application(); - testApplication.setName("mergeApplication_gitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully"); + testApplication.setName( + "mergeApplication_gitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully"); testApplication.setWorkspaceId(workspaceId); testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); @@ -3393,15 +3714,18 @@ public void mergeApplication_gitConnectedApplicationSelectedSpecificPages_select gitData.setDefaultBranchName("master"); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication, workspaceId) + Application application = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); + }) + .block(); // Create branch for the application testApplication = new Application(); - testApplication.setName("mergeApplication_gitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully1"); + testApplication.setName( + "mergeApplication_gitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully1"); testApplication.setWorkspaceId(workspaceId); testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); @@ -3412,32 +3736,36 @@ public void mergeApplication_gitConnectedApplicationSelectedSpecificPages_select gitData1.setDefaultBranchName("master"); testApplication.setGitApplicationMetadata(gitData1); - Application branchApp = applicationPageService.createApplication(testApplication, workspaceId) + Application branchApp = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application2 -> { application2.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); return applicationService.save(application2); - }).block(); + }) + .block(); - Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJson = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); Application finalApplication = application; - Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson - .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( - workspaceId, - branchApp.getId(), - "feature", - applicationJson1, - List.of("Page1")) - ) - .flatMap(application2 -> { - Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES).collectList(); - Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); - Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); - return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); - }); - - StepVerifier - .create(importedApplication) + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = + applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, branchApp.getId(), "feature", applicationJson1, List.of("Page1"))) + .flatMap(application2 -> { + Mono<List<NewPage>> pageList = newPageService + .findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES) + .collectList(); + Mono<List<NewAction>> actionList = newActionService + .findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService + .findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); + }); + + StepVerifier.create(importedApplication) .assertNext(tuple -> { Application application3 = tuple.getT1(); List<NewPage> pageList = tuple.getT2(); @@ -3445,8 +3773,10 @@ public void mergeApplication_gitConnectedApplicationSelectedSpecificPages_select List<ActionCollection> actionCollectionList = tuple.getT4(); assertThat(application3.getId()).isNotEqualTo(finalApplication.getId()); - assertThat(finalApplication.getPages().size()).isLessThan(application3.getPages().size()); - assertThat(finalApplication.getPages().size()).isEqualTo(application3.getPublishedPages().size()); + assertThat(finalApplication.getPages().size()) + .isLessThan(application3.getPages().size()); + assertThat(finalApplication.getPages().size()) + .isEqualTo(application3.getPublishedPages().size()); // Verify the pages after merging the template pageList.forEach(newPage -> { @@ -3454,17 +3784,24 @@ public void mergeApplication_gitConnectedApplicationSelectedSpecificPages_select assertThat(newPage.getGitSyncId()).isNotNull(); }); - NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + NewPage page = pageList.stream() + .filter(newPage -> + newPage.getUnpublishedPage().getName().equals("Page12")) + .collect(Collectors.toList()) + .get(0); // Verify the actions after merging the template actionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getName()) + .containsAnyOf("api_wo_auth", "get_users", "run"); assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); }); // Verify the actionCollections after merging the template actionCollectionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); - assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(newAction.getUnpublishedCollection().getName()) + .containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()) + .isEqualTo(page.getId()); }); }) .verifyComplete(); @@ -3473,9 +3810,10 @@ public void mergeApplication_gitConnectedApplicationSelectedSpecificPages_select @Test @WithUserDetails(value = "api_user") public void mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully() { - //Create application connected to git + // Create application connected to git Application testApplication = new Application(); - testApplication.setName("mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully"); + testApplication.setName( + "mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully"); testApplication.setWorkspaceId(workspaceId); testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); @@ -3486,15 +3824,18 @@ public void mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPag gitData.setDefaultBranchName("master"); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication, workspaceId) + Application application = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); + }) + .block(); // Create branch for the application testApplication = new Application(); - testApplication.setName("mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully1"); + testApplication.setName( + "mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully1"); testApplication.setWorkspaceId(workspaceId); testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); @@ -3505,32 +3846,36 @@ public void mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPag gitData1.setDefaultBranchName("master"); testApplication.setGitApplicationMetadata(gitData1); - Application branchApp = applicationPageService.createApplication(testApplication, workspaceId) + Application branchApp = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application2 -> { application2.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); return applicationService.save(application2); - }).block(); + }) + .block(); - Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJson = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); Application finalApplication = application; - Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson - .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( - workspaceId, - branchApp.getId(), - "feature", - applicationJson1, - List.of("Page1", "Page2")) - ) - .flatMap(application2 -> { - Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES).collectList(); - Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); - Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); - return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); - }); - - StepVerifier - .create(importedApplication) + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = + applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, branchApp.getId(), "feature", applicationJson1, List.of("Page1", "Page2"))) + .flatMap(application2 -> { + Mono<List<NewPage>> pageList = newPageService + .findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES) + .collectList(); + Mono<List<NewAction>> actionList = newActionService + .findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService + .findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); + }); + + StepVerifier.create(importedApplication) .assertNext(tuple -> { Application application3 = tuple.getT1(); List<NewPage> pageList = tuple.getT2(); @@ -3538,8 +3883,10 @@ public void mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPag List<ActionCollection> actionCollectionList = tuple.getT4(); assertThat(application3.getId()).isNotEqualTo(finalApplication.getId()); - assertThat(finalApplication.getPages().size()).isLessThan(application3.getPages().size()); - assertThat(finalApplication.getPages().size()).isEqualTo(application3.getPublishedPages().size()); + assertThat(finalApplication.getPages().size()) + .isLessThan(application3.getPages().size()); + assertThat(finalApplication.getPages().size()) + .isEqualTo(application3.getPublishedPages().size()); // Verify the pages after merging the template pageList.forEach(newPage -> { @@ -3547,17 +3894,24 @@ public void mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPag assertThat(newPage.getGitSyncId()).isNotNull(); }); - NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + NewPage page = pageList.stream() + .filter(newPage -> + newPage.getUnpublishedPage().getName().equals("Page12")) + .collect(Collectors.toList()) + .get(0); // Verify the actions after merging the template actionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getName()) + .containsAnyOf("api_wo_auth", "get_users", "run"); assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); }); // Verify the actionCollections after merging the template actionCollectionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); - assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(newAction.getUnpublishedCollection().getName()) + .containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()) + .isEqualTo(page.getId()); }); }) .verifyComplete(); @@ -3566,33 +3920,37 @@ public void mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPag @Test @WithUserDetails(value = "api_user") public void mergeApplication_nonGitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully() { - //Create application + // Create application Application application = new Application(); - application.setName("mergeApplication_nonGitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully"); + application.setName( + "mergeApplication_nonGitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully"); application.setWorkspaceId(workspaceId); application = applicationPageService.createApplication(application).block(); - Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJson = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); Application finalApplication = application; - Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson - .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( - workspaceId, - finalApplication.getId(), - null, - applicationJson1, - List.of("Page1")) - ) - .flatMap(application1 -> { - Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES).collectList(); - Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); - Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); - return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); - }); - - - StepVerifier - .create(importedApplication) + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = + applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, finalApplication.getId(), null, applicationJson1, List.of("Page1"))) + .flatMap(application1 -> { + Mono<List<NewPage>> pageList = newPageService + .findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES) + .collectList(); + Mono<List<NewAction>> actionList = newActionService + .findAllByApplicationIdAndViewMode( + application1.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService + .findAllByApplicationIdAndViewMode( + application1.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); + }); + + StepVerifier.create(importedApplication) .assertNext(tuple -> { Application application1 = tuple.getT1(); List<NewPage> pageList = tuple.getT2(); @@ -3600,8 +3958,10 @@ public void mergeApplication_nonGitConnectedApplicationSelectedSpecificPages_sel List<ActionCollection> actionCollectionList = tuple.getT4(); assertThat(application1.getId()).isEqualTo(finalApplication.getId()); - assertThat(finalApplication.getPages().size()).isLessThan(application1.getPages().size()); - assertThat(finalApplication.getPages().size()).isEqualTo(application1.getPublishedPages().size()); + assertThat(finalApplication.getPages().size()) + .isLessThan(application1.getPages().size()); + assertThat(finalApplication.getPages().size()) + .isEqualTo(application1.getPublishedPages().size()); // Verify the pages after merging the template pageList.forEach(newPage -> { @@ -3609,17 +3969,24 @@ public void mergeApplication_nonGitConnectedApplicationSelectedSpecificPages_sel assertThat(newPage.getGitSyncId()).isNotNull(); }); - NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + NewPage page = pageList.stream() + .filter(newPage -> + newPage.getUnpublishedPage().getName().equals("Page12")) + .collect(Collectors.toList()) + .get(0); // Verify the actions after merging the template actionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getName()) + .containsAnyOf("api_wo_auth", "get_users", "run"); assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); }); // Verify the actionCollections after merging the template actionCollectionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); - assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(newAction.getUnpublishedCollection().getName()) + .containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()) + .isEqualTo(page.getId()); }); }) .verifyComplete(); @@ -3628,33 +3995,41 @@ public void mergeApplication_nonGitConnectedApplicationSelectedSpecificPages_sel @Test @WithUserDetails(value = "api_user") public void mergeApplication_nonGitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully() { - //Create application + // Create application Application application = new Application(); - application.setName("mergeApplication_nonGitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully"); + application.setName( + "mergeApplication_nonGitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully"); application.setWorkspaceId(workspaceId); application = applicationPageService.createApplication(application).block(); - Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJson = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); Application finalApplication = application; - Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson - .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( - workspaceId, - finalApplication.getId(), - null, - applicationJson1, - List.of("Page1", "Page2")) - ) - .flatMap(application1 -> { - Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES).collectList(); - Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); - Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); - return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); - }); - - - StepVerifier - .create(importedApplication) + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = + applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, + finalApplication.getId(), + null, + applicationJson1, + List.of("Page1", "Page2"))) + .flatMap(application1 -> { + Mono<List<NewPage>> pageList = newPageService + .findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES) + .collectList(); + Mono<List<NewAction>> actionList = newActionService + .findAllByApplicationIdAndViewMode( + application1.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService + .findAllByApplicationIdAndViewMode( + application1.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); + }); + + StepVerifier.create(importedApplication) .assertNext(tuple -> { Application application1 = tuple.getT1(); List<NewPage> pageList = tuple.getT2(); @@ -3662,8 +4037,10 @@ public void mergeApplication_nonGitConnectedApplicationSelectedAllPages_selected List<ActionCollection> actionCollectionList = tuple.getT4(); assertThat(application1.getId()).isEqualTo(finalApplication.getId()); - assertThat(finalApplication.getPages().size()).isLessThan(application1.getPages().size()); - assertThat(finalApplication.getPages().size()).isEqualTo(application1.getPublishedPages().size()); + assertThat(finalApplication.getPages().size()) + .isLessThan(application1.getPages().size()); + assertThat(finalApplication.getPages().size()) + .isEqualTo(application1.getPublishedPages().size()); // Verify the pages after merging the template pageList.forEach(newPage -> { @@ -3671,17 +4048,24 @@ public void mergeApplication_nonGitConnectedApplicationSelectedAllPages_selected assertThat(newPage.getGitSyncId()).isNotNull(); }); - NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + NewPage page = pageList.stream() + .filter(newPage -> + newPage.getUnpublishedPage().getName().equals("Page12")) + .collect(Collectors.toList()) + .get(0); // Verify the actions after merging the template actionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getName()) + .containsAnyOf("api_wo_auth", "get_users", "run"); assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); }); // Verify the actionCollections after merging the template actionCollectionList.forEach(newAction -> { - assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); - assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + assertThat(newAction.getUnpublishedCollection().getName()) + .containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()) + .isEqualTo(page.getId()); }); }) .verifyComplete(); @@ -3692,24 +4076,29 @@ public void mergeApplication_nonGitConnectedApplicationSelectedAllPages_selected public void importApplication_invalidJson_createdAppIsDeleted() { FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-json-without-pages.json"); - List<Application> applicationList = applicationService.findAllApplicationsByWorkspaceId(workspaceId).collectList().block(); + List<Application> applicationList = applicationService + .findAllApplicationsByWorkspaceId(workspaceId) + .collectList() + .block(); - Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); + Mono<ApplicationImportDTO> resultMono = + importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); - StepVerifier - .create(resultMono) - .expectErrorMatches(throwable -> throwable instanceof AppsmithException && - throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PAGES, INVALID_JSON_FILE))) + StepVerifier.create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PAGES, INVALID_JSON_FILE))) .verify(); // Verify that the app card is not created - StepVerifier - .create(applicationService.findAllApplicationsByWorkspaceId(workspaceId).collectList()) + StepVerifier.create(applicationService + .findAllApplicationsByWorkspaceId(workspaceId) + .collectList()) .assertNext(applications -> { assertThat(applicationList.size()).isEqualTo(applications.size()); }) .verifyComplete(); - } @Test @@ -3726,15 +4115,18 @@ public void exportApplication_WithBearerTokenAndExportWithConfig_exportedWithDec testApplication.setExportWithConfiguration(true); testApplication.setWorkspaceId(workspace.getId()); - Mono<Application> applicationMono = applicationPageService. - createApplication(testApplication) + Mono<Application> applicationMono = applicationPageService + .createApplication(testApplication) .flatMap(application -> { ApplicationAccessDTO accessDTO = new ApplicationAccessDTO(); accessDTO.setPublicAccess(true); - return applicationService.changeViewAccess(application.getId(), accessDTO).thenReturn(application); + return applicationService + .changeViewAccess(application.getId(), accessDTO) + .thenReturn(application); }); - Mono<Datasource> datasourceMono = workspaceService.getDefaultEnvironmentId(workspace.getId()) + Mono<Datasource> datasourceMono = workspaceService + .getDefaultEnvironmentId(workspace.getId()) .zipWith(pluginRepository.findByPackageName("restapi-plugin")) .flatMap(objects -> { String defaultEnvironmentId = objects.getT1(); @@ -3769,27 +4161,31 @@ public void exportApplication_WithBearerTokenAndExportWithConfig_exportedWithDec return datasourceService.create(datasource); }); - Mono<ApplicationJson> exportAppMono = Mono.zip(applicationMono, datasourceMono).flatMap(objects -> { - ApplicationPage applicationPage = objects.getT1().getPages().get(0); - ActionDTO action = new ActionDTO(); - action.setName("validAction"); - action.setPageId(applicationPage.getId()); - action.setPluginId(objects.getT2().getPluginId()); - action.setDatasource(objects.getT2()); - - ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setHttpMethod(HttpMethod.GET); - actionConfiguration.setPath("/test/path"); - action.setActionConfiguration(actionConfiguration); - - return layoutActionService.createSingleAction(action, Boolean.FALSE) - .then(importExportApplicationService.exportApplicationById(objects.getT1().getId(), "")); - }); + Mono<ApplicationJson> exportAppMono = Mono.zip(applicationMono, datasourceMono) + .flatMap(objects -> { + ApplicationPage applicationPage = objects.getT1().getPages().get(0); + ActionDTO action = new ActionDTO(); + action.setName("validAction"); + action.setPageId(applicationPage.getId()); + action.setPluginId(objects.getT2().getPluginId()); + action.setDatasource(objects.getT2()); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + actionConfiguration.setPath("/test/path"); + action.setActionConfiguration(actionConfiguration); + + return layoutActionService + .createSingleAction(action, Boolean.FALSE) + .then(importExportApplicationService.exportApplicationById( + objects.getT1().getId(), "")); + }); StepVerifier.create(exportAppMono) .assertNext(applicationJson -> { assertThat(applicationJson.getDecryptedFields()).isNotEmpty(); - DecryptedSensitiveFields fields = applicationJson.getDecryptedFields().get("RestAPIWithBearerToken"); + DecryptedSensitiveFields fields = + applicationJson.getDecryptedFields().get("RestAPIWithBearerToken"); assertThat(fields.getBearerTokenAuth().getBearerToken()).isEqualTo("token_" + randomUUID); }) .verifyComplete(); @@ -3805,18 +4201,26 @@ public void exportApplicationTest_WithNavigationSettings() { navSetting.setOrientation("top"); application.setUnpublishedApplicationDetail(new ApplicationDetail()); application.getUnpublishedApplicationDetail().setNavigationSetting(navSetting); - Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById(createdApplication.getId(), ""); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(applicationJson -> { Application exportedApplication = applicationJson.getExportedApplication(); assertThat(exportedApplication).isNotNull(); - assertThat(exportedApplication.getUnpublishedApplicationDetail().getNavigationSetting()).isNotNull(); - assertThat(exportedApplication.getUnpublishedApplicationDetail().getNavigationSetting().getOrientation()).isEqualTo("top"); + assertThat(exportedApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting()) + .isNotNull(); + assertThat(exportedApplication + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getOrientation()) + .isEqualTo("top"); }) .verifyComplete(); } @@ -3827,7 +4231,9 @@ public void exportApplication_WithPageIcon_ValidPageIcon() { String randomId = UUID.randomUUID().toString(); Application application = new Application(); application.setName("exportPageIconApplicationTest"); - Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + Application createdApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); PageDTO pageDTO = new PageDTO(); pageDTO.setName("page_" + randomId); @@ -3839,8 +4245,7 @@ public void exportApplication_WithPageIcon_ValidPageIcon() { Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById(applicationPageDTO.getApplicationId(), ""); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(applicationJson -> { List<NewPage> pages = applicationJson.getPageList(); assertThat(pages.size()).isEqualTo(2); @@ -3854,35 +4259,50 @@ public void exportApplication_WithPageIcon_ValidPageIcon() { @WithUserDetails(value = "api_user") public void importApplication_existingApplication_ApplicationReplacedWithImportedOne() { String randomUUID = UUID.randomUUID().toString(); - Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + Mono<ApplicationJson> applicationJson = + createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); // Create the initial application Application application = new Application(); application.setName("Application_" + randomUUID); application.setWorkspaceId(workspaceId); - Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationPageService.createApplication(application).flatMap(createdApp -> { - PageDTO pageDTO = new PageDTO(); - pageDTO.setApplicationId(application.getId()); - pageDTO.setName("Home Page"); - return applicationPageService.createPage(pageDTO).thenReturn(createdApp); - }) - .zipWith(applicationJson) - .flatMap(objects -> importExportApplicationService.restoreSnapshot(workspaceId, objects.getT2(), objects.getT1().getId(), null) - .zipWith(Mono.just(objects.getT1()))).flatMap(objects -> { - Application newApp = objects.getT1(); - Application oldApp = objects.getT2(); - // after import, application id should not change - assert Objects.equals(newApp.getId(), oldApp.getId()); - - Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(newApp.getId(), MANAGE_PAGES).collectList(); - Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(newApp.getId(), false, MANAGE_ACTIONS, null).collectList(); - Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(newApp.getId(), false, MANAGE_ACTIONS, null).collectList(); - return Mono.zip(Mono.just(newApp), pageList, actionList, actionCollectionList); - }); - - StepVerifier - .create(importedApplication) + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = + applicationPageService + .createApplication(application) + .flatMap(createdApp -> { + PageDTO pageDTO = new PageDTO(); + pageDTO.setApplicationId(application.getId()); + pageDTO.setName("Home Page"); + return applicationPageService.createPage(pageDTO).thenReturn(createdApp); + }) + .zipWith(applicationJson) + .flatMap(objects -> importExportApplicationService + .restoreSnapshot( + workspaceId, + objects.getT2(), + objects.getT1().getId(), + null) + .zipWith(Mono.just(objects.getT1()))) + .flatMap(objects -> { + Application newApp = objects.getT1(); + Application oldApp = objects.getT2(); + // after import, application id should not change + assert Objects.equals(newApp.getId(), oldApp.getId()); + + Mono<List<NewPage>> pageList = newPageService + .findNewPagesByApplicationId(newApp.getId(), MANAGE_PAGES) + .collectList(); + Mono<List<NewAction>> actionList = newActionService + .findAllByApplicationIdAndViewMode(newApp.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService + .findAllByApplicationIdAndViewMode(newApp.getId(), false, MANAGE_ACTIONS, null) + .collectList(); + return Mono.zip(Mono.just(newApp), pageList, actionList, actionCollectionList); + }); + + StepVerifier.create(importedApplication) .assertNext(tuple -> { List<NewPage> pageList = tuple.getT2(); List<NewAction> actionList = tuple.getT3(); @@ -3913,7 +4333,6 @@ public void importApplication_existingApplication_ApplicationReplacedWithImporte assertThat(actionCollectionNames).contains("JSObject1", "JSObject2"); }) .verifyComplete(); - } /** @@ -3939,7 +4358,8 @@ public void extractFileAndUpdateApplication_addNewPageAfterImport_addedPageRemov FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application.json"); String workspaceId = createTemplateWorkspace().getId(); - final Mono<Application> resultMonoWithoutDiscardOperation = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart) + final Mono<Application> resultMonoWithoutDiscardOperation = importExportApplicationService + .extractFileAndSaveApplication(workspaceId, filePart) .flatMap(applicationImportDTO -> { PageDTO page = new PageDTO(); page.setName("discard-page-test"); @@ -3949,12 +4369,11 @@ public void extractFileAndUpdateApplication_addNewPageAfterImport_addedPageRemov .flatMap(page -> applicationRepository.findById(page.getApplicationId())) .cache(); - StepVerifier - .create(resultMonoWithoutDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() - ))) + StepVerifier.create(resultMonoWithoutDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<PageDTO> pageList = tuple.getT2(); @@ -3970,18 +4389,20 @@ public void extractFileAndUpdateApplication_addNewPageAfterImport_addedPageRemov assertThat(pageList).hasSize(3); - ApplicationPage defaultAppPage = application.getPages() - .stream() + ApplicationPage defaultAppPage = application.getPages().stream() .filter(ApplicationPage::getIsDefault) .findFirst() .orElse(null); assertThat(defaultAppPage).isNotNull(); PageDTO defaultPageDTO = pageList.stream() - .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())) + .findFirst() + .orElse(null); assertThat(defaultPageDTO).isNotNull(); - assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()).isNotEmpty(); + assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()) + .isNotEmpty(); List<String> pageNames = new ArrayList<>(); pageList.forEach(page -> pageNames.add(page.getName())); @@ -3992,15 +4413,15 @@ public void extractFileAndUpdateApplication_addNewPageAfterImport_addedPageRemov // Import the same application again to find if the added page is deleted final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation .flatMap(importedApplication -> applicationService.save(importedApplication)) - .flatMap(savedApplication -> importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart, savedApplication.getId())) + .flatMap(savedApplication -> importExportApplicationService.extractFileAndSaveApplication( + workspaceId, filePart, savedApplication.getId())) .map(ApplicationImportDTO::getApplication); - StepVerifier - .create(resultMonoWithDiscardOperation - .flatMap(application -> Mono.zip( - Mono.just(application), - newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() - ))) + StepVerifier.create(resultMonoWithDiscardOperation.flatMap(application -> Mono.zip( + Mono.just(application), + newPageService + .findByApplicationId(application.getId(), MANAGE_PAGES, false) + .collectList()))) .assertNext(tuple -> { final Application application = tuple.getT1(); final List<PageDTO> pageList = tuple.getT2(); @@ -4027,66 +4448,86 @@ public void extractFileAndUpdateExistingApplication_gitConnectedApplication_thro 3. Unsupported operation exception should be thrown */ - //Create application connected to git + // Create application connected to git Application testApplication = new Application(); - testApplication.setName("extractFileAndUpdateExistingApplication_gitConnectedApplication_throwUnsupportedOperationException"); + testApplication.setName( + "extractFileAndUpdateExistingApplication_gitConnectedApplication_throwUnsupportedOperationException"); testApplication.setWorkspaceId(workspaceId); testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); GitApplicationMetadata gitData = new GitApplicationMetadata(); gitData.setRemoteUrl("[email protected]:username/git-repo.git"); testApplication.setGitApplicationMetadata(gitData); - Application application = applicationPageService.createApplication(testApplication, workspaceId) + Application application = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application1 -> { application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); return applicationService.save(application1); - }).block(); + }) + .block(); FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application.json"); - final Mono<ApplicationImportDTO> resultMono = importExportApplicationService - .extractFileAndSaveApplication(workspaceId, filePart, application.getId()); + final Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication( + workspaceId, filePart, application.getId()); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithException - && throwable.getMessage().equals(AppsmithError.UNSUPPORTED_IMPORT_OPERATION_FOR_GIT_CONNECTED_APPLICATION.getMessage())) + && throwable + .getMessage() + .equals( + AppsmithError.UNSUPPORTED_IMPORT_OPERATION_FOR_GIT_CONNECTED_APPLICATION + .getMessage())) .verify(); - } @Test @WithUserDetails(value = "api_user") public void createExportAppJsonWithCustomJSLibTest() { CustomJSLib jsLib = new CustomJSLib("TestLib", Set.of("accessor1"), "url", "docsUrl", "1.0", "defs_string"); - Mono<Boolean> addJSLibMonoCached = - customJSLibService.addJSLibToApplication(testAppId, jsLib, null, false) - .flatMap(isJSLibAdded -> Mono.zip(Mono.just(isJSLibAdded), - applicationPageService.publish(testAppId, true))) - .map(tuple2 -> { - Boolean isJSLibAdded = tuple2.getT1(); - Application application = tuple2.getT2(); - return isJSLibAdded; - }) - .cache(); - Mono<ApplicationJson> getExportedAppMono = addJSLibMonoCached - .then(importExportApplicationService.exportApplicationById(testAppId, "")); + Mono<Boolean> addJSLibMonoCached = customJSLibService + .addJSLibToApplication(testAppId, jsLib, null, false) + .flatMap(isJSLibAdded -> + Mono.zip(Mono.just(isJSLibAdded), applicationPageService.publish(testAppId, true))) + .map(tuple2 -> { + Boolean isJSLibAdded = tuple2.getT1(); + Application application = tuple2.getT2(); + return isJSLibAdded; + }) + .cache(); + Mono<ApplicationJson> getExportedAppMono = + addJSLibMonoCached.then(importExportApplicationService.exportApplicationById(testAppId, "")); StepVerifier.create(Mono.zip(addJSLibMonoCached, getExportedAppMono)) .assertNext(tuple2 -> { Boolean isJSLibAdded = tuple2.getT1(); assertEquals(true, isJSLibAdded); ApplicationJson exportedAppJson = tuple2.getT2(); assertEquals(1, exportedAppJson.getCustomJSLibList().size()); - CustomJSLib exportedJSLib = exportedAppJson.getCustomJSLibList().get(0); + CustomJSLib exportedJSLib = + exportedAppJson.getCustomJSLibList().get(0); assertEquals(jsLib.getName(), exportedJSLib.getName()); assertEquals(jsLib.getAccessor(), exportedJSLib.getAccessor()); assertEquals(jsLib.getUrl(), exportedJSLib.getUrl()); assertEquals(jsLib.getDocsUrl(), exportedJSLib.getDocsUrl()); assertEquals(jsLib.getVersion(), exportedJSLib.getVersion()); assertEquals(jsLib.getDefs(), exportedJSLib.getDefs()); - assertEquals(getDTOFromCustomJSLib(jsLib), - exportedAppJson.getExportedApplication().getUnpublishedCustomJSLibs().toArray()[0]); - assertEquals(1, exportedAppJson.getExportedApplication().getUnpublishedCustomJSLibs().size()); - assertEquals(0, exportedAppJson.getExportedApplication().getPublishedCustomJSLibs().size()); + assertEquals( + getDTOFromCustomJSLib(jsLib), + exportedAppJson + .getExportedApplication() + .getUnpublishedCustomJSLibs() + .toArray()[0]); + assertEquals( + 1, + exportedAppJson + .getExportedApplication() + .getUnpublishedCustomJSLibs() + .size()); + assertEquals( + 0, + exportedAppJson + .getExportedApplication() + .getPublishedCustomJSLibs() + .size()); }) .verifyComplete(); } @@ -4107,14 +4548,15 @@ public void extractFileAndUpdateExistingApplication_existingApplication_applicat testApplication.setWorkspaceId(workspaceId); testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); - Application application = applicationPageService.createApplication(testApplication, workspaceId).block(); + Application application = applicationPageService + .createApplication(testApplication, workspaceId) + .block(); FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application.json"); - final Mono<ApplicationImportDTO> resultMono = importExportApplicationService - .extractFileAndSaveApplication(workspaceId, filePart, application.getId()); + final Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication( + workspaceId, filePart, application.getId()); - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(applicationImportDTO -> { Application application1 = applicationImportDTO.getApplication(); assertThat(application1.getName()).isEqualTo(appName); @@ -4133,22 +4575,26 @@ public void mergeApplicationJsonWithApplication_WhenNoPermissionToCreatePage_Fai testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); - Mono<Application> applicationImportDTOMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<Application> applicationImportDTOMono = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { // remove page create permission from this application for current user - application.getPolicies().removeIf( - policy -> policy.getPermission().equals(applicationPermission.getPageCreatePermission().getValue()) - ); + application.getPolicies().removeIf(policy -> policy.getPermission() + .equals(applicationPermission + .getPageCreatePermission() + .getValue())); return applicationRepository.save(application); - }).flatMap(application -> { + }) + .flatMap(application -> { FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application.json"); - return importExportApplicationService.extractApplicationJson(filePart).flatMap(applicationJson -> - importExportApplicationService.mergeApplicationJsonWithApplication(workspaceId, application.getId(), null, applicationJson, null) - ); + return importExportApplicationService + .extractApplicationJson(filePart) + .flatMap(applicationJson -> + importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, application.getId(), null, applicationJson, null)); }); - StepVerifier - .create(applicationImportDTOMono) + StepVerifier.create(applicationImportDTOMono) .expectError(AppsmithException.class) .verify(); } @@ -4163,23 +4609,24 @@ public void extractFileAndUpdateNonGitConnectedApplication_WhenNoPermissionToCre testApplication.setUpdatedAt(Instant.now()); testApplication.setLastDeployedAt(Instant.now()); - Mono<ApplicationImportDTO> applicationImportDTOMono = applicationPageService.createApplication(testApplication, workspaceId) + Mono<ApplicationImportDTO> applicationImportDTOMono = applicationPageService + .createApplication(testApplication, workspaceId) .flatMap(application -> { // remove page create permission from this application for current user - application.getPolicies().removeIf( - policy -> policy.getPermission().equals(applicationPermission.getPageCreatePermission().getValue()) - ); + application.getPolicies().removeIf(policy -> policy.getPermission() + .equals(applicationPermission + .getPageCreatePermission() + .getValue())); return applicationRepository.save(application); - }).flatMap(application -> { + }) + .flatMap(application -> { FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application.json"); - return importExportApplicationService - .extractFileAndSaveApplication(workspaceId, filePart, application.getId()); + return importExportApplicationService.extractFileAndSaveApplication( + workspaceId, filePart, application.getId()); }); - StepVerifier - .create(applicationImportDTOMono) + StepVerifier.create(applicationImportDTOMono) .expectError(AppsmithException.class) .verify(); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ReleaseNotesServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ReleaseNotesServiceTest.java index b0ac993b0f47..a32e1c1576d3 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ReleaseNotesServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ReleaseNotesServiceTest.java @@ -22,11 +22,7 @@ public class ReleaseNotesServiceTest { @Test public void testComputeNewReleases() { List<ReleaseNode> releaseNodes = new ArrayList<>(); - releaseNodes.addAll(List.of( - new ReleaseNode("v3"), - new ReleaseNode("v2"), - new ReleaseNode("v1") - )); + releaseNodes.addAll(List.of(new ReleaseNode("v3"), new ReleaseNode("v2"), new ReleaseNode("v1"))); releaseNotesService.setReleaseNodesCache(releaseNodes); @@ -35,5 +31,4 @@ public void testComputeNewReleases() { assertThat(releaseNotesService.computeNewFrom("v1")).isEqualTo("2"); assertThat(releaseNotesService.computeNewFrom("v0")).isEqualTo("2+"); } - } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ShareWorkspacePermissionTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ShareWorkspacePermissionTests.java index ede5d42ec7b6..46a2709d3c90 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ShareWorkspacePermissionTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ShareWorkspacePermissionTests.java @@ -118,23 +118,31 @@ public void setup() { Application application = new Application(); application.setName("Share Test Application"); application.setWorkspaceId(workspaceId); - savedApplication = applicationPageService.createApplication(application, workspaceId).block(); - - PermissionGroup adminPermissionGroup = permissionGroupService.getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + savedApplication = applicationPageService + .createApplication(application, workspaceId) + .block(); + + PermissionGroup adminPermissionGroup = permissionGroupService + .getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); - PermissionGroup developerPermissionGroup = permissionGroupService.getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + PermissionGroup developerPermissionGroup = permissionGroupService + .getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.DEVELOPER)) - .findFirst().get(); - + .findFirst() + .get(); User userAdmin = userService.findByEmail("[email protected]").block(); - User userDeveloper = userService.findByEmail("[email protected]").block(); + User userDeveloper = + userService.findByEmail("[email protected]").block(); // Manually set the admin and developer access for the workspace (instead of going via the service functions) adminPermissionGroup.setAssignedToUserIds(Set.of(apiUser.getId(), userAdmin.getId())); @@ -142,35 +150,49 @@ public void setup() { developerPermissionGroup.setAssignedToUserIds(Set.of(userDeveloper.getId())); permissionGroupRepository.save(developerPermissionGroup).block(); - permissionGroupService.cleanPermissionGroupCacheForUsers(List.of(userAdmin.getEmail(), userDeveloper.getEmail())).block(); + permissionGroupService + .cleanPermissionGroupCacheForUsers(List.of(userAdmin.getEmail(), userDeveloper.getEmail())) + .block(); } @Test @WithUserDetails(value = "[email protected]") public void testAdminPermissionsForInviteAndMakePublic() { - PermissionGroup adminPermissionGroup = permissionGroupService.getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + PermissionGroup adminPermissionGroup = permissionGroupService + .getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); - PermissionGroup developerPermissionGroup = permissionGroupService.getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + PermissionGroup developerPermissionGroup = permissionGroupService + .getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); - PermissionGroup viewerPermissionGroup = permissionGroupService.getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + PermissionGroup viewerPermissionGroup = permissionGroupService + .getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy inviteUserPolicy = Policy.builder().permission(WORKSPACE_INVITE_USERS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy inviteUserPolicy = Policy.builder() + .permission(WORKSPACE_INVITE_USERS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); - Policy makePublicApp = Policy.builder().permission(MAKE_PUBLIC_APPLICATIONS.getValue()) + Policy makePublicApp = Policy.builder() + .permission(MAKE_PUBLIC_APPLICATIONS.getValue()) .permissionGroups(Set.of(adminPermissionGroup.getId())) .build(); @@ -186,21 +208,24 @@ public void testAdminPermissionsForInviteAndMakePublic() { assertThat(workspace.getPolicies()).contains(inviteUserPolicy); }) .verifyComplete(); - } @Test @WithUserDetails(value = "[email protected]") public void testAdminInviteRoles() { - Mono<List<PermissionGroupInfoDTO>> userRolesForWorkspace = workspaceService.getPermissionGroupsForWorkspace(workspaceId); + Mono<List<PermissionGroupInfoDTO>> userRolesForWorkspace = + workspaceService.getPermissionGroupsForWorkspace(workspaceId); StepVerifier.create(userRolesForWorkspace) .assertNext(userGroupInfos -> { assertThat(userGroupInfos).isNotEmpty(); - assertThat(userGroupInfos).anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.ADMINISTRATOR)); - assertThat(userGroupInfos).anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.VIEWER)); - assertThat(userGroupInfos).anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.DEVELOPER)); + assertThat(userGroupInfos) + .anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.ADMINISTRATOR)); + assertThat(userGroupInfos) + .anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.VIEWER)); + assertThat(userGroupInfos) + .anyMatch(userGroupInfo -> userGroupInfo.getName().startsWith(FieldName.DEVELOPER)); }) .verifyComplete(); } @@ -208,26 +233,37 @@ public void testAdminInviteRoles() { @Test @WithUserDetails(value = "[email protected]") public void testDevPermissionsForInvite() { - PermissionGroup adminPermissionGroup = permissionGroupService.getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + PermissionGroup adminPermissionGroup = permissionGroupService + .getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.ADMINISTRATOR)) - .findFirst().get(); + .findFirst() + .get(); - PermissionGroup developerPermissionGroup = permissionGroupService.getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + PermissionGroup developerPermissionGroup = permissionGroupService + .getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.DEVELOPER)) - .findFirst().get(); + .findFirst() + .get(); - PermissionGroup viewerPermissionGroup = permissionGroupService.getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) - .collectList().block() + PermissionGroup viewerPermissionGroup = permissionGroupService + .getByDefaultWorkspace(savedWorkspace, AclPermission.READ_PERMISSION_GROUP_MEMBERS) + .collectList() + .block() .stream() .filter(permissionGroupElem -> permissionGroupElem.getName().startsWith(FieldName.VIEWER)) - .findFirst().get(); + .findFirst() + .get(); - Policy inviteUserPolicy = Policy.builder().permission(WORKSPACE_INVITE_USERS.getValue()) - .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) + Policy inviteUserPolicy = Policy.builder() + .permission(WORKSPACE_INVITE_USERS.getValue()) + .permissionGroups(Set.of( + adminPermissionGroup.getId(), developerPermissionGroup.getId(), viewerPermissionGroup.getId())) .build(); Mono<Workspace> workspaceMono = workspaceService.findById(workspaceId, READ_WORKSPACES); @@ -237,7 +273,6 @@ public void testDevPermissionsForInvite() { assertThat(workspace.getPolicies()).contains(inviteUserPolicy); }) .verifyComplete(); - } @Test diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/UserSignupTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/UserSignupTest.java index 64c2e15c1a13..ded3ff7621b5 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/UserSignupTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/UserSignupTest.java @@ -61,8 +61,17 @@ public class UserSignupTest { @BeforeEach public void setup() { - userSignup = new UserSignupImpl(userService, userDataService, captchaService, authenticationSuccessHandler, - configService, analyticsService, envManager, commonConfig, userUtils, networkUtils); + userSignup = new UserSignupImpl( + userService, + userDataService, + captchaService, + authenticationSuccessHandler, + configService, + analyticsService, + envManager, + commonConfig, + userUtils, + networkUtils); } private String createRandomString(int length) { @@ -80,12 +89,11 @@ public void signupAndLogin_WhenPasswordTooShort_RaisesException() { .expectErrorSatisfies(error -> { assertTrue(error instanceof AppsmithException); - String expectedErrorMessage = AppsmithError.INVALID_PASSWORD_LENGTH - .getMessage(LOGIN_PASSWORD_MIN_LENGTH, LOGIN_PASSWORD_MAX_LENGTH); + String expectedErrorMessage = AppsmithError.INVALID_PASSWORD_LENGTH.getMessage( + LOGIN_PASSWORD_MIN_LENGTH, LOGIN_PASSWORD_MAX_LENGTH); assertEquals(expectedErrorMessage, error.getMessage()); }) .verify(); - } @Test @@ -99,8 +107,8 @@ public void signupAndLogin_WhenPasswordTooLong_RaisesException() { .expectErrorSatisfies(error -> { assertTrue(error instanceof AppsmithException); - String expectedErrorMessage = AppsmithError.INVALID_PASSWORD_LENGTH - .getMessage(LOGIN_PASSWORD_MIN_LENGTH, LOGIN_PASSWORD_MAX_LENGTH); + String expectedErrorMessage = AppsmithError.INVALID_PASSWORD_LENGTH.getMessage( + LOGIN_PASSWORD_MIN_LENGTH, LOGIN_PASSWORD_MAX_LENGTH); assertEquals(expectedErrorMessage, error.getMessage()); }) .verify(); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImplTest.java index 8e06392fd7c3..eae844f62721 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImplTest.java @@ -77,36 +77,52 @@ class ActionExecutionSolutionCEImplTest { @SpyBean NewActionService newActionService; + @MockBean ActionPermission actionPermission; + @MockBean ObservationRegistry observationRegistry; + @SpyBean ObjectMapper objectMapper; + @MockBean NewActionRepository repository; + @SpyBean DatasourceService datasourceService; + @MockBean PluginService pluginService; + @MockBean DatasourceContextService datasourceContextService; + @MockBean PluginExecutorHelper pluginExecutorHelper; + @MockBean NewPageService newPageService; + @MockBean ApplicationService applicationService; + @MockBean SessionUserService sessionUserService; + @MockBean AuthenticationValidator authenticationValidator; + @MockBean DatasourcePermission datasourcePermission; + @MockBean AnalyticsService analyticsService; + @MockBean DatasourceStorageService datasourceStorageService; + @MockBean DatasourceStorageTransferSolution datasourceStorageTransferSolution; @@ -135,7 +151,8 @@ public void beforeEach() { datasourceStorageService, datasourceStorageTransferSolution); - ObservationRegistry.ObservationConfig mockObservationConfig = Mockito.mock(ObservationRegistry.ObservationConfig.class); + ObservationRegistry.ObservationConfig mockObservationConfig = + Mockito.mock(ObservationRegistry.ObservationConfig.class); Mockito.when(observationRegistry.observationConfig()).thenReturn(mockObservationConfig); } @@ -170,25 +187,23 @@ public Map<String, Object> hints() { this.hints = new HashMap<>(); } - @Test public void testExecuteAction_withoutExecuteActionDTOPart_failsValidation() { - final Mono<ActionExecutionResult> actionExecutionResultMono = actionExecutionSolution - .executeAction(Flux.empty(), null, FieldName.UNUSED_ENVIRONMENT_ID); + final Mono<ActionExecutionResult> actionExecutionResultMono = + actionExecutionSolution.executeAction(Flux.empty(), null, FieldName.UNUSED_ENVIRONMENT_ID); - StepVerifier - .create(actionExecutionResultMono) - .expectErrorMatches(e -> e instanceof AppsmithException && - e.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ACTION_ID))) + StepVerifier.create(actionExecutionResultMono) + .expectErrorMatches(e -> e instanceof AppsmithException + && e.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ACTION_ID))) .verify(); } @Test public void testExecuteAction_withMalformedExecuteActionDTO_failsValidation() { - MockServerHttpRequest mock = MockServerHttpRequest - .method(HttpMethod.POST, URI.create("https://example.com")) + MockServerHttpRequest mock = MockServerHttpRequest.method(HttpMethod.POST, URI.create("https://example.com")) .contentType(new MediaType("multipart", "form-data", Map.of("boundary", "boundary"))) - .body(""" + .body( + """ --boundary\r Content-Disposition: form-data; name="executeActionDTO"\r \r @@ -196,25 +211,23 @@ public void testExecuteAction_withMalformedExecuteActionDTO_failsValidation() { --boundary--\r """); - final Flux<Part> partsFlux = BodyExtractors.toParts() - .extract(mock, this.context); + final Flux<Part> partsFlux = BodyExtractors.toParts().extract(mock, this.context); - final Mono<ActionExecutionResult> actionExecutionResultMono = actionExecutionSolution - .executeAction(partsFlux, null, FieldName.UNUSED_ENVIRONMENT_ID); + final Mono<ActionExecutionResult> actionExecutionResultMono = + actionExecutionSolution.executeAction(partsFlux, null, FieldName.UNUSED_ENVIRONMENT_ID); - StepVerifier - .create(actionExecutionResultMono) - .expectErrorMatches(e -> e instanceof AppsmithException && - e.getMessage().equals(AppsmithError.GENERIC_REQUEST_BODY_PARSE_ERROR.getMessage())) + StepVerifier.create(actionExecutionResultMono) + .expectErrorMatches(e -> e instanceof AppsmithException + && e.getMessage().equals(AppsmithError.GENERIC_REQUEST_BODY_PARSE_ERROR.getMessage())) .verify(); } @Test public void testExecuteAction_withoutActionId_failsValidation() { - MockServerHttpRequest mock = MockServerHttpRequest - .method(HttpMethod.POST, URI.create("https://example.com")) + MockServerHttpRequest mock = MockServerHttpRequest.method(HttpMethod.POST, URI.create("https://example.com")) .contentType(new MediaType("multipart", "form-data", Map.of("boundary", "boundary"))) - .body(""" + .body( + """ --boundary\r Content-Disposition: form-data; name="executeActionDTO"\r \r @@ -222,22 +235,21 @@ public void testExecuteAction_withoutActionId_failsValidation() { --boundary--\r """); - final Flux<Part> partsFlux = BodyExtractors.toParts() - .extract(mock, this.context); + final Flux<Part> partsFlux = BodyExtractors.toParts().extract(mock, this.context); - final Mono<ActionExecutionResult> actionExecutionResultMono = actionExecutionSolution.executeAction(partsFlux, null, null); + final Mono<ActionExecutionResult> actionExecutionResultMono = + actionExecutionSolution.executeAction(partsFlux, null, null); - StepVerifier - .create(actionExecutionResultMono) - .expectErrorMatches(e -> e instanceof AppsmithException && - e.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ACTION_ID))) + StepVerifier.create(actionExecutionResultMono) + .expectErrorMatches(e -> e instanceof AppsmithException + && e.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.ACTION_ID))) .verify(); } - @Test public void testExecuteAPIWithUsualOrderingOfTheParts() { - String usualOrderOfParts = """ + String usualOrderOfParts = + """ --boundary\r Content-Disposition: form-data; name="executeActionDTO"\r \r @@ -253,17 +265,16 @@ public void testExecuteAPIWithUsualOrderingOfTheParts() { xyz\r --boundary--"""; - MockServerHttpRequest mock = MockServerHttpRequest - .method(HttpMethod.POST, URI.create("https://example.com")) + MockServerHttpRequest mock = MockServerHttpRequest.method(HttpMethod.POST, URI.create("https://example.com")) .contentType(new MediaType("multipart", "form-data", Map.of("boundary", "boundary"))) .body(usualOrderOfParts); - final Flux<Part> partsFlux = BodyExtractors.toParts() - .extract(mock, this.context); + final Flux<Part> partsFlux = BodyExtractors.toParts().extract(mock, this.context); ActionExecutionSolutionCE executionSolutionSpy = spy(actionExecutionSolution); - Mono<ActionExecutionResult> actionExecutionResultMono = executionSolutionSpy.executeAction(partsFlux, null, null); + Mono<ActionExecutionResult> actionExecutionResultMono = + executionSolutionSpy.executeAction(partsFlux, null, null); ActionExecutionResult mockResult = new ActionExecutionResult(); mockResult.setIsExecutionSuccess(true); @@ -272,24 +283,26 @@ public void testExecuteAPIWithUsualOrderingOfTheParts() { NewAction newAction = new NewAction(); newAction.setId("63285a3388e48972c7519b18"); - doReturn(Mono.just(FieldName.UNUSED_ENVIRONMENT_ID)).when(datasourceService).getTrueEnvironmentId(any(), any()); + doReturn(Mono.just(FieldName.UNUSED_ENVIRONMENT_ID)) + .when(datasourceService) + .getTrueEnvironmentId(any(), any()); doReturn(Mono.just(mockResult)).when(executionSolutionSpy).executeAction(any(), any()); doReturn(Mono.just(newAction)).when(newActionService).findByBranchNameAndDefaultActionId(any(), any(), any()); - - StepVerifier - .create(actionExecutionResultMono) + StepVerifier.create(actionExecutionResultMono) .assertNext(response -> { assertNotNull(response); assertTrue(response.getIsExecutionSuccess()); - assertEquals(mockResult.getBody().toString(), response.getBody().toString()); + assertEquals( + mockResult.getBody().toString(), response.getBody().toString()); }) .verifyComplete(); } @Test public void testExecuteAPIWithParameterMapAsLastPart() { - String parameterMapAtLast = """ + String parameterMapAtLast = + """ --boundary\r Content-Disposition: form-data; name="executeActionDTO"\r \r @@ -305,17 +318,16 @@ public void testExecuteAPIWithParameterMapAsLastPart() { {"Input1.text":"k0"}\r --boundary--"""; - MockServerHttpRequest mock = MockServerHttpRequest - .method(HttpMethod.POST, URI.create("https://example.com")) + MockServerHttpRequest mock = MockServerHttpRequest.method(HttpMethod.POST, URI.create("https://example.com")) .contentType(new MediaType("multipart", "form-data", Map.of("boundary", "boundary"))) .body(parameterMapAtLast); - final Flux<Part> partsFlux = BodyExtractors.toParts() - .extract(mock, this.context); + final Flux<Part> partsFlux = BodyExtractors.toParts().extract(mock, this.context); ActionExecutionSolutionCE executionSolutionSpy = spy(actionExecutionSolution); - Mono<ActionExecutionResult> actionExecutionResultMono = executionSolutionSpy.executeAction(partsFlux, null, null); + Mono<ActionExecutionResult> actionExecutionResultMono = + executionSolutionSpy.executeAction(partsFlux, null, null); ActionExecutionResult mockResult = new ActionExecutionResult(); mockResult.setIsExecutionSuccess(true); @@ -324,24 +336,26 @@ public void testExecuteAPIWithParameterMapAsLastPart() { NewAction newAction = new NewAction(); newAction.setId("63285a3388e48972c7519b18"); - doReturn(Mono.just(FieldName.UNUSED_ENVIRONMENT_ID)).when(datasourceService).getTrueEnvironmentId(any(), any()); + doReturn(Mono.just(FieldName.UNUSED_ENVIRONMENT_ID)) + .when(datasourceService) + .getTrueEnvironmentId(any(), any()); doReturn(Mono.just(mockResult)).when(executionSolutionSpy).executeAction(any(), any()); doReturn(Mono.just(newAction)).when(newActionService).findByBranchNameAndDefaultActionId(any(), any(), any()); - - StepVerifier - .create(actionExecutionResultMono) + StepVerifier.create(actionExecutionResultMono) .assertNext(response -> { assertNotNull(response); assertTrue(response.getIsExecutionSuccess()); - assertEquals(mockResult.getBody().toString(), response.getBody().toString()); + assertEquals( + mockResult.getBody().toString(), response.getBody().toString()); }) .verifyComplete(); } @Test public void testParsePartsAndGetParamsFlux_withBlobIdentifiers_replacesValueInParam() { - String partsWithBlobRefs = """ + String partsWithBlobRefs = + """ --boundary\r Content-Disposition: form-data; name="executeActionDTO"\r \r @@ -362,23 +376,26 @@ public void testParsePartsAndGetParamsFlux_withBlobIdentifiers_replacesValueInPa xy\\nz\r --boundary--"""; - MockServerHttpRequest mock = MockServerHttpRequest - .method(HttpMethod.POST, URI.create("https://example.com")) + MockServerHttpRequest mock = MockServerHttpRequest.method(HttpMethod.POST, URI.create("https://example.com")) .contentType(new MediaType("multipart", "form-data", Map.of("boundary", "boundary"))) .body(partsWithBlobRefs); - final Flux<Part> partsFlux = BodyExtractors.toParts() - .extract(mock, this.context); + final Flux<Part> partsFlux = BodyExtractors.toParts().extract(mock, this.context); AtomicLong atomicLong = new AtomicLong(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); - Mono<List<Param>> paramsListMono = actionExecutionSolution.parsePartsAndGetParamsFlux(partsFlux, atomicLong, executeActionDTO).collectList().cache(); + Mono<List<Param>> paramsListMono = actionExecutionSolution + .parsePartsAndGetParamsFlux(partsFlux, atomicLong, executeActionDTO) + .collectList() + .cache(); StepVerifier.create(paramsListMono) .assertNext(paramsList -> { assertEquals(1, paramsList.size()); Param param = paramsList.get(0); - assertEquals("{\"name\": \"randomName\", \"data\": \"blob:12345678-1234-1234-1234-123456781234\"}", param.getValue()); + assertEquals( + "{\"name\": \"randomName\", \"data\": \"blob:12345678-1234-1234-1234-123456781234\"}", + param.getValue()); }) .verifyComplete(); } @@ -397,7 +414,8 @@ public void testEnrichExecutionParams_withBlobReference_performsSubstitutionCorr param1.setPseudoBindingName("k0"); List<Param> params = List.of(param1); - Mono<ExecuteActionDTO> enrichedDto = actionExecutionSolution.enrichExecutionParam(atomicLong, executeActionDTO, params); + Mono<ExecuteActionDTO> enrichedDto = + actionExecutionSolution.enrichExecutionParam(atomicLong, executeActionDTO, params); StepVerifier.create(enrichedDto) .assertNext(dto -> { @@ -409,4 +427,4 @@ public void testEnrichExecutionParams_withBlobReference_performsSubstitutionCorr }) .verifyComplete(); } -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCETest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCETest.java index 2b51ed2fb38d..9226d5e79c6f 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCETest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCETest.java @@ -139,6 +139,7 @@ public class ActionExecutionSolutionCETest { @SpyBean AstService astService; + @Autowired DatasourceRepository datasourceRepository; @@ -168,17 +169,21 @@ public void setup() { toCreate.setName("ActionServiceCE_Test"); if (workspaceId == null) { - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); - defaultEnvironmentId = workspaceService.getDefaultEnvironmentId(workspaceId).block(); + defaultEnvironmentId = + workspaceService.getDefaultEnvironmentId(workspaceId).block(); } if (testApp == null && testPage == null) { - //Create application and page which will be used by the tests to create actions for. + // Create application and page which will be used by the tests to create actions for. Application application = new Application(); application.setName(UUID.randomUUID().toString()); - testApp = applicationPageService.createApplication(application, workspaceId).block(); + testApp = applicationPageService + .createApplication(application, workspaceId) + .block(); final String pageId = testApp.getPages().get(0).getId(); @@ -212,17 +217,23 @@ public void setup() { GitApplicationMetadata gitData = new GitApplicationMetadata(); gitData.setBranchName("actionServiceTest"); newApp.setGitApplicationMetadata(gitData); - gitConnectedApp = applicationPageService.createApplication(newApp, workspaceId) + gitConnectedApp = applicationPageService + .createApplication(newApp, workspaceId) .flatMap(application -> { application.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); - return applicationService.save(application) - .zipWhen(application1 -> importExportApplicationService.exportApplicationById(application1.getId(), gitData.getBranchName())); + return applicationService + .save(application) + .zipWhen(application1 -> importExportApplicationService.exportApplicationById( + application1.getId(), gitData.getBranchName())); }) // Assign the branchName to all the resources connected to the application - .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) + .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) .block(); - gitConnectedPage = newPageService.findPageById(gitConnectedApp.getPages().get(0).getId(), READ_PAGES, false).block(); + gitConnectedPage = newPageService + .findPageById(gitConnectedApp.getPages().get(0).getId(), READ_PAGES, false) + .block(); branchName = gitConnectedApp.getGitApplicationMetadata().getBranchName(); } @@ -230,7 +241,8 @@ public void setup() { datasource = new Datasource(); datasource.setName("Default Database"); datasource.setWorkspaceId(workspaceId); - Plugin installed_plugin = pluginRepository.findByPackageName("restapi-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("restapi-plugin").block(); datasource.setPluginId(installed_plugin.getId()); datasource.setDatasourceConfiguration(new DatasourceConfiguration()); DatasourceStorage datasourceStorage = new DatasourceStorage(datasource, defaultEnvironmentId); @@ -245,12 +257,12 @@ public void cleanup() { applicationPageService.deleteApplication(testApp.getId()).block(); testApp = null; testPage = null; - } - private void executeAndAssertAction(ExecuteActionDTO executeActionDTO, - ActionExecutionResult mockResult, - List<ParsedDataType> expectedReturnDataTypes) { + private void executeAndAssertAction( + ExecuteActionDTO executeActionDTO, + ActionExecutionResult mockResult, + List<ParsedDataType> expectedReturnDataTypes) { List<WidgetSuggestionDTO> expectedWidgets = mockResult.getSuggestedWidgets(); Mono<ActionExecutionResult> actionExecutionResultMono = executeAction(executeActionDTO, mockResult); @@ -269,51 +281,52 @@ private void executeAndAssertAction(ExecuteActionDTO executeActionDTO, .verifyComplete(); } - private Mono<ActionExecutionResult> executeAction(ExecuteActionDTO executeActionDTO, - ActionExecutionResult mockResult) { + private Mono<ActionExecutionResult> executeAction( + ExecuteActionDTO executeActionDTO, ActionExecutionResult mockResult) { Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(pluginExecutor)); - Mockito.when(pluginExecutor.executeParameterizedWithMetrics(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(pluginExecutor.executeParameterizedWithMetrics( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(mockResult)); Mockito.when(pluginExecutor.datasourceCreate(Mockito.any())).thenReturn(Mono.empty()); - Mono<ActionExecutionResult> actionExecutionResultMono = actionExecutionSolution.executeAction(executeActionDTO, defaultEnvironmentId); + Mono<ActionExecutionResult> actionExecutionResultMono = + actionExecutionSolution.executeAction(executeActionDTO, defaultEnvironmentId); return actionExecutionResultMono; } @Test @WithUserDetails(value = "api_user") public void testVariableSubstitution() { - String json = "{\n" + - " \n" + - " \"deleted\": false,\n" + - " \"config\": {\n" + - " \"CONTAINER_WIDGET\": [\n" + - " {\n" + - " \"_id\": \"7\",\n" + - " \"sectionName\": \"General\",\n" + - " \"children\": [\n" + - " {\n" + - " \"_id\": \"7.1\",\n" + - " \"helpText\": \"Use a html color name, HEX, RGB or RGBA value\",\n" + - " \"placeholderText\": \"#FFFFFF / Gray / rgb(255, 99, 71)\",\n" + - " \"propertyName\": \"backgroundColor\",\n" + - " \"label\": \"Background Color\",\n" + - " \"controlType\": \"INPUT_TEXT\"\n" + - " },\n" + - " {\n" + - " \"_id\": \"7.2\",\n" + - " \"helpText\": \"Controls the visibility of the widget\",\n" + - " \"propertyName\": \"isVisible\",\n" + - " \"label\": \"Visible\",\n" + - " \"controlType\": \"SWITCH\",\n" + - " \"isJSConvertible\": true\n" + - " }\n" + - " ]\n" + - " }\n" + - " ]\n" + - " },\n" + - " \"name\": \"propertyPane\"\n" + - "}"; + String json = "{\n" + " \n" + + " \"deleted\": false,\n" + + " \"config\": {\n" + + " \"CONTAINER_WIDGET\": [\n" + + " {\n" + + " \"_id\": \"7\",\n" + + " \"sectionName\": \"General\",\n" + + " \"children\": [\n" + + " {\n" + + " \"_id\": \"7.1\",\n" + + " \"helpText\": \"Use a html color name, HEX, RGB or RGBA value\",\n" + + " \"placeholderText\": \"#FFFFFF / Gray / rgb(255, 99, 71)\",\n" + + " \"propertyName\": \"backgroundColor\",\n" + + " \"label\": \"Background Color\",\n" + + " \"controlType\": \"INPUT_TEXT\"\n" + + " },\n" + + " {\n" + + " \"_id\": \"7.2\",\n" + + " \"helpText\": \"Controls the visibility of the widget\",\n" + + " \"propertyName\": \"isVisible\",\n" + + " \"label\": \"Visible\",\n" + + " \"controlType\": \"SWITCH\",\n" + + " \"isJSConvertible\": true\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " },\n" + + " \"name\": \"propertyPane\"\n" + + "}"; ActionDTO action = new ActionDTO(); action.setActionConfiguration(new ActionConfiguration()); @@ -331,7 +344,8 @@ public void testVariableSubstitutionWithNewline() { action.setActionConfiguration(new ActionConfiguration()); action.getActionConfiguration().setBody("{{Input.text}}"); - ActionDTO renderedAction = actionExecutionSolution.variableSubstitution(action, Map.of("Input.text", "name\nvalue")); + ActionDTO renderedAction = + actionExecutionSolution.variableSubstitution(action, Map.of("Input.text", "name\nvalue")); assertThat(renderedAction).isNotNull(); assertThat(renderedAction.getActionConfiguration().getBody()).isEqualTo("name\nvalue"); } @@ -362,7 +376,8 @@ public void testActionExecute() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); @@ -396,7 +411,8 @@ public void testActionExecuteNullRequestBody() { action.setName("testActionExecuteNullRequestBody"); action.setPageId(testPage.getId()); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); @@ -427,14 +443,14 @@ public void testActionExecuteDbQuery() { action.setPageId(testPage.getId()); action.setName("testActionExecuteDbQuery"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -450,15 +466,14 @@ public void testActionExecuteErrorResponse() { ActionDTO action = new ActionDTO(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setHeaders(List.of( - new Property("random-header-key", "random-header-value"), - new Property("", "") - )); + actionConfiguration.setHeaders( + List.of(new Property("random-header-key", "random-header-value"), new Property("", ""))); action.setActionConfiguration(actionConfiguration); action.setPageId(testPage.getId()); action.setName("testActionExecuteErrorResponse"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); @@ -466,7 +481,9 @@ public void testActionExecuteErrorResponse() { AppsmithPluginException pluginException = new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(pluginExecutor)); - Mockito.when(pluginExecutor.executeParameterizedWithMetrics(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Mono.error(pluginException)); + Mockito.when(pluginExecutor.executeParameterizedWithMetrics( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(Mono.error(pluginException)); Mockito.when(pluginExecutor.datasourceCreate(Mockito.any())).thenReturn(Mono.empty()); Mono<ActionExecutionResult> executionResultMono = actionExecutionSolution.executeAction(executeActionDTO, null); @@ -495,10 +512,8 @@ public void testActionExecuteNullPaginationParameters() { ActionDTO action = new ActionDTO(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setHeaders(List.of( - new Property("random-header-key", "random-header-value"), - new Property("", "") - )); + actionConfiguration.setHeaders( + List.of(new Property("random-header-key", "random-header-value"), new Property("", ""))); actionConfiguration.setPaginationType(PaginationType.URL); actionConfiguration.setNext(null); action.setActionConfiguration(actionConfiguration); @@ -507,7 +522,8 @@ public void testActionExecuteNullPaginationParameters() { DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasource.setDatasourceConfiguration(datasourceConfiguration); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); @@ -516,7 +532,9 @@ public void testActionExecuteNullPaginationParameters() { AppsmithPluginException pluginException = new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(pluginExecutor)); - Mockito.when(pluginExecutor.executeParameterizedWithMetrics(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Mono.error(pluginException)); + Mockito.when(pluginExecutor.executeParameterizedWithMetrics( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(Mono.error(pluginException)); Mockito.when(pluginExecutor.datasourceCreate(Mockito.any())).thenReturn(Mono.empty()); Mono<ActionExecutionResult> executionResultMono = actionExecutionSolution.executeAction(executeActionDTO, null); @@ -543,24 +561,25 @@ public void testActionExecuteSecondaryStaleConnection() { ActionDTO action = new ActionDTO(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setHeaders(List.of( - new Property("random-header-key", "random-header-value"), - new Property("", "") - )); + actionConfiguration.setHeaders( + List.of(new Property("random-header-key", "random-header-value"), new Property("", ""))); actionConfiguration.setTimeoutInMillisecond(String.valueOf(1000)); action.setActionConfiguration(actionConfiguration); action.setPageId(testPage.getId()); action.setName("testActionExecuteSecondaryStaleConnection"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(pluginExecutor)); - Mockito.when(pluginExecutor.executeParameterizedWithMetrics(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(Mono.error(new StaleConnectionException())).thenReturn(Mono.error(new StaleConnectionException())); + Mockito.when(pluginExecutor.executeParameterizedWithMetrics( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(Mono.error(new StaleConnectionException())) + .thenReturn(Mono.error(new StaleConnectionException())); Mockito.when(pluginExecutor.datasourceCreate(Mockito.any())).thenReturn(Mono.empty()); Mono<ActionExecutionResult> executionResultMono = actionExecutionSolution.executeAction(executeActionDTO, null); @@ -568,7 +587,8 @@ public void testActionExecuteSecondaryStaleConnection() { StepVerifier.create(executionResultMono) .assertNext(result -> { assertThat(result.getIsExecutionSuccess()).isFalse(); - assertThat(result.getStatusCode()).isEqualTo(AppsmithPluginError.STALE_CONNECTION_ERROR.getAppErrorCode()); + assertThat(result.getStatusCode()) + .isEqualTo(AppsmithPluginError.STALE_CONNECTION_ERROR.getAppErrorCode()); assertThat(result.getTitle()).isEqualTo(AppsmithPluginError.STALE_CONNECTION_ERROR.getTitle()); }) .verifyComplete(); @@ -587,23 +607,23 @@ public void testActionExecuteTimeout() { ActionDTO action = new ActionDTO(); ActionConfiguration actionConfiguration = new ActionConfiguration(); - actionConfiguration.setHeaders(List.of( - new Property("random-header-key", "random-header-value"), - new Property("", "") - )); + actionConfiguration.setHeaders( + List.of(new Property("random-header-key", "random-header-value"), new Property("", ""))); actionConfiguration.setTimeoutInMillisecond(String.valueOf(10)); action.setActionConfiguration(actionConfiguration); action.setPageId(testPage.getId()); action.setName("testActionExecuteTimeout"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(pluginExecutor)); - Mockito.when(pluginExecutor.executeParameterizedWithMetrics(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(pluginExecutor.executeParameterizedWithMetrics( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenAnswer(x -> Mono.delay(Duration.ofMillis(1000)).ofType(ActionExecutionResult.class)); Mockito.when(pluginExecutor.datasourceCreate(Mockito.any())).thenReturn(Mono.empty()); @@ -612,13 +632,13 @@ public void testActionExecuteTimeout() { StepVerifier.create(executionResultMono) .assertNext(result -> { assertThat(result.getIsExecutionSuccess()).isFalse(); - assertThat(result.getStatusCode()).isEqualTo(AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR.getAppErrorCode()); + assertThat(result.getStatusCode()) + .isEqualTo(AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR.getAppErrorCode()); assertThat(result.getTitle()).isEqualTo(AppsmithPluginError.PLUGIN_QUERY_TIMEOUT_ERROR.getTitle()); }) .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void checkRecoveryFromStaleConnections() { @@ -627,14 +647,14 @@ public void checkRecoveryFromStaleConnections() { mockResult.setBody("response-body"); Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(pluginExecutor)); - Mockito.when(pluginExecutor.executeParameterizedWithMetrics(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(pluginExecutor.executeParameterizedWithMetrics( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenThrow(new StaleConnectionException()) .thenReturn(Mono.just(mockResult)); Mockito.when(pluginExecutor.datasourceCreate(Mockito.any())).thenReturn(Mono.empty()); Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); - ActionDTO action = new ActionDTO(); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("select * from users"); @@ -642,13 +662,15 @@ public void checkRecoveryFromStaleConnections() { action.setPageId(testPage.getId()); action.setName("checkRecoveryFromStaleConnections"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - Mono<ActionExecutionResult> actionExecutionResultMono = actionExecutionSolution.executeAction(executeActionDTO, null); + Mono<ActionExecutionResult> actionExecutionResultMono = + actionExecutionSolution.executeAction(executeActionDTO, null); StepVerifier.create(actionExecutionResultMono) .assertNext(result -> { @@ -658,17 +680,18 @@ public void checkRecoveryFromStaleConnections() { .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void executeActionWithExternalDatasource() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mockito.when(pluginService.getEditorConfigLabelMap(Mockito.anyString())).thenReturn(Mono.just(new HashMap<>())); Datasource externalDatasource = new Datasource(); externalDatasource.setName("Default Database"); externalDatasource.setWorkspaceId(workspaceId); - Plugin restApiPlugin = pluginRepository.findByPackageName("restapi-plugin").block(); + Plugin restApiPlugin = + pluginRepository.findByPackageName("restapi-plugin").block(); externalDatasource.setPluginId(restApiPlugin.getId()); DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); datasourceConfiguration.setUrl("some url here"); @@ -687,8 +710,8 @@ public void executeActionWithExternalDatasource() { action.setActionConfiguration(actionConfiguration); action.setDatasource(savedDs); - - Mono<ActionExecutionResult> resultMono = layoutActionService.createSingleAction(action, Boolean.FALSE) + Mono<ActionExecutionResult> resultMono = layoutActionService + .createSingleAction(action, Boolean.FALSE) .flatMap(savedAction -> { ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(savedAction.getId()); @@ -696,9 +719,7 @@ public void executeActionWithExternalDatasource() { return actionExecutionSolution.executeAction(executeActionDTO, defaultEnvironmentId); }); - - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .assertNext(result -> { assertThat(result).isNotNull(); assertThat(result.getStatusCode()).isEqualTo("200"); @@ -715,11 +736,10 @@ public void testActionExecuteWithTableReturnType() { ActionExecutionResult mockResult = new ActionExecutionResult(); mockResult.setIsExecutionSuccess(true); - mockResult.setBody("[\n" + - "{\"name\": \"Richard\", \"profession\": \"medical\"},\n" + - "{\"name\": \"John\", \"profession\": \"self employed\"},\n" + - "{\"name\": \"Mary\", \"profession\": \"engineer\"}\n" + - "]"); + mockResult.setBody("[\n" + "{\"name\": \"Richard\", \"profession\": \"medical\"},\n" + + "{\"name\": \"John\", \"profession\": \"self employed\"},\n" + + "{\"name\": \"Mary\", \"profession\": \"engineer\"}\n" + + "]"); mockResult.setStatusCode("200"); mockResult.setHeaders(objectMapper.valueToTree(Map.of("response-header-key", "response-header-value"))); @@ -736,15 +756,20 @@ public void testActionExecuteWithTableReturnType() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.TABLE), new ParsedDataType(DisplayDataType.JSON) - , new ParsedDataType(DisplayDataType.RAW))); + executeAndAssertAction( + executeActionDTO, + mockResult, + List.of( + new ParsedDataType(DisplayDataType.TABLE), + new ParsedDataType(DisplayDataType.JSON), + new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -756,15 +781,14 @@ public void testActionExecuteWithJsonReturnType() { ActionExecutionResult mockResult = new ActionExecutionResult(); mockResult.setIsExecutionSuccess(true); - mockResult.setBody("{\n" + - " \"name\":\"John\",\n" + - " \"age\":30,\n" + - " \"cars\": {\n" + - " \"car1\":\"Ford\",\n" + - " \"car2\":\"BMW\",\n" + - " \"car3\":\"Fiat\"\n" + - " }\n" + - " }"); + mockResult.setBody("{\n" + " \"name\":\"John\",\n" + + " \"age\":30,\n" + + " \"cars\": {\n" + + " \"car1\":\"Ford\",\n" + + " \"car2\":\"BMW\",\n" + + " \"car3\":\"Fiat\"\n" + + " }\n" + + " }"); mockResult.setStatusCode("200"); mockResult.setHeaders(objectMapper.valueToTree(Map.of("response-header-key", "response-header-value"))); @@ -781,13 +805,16 @@ public void testActionExecuteWithJsonReturnType() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, + executeAndAssertAction( + executeActionDTO, + mockResult, List.of(new ParsedDataType(DisplayDataType.JSON), new ParsedDataType(DisplayDataType.RAW))); } @@ -800,15 +827,14 @@ public void testActionExecuteWithPreAssignedReturnType() { ActionExecutionResult mockResult = new ActionExecutionResult(); mockResult.setIsExecutionSuccess(true); - mockResult.setBody("{\n" + - " \"name\":\"John\",\n" + - " \"age\":30,\n" + - " \"cars\": {\n" + - " \"car1\":\"Ford\",\n" + - " \"car2\":\"BMW\",\n" + - " \"car3\":\"Fiat\"\n" + - " }\n" + - " }"); + mockResult.setBody("{\n" + " \"name\":\"John\",\n" + + " \"age\":30,\n" + + " \"cars\": {\n" + + " \"car1\":\"Ford\",\n" + + " \"car2\":\"BMW\",\n" + + " \"car3\":\"Fiat\"\n" + + " }\n" + + " }"); mockResult.setStatusCode("200"); mockResult.setHeaders(objectMapper.valueToTree(Map.of("response-header-key", "response-header-value"))); mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW))); @@ -826,14 +852,14 @@ public void testActionExecuteWithPreAssignedReturnType() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -861,7 +887,8 @@ public void testActionExecuteReturnTypeWithNullResultBody() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); @@ -879,36 +906,35 @@ public void testWidgetSuggestionAfterExecutionWithChartWidgetData() throws JsonP .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{ \"data\": [\n" + - " {\n" + - " \"x\": \"Mon\",\n" + - " \"y\": 10000\n" + - " },\n" + - " {\n" + - " \"x\": \"Tue\",\n" + - " \"y\": 12000\n" + - " },\n" + - " {\n" + - " \"x\": \"Wed\",\n" + - " \"y\": 32000\n" + - " },\n" + - " {\n" + - " \"x\": \"Thu\",\n" + - " \"y\": 28000\n" + - " },\n" + - " {\n" + - " \"x\": \"Fri\",\n" + - " \"y\": 14000\n" + - " },\n" + - " {\n" + - " \"x\": \"Sat\",\n" + - " \"y\": 19000\n" + - " },\n" + - " {\n" + - " \"x\": \"Sun\",\n" + - " \"y\": 36000\n" + - " }\n" + - "]}"; + final String data = "{ \"data\": [\n" + " {\n" + + " \"x\": \"Mon\",\n" + + " \"y\": 10000\n" + + " },\n" + + " {\n" + + " \"x\": \"Tue\",\n" + + " \"y\": 12000\n" + + " },\n" + + " {\n" + + " \"x\": \"Wed\",\n" + + " \"y\": 32000\n" + + " },\n" + + " {\n" + + " \"x\": \"Thu\",\n" + + " \"y\": 28000\n" + + " },\n" + + " {\n" + + " \"x\": \"Fri\",\n" + + " \"y\": 14000\n" + + " },\n" + + " {\n" + + " \"x\": \"Sat\",\n" + + " \"y\": 19000\n" + + " },\n" + + " {\n" + + " \"x\": \"Sun\",\n" + + " \"y\": 36000\n" + + " }\n" + + "]}"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -933,15 +959,14 @@ public void testWidgetSuggestionAfterExecutionWithChartWidgetData() throws JsonP action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -952,76 +977,75 @@ public void testWidgetSuggestionAfterExecutionWithTableWidgetData() throws JsonP Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{ \"data\": [\n" + - "\t{\n" + - "\t\t\"id\": \"0001\",\n" + - "\t\t\"type\": \"donut\",\n" + - "\t\t\"name\": \"Cake\",\n" + - "\t\t\"ppu\": 0.55,\n" + - "\t\t\"batters\":\n" + - "\t\t\t{\n" + - "\t\t\t\t\"batter\":\n" + - "\t\t\t\t\t[\n" + - "\t\t\t\t\t\t{ \"id\": \"1001\", \"type\": \"Regular\" },\n" + - "\t\t\t\t\t\t{ \"id\": \"1002\", \"type\": \"Chocolate\" },\n" + - "\t\t\t\t\t\t{ \"id\": \"1003\", \"type\": \"Blueberry\" },\n" + - "\t\t\t\t\t\t{ \"id\": \"1004\", \"type\": \"Devil's Food\" }\n" + - "\t\t\t\t\t]\n" + - "\t\t\t},\n" + - "\t\t\"topping\":\n" + - "\t\t\t[\n" + - "\t\t\t\t{ \"id\": \"5001\", \"type\": \"None\" },\n" + - "\t\t\t\t{ \"id\": \"5002\", \"type\": \"Glazed\" },\n" + - "\t\t\t\t{ \"id\": \"5005\", \"type\": \"Sugar\" },\n" + - "\t\t\t\t{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },\n" + - "\t\t\t\t{ \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },\n" + - "\t\t\t\t{ \"id\": \"5003\", \"type\": \"Chocolate\" },\n" + - "\t\t\t\t{ \"id\": \"5004\", \"type\": \"Maple\" }\n" + - "\t\t\t]\n" + - "\t},\n" + - "\t{\n" + - "\t\t\"id\": \"0002\",\n" + - "\t\t\"type\": \"donut\",\n" + - "\t\t\"name\": \"Raised\",\n" + - "\t\t\"ppu\": 0.55,\n" + - "\t\t\"batters\":\n" + - "\t\t\t{\n" + - "\t\t\t\t\"batter\":\n" + - "\t\t\t\t\t[\n" + - "\t\t\t\t\t\t{ \"id\": \"1001\", \"type\": \"Regular\" }\n" + - "\t\t\t\t\t]\n" + - "\t\t\t},\n" + - "\t\t\"topping\":\n" + - "\t\t\t[\n" + - "\t\t\t\t{ \"id\": \"5001\", \"type\": \"None\" },\n" + - "\t\t\t\t{ \"id\": \"5002\", \"type\": \"Glazed\" },\n" + - "\t\t\t\t{ \"id\": \"5005\", \"type\": \"Sugar\" },\n" + - "\t\t\t\t{ \"id\": \"5003\", \"type\": \"Chocolate\" },\n" + - "\t\t\t\t{ \"id\": \"5004\", \"type\": \"Maple\" }\n" + - "\t\t\t]\n" + - "\t},\n" + - "\t{\n" + - "\t\t\"id\": \"0003\",\n" + - "\t\t\"type\": \"donut\",\n" + - "\t\t\"name\": \"Old Fashioned\",\n" + - "\t\t\"ppu\": 0.55,\n" + - "\t\t\"batters\":\n" + - "\t\t\t{\n" + - "\t\t\t\t\"batter\":\n" + - "\t\t\t\t\t[\n" + - "\t\t\t\t\t\t{ \"id\": \"1001\", \"type\": \"Regular\" },\n" + - "\t\t\t\t\t\t{ \"id\": \"1002\", \"type\": \"Chocolate\" }\n" + - "\t\t\t\t\t]\n" + - "\t\t\t},\n" + - "\t\t\"topping\":\n" + - "\t\t\t[\n" + - "\t\t\t\t{ \"id\": \"5001\", \"type\": \"None\" },\n" + - "\t\t\t\t{ \"id\": \"5002\", \"type\": \"Glazed\" },\n" + - "\t\t\t\t{ \"id\": \"5003\", \"type\": \"Chocolate\" },\n" + - "\t\t\t\t{ \"id\": \"5004\", \"type\": \"Maple\" }\n" + - "\t\t\t]\n" + - "\t}\n" + - "]}"; + final String data = "{ \"data\": [\n" + "\t{\n" + + "\t\t\"id\": \"0001\",\n" + + "\t\t\"type\": \"donut\",\n" + + "\t\t\"name\": \"Cake\",\n" + + "\t\t\"ppu\": 0.55,\n" + + "\t\t\"batters\":\n" + + "\t\t\t{\n" + + "\t\t\t\t\"batter\":\n" + + "\t\t\t\t\t[\n" + + "\t\t\t\t\t\t{ \"id\": \"1001\", \"type\": \"Regular\" },\n" + + "\t\t\t\t\t\t{ \"id\": \"1002\", \"type\": \"Chocolate\" },\n" + + "\t\t\t\t\t\t{ \"id\": \"1003\", \"type\": \"Blueberry\" },\n" + + "\t\t\t\t\t\t{ \"id\": \"1004\", \"type\": \"Devil's Food\" }\n" + + "\t\t\t\t\t]\n" + + "\t\t\t},\n" + + "\t\t\"topping\":\n" + + "\t\t\t[\n" + + "\t\t\t\t{ \"id\": \"5001\", \"type\": \"None\" },\n" + + "\t\t\t\t{ \"id\": \"5002\", \"type\": \"Glazed\" },\n" + + "\t\t\t\t{ \"id\": \"5005\", \"type\": \"Sugar\" },\n" + + "\t\t\t\t{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },\n" + + "\t\t\t\t{ \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },\n" + + "\t\t\t\t{ \"id\": \"5003\", \"type\": \"Chocolate\" },\n" + + "\t\t\t\t{ \"id\": \"5004\", \"type\": \"Maple\" }\n" + + "\t\t\t]\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"id\": \"0002\",\n" + + "\t\t\"type\": \"donut\",\n" + + "\t\t\"name\": \"Raised\",\n" + + "\t\t\"ppu\": 0.55,\n" + + "\t\t\"batters\":\n" + + "\t\t\t{\n" + + "\t\t\t\t\"batter\":\n" + + "\t\t\t\t\t[\n" + + "\t\t\t\t\t\t{ \"id\": \"1001\", \"type\": \"Regular\" }\n" + + "\t\t\t\t\t]\n" + + "\t\t\t},\n" + + "\t\t\"topping\":\n" + + "\t\t\t[\n" + + "\t\t\t\t{ \"id\": \"5001\", \"type\": \"None\" },\n" + + "\t\t\t\t{ \"id\": \"5002\", \"type\": \"Glazed\" },\n" + + "\t\t\t\t{ \"id\": \"5005\", \"type\": \"Sugar\" },\n" + + "\t\t\t\t{ \"id\": \"5003\", \"type\": \"Chocolate\" },\n" + + "\t\t\t\t{ \"id\": \"5004\", \"type\": \"Maple\" }\n" + + "\t\t\t]\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"id\": \"0003\",\n" + + "\t\t\"type\": \"donut\",\n" + + "\t\t\"name\": \"Old Fashioned\",\n" + + "\t\t\"ppu\": 0.55,\n" + + "\t\t\"batters\":\n" + + "\t\t\t{\n" + + "\t\t\t\t\"batter\":\n" + + "\t\t\t\t\t[\n" + + "\t\t\t\t\t\t{ \"id\": \"1001\", \"type\": \"Regular\" },\n" + + "\t\t\t\t\t\t{ \"id\": \"1002\", \"type\": \"Chocolate\" }\n" + + "\t\t\t\t\t]\n" + + "\t\t\t},\n" + + "\t\t\"topping\":\n" + + "\t\t\t[\n" + + "\t\t\t\t{ \"id\": \"5001\", \"type\": \"None\" },\n" + + "\t\t\t\t{ \"id\": \"5002\", \"type\": \"Glazed\" },\n" + + "\t\t\t\t{ \"id\": \"5003\", \"type\": \"Chocolate\" },\n" + + "\t\t\t\t{ \"id\": \"5004\", \"type\": \"Maple\" }\n" + + "\t\t\t]\n" + + "\t}\n" + + "]}"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -1046,15 +1070,14 @@ public void testWidgetSuggestionAfterExecutionWithTableWidgetData() throws JsonP action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1065,68 +1088,67 @@ public void testWidgetSuggestionAfterExecutionWithListWidgetData() throws JsonPr Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{ \"data\": [\n" + - " {\n" + - " \"url\": \"images/thumbnails/0001.jpg\",\n" + - " \"width\": 32,\n" + - " \"height\": 32\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0001.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0002.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0002.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0003.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0004.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0005.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0006.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0007.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0008.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0009.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " },\n" + - " {\n" + - " \"url\": \"images/0010.jpg\",\n" + - " \"width\": 200,\n" + - " \"height\": 200\n" + - " }\n" + - "]}"; + final String data = "{ \"data\": [\n" + " {\n" + + " \"url\": \"images/thumbnails/0001.jpg\",\n" + + " \"width\": 32,\n" + + " \"height\": 32\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0001.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0002.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0002.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0003.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0004.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0005.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0006.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0007.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0008.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0009.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " },\n" + + " {\n" + + " \"url\": \"images/0010.jpg\",\n" + + " \"width\": 200,\n" + + " \"height\": 200\n" + + " }\n" + + "]}"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -1151,15 +1173,14 @@ public void testWidgetSuggestionAfterExecutionWithListWidgetData() throws JsonPr action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1170,24 +1191,23 @@ public void testWidgetSuggestionAfterExecutionWithDropdownWidgetData() throws Js Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{ \"data\": [\n" + - " {\n" + - " \"CarType\": \"BMW\",\n" + - " \"carID\": \"bmw123\"\n" + - " },\n" + - " {\n" + - " \"CarType\": \"mercedes\",\n" + - " \"carID\": \"merc123\"\n" + - " },\n" + - " {\n" + - " \"CarType\": \"volvo\",\n" + - " \"carID\": \"vol123r\"\n" + - " },\n" + - " {\n" + - " \"CarType\": \"ford\",\n" + - " \"carID\": \"ford123\"\n" + - " }\n" + - " ]}"; + final String data = "{ \"data\": [\n" + " {\n" + + " \"CarType\": \"BMW\",\n" + + " \"carID\": \"bmw123\"\n" + + " },\n" + + " {\n" + + " \"CarType\": \"mercedes\",\n" + + " \"carID\": \"merc123\"\n" + + " },\n" + + " {\n" + + " \"CarType\": \"volvo\",\n" + + " \"carID\": \"vol123r\"\n" + + " },\n" + + " {\n" + + " \"CarType\": \"ford\",\n" + + " \"carID\": \"ford123\"\n" + + " }\n" + + " ]}"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -1211,15 +1231,14 @@ public void testWidgetSuggestionAfterExecutionWithDropdownWidgetData() throws Js action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1252,15 +1271,14 @@ public void testWidgetSuggestionAfterExecutionWithArrayOfStringsDropDownWidget() action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1271,9 +1289,9 @@ public void testWidgetSuggestionAfterExecutionWithArrayOfArray() throws JsonProc Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{ \"data\":[[\"string1\", \"string2\", \"string3\", \"string4\"]," + - "[\"string5\", \"string6\", \"string7\", \"string8\"]," + - "[\"string9\", \"string10\", \"string11\", \"string12\"]] }"; + final String data = "{ \"data\":[[\"string1\", \"string2\", \"string3\", \"string4\"]," + + "[\"string5\", \"string6\", \"string7\", \"string8\"]," + + "[\"string9\", \"string10\", \"string11\", \"string12\"]] }"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -1296,15 +1314,14 @@ public void testWidgetSuggestionAfterExecutionWithArrayOfArray() throws JsonProc action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1336,15 +1353,14 @@ public void testWidgetSuggestionAfterExecutionWithEmptyData() throws JsonProcess action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1378,15 +1394,14 @@ public void testWidgetSuggestionAfterExecutionWithNumericData() throws JsonProce action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1397,34 +1412,34 @@ public void testWidgetSuggestionAfterExecutionWithJsonNodeData() throws JsonProc Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{\"data\": {\n" + - " \"next\": \"https://mock-api.appsmith.com/users?page=2&pageSize=10\",\n" + - " \"previous\": null,\n" + - " \"users\": [\n" + - " {\n" + - " \"id\": 3,\n" + - " \"name\": \"Demetre\",\n" + - " \"status\": \"APPROVED\",\n" + - " \"gender\": \"Male\",\n" + - " \"avatar\": \"https://robohash.org/iustooptiocum.jpg?size=100x100&set=set1\",\n" + - " \"email\": \"[email protected]\",\n" + - " \"address\": \"262 Saint Paul Park\",\n" + - " \"createdAt\": \"2020-05-01T17:30:50.000Z\",\n" + - " \"updatedAt\": \"2019-10-08T14:55:53.000Z\"\n" + - " },\n" + - " {\n" + - " \"id\": 4,\n" + - " \"name\": \"Currey\",\n" + - " \"status\": \"APPROVED\",\n" + - " \"gender\": \"Female\",\n" + - " \"avatar\": \"https://robohash.org/aspernaturnatusrepellat.jpg?size=100x100&set=set1\",\n" + - " \"email\": \"[email protected]\",\n" + - " \"address\": \"35180 Lotheville Street!\",\n" + - " \"createdAt\": \"2019-12-30T03:54:23.000Z\",\n" + - " \"updatedAt\": \"2020-08-12T17:43:01.016Z\"\n" + - " }\n" + - " ]\n" + - "}}"; + final String data = + "{\"data\": {\n" + " \"next\": \"https://mock-api.appsmith.com/users?page=2&pageSize=10\",\n" + + " \"previous\": null,\n" + + " \"users\": [\n" + + " {\n" + + " \"id\": 3,\n" + + " \"name\": \"Demetre\",\n" + + " \"status\": \"APPROVED\",\n" + + " \"gender\": \"Male\",\n" + + " \"avatar\": \"https://robohash.org/iustooptiocum.jpg?size=100x100&set=set1\",\n" + + " \"email\": \"[email protected]\",\n" + + " \"address\": \"262 Saint Paul Park\",\n" + + " \"createdAt\": \"2020-05-01T17:30:50.000Z\",\n" + + " \"updatedAt\": \"2019-10-08T14:55:53.000Z\"\n" + + " },\n" + + " {\n" + + " \"id\": 4,\n" + + " \"name\": \"Currey\",\n" + + " \"status\": \"APPROVED\",\n" + + " \"gender\": \"Female\",\n" + + " \"avatar\": \"https://robohash.org/aspernaturnatusrepellat.jpg?size=100x100&set=set1\",\n" + + " \"email\": \"[email protected]\",\n" + + " \"address\": \"35180 Lotheville Street!\",\n" + + " \"createdAt\": \"2019-12-30T03:54:23.000Z\",\n" + + " \"updatedAt\": \"2020-08-12T17:43:01.016Z\"\n" + + " }\n" + + " ]\n" + + "}}"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -1437,7 +1452,8 @@ public void testWidgetSuggestionAfterExecutionWithJsonNodeData() throws JsonProc widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.TEXT_WIDGET, "users")); widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.CHART_WIDGET, "users", "name", "id")); widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.TABLE_WIDGET_V2, "users")); - widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.SELECT_WIDGET, "users", "name", "status")); + widgetTypeList.add( + WidgetSuggestionHelper.getWidgetNestedData(WidgetType.SELECT_WIDGET, "users", "name", "status")); mockResult.setSuggestedWidgets(widgetTypeList); ActionDTO action = new ActionDTO(); @@ -1449,15 +1465,14 @@ public void testWidgetSuggestionAfterExecutionWithJsonNodeData() throws JsonProc action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1468,17 +1483,16 @@ public void testWidgetSuggestionAfterExecutionWithJsonObjectData() throws JsonPr Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{ \"data\": {\n" + - " \"id\": 1,\n" + - " \"name\": \"Barty Crouch\",\n" + - " \"status\": \"APPROVED\",\n" + - " \"gender\": \"\",\n" + - " \"avatar\": \"https://robohash.org/sednecessitatibuset.png?size=100x100&set=set1\",\n" + - " \"email\": \"[email protected]\",\n" + - " \"address\": \"St Petersberg #911 4th main\",\n" + - " \"createdAt\": \"2020-03-16T18:00:05.000Z\",\n" + - " \"updatedAt\": \"2020-08-12T17:29:31.980Z\"\n" + - " } }"; + final String data = "{ \"data\": {\n" + " \"id\": 1,\n" + + " \"name\": \"Barty Crouch\",\n" + + " \"status\": \"APPROVED\",\n" + + " \"gender\": \"\",\n" + + " \"avatar\": \"https://robohash.org/sednecessitatibuset.png?size=100x100&set=set1\",\n" + + " \"email\": \"[email protected]\",\n" + + " \"address\": \"St Petersberg #911 4th main\",\n" + + " \"createdAt\": \"2020-03-16T18:00:05.000Z\",\n" + + " \"updatedAt\": \"2020-08-12T17:29:31.980Z\"\n" + + " } }"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -1500,15 +1514,14 @@ public void testWidgetSuggestionAfterExecutionWithJsonObjectData() throws JsonPr action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1519,28 +1532,27 @@ public void testWidgetSuggestionAfterExecutionWithJsonArrayObjectData() throws J Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{ \"data\": {\n" + - " \"id\": 1,\n" + - " \"name\": \"Barty Crouch\",\n" + - " \"status\": \"APPROVED\",\n" + - " \"gender\": \"\",\n" + - " \"avatar\": \"https://robohash.org/sednecessitatibuset.png?size=100x100&set=set1\",\n" + - " \"email\": \"[email protected]\",\n" + - " \"address\": \"St Petersberg #911 4th main\",\n" + - " \"createdAt\": \"2020-03-16T18:00:05.000Z\",\n" + - " \"updatedAt\": \"2020-08-12T17:29:31.980Z\"\n" + - " }," + - "\"data\": {\n" + - " \"id\": 2,\n" + - " \"name\": \"Jenelle Kibbys\",\n" + - " \"status\": \"APPROVED\",\n" + - " \"gender\": \"Female\",\n" + - " \"avatar\": \"https://robohash.org/quiaasperiorespariatur.bmp?size=100x100&set=set1\",\n" + - " \"email\": \"[email protected]\",\n" + - " \"address\": \"85 Tennessee Plaza\",\n" + - " \"createdAt\": \"2019-10-04T03:22:23.000Z\",\n" + - " \"updatedAt\": \"2019-09-11T20:18:38.000Z\"\n" + - " } }"; + final String data = "{ \"data\": {\n" + " \"id\": 1,\n" + + " \"name\": \"Barty Crouch\",\n" + + " \"status\": \"APPROVED\",\n" + + " \"gender\": \"\",\n" + + " \"avatar\": \"https://robohash.org/sednecessitatibuset.png?size=100x100&set=set1\",\n" + + " \"email\": \"[email protected]\",\n" + + " \"address\": \"St Petersberg #911 4th main\",\n" + + " \"createdAt\": \"2020-03-16T18:00:05.000Z\",\n" + + " \"updatedAt\": \"2020-08-12T17:29:31.980Z\"\n" + + " }," + + "\"data\": {\n" + + " \"id\": 2,\n" + + " \"name\": \"Jenelle Kibbys\",\n" + + " \"status\": \"APPROVED\",\n" + + " \"gender\": \"Female\",\n" + + " \"avatar\": \"https://robohash.org/quiaasperiorespariatur.bmp?size=100x100&set=set1\",\n" + + " \"email\": \"[email protected]\",\n" + + " \"address\": \"85 Tennessee Plaza\",\n" + + " \"createdAt\": \"2019-10-04T03:22:23.000Z\",\n" + + " \"updatedAt\": \"2019-09-11T20:18:38.000Z\"\n" + + " } }"; final JsonNode arrNode = new ObjectMapper().readTree(data); mockResult.setIsExecutionSuccess(true); @@ -1562,15 +1574,14 @@ public void testWidgetSuggestionAfterExecutionWithJsonArrayObjectData() throws J action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1581,11 +1592,11 @@ public void testWidgetSuggestionNestedData() throws JsonProcessingException { Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{\"data\": {\n" + - " \"next\": \"https://mock-api.appsmith.com/users?page=2&pageSize=10\",\n" + - " \"previous\": null,\n" + - " \"users\": [1, 2, 3]\n" + - "}}"; + final String data = + "{\"data\": {\n" + " \"next\": \"https://mock-api.appsmith.com/users?page=2&pageSize=10\",\n" + + " \"previous\": null,\n" + + " \"users\": [1, 2, 3]\n" + + "}}"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -1608,15 +1619,14 @@ public void testWidgetSuggestionNestedData() throws JsonProcessingException { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1627,11 +1637,11 @@ public void testWidgetSuggestionNestedDataEmpty() throws JsonProcessingException Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); ActionExecutionResult mockResult = new ActionExecutionResult(); - final String data = "{\"data\": {\n" + - " \"next\": \"https://mock-api.appsmith.com/users?page=2&pageSize=10\",\n" + - " \"previous\": null,\n" + - " \"users\": []\n" + - "}}"; + final String data = + "{\"data\": {\n" + " \"next\": \"https://mock-api.appsmith.com/users?page=2&pageSize=10\",\n" + + " \"previous\": null,\n" + + " \"users\": []\n" + + "}}"; final JsonNode arrNode = new ObjectMapper().readTree(data).get("data"); mockResult.setIsExecutionSuccess(true); @@ -1653,15 +1663,14 @@ public void testWidgetSuggestionNestedDataEmpty() throws JsonProcessingException action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1702,14 +1711,14 @@ public void suggestWidget_ArrayListData_SuggestTableTextChartDropDownWidget() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1721,7 +1730,8 @@ public void suggestWidget_ArrayListData_SuggestTableTextDropDownWidget() { ActionExecutionResult mockResult = new ActionExecutionResult(); ArrayList<JSONObject> listData = new ArrayList<>(); - JSONObject jsonObject = new JSONObject(Map.of("url", "images/thumbnails/0001.jpg", "width", "32", "height", "32")); + JSONObject jsonObject = + new JSONObject(Map.of("url", "images/thumbnails/0001.jpg", "width", "32", "height", "32")); listData.add(jsonObject); jsonObject = new JSONObject(Map.of("url", "images/0001.jpg", "width", "42", "height", "22")); listData.add(jsonObject); @@ -1750,14 +1760,14 @@ public void suggestWidget_ArrayListData_SuggestTableTextDropDownWidget() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } @Test @@ -1787,22 +1797,21 @@ public void suggestWidget_ArrayListDataEmpty_SuggestTextWidget() { action.setPageId(testPage.getId()); action.setName("testActionExecute"); action.setDatasource(datasource); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); - + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } - @Test @WithUserDetails(value = "api_user") public void executeAction_actionOnMockDatasource_success() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); Mockito.when(pluginService.getEditorConfigLabelMap(Mockito.anyString())).thenReturn(Mono.just(new HashMap<>())); Mockito.when(pluginExecutor.getHintMessages(Mockito.any(), Mockito.any())) .thenReturn(Mono.zip(Mono.just(new HashSet<>()), Mono.just(new HashSet<>()))); @@ -1811,13 +1820,16 @@ public void executeAction_actionOnMockDatasource_success() { mockResult.setIsExecutionSuccess(true); mockResult.setBody("response-body"); - Plugin installed_plugin = pluginRepository.findByPackageName("restapi-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("restapi-plugin").block(); MockDataSource mockDataSource = new MockDataSource(); mockDataSource.setName("Users"); mockDataSource.setWorkspaceId(workspaceId); mockDataSource.setPackageName("postgres-plugin"); mockDataSource.setPluginId(installed_plugin.getId()); - Datasource mockDatasource = mockDataService.createMockDataSet(mockDataSource, defaultEnvironmentId).block(); + Datasource mockDatasource = mockDataService + .createMockDataSet(mockDataSource, defaultEnvironmentId) + .block(); List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>(); widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET)); @@ -1831,13 +1843,13 @@ public void executeAction_actionOnMockDatasource_success() { action.setName("testActionExecuteDbQuery"); Datasource datasource1 = mockDatasource; action.setDatasource(datasource1); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); executeActionDTO.setActionId(createdAction.getId()); executeActionDTO.setViewMode(false); - executeAndAssertAction(executeActionDTO, mockResult, - List.of(new ParsedDataType(DisplayDataType.RAW))); + executeAndAssertAction(executeActionDTO, mockResult, List.of(new ParsedDataType(DisplayDataType.RAW))); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/RefactoringSolutionCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/RefactoringSolutionCEImplTest.java index 5601e5c61aac..110c9c2ee113 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/RefactoringSolutionCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/RefactoringSolutionCEImplTest.java @@ -41,26 +41,37 @@ class RefactoringSolutionCEImplTest { PagePermission pagePermission; ActionPermission actionPermission; ObjectMapper mapper = new ObjectMapper(); + @MockBean private ObjectMapper objectMapper; + @MockBean private NewPageService newPageService; + @MockBean private NewActionService newActionService; + @MockBean private ActionCollectionService actionCollectionService; + @MockBean private ResponseUtils responseUtils; + @MockBean private LayoutActionService layoutActionService; + @MockBean private ApplicationService applicationService; + @MockBean private AstService astService; + @MockBean private InstanceConfig instanceConfig; + @MockBean private AnalyticsService analyticsService; + @MockBean private SessionUserService sessionUserService; @@ -68,7 +79,8 @@ class RefactoringSolutionCEImplTest { public void setUp() { pagePermission = new PagePermissionImpl(); actionPermission = new ActionPermissionImpl(); - refactoringSolutionCE = new RefactoringSolutionCEImpl(objectMapper, + refactoringSolutionCE = new RefactoringSolutionCEImpl( + objectMapper, newPageService, newActionService, actionCollectionService, @@ -86,24 +98,20 @@ public void setUp() { @Test void testRefactorNameInDsl_whenRenamingTextWidget_replacesAllReferences() { try (InputStream initialStream = this.getClass().getResourceAsStream("refactorDslWithOnlyWidgets.json"); - InputStream finalStream = this.getClass().getResourceAsStream("refactorDslWithOnlyWidgetsWithNewText.json")) { + InputStream finalStream = + this.getClass().getResourceAsStream("refactorDslWithOnlyWidgetsWithNewText.json")) { assert initialStream != null; JsonNode dslAsJsonNode = mapper.readTree(initialStream); final String oldName = "Text"; Mono<Set<String>> updatesMono = refactoringSolutionCE.refactorNameInDsl( - dslAsJsonNode, - oldName, - "newText", - 2, - Pattern.compile(preWord + oldName + postWord)); + dslAsJsonNode, oldName, "newText", 2, Pattern.compile(preWord + oldName + postWord)); StepVerifier.create(updatesMono) .assertNext(updatedPaths -> { Assertions.assertThat(updatedPaths).hasSize(3); - Assertions.assertThat(updatedPaths).containsExactlyInAnyOrder( - "Text.widgetName", - "List1.template", - "List1.onListItemClick"); + Assertions.assertThat(updatedPaths) + .containsExactlyInAnyOrder( + "Text.widgetName", "List1.template", "List1.onListItemClick"); }) .verifyComplete(); @@ -118,25 +126,23 @@ void testRefactorNameInDsl_whenRenamingTextWidget_replacesAllReferences() { @Test void testRefactorNameInDsl_whenRenamingListWidget_replacesTemplateReferences() { try (InputStream initialStream = this.getClass().getResourceAsStream("refactorDslWithOnlyWidgets.json"); - InputStream finalStream = this.getClass().getResourceAsStream("refactorDslWithOnlyWidgetsWithNewList.json")) { + InputStream finalStream = + this.getClass().getResourceAsStream("refactorDslWithOnlyWidgetsWithNewList.json")) { assert initialStream != null; JsonNode dslAsJsonNode = mapper.readTree(initialStream); final String oldName = "List1"; Mono<Set<String>> updatesMono = refactoringSolutionCE.refactorNameInDsl( - dslAsJsonNode, - oldName, - "newList", - 2, - Pattern.compile(preWord + oldName + postWord)); + dslAsJsonNode, oldName, "newList", 2, Pattern.compile(preWord + oldName + postWord)); StepVerifier.create(updatesMono) .assertNext(updatedPaths -> { Assertions.assertThat(updatedPaths).hasSize(4); - Assertions.assertThat(updatedPaths).containsExactlyInAnyOrder( - "List1.widgetName", - "List1.template.Text4.text", - "List1.template.Image1.image", - "List1.template.Text.text"); + Assertions.assertThat(updatedPaths) + .containsExactlyInAnyOrder( + "List1.widgetName", + "List1.template.Text4.text", + "List1.template.Image1.image", + "List1.template.Text.text"); }) .verifyComplete(); @@ -147,5 +153,4 @@ void testRefactorNameInDsl_whenRenamingListWidget_replacesTemplateReferences() { Assertions.fail("Unexpected IOException", e); } } - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/RefactoringSolutionCETest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/RefactoringSolutionCETest.java index 1b46d5c45c3f..74eb96e5af4c 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/RefactoringSolutionCETest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/RefactoringSolutionCETest.java @@ -144,14 +144,17 @@ public void setup() { Workspace toCreate = new Workspace(); toCreate.setName("LayoutActionServiceTest"); - Workspace workspace = workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); workspaceId = workspace.getId(); if (testApp == null && testPage == null) { - //Create application and page which will be used by the tests to create actions for. + // Create application and page which will be used by the tests to create actions for. Application application = new Application(); application.setName(UUID.randomUUID().toString()); - testApp = applicationPageService.createApplication(application, workspace.getId()).block(); + testApp = applicationPageService + .createApplication(application, workspace.getId()) + .block(); final String pageId = testApp.getPages().get(0).getId(); @@ -161,8 +164,8 @@ public void setup() { JSONObject dsl = new JSONObject(); dsl.put("widgetName", "firstWidget"); JSONArray temp = new JSONArray(); - temp.addAll(List.of(new JSONObject(Map.of("key", "testField")), - new JSONObject(Map.of("key", "testField2")))); + temp.addAll( + List.of(new JSONObject(Map.of("key", "testField")), new JSONObject(Map.of("key", "testField2")))); dsl.put("dynamicBindingPathList", temp); dsl.put("testField", "{{ query1.data }}"); dsl.put("testField2", "{{jsObject.jsFunction.data}}"); @@ -184,7 +187,9 @@ public void setup() { layout.setDsl(dsl); layout.setPublishedDsl(dsl); - layoutActionService.updateLayout(pageId, testApp.getId(), layout.getId(), layout).block(); + layoutActionService + .updateLayout(pageId, testApp.getId(), layout.getId(), layout) + .block(); testPage = newPageService.findPageById(pageId, READ_PAGES, false).block(); } @@ -195,17 +200,23 @@ public void setup() { GitApplicationMetadata gitData = new GitApplicationMetadata(); gitData.setBranchName("actionServiceTest"); newApp.setGitApplicationMetadata(gitData); - gitConnectedApp = applicationPageService.createApplication(newApp, workspaceId) + gitConnectedApp = applicationPageService + .createApplication(newApp, workspaceId) .flatMap(application -> { application.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); - return applicationService.save(application) - .zipWhen(application1 -> importExportApplicationService.exportApplicationById(application1.getId(), gitData.getBranchName())); + return applicationService + .save(application) + .zipWhen(application1 -> importExportApplicationService.exportApplicationById( + application1.getId(), gitData.getBranchName())); }) // Assign the branchName to all the resources connected to the application - .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit(workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) + .flatMap(tuple -> importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, tuple.getT2(), tuple.getT1().getId(), gitData.getBranchName())) .block(); - gitConnectedPage = newPageService.findPageById(gitConnectedApp.getPages().get(0).getId(), READ_PAGES, false).block(); + gitConnectedPage = newPageService + .findPageById(gitConnectedApp.getPages().get(0).getId(), READ_PAGES, false) + .block(); branchName = gitConnectedApp.getGitApplicationMetadata().getBranchName(); } @@ -214,13 +225,15 @@ public void setup() { datasource = new Datasource(); datasource.setName("Default Database"); datasource.setWorkspaceId(workspaceId); - Plugin installed_plugin = pluginRepository.findByPackageName("installed-plugin").block(); + Plugin installed_plugin = + pluginRepository.findByPackageName("installed-plugin").block(); datasource.setPluginId(installed_plugin.getId()); jsDatasource = new Datasource(); jsDatasource.setName("Default JS Database"); jsDatasource.setWorkspaceId(workspaceId); - Plugin installedJsPlugin = pluginRepository.findByPackageName("installed-js-plugin").block(); + Plugin installedJsPlugin = + pluginRepository.findByPackageName("installed-js-plugin").block(); assert installedJsPlugin != null; jsDatasource.setPluginId(installedJsPlugin.getId()); } @@ -233,11 +246,11 @@ public void cleanup() { testPage = null; } - @Test @WithUserDetails(value = "api_user") public void refactorActionName() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("beforeNameChange"); @@ -251,7 +264,8 @@ public void refactorActionName() { dsl.put("widgetId", "firstWidgetId"); dsl.put("widgetName", "firstWidget"); JSONArray temp = new JSONArray(); - temp.addAll(List.of(new JSONObject(Map.of("key", "innerArrayReference[0].innerK")), + temp.addAll(List.of( + new JSONObject(Map.of("key", "innerArrayReference[0].innerK")), new JSONObject(Map.of("key", "innerObjectReference.k")), new JSONObject(Map.of("key", "testField")))); dsl.put("dynamicBindingPathList", temp); @@ -267,10 +281,12 @@ public void refactorActionName() { layout.setDsl(dsl); layout.setPublishedDsl(dsl); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); - - LayoutDTO firstLayout = layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + LayoutDTO firstLayout = layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); RefactorActionNameDTO refactorActionNameDTO = new RefactorActionNameDTO(); refactorActionNameDTO.setPageId(testPage.getId()); @@ -279,17 +295,20 @@ public void refactorActionName() { refactorActionNameDTO.setNewName("PostNameChange"); refactorActionNameDTO.setActionId(createdAction.getId()); - LayoutDTO postNameChangeLayout = refactoringSolution.refactorActionName(refactorActionNameDTO).block(); + LayoutDTO postNameChangeLayout = + refactoringSolution.refactorActionName(refactorActionNameDTO).block(); Mono<NewAction> postNameChangeActionMono = newActionService.findById(createdAction.getId(), READ_ACTIONS); - StepVerifier - .create(postNameChangeActionMono) + StepVerifier.create(postNameChangeActionMono) .assertNext(updatedAction -> { - assertThat(updatedAction.getUnpublishedAction().getName()).isEqualTo("PostNameChange"); - DslActionDTO actionDTO = postNameChangeLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO = postNameChangeLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO.getName()).isEqualTo("PostNameChange"); dsl.put("testField", "{{ \tPostNameChange.data }}"); @@ -304,7 +323,8 @@ public void refactorActionName() { @Test @WithUserDetails(value = "api_user") public void refactorActionName_forGitConnectedAction_success() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("beforeNameChange"); @@ -318,7 +338,8 @@ public void refactorActionName_forGitConnectedAction_success() { dsl.put("widgetId", "firstWidgetId"); dsl.put("widgetName", "firstWidget"); JSONArray temp = new JSONArray(); - temp.addAll(List.of(new JSONObject(Map.of("key", "innerArrayReference[0].innerK")), + temp.addAll(List.of( + new JSONObject(Map.of("key", "innerArrayReference[0].innerK")), new JSONObject(Map.of("key", "innerObjectReference.k")), new JSONObject(Map.of("key", "testField")))); dsl.put("dynamicBindingPathList", temp); @@ -334,10 +355,12 @@ public void refactorActionName_forGitConnectedAction_success() { layout.setDsl(dsl); layout.setPublishedDsl(dsl); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); - - LayoutDTO firstLayout = layoutActionService.updateLayout(gitConnectedPage.getId(), testApp.getId(), layout.getId(), layout, branchName).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + LayoutDTO firstLayout = layoutActionService + .updateLayout(gitConnectedPage.getId(), testApp.getId(), layout.getId(), layout, branchName) + .block(); RefactorActionNameDTO refactorActionNameDTO = new RefactorActionNameDTO(); refactorActionNameDTO.setPageId(gitConnectedPage.getId()); @@ -346,17 +369,20 @@ public void refactorActionName_forGitConnectedAction_success() { refactorActionNameDTO.setNewName("PostNameChange"); refactorActionNameDTO.setActionId(createdAction.getId()); - LayoutDTO postNameChangeLayout = refactoringSolution.refactorActionName(refactorActionNameDTO).block(); + LayoutDTO postNameChangeLayout = + refactoringSolution.refactorActionName(refactorActionNameDTO).block(); Mono<NewAction> postNameChangeActionMono = newActionService.findById(createdAction.getId(), READ_ACTIONS); - StepVerifier - .create(postNameChangeActionMono) + StepVerifier.create(postNameChangeActionMono) .assertNext(updatedAction -> { - assertThat(updatedAction.getUnpublishedAction().getName()).isEqualTo("PostNameChange"); - DslActionDTO actionDTO = postNameChangeLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO = postNameChangeLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO.getName()).isEqualTo("PostNameChange"); dsl.put("testField", "{{ \tPostNameChange.data }}"); @@ -365,9 +391,15 @@ public void refactorActionName_forGitConnectedAction_success() { innerArrayReference.add(new JSONObject(Map.of("innerK", "{{\tPostNameChange.data}}"))); assertThat(postNameChangeLayout.getDsl()).isEqualTo(dsl); assertThat(updatedAction.getDefaultResources()).isNotNull(); - assertThat(updatedAction.getDefaultResources().getActionId()).isEqualTo(updatedAction.getId()); - assertThat(updatedAction.getDefaultResources().getApplicationId()).isEqualTo(gitConnectedApp.getId()); - assertThat(updatedAction.getUnpublishedAction().getDefaultResources().getPageId()).isEqualTo(gitConnectedPage.getId()); + assertThat(updatedAction.getDefaultResources().getActionId()) + .isEqualTo(updatedAction.getId()); + assertThat(updatedAction.getDefaultResources().getApplicationId()) + .isEqualTo(gitConnectedApp.getId()); + assertThat(updatedAction + .getUnpublishedAction() + .getDefaultResources() + .getPageId()) + .isEqualTo(gitConnectedPage.getId()); }) .verifyComplete(); } @@ -375,7 +407,8 @@ public void refactorActionName_forGitConnectedAction_success() { @Test @WithUserDetails(value = "api_user") public void refactorActionNameToDeletedName() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("Query1"); @@ -387,10 +420,13 @@ public void refactorActionNameToDeletedName() { Layout layout = testPage.getLayouts().get(0); - ActionDTO firstAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO firstAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); layout.setDsl(layoutActionService.unescapeMongoSpecialCharacters(layout)); - LayoutDTO firstLayout = layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + LayoutDTO firstLayout = layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); applicationPageService.publish(testPage.getApplicationId(), true).block(); @@ -398,7 +434,8 @@ public void refactorActionNameToDeletedName() { // Create another action with the same name as the erstwhile deleted action action.setId(null); - ActionDTO secondAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO secondAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); RefactorActionNameDTO refactorActionNameDTO = new RefactorActionNameDTO(); refactorActionNameDTO.setPageId(testPage.getId()); @@ -411,12 +448,9 @@ public void refactorActionNameToDeletedName() { Mono<NewAction> postNameChangeActionMono = newActionService.findById(secondAction.getId(), READ_ACTIONS); - StepVerifier - .create(postNameChangeActionMono) + StepVerifier.create(postNameChangeActionMono) .assertNext(updatedAction -> { - assertThat(updatedAction.getUnpublishedAction().getName()).isEqualTo("NewActionName"); - }) .verifyComplete(); } @@ -424,7 +458,8 @@ public void refactorActionNameToDeletedName() { @Test @WithUserDetails(value = "api_user") public void testRefactorActionName_withInvalidName_throwsError() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionDTO action = new ActionDTO(); action.setName("beforeNameChange"); @@ -445,9 +480,12 @@ public void testRefactorActionName_withInvalidName_throwsError() { layout.setDsl(dsl); layout.setPublishedDsl(dsl); - ActionDTO createdAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO createdAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); - LayoutDTO firstLayout = layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + LayoutDTO firstLayout = layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); RefactorActionNameDTO refactorActionNameDTO = new RefactorActionNameDTO(); refactorActionNameDTO.setPageId(testPage.getId()); @@ -460,18 +498,17 @@ public void testRefactorActionName_withInvalidName_throwsError() { final Mono<LayoutDTO> layoutDTOMono = refactoringSolution.refactorActionName(refactorActionNameDTO); - StepVerifier - .create(layoutDTOMono) - .expectErrorMatches(e -> e instanceof AppsmithException && - AppsmithError.INVALID_ACTION_NAME.getMessage().equalsIgnoreCase(e.getMessage())) + StepVerifier.create(layoutDTOMono) + .expectErrorMatches(e -> e instanceof AppsmithException + && AppsmithError.INVALID_ACTION_NAME.getMessage().equalsIgnoreCase(e.getMessage())) .verify(); } - @Test @WithUserDetails(value = "api_user") public void refactorDuplicateActionName() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); String name = "duplicateName"; @@ -495,7 +532,8 @@ public void refactorDuplicateActionName() { layout.setDsl(dsl); layout.setPublishedDsl(dsl); - ActionDTO firstAction = layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + ActionDTO firstAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); ActionDTO duplicateName = new ActionDTO(); duplicateName.setName(name); @@ -518,7 +556,9 @@ public void refactorDuplicateActionName() { // Now save this action directly in the repo to create a duplicate action name scenario actionRepository.save(duplicateNameCompleteAction).block(); - LayoutDTO firstLayout = layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + LayoutDTO firstLayout = layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); RefactorActionNameDTO refactorActionNameDTO = new RefactorActionNameDTO(); refactorActionNameDTO.setPageId(testPage.getId()); @@ -527,17 +567,20 @@ public void refactorDuplicateActionName() { refactorActionNameDTO.setNewName("newName"); refactorActionNameDTO.setActionId(firstAction.getId()); - LayoutDTO postNameChangeLayout = refactoringSolution.refactorActionName(refactorActionNameDTO).block(); + LayoutDTO postNameChangeLayout = + refactoringSolution.refactorActionName(refactorActionNameDTO).block(); Mono<NewAction> postNameChangeActionMono = newActionService.findById(firstAction.getId(), READ_ACTIONS); - StepVerifier - .create(postNameChangeActionMono) + StepVerifier.create(postNameChangeActionMono) .assertNext(updatedAction -> { - assertThat(updatedAction.getUnpublishedAction().getName()).isEqualTo("newName"); - DslActionDTO actionDTO = postNameChangeLayout.getLayoutOnLoadActions().get(0).iterator().next(); + DslActionDTO actionDTO = postNameChangeLayout + .getLayoutOnLoadActions() + .get(0) + .iterator() + .next(); assertThat(actionDTO.getName()).isEqualTo("newName"); dsl.put("testField", "{{ newName.data }}"); @@ -546,11 +589,11 @@ public void refactorDuplicateActionName() { .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void tableWidgetKeyEscapeRefactorName() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); JSONObject dsl = new JSONObject(); dsl.put("widgetId", "testId"); @@ -564,7 +607,9 @@ public void tableWidgetKeyEscapeRefactorName() { Layout layout = testPage.getLayouts().get(0); layout.setDsl(dsl); - layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); RefactorNameDTO refactorNameDTO = new RefactorNameDTO(); refactorNameDTO.setPageId(testPage.getId()); @@ -572,12 +617,13 @@ public void tableWidgetKeyEscapeRefactorName() { refactorNameDTO.setOldName("Table1"); refactorNameDTO.setNewName("NewNameTable1"); - Mono<LayoutDTO> widgetRenameMono = refactoringSolution.refactorWidgetName(refactorNameDTO).cache(); + Mono<LayoutDTO> widgetRenameMono = + refactoringSolution.refactorWidgetName(refactorNameDTO).cache(); - Mono<PageDTO> pageFromRepoMono = widgetRenameMono.then(newPageService.findPageById(testPage.getId(), READ_PAGES, false)); + Mono<PageDTO> pageFromRepoMono = + widgetRenameMono.then(newPageService.findPageById(testPage.getId(), READ_PAGES, false)); - StepVerifier - .create(Mono.zip(widgetRenameMono, pageFromRepoMono)) + StepVerifier.create(Mono.zip(widgetRenameMono, pageFromRepoMono)) .assertNext(tuple -> { LayoutDTO updatedLayout = tuple.getT1(); PageDTO pageFromRepo = tuple.getT2(); @@ -586,10 +632,13 @@ public void tableWidgetKeyEscapeRefactorName() { assertThat(widgetName).isEqualTo("NewNameTable1"); Map primaryColumns1 = (Map) updatedLayout.getDsl().get("primaryColumns"); - assertThat(primaryColumns1.keySet()).containsAll(Set.of(FieldName.MONGO_UNESCAPED_ID, FieldName.MONGO_UNESCAPED_CLASS)); + assertThat(primaryColumns1.keySet()) + .containsAll(Set.of(FieldName.MONGO_UNESCAPED_ID, FieldName.MONGO_UNESCAPED_CLASS)); - Map primaryColumns2 = (Map) pageFromRepo.getLayouts().get(0).getDsl().get("primaryColumns"); - assertThat(primaryColumns2.keySet()).containsAll(Set.of(FieldName.MONGO_ESCAPE_ID, FieldName.MONGO_ESCAPE_CLASS)); + Map primaryColumns2 = + (Map) pageFromRepo.getLayouts().get(0).getDsl().get("primaryColumns"); + assertThat(primaryColumns2.keySet()) + .containsAll(Set.of(FieldName.MONGO_ESCAPE_ID, FieldName.MONGO_ESCAPE_CLASS)); }) .verifyComplete(); } @@ -597,7 +646,8 @@ public void tableWidgetKeyEscapeRefactorName() { @Test @WithUserDetails(value = "api_user") public void simpleWidgetNameRefactor() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); JSONObject dsl = new JSONObject(); dsl.put("widgetId", "simpleRefactorId"); @@ -606,7 +656,9 @@ public void simpleWidgetNameRefactor() { Layout layout = testPage.getLayouts().get(0); layout.setDsl(dsl); - layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); RefactorNameDTO refactorNameDTO = new RefactorNameDTO(); refactorNameDTO.setPageId(testPage.getId()); @@ -614,12 +666,13 @@ public void simpleWidgetNameRefactor() { refactorNameDTO.setOldName("Table1"); refactorNameDTO.setNewName("NewNameTable1"); - Mono<LayoutDTO> widgetRenameMono = refactoringSolution.refactorWidgetName(refactorNameDTO).cache(); + Mono<LayoutDTO> widgetRenameMono = + refactoringSolution.refactorWidgetName(refactorNameDTO).cache(); - Mono<PageDTO> pageFromRepoMono = widgetRenameMono.then(newPageService.findPageById(testPage.getId(), READ_PAGES, false)); + Mono<PageDTO> pageFromRepoMono = + widgetRenameMono.then(newPageService.findPageById(testPage.getId(), READ_PAGES, false)); - StepVerifier - .create(Mono.zip(widgetRenameMono, pageFromRepoMono)) + StepVerifier.create(Mono.zip(widgetRenameMono, pageFromRepoMono)) .assertNext(tuple -> { LayoutDTO updatedLayout = tuple.getT1(); PageDTO pageFromRepo = tuple.getT2(); @@ -633,7 +686,8 @@ public void simpleWidgetNameRefactor() { @Test @WithUserDetails(value = "api_user") public void testRefactorWidgetName_forDefaultWidgetsInList_updatesBothWidgetsAndTemplateReferences() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); JSONObject dsl = new JSONObject(); dsl.put("widgetId", "testId"); @@ -654,7 +708,9 @@ public void testRefactorWidgetName_forDefaultWidgetsInList_updatesBothWidgetsAnd Layout layout = testPage.getLayouts().get(0); layout.setDsl(dsl); - layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); RefactorNameDTO refactorNameDTO = new RefactorNameDTO(); refactorNameDTO.setPageId(testPage.getId()); @@ -664,11 +720,11 @@ public void testRefactorWidgetName_forDefaultWidgetsInList_updatesBothWidgetsAnd Mono<LayoutDTO> widgetRenameMono = refactoringSolution.refactorWidgetName(refactorNameDTO); - StepVerifier - .create(widgetRenameMono) + StepVerifier.create(widgetRenameMono) .assertNext(updatedLayout -> { assertTrue(((Map) updatedLayout.getDsl().get("template")).containsKey("newWidgetName")); - assertEquals("newWidgetName", + assertEquals( + "newWidgetName", ((Map) (((List) updatedLayout.getDsl().get("children")).get(0))).get("widgetName")); }) .verifyComplete(); @@ -677,7 +733,8 @@ public void testRefactorWidgetName_forDefaultWidgetsInList_updatesBothWidgetsAnd @Test @WithUserDetails(value = "api_user") public void testWidgetNameRefactor_withSimpleUpdate_refactorsActionCollectionAndItsAction() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); // Set up table widget in DSL JSONObject dsl = new JSONObject(); @@ -687,7 +744,9 @@ public void testWidgetNameRefactor_withSimpleUpdate_refactorsActionCollectionAnd Layout layout = testPage.getLayouts().get(0); layout.setDsl(dsl); - layoutActionService.updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout).block(); + layoutActionService + .updateLayout(testPage.getId(), testApp.getId(), layout.getId(), layout) + .block(); // Create an action collection that refers to the table ActionCollectionDTO actionCollectionDTO1 = new ActionCollectionDTO(); @@ -709,7 +768,8 @@ public void testWidgetNameRefactor_withSimpleUpdate_refactorsActionCollectionAnd actionCollectionDTO1.setActions(List.of(action1)); actionCollectionDTO1.setPluginType(PluginType.JS); - final ActionCollectionDTO createdActionCollectionDTO1 = layoutCollectionService.createCollection(actionCollectionDTO1).block(); + final ActionCollectionDTO createdActionCollectionDTO1 = + layoutCollectionService.createCollection(actionCollectionDTO1).block(); RefactorNameDTO refactorNameDTO = new RefactorNameDTO(); refactorNameDTO.setPageId(testPage.getId()); @@ -717,35 +777,41 @@ public void testWidgetNameRefactor_withSimpleUpdate_refactorsActionCollectionAnd refactorNameDTO.setOldName("Table1"); refactorNameDTO.setNewName("NewNameTable1"); - LayoutDTO updatedLayout = refactoringSolution.refactorWidgetName(refactorNameDTO).block(); + LayoutDTO updatedLayout = + refactoringSolution.refactorWidgetName(refactorNameDTO).block(); assert createdActionCollectionDTO1 != null; - final Mono<ActionCollection> actionCollectionMono = actionCollectionService.getById(createdActionCollectionDTO1.getId()); - final Optional<String> optional = createdActionCollectionDTO1.getDefaultToBranchedActionIdsMap().values().stream().findFirst(); + final Mono<ActionCollection> actionCollectionMono = + actionCollectionService.getById(createdActionCollectionDTO1.getId()); + final Optional<String> optional = + createdActionCollectionDTO1.getDefaultToBranchedActionIdsMap().values().stream() + .findFirst(); assert optional.isPresent(); final Mono<NewAction> actionMono = newActionService.findById(optional.get()); - StepVerifier - .create(Mono.zip(actionCollectionMono, actionMono)) + StepVerifier.create(Mono.zip(actionCollectionMono, actionMono)) .assertNext(tuple -> { final ActionCollection actionCollection = tuple.getT1(); final NewAction action = tuple.getT2(); - assertThat(actionCollection.getUnpublishedCollection().getBody()).isEqualTo("export default { x : \tNewNameTable1 }"); + assertThat(actionCollection.getUnpublishedCollection().getBody()) + .isEqualTo("export default { x : \tNewNameTable1 }"); final ActionDTO unpublishedAction = action.getUnpublishedAction(); assertThat(unpublishedAction.getJsonPathKeys().size()).isEqualTo(1); - final Optional<String> first = unpublishedAction.getJsonPathKeys().stream().findFirst(); + final Optional<String> first = + unpublishedAction.getJsonPathKeys().stream().findFirst(); assert first.isPresent(); assertThat(first.get()).isEqualTo("\tNewNameTable1"); - assertThat(unpublishedAction.getActionConfiguration().getBody()).isEqualTo("\tNewNameTable1"); + assertThat(unpublishedAction.getActionConfiguration().getBody()) + .isEqualTo("\tNewNameTable1"); }) .verifyComplete(); } - @Test @WithUserDetails(value = "api_user") public void testRefactorCollection_withModifiedName_ignoresName() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); ActionCollectionDTO originalActionCollectionDTO = new ActionCollectionDTO(); originalActionCollectionDTO.setName("originalName"); @@ -763,7 +829,9 @@ public void testRefactorCollection_withModifiedName_ignoresName() { originalActionCollectionDTO.setActions(List.of(action1)); - final ActionCollectionDTO dto = layoutCollectionService.createCollection(originalActionCollectionDTO).block(); + final ActionCollectionDTO dto = layoutCollectionService + .createCollection(originalActionCollectionDTO) + .block(); ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); assert dto != null; @@ -779,27 +847,29 @@ public void testRefactorCollection_withModifiedName_ignoresName() { testPage.getLayouts().get(0).getId(), "testAction1", "newTestAction", - "originalName" - ); + "originalName"); refactorActionNameInCollectionDTO.setRefactorAction(refactorActionNameDTO); final Mono<Tuple2<ActionCollection, NewAction>> tuple2Mono = layoutCollectionService .refactorAction(refactorActionNameInCollectionDTO) - .then(actionCollectionService.getById(dto.getId()) - .zipWith(newActionService.findById(dto.getActions().get(0).getId()))); + .then(actionCollectionService + .getById(dto.getId()) + .zipWith(newActionService.findById( + dto.getActions().get(0).getId()))); StepVerifier.create(tuple2Mono) .assertNext(tuple -> { - final ActionCollectionDTO actionCollectionDTOResult = tuple.getT1().getUnpublishedCollection(); + final ActionCollectionDTO actionCollectionDTOResult = + tuple.getT1().getUnpublishedCollection(); final NewAction newAction = tuple.getT2(); assertEquals("originalName", actionCollectionDTOResult.getName()); assertEquals("export default { x: Table1 }", actionCollectionDTOResult.getBody()); - assertEquals("newTestAction", newAction.getUnpublishedAction().getName()); - assertEquals("originalName.newTestAction", newAction.getUnpublishedAction().getFullyQualifiedName()); + assertEquals( + "newTestAction", newAction.getUnpublishedAction().getName()); + assertEquals( + "originalName.newTestAction", + newAction.getUnpublishedAction().getFullyQualifiedName()); }) .verifyComplete(); - } - - -} \ No newline at end of file +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/transactions/ImportApplicationTransactionServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/transactions/ImportApplicationTransactionServiceTest.java index c599df52624c..f7ff88c78857 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/transactions/ImportApplicationTransactionServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/transactions/ImportApplicationTransactionServiceTest.java @@ -45,12 +45,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -// All the test case are for failure or exception. Test cases for valid json file is already present in ImportExportApplicationServiceTest class +// All the test case are for failure or exception. Test cases for valid json file is already present in +// ImportExportApplicationServiceTest class @AutoConfigureDataMongo -@SpringBootTest( - properties = "de.flapdoodle.mongodb.embedded.version=5.0.5" -) +@SpringBootTest(properties = "de.flapdoodle.mongodb.embedded.version=5.0.5") @EnableAutoConfiguration() @TestPropertySource(properties = "property=C") @DirtiesContext @@ -79,49 +78,43 @@ public class ImportApplicationTransactionServiceTest { @MockBean PluginExecutorHelper pluginExecutorHelper; + Long applicationCount = 0L, pageCount = 0L, actionCount = 0L, actionCollectionCount = 0L; private ApplicationJson applicationJson = new ApplicationJson(); @BeforeEach public void setup() { - Mockito - .when(pluginExecutorHelper.getPluginExecutor(any())) - .thenReturn(Mono.just(new MockPluginExecutor())); + Mockito.when(pluginExecutorHelper.getPluginExecutor(any())).thenReturn(Mono.just(new MockPluginExecutor())); - applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json").block(); + applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json") + .block(); applicationCount = mongoTemplate.count(new Query(), Application.class); pageCount = mongoTemplate.count(new Query(), NewPage.class); actionCount = mongoTemplate.count(new Query(), NewAction.class); actionCollectionCount = mongoTemplate.count(new Query(), ActionCollection.class); } - private FilePart createFilePart(String filePath) { FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); - Flux<DataBuffer> dataBufferFlux = DataBufferUtils - .read( - new ClassPathResource(filePath), - new DefaultDataBufferFactory(), - 4096) + Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read( + new ClassPathResource(filePath), new DefaultDataBufferFactory(), 4096) .cache(); Mockito.when(filepart.content()).thenReturn(dataBufferFlux); Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.APPLICATION_JSON); return filepart; - } private Mono<ApplicationJson> createAppJson(String filePath) { FilePart filePart = createFilePart(filePath); - Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()) - .map(dataBuffer -> { - byte[] data = new byte[dataBuffer.readableByteCount()]; - dataBuffer.read(data); - DataBufferUtils.release(dataBuffer); - return new String(data); - }); + Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()).map(dataBuffer -> { + byte[] data = new byte[dataBuffer.readableByteCount()]; + dataBuffer.read(data); + DataBufferUtils.release(dataBuffer); + return new String(data); + }); return stringifiedFile .map(data -> { @@ -143,15 +136,19 @@ public void importApplication_exceptionDuringImportActions_savedPagesAndApplicat Workspace createdWorkspace = workspaceService.create(newWorkspace).block(); - Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson(createdWorkspace.getId(), applicationJson); + Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson( + createdWorkspace.getId(), applicationJson); // Check if expected exception is thrown - StepVerifier - .create(resultMono) - .expectErrorMatches(error -> error instanceof AppsmithException && error.getMessage().contains(AppsmithError.GENERIC_JSON_IMPORT_ERROR.getMessage(createdWorkspace.getId(), ""))) + StepVerifier.create(resultMono) + .expectErrorMatches(error -> error instanceof AppsmithException + && error.getMessage() + .contains(AppsmithError.GENERIC_JSON_IMPORT_ERROR.getMessage( + createdWorkspace.getId(), ""))) .verify(); - // After the import application failed in the middle of execution after the application and pages are saved to DB + // After the import application failed in the middle of execution after the application and pages are saved to + // DB // check if the saved pages reverted after the exception assertThat(mongoTemplate.count(new Query(), Application.class)).isEqualTo(applicationCount); assertThat(mongoTemplate.count(new Query(), NewPage.class)).isEqualTo(pageCount); @@ -166,17 +163,20 @@ public void importApplication_transactionExceptionDuringListActionSave_omitTrans newWorkspace.setName("Template Workspace"); Mockito.when(newActionService.importActions(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(Mono.error(new MongoTransactionException("Command failed with error 251 (NoSuchTransaction): 'Transaction 1 has been aborted.'"))); + .thenReturn(Mono.error(new MongoTransactionException( + "Command failed with error 251 (NoSuchTransaction): 'Transaction 1 has been aborted.'"))); Workspace createdWorkspace = workspaceService.create(newWorkspace).block(); - Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson(createdWorkspace.getId(), applicationJson); + Mono<Application> resultMono = importExportApplicationService.importNewApplicationInWorkspaceFromJson( + createdWorkspace.getId(), applicationJson); // Check if expected exception is thrown - StepVerifier - .create(resultMono) + StepVerifier.create(resultMono) .expectErrorMatches(error -> error instanceof AppsmithException - && error.getMessage().equals(AppsmithError.GENERIC_JSON_IMPORT_ERROR.getMessage(createdWorkspace.getId(), ""))) + && error.getMessage() + .equals(AppsmithError.GENERIC_JSON_IMPORT_ERROR.getMessage( + createdWorkspace.getId(), ""))) .verify(); } -} \ No newline at end of file +} diff --git a/app/server/pom.xml b/app/server/pom.xml index 13cdbf09216f..21de7ca26d64 100644 --- a/app/server/pom.xml +++ b/app/server/pom.xml @@ -1,42 +1,52 @@ -<?xml version="1.0"?> +<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.0.6</version> - <relativePath/> <!-- lookup parent from repository --> + <relativePath/> + <!-- lookup parent from repository --> </parent> - - <modelVersion>4.0.0</modelVersion> <groupId>com.appsmith</groupId> <artifactId>integrated</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>Integrated Appsmith</name> + <modules> + <module>reactive-caching</module> + <module>appsmith-interfaces</module> + <module>appsmith-plugins</module> + <module>appsmith-server</module> + <module>appsmith-git</module> + </modules> + <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <java.version>17</java.version> - <javadoc.disabled>true</javadoc.disabled> <deploy.disabled>true</deploy.disabled> - <source.disabled>true</source.disabled> - <project.groupId>com.appsmith</project.groupId> - <project.version>1.0-SNAPSHOT</project.version> - <!-- By default skip the dockerization step. Only activate if necessary --> - <skipDockerBuild>true</skipDockerBuild> - <spring-boot.version>3.0.6</spring-boot.version> <h2.version>2.1.210</h2.version> - <testcontainers.version>1.17.3</testcontainers.version> + <java.version>17</java.version> + <javadoc.disabled>true</javadoc.disabled> + <maven.compiler.source>${java.version}</maven.compiler.source> + <maven.compiler.target>${java.version}</maven.compiler.target> <mockito.version>4.4.0</mockito.version> <mockwebserver.version>5.0.0-alpha.2</mockwebserver.version> <okhttp3.version>4.10.0</okhttp3.version> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <project.groupId>com.appsmith</project.groupId> + <project.version>1.0-SNAPSHOT</project.version> <reactor-test.version>3.5.1</reactor-test.version> - <maven.compiler.source>${java.version}</maven.compiler.source> - <maven.compiler.target>${java.version}</maven.compiler.target> + <!-- By default skip the dockerization step. Only activate if necessary --> + <skipDockerBuild>true</skipDockerBuild> <!-- We're forcing this version temporarily to fix CVE-2022-1471--> <snakeyaml.version>2.0</snakeyaml.version> + <source.disabled>true</source.disabled> + <spotless.version>2.36.0</spotless.version> + <spring-boot.version>3.0.6</spring-boot.version> + <testcontainers.version>1.17.3</testcontainers.version> </properties> <build> @@ -67,6 +77,12 @@ <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M5</version> + <configuration> + <!-- Allow JUnit to access the test classes --> + <argLine>--add-opens java.base/java.lang=ALL-UNNAMED + --add-opens java.base/java.time=ALL-UNNAMED + --add-opens java.base/java.util=ALL-UNNAMED</argLine> + </configuration> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> @@ -80,14 +96,6 @@ </exclusions> </dependency> </dependencies> - <configuration> - <!-- Allow JUnit to access the test classes --> - <argLine> - --add-opens java.base/java.lang=ALL-UNNAMED - --add-opens java.base/java.time=ALL-UNNAMED - --add-opens java.base/java.util=ALL-UNNAMED - </argLine> - </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> @@ -112,17 +120,66 @@ </execution> </executions> </plugin> + <plugin> + <groupId>com.diffplug.spotless</groupId> + <artifactId>spotless-maven-plugin</artifactId> + <version>${spotless.version}</version> + <configuration> + <formats> + <!-- you can define as many formats as you want, each is independent --> + <format> + <!-- define the files to apply to --> + <includes> + <include>*.md</include> + <include>.gitignore</include> + </includes> + <!-- define the steps to apply to those files --> + <trimTrailingWhitespace/> + <endWithNewline/> + <indent> + <tabs>true</tabs> + <spacesPerTab>2</spacesPerTab> + </indent> + </format> + </formats> + <!-- define a language-specific format --> + <java> + <!-- Cleanthat will refactor your code, but it may break your style: apply it before your formatter --> + <cleanthat/> + <!-- apply a specific flavor of google-java-format and reflow long strings --> + <palantirJavaFormat/> + <importOrder> + <order>,javax|java,\#</order> + </importOrder> + <removeUnusedImports/> + <formatAnnotations/> + </java> + <pom> + <includes> + <include>pom.xml</include> + </includes> + <sortPom> + <encoding>UTF-8</encoding> + <keepBlankLines>true</keepBlankLines> + <nrOfIndentSpace>4</nrOfIndentSpace> + <indentBlankLines>false</indentBlankLines> + <indentSchemaLocation>true</indentSchemaLocation> + <expandEmptyElements>false</expandEmptyElements> + <sortProperties>true</sortProperties> + </sortPom> + </pom> + </configuration> + <executions> + <execution> + <goals> + <goal>apply</goal> + </goals> + <phase>compile</phase> + </execution> + </executions> + </plugin> </plugins> </build> - <modules> - <module>reactive-caching</module> - <module>appsmith-interfaces</module> - <module>appsmith-plugins</module> - <module>appsmith-server</module> - <module>appsmith-git</module> - </modules> - </project> - diff --git a/app/server/reactive-caching/pom.xml b/app/server/reactive-caching/pom.xml index ccfb5b2872cd..8b46bee19edc 100644 --- a/app/server/reactive-caching/pom.xml +++ b/app/server/reactive-caching/pom.xml @@ -1,14 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> - <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.appsmith</groupId> <artifactId>integrated</artifactId> <version>1.0-SNAPSHOT</version> </parent> - - <modelVersion>4.0.0</modelVersion> <artifactId>reactiveCaching</artifactId> <version>1.0-SNAPSHOT</version> @@ -19,7 +18,7 @@ <org.projectlombok.version>1.18.22</org.projectlombok.version> <org.testcontainers.junit-jupiter.version>1.17.2</org.testcontainers.junit-jupiter.version> <uk.co.jemos.podam.podam.version>7.2.11.RELEASE</uk.co.jemos.podam.podam.version> -<!-- <maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version>--> + <!-- <maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version>--> </properties> <dependencies> @@ -55,9 +54,9 @@ <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> - <exclusion> - <groupId>junit</groupId> - <artifactId>junit</artifactId> + <exclusion> + <groupId>junit</groupId> + <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> @@ -94,8 +93,8 @@ <scope>test</scope> <exclusions> <exclusion> - <artifactId>junit</artifactId> <groupId>junit</groupId> + <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> diff --git a/app/server/reactive-caching/src/main/java/com/appsmith/caching/CachingConfig.java b/app/server/reactive-caching/src/main/java/com/appsmith/caching/CachingConfig.java index 91afebc70faa..bc7c004bc921 100644 --- a/app/server/reactive-caching/src/main/java/com/appsmith/caching/CachingConfig.java +++ b/app/server/reactive-caching/src/main/java/com/appsmith/caching/CachingConfig.java @@ -5,5 +5,4 @@ @Configuration @ComponentScan -public class CachingConfig { -} +public class CachingConfig {} diff --git a/app/server/reactive-caching/src/main/java/com/appsmith/caching/annotations/Cache.java b/app/server/reactive-caching/src/main/java/com/appsmith/caching/annotations/Cache.java index 4ac132a03d2a..f9cb8cd87cfc 100644 --- a/app/server/reactive-caching/src/main/java/com/appsmith/caching/annotations/Cache.java +++ b/app/server/reactive-caching/src/main/java/com/appsmith/caching/annotations/Cache.java @@ -22,5 +22,4 @@ * All method arguments can be used in the expression */ String key() default ""; - } diff --git a/app/server/reactive-caching/src/main/java/com/appsmith/caching/annotations/CacheEvict.java b/app/server/reactive-caching/src/main/java/com/appsmith/caching/annotations/CacheEvict.java index 99cc9a7e9a20..001aaa0b648a 100644 --- a/app/server/reactive-caching/src/main/java/com/appsmith/caching/annotations/CacheEvict.java +++ b/app/server/reactive-caching/src/main/java/com/appsmith/caching/annotations/CacheEvict.java @@ -27,5 +27,4 @@ * Whether to evict all keys for a given cache name. */ boolean all() default false; - } diff --git a/app/server/reactive-caching/src/main/java/com/appsmith/caching/aspects/CacheAspect.java b/app/server/reactive-caching/src/main/java/com/appsmith/caching/aspects/CacheAspect.java index 85fb7c072e81..0ef5e9410e8a 100644 --- a/app/server/reactive-caching/src/main/java/com/appsmith/caching/aspects/CacheAspect.java +++ b/app/server/reactive-caching/src/main/java/com/appsmith/caching/aspects/CacheAspect.java @@ -15,12 +15,6 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.stereotype.Component; - -import com.appsmith.caching.annotations.CacheEvict; -import com.appsmith.caching.annotations.Cache; -import com.appsmith.caching.components.CacheManager; - -import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -56,15 +50,18 @@ public CacheAspect(CacheManager cacheManager) { private Mono<Object> callMonoMethodAndCache(ProceedingJoinPoint joinPoint, String cacheName, String key) { try { return ((Mono<?>) joinPoint.proceed()) - .zipWhen(value -> cacheManager.put(cacheName, key, value)) //Call CacheManager.put() to cache the object - .flatMap(value -> Mono.just(value.getT1())); //Maps to the original object + .zipWhen(value -> + cacheManager.put(cacheName, key, value)) // Call CacheManager.put() to cache the object + .flatMap(value -> Mono.just(value.getT1())); // Maps to the original object } catch (Throwable e) { - log.error("Error occurred in saving to cache when invoking function {}", joinPoint.getSignature().getName(), e); + log.error( + "Error occurred in saving to cache when invoking function {}", + joinPoint.getSignature().getName(), + e); return Mono.error(e); } } - /** * This method is used to call original Flux<T> returning method and return the the result after caching it with CacheManager * @@ -77,11 +74,15 @@ private Flux<?> callFluxMethodAndCache(ProceedingJoinPoint joinPoint, String cac try { return ((Flux<?>) joinPoint.proceed()) .collectList() // Collect Flux<T> into Mono<List<T>> - .zipWhen(value -> cacheManager.put(cacheName, key, value)) //Call CacheManager.put() to cache the list - .flatMap(value -> Mono.just(value.getT1())) //Maps to the original list - .flatMapMany(Flux::fromIterable); //Convert it back to Flux<T> + .zipWhen(value -> + cacheManager.put(cacheName, key, value)) // Call CacheManager.put() to cache the list + .flatMap(value -> Mono.just(value.getT1())) // Maps to the original list + .flatMapMany(Flux::fromIterable); // Convert it back to Flux<T> } catch (Throwable e) { - log.error("Error occurred in saving to cache when invoking function {}", joinPoint.getSignature().getName(), e); + log.error( + "Error occurred in saving to cache when invoking function {}", + joinPoint.getSignature().getName(), + e); return Flux.error(e); } } @@ -94,15 +95,15 @@ private Flux<?> callFluxMethodAndCache(ProceedingJoinPoint joinPoint, String cac * @return Key name for caching the result of the method call */ private String deriveKeyWithArguments(Object[] args) { - if (args.length == 0) { //If there are no arguments, return SimpleKey.EMPTY + if (args.length == 0) { // If there are no arguments, return SimpleKey.EMPTY return SimpleKey.EMPTY.toString(); } - if (args.length == 1) { //If there is only one argument, return its toString() value + if (args.length == 1) { // If there is only one argument, return its toString() value return args[0].toString(); } - SimpleKey simpleKey = new SimpleKey(args); //Create SimpleKey from arguments and return its toString() value + SimpleKey simpleKey = new SimpleKey(args); // Create SimpleKey from arguments and return its toString() value return simpleKey.toString(); } @@ -115,13 +116,13 @@ private String deriveKeyWithArguments(Object[] args) { * @return Key name for caching the result of the method call */ private String deriveKeyWithExpression(String expression, String[] parameterNames, Object[] args) { - //Create EvaluationContext for the expression + // Create EvaluationContext for the expression EvaluationContext evaluationContext = new StandardEvaluationContext(); for (int i = 0; i < args.length; i++) { - //Add method arguments to evaluation context + // Add method arguments to evaluation context evaluationContext.setVariable(parameterNames[i], args[i]); } - //Parse expression and return the result + // Parse expression and return the result return EXPRESSION_PARSER.parseExpression(expression).getValue(evaluationContext, String.class); } @@ -134,11 +135,11 @@ private String deriveKeyWithExpression(String expression, String[] parameterName * @return Key name for caching the result of the method call */ private String deriveKey(String expression, String[] parameterNames, Object[] args) { - if (expression.isEmpty()) { //If expression is empty, use default strategy + if (expression.isEmpty()) { // If expression is empty, use default strategy return deriveKeyWithArguments(args); } - //If expression is not empty, use expression strategy + // If expression is not empty, use expression strategy return deriveKeyWithExpression(expression, parameterNames, args); } @@ -156,26 +157,33 @@ public Object cacheable(ProceedingJoinPoint joinPoint) throws Throwable { Cache annotation = method.getAnnotation(Cache.class); String cacheName = annotation.cacheName(); - //derive key + // derive key String[] parameterNames = signature.getParameterNames(); Object[] args = joinPoint.getArgs(); String key = deriveKey(annotation.key(), parameterNames, args); Class<?> returnType = method.getReturnType(); - if (returnType.isAssignableFrom(Mono.class)) { //If method returns Mono<T> - return cacheManager.get(cacheName, key) - .switchIfEmpty(Mono.defer(() -> callMonoMethodAndCache(joinPoint, cacheName, key))); //defer the creation of Mono until subscription as it will call original function + if (returnType.isAssignableFrom(Mono.class)) { // If method returns Mono<T> + return cacheManager + .get(cacheName, key) + .switchIfEmpty(Mono.defer(() -> callMonoMethodAndCache( + joinPoint, cacheName, + key))); // defer the creation of Mono until subscription as it will call original function } - if (returnType.isAssignableFrom(Flux.class)) { //If method returns Flux<T> - return cacheManager.get(cacheName, key) - .switchIfEmpty(Mono.defer(() -> callFluxMethodAndCache(joinPoint, cacheName, key).collectList())) //defer the creation of Flux until subscription as it will call original function + if (returnType.isAssignableFrom(Flux.class)) { // If method returns Flux<T> + return cacheManager + .get(cacheName, key) + .switchIfEmpty(Mono.defer(() -> callFluxMethodAndCache(joinPoint, cacheName, key) + .collectList())) // defer the creation of Flux until subscription as it will call original + // function .map(value -> (List<?>) value) .flatMapMany(Flux::fromIterable); } - //If method does not returns Mono<T> or Flux<T> raise exception - throw new IllegalAccessException("Invalid usage of @Cache annotation. Only reactive objects Mono and Flux are supported for caching."); + // If method does not returns Mono<T> or Flux<T> raise exception + throw new IllegalAccessException( + "Invalid usage of @Cache annotation. Only reactive objects Mono and Flux are supported for caching."); } /** @@ -196,20 +204,19 @@ public Object cacheEvict(ProceedingJoinPoint joinPoint) throws Throwable { Class<?> returnType = method.getReturnType(); if (!returnType.isAssignableFrom(Mono.class)) { - throw new RuntimeException("Invalid usage of @CacheEvict for " + method.getName() + ". Only Mono<?> is allowed."); + throw new RuntimeException( + "Invalid usage of @CacheEvict for " + method.getName() + ". Only Mono<?> is allowed."); } - if (all) { //If all is true, evict all keys from the cache - return cacheManager.evictAll(cacheName) - .then((Mono<?>) joinPoint.proceed()); + if (all) { // If all is true, evict all keys from the cache + return cacheManager.evictAll(cacheName).then((Mono<?>) joinPoint.proceed()); } - //derive key + // derive key String[] parameterNames = signature.getParameterNames(); Object[] args = joinPoint.getArgs(); String key = deriveKey(annotation.key(), parameterNames, args); - //Evict key from the cache then call the original method - return cacheManager.evict(cacheName, key) - .then((Mono<?>) joinPoint.proceed()); + // Evict key from the cache then call the original method + return cacheManager.evict(cacheName, key).then((Mono<?>) joinPoint.proceed()); } } diff --git a/app/server/reactive-caching/src/main/java/com/appsmith/caching/components/CacheManager.java b/app/server/reactive-caching/src/main/java/com/appsmith/caching/components/CacheManager.java index d433dd49980f..c74ea87c7abc 100644 --- a/app/server/reactive-caching/src/main/java/com/appsmith/caching/components/CacheManager.java +++ b/app/server/reactive-caching/src/main/java/com/appsmith/caching/components/CacheManager.java @@ -7,7 +7,7 @@ public interface CacheManager { * This will log the cache stats with INFO severity. */ void logStats(); - + /** * This will get item from the cache, Mono.empty() if not found. * @param cacheName The name of the cache. diff --git a/app/server/reactive-caching/src/main/java/com/appsmith/caching/components/RedisCacheManagerImpl.java b/app/server/reactive-caching/src/main/java/com/appsmith/caching/components/RedisCacheManagerImpl.java index 2afbeb892f1f..7488be2bfd10 100644 --- a/app/server/reactive-caching/src/main/java/com/appsmith/caching/components/RedisCacheManagerImpl.java +++ b/app/server/reactive-caching/src/main/java/com/appsmith/caching/components/RedisCacheManagerImpl.java @@ -41,7 +41,13 @@ private void ensureStats(String cacheName) { public void logStats() { statsMap.keySet().forEach(key -> { CacheStats stats = statsMap.get(key); - log.debug("Cache {} stats: hits = {}, misses = {}, singleEvictions = {}, completeEvictions = {}", key, stats.getHits(), stats.getMisses(), stats.getSingleEvictions(), stats.getCompleteEvictions()); + log.debug( + "Cache {} stats: hits = {}, misses = {}, singleEvictions = {}, completeEvictions = {}", + key, + stats.getHits(), + stats.getMisses(), + stats.getSingleEvictions(), + stats.getCompleteEvictions()); }); } @@ -53,7 +59,8 @@ public void resetStats() { } @Autowired - public RedisCacheManagerImpl(ReactiveRedisTemplate<String, Object> reactiveRedisTemplate, + public RedisCacheManagerImpl( + ReactiveRedisTemplate<String, Object> reactiveRedisTemplate, ReactiveRedisOperations<String, String> reactiveRedisOperations) { this.reactiveRedisTemplate = reactiveRedisTemplate; this.reactiveRedisOperations = reactiveRedisOperations; @@ -63,18 +70,20 @@ public RedisCacheManagerImpl(ReactiveRedisTemplate<String, Object> reactiveRedis public Mono<Object> get(String cacheName, String key) { ensureStats(cacheName); String path = cacheName + ":" + key; - return reactiveRedisTemplate.opsForValue().get(path) - .map(value -> { - //This is a cache hit, update stats and return value - statsMap.get(cacheName).getHits().incrementAndGet(); - return value; - }) - .switchIfEmpty(Mono.defer(() -> { - //This is a cache miss, update stats and return empty - statsMap.get(cacheName).getMisses().incrementAndGet(); - log.debug("Cache miss for key {}", path); - return Mono.empty(); - })); + return reactiveRedisTemplate + .opsForValue() + .get(path) + .map(value -> { + // This is a cache hit, update stats and return value + statsMap.get(cacheName).getHits().incrementAndGet(); + return value; + }) + .switchIfEmpty(Mono.defer(() -> { + // This is a cache miss, update stats and return empty + statsMap.get(cacheName).getMisses().incrementAndGet(); + log.debug("Cache miss for key {}", path); + return Mono.empty(); + })); } @Override @@ -99,12 +108,9 @@ public Mono<Void> evictAll(String cacheName) { ensureStats(cacheName); statsMap.get(cacheName).getCompleteEvictions().incrementAndGet(); String path = cacheName; - //Remove all matching keys with wildcard + // Remove all matching keys with wildcard final String script = - "for _,k in ipairs(redis.call('keys','" + path + ":*'))" + - " do redis.call('del',k) " + - "end"; + "for _,k in ipairs(redis.call('keys','" + path + ":*'))" + " do redis.call('del',k) " + "end"; return reactiveRedisOperations.execute(RedisScript.of(script)).then(); } - } diff --git a/app/server/reactive-caching/src/main/java/com/appsmith/caching/model/CacheStats.java b/app/server/reactive-caching/src/main/java/com/appsmith/caching/model/CacheStats.java index cd39a54b1ad9..6ec5b391773f 100644 --- a/app/server/reactive-caching/src/main/java/com/appsmith/caching/model/CacheStats.java +++ b/app/server/reactive-caching/src/main/java/com/appsmith/caching/model/CacheStats.java @@ -1,10 +1,10 @@ package com.appsmith.caching.model; -import java.util.concurrent.atomic.AtomicInteger; - import lombok.Data; import lombok.NoArgsConstructor; +import java.util.concurrent.atomic.AtomicInteger; + /** * This is a CacheStats class that is used to store the stats of a cache. * It is maintained for all cacheNames in the memory diff --git a/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/configuration/RedisTestContainerConfig.java b/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/configuration/RedisTestContainerConfig.java index 106a06b06556..931fc8fa1d4d 100644 --- a/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/configuration/RedisTestContainerConfig.java +++ b/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/configuration/RedisTestContainerConfig.java @@ -23,15 +23,15 @@ public class RedisTestContainerConfig { @Container - public static GenericContainer redisContainer = new GenericContainer(DockerImageName.parse("redis:6.2.6-alpine")) - .withExposedPorts(6379); + public static GenericContainer redisContainer = + new GenericContainer(DockerImageName.parse("redis:6.2.6-alpine")).withExposedPorts(6379); @Bean @Primary public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() { redisContainer.start(); - RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration(redisContainer.getHost(), - redisContainer.getMappedPort(6379)); + RedisStandaloneConfiguration redisConf = + new RedisStandaloneConfiguration(redisContainer.getHost(), redisContainer.getMappedPort(6379)); return new LettuceConnectionFactory(redisConf); } @@ -40,9 +40,11 @@ public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() { ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) { RedisSerializer<String> keySerializer = new StringRedisSerializer(); RedisSerializer<Object> defaultSerializer = new GenericJackson2JsonRedisSerializer(); - RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext - .<String, Object>newSerializationContext(defaultSerializer).key(keySerializer).hashKey(keySerializer) - .build(); + RedisSerializationContext<String, Object> serializationContext = + RedisSerializationContext.<String, Object>newSerializationContext(defaultSerializer) + .key(keySerializer) + .hashKey(keySerializer) + .build(); return new ReactiveRedisTemplate<>(factory, serializationContext); } @@ -52,7 +54,8 @@ ReactiveRedisOperations<String, String> reactiveRedisOperations(ReactiveRedisCon Jackson2JsonRedisSerializer<String> serializer = new Jackson2JsonRedisSerializer<>(String.class); RedisSerializationContext.RedisSerializationContextBuilder<String, String> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer()); - RedisSerializationContext<String, String> context = builder.value(serializer).build(); + RedisSerializationContext<String, String> context = + builder.value(serializer).build(); return new ReactiveRedisTemplate<>(factory, context); } -} \ No newline at end of file +} diff --git a/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/model/TestModel.java b/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/model/TestModel.java index e50c5b29c200..87f64c5fcfaa 100644 --- a/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/model/TestModel.java +++ b/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/model/TestModel.java @@ -1,7 +1,5 @@ package com.appsmith.testcaching.model; -import java.time.Instant; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/service/CacheTestService.java b/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/service/CacheTestService.java index ed8b2288f667..3d7379014b82 100644 --- a/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/service/CacheTestService.java +++ b/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/service/CacheTestService.java @@ -1,21 +1,19 @@ package com.appsmith.testcaching.service; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; - -import org.springframework.stereotype.Service; - +import com.appsmith.caching.annotations.Cache; import com.appsmith.caching.annotations.CacheEvict; import com.appsmith.testcaching.model.ArgumentModel; import com.appsmith.testcaching.model.TestModel; -import com.appsmith.caching.annotations.Cache; - +import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import uk.co.jemos.podam.api.PodamFactory; import uk.co.jemos.podam.api.PodamFactoryImpl; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + @Service public class CacheTestService { @@ -60,7 +58,7 @@ public Mono<Void> evictAllObjects() { @Cache(cacheName = "listcache") public Flux<TestModel> getListFor(String id) { List<TestModel> testModels = new ArrayList<>(); - for(int i = 0;i < 5;i++) { + for (int i = 0; i < 5; i++) { TestModel model = factory.manufacturePojo(TestModel.class); model.setId(id); testModels.add(model); @@ -86,7 +84,6 @@ public Mono<Void> evictListFor(String id) { public Mono<Void> evictAllLists() { return Mono.empty(); } - /** * This method is used to test SPEL expression in the caching annotation. diff --git a/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/test/TestCachingMethods.java b/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/test/TestCachingMethods.java index 85f787fd51c0..03118403f240 100644 --- a/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/test/TestCachingMethods.java +++ b/app/server/reactive-caching/src/test/java/com/appsmith/testcaching/test/TestCachingMethods.java @@ -1,23 +1,21 @@ package com.appsmith.testcaching.test; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.util.List; - +import com.appsmith.caching.components.CacheManager; +import com.appsmith.testcaching.model.ArgumentModel; +import com.appsmith.testcaching.model.TestModel; +import com.appsmith.testcaching.service.CacheTestService; +import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import com.appsmith.caching.components.CacheManager; -import com.appsmith.testcaching.model.ArgumentModel; -import com.appsmith.testcaching.model.TestModel; -import com.appsmith.testcaching.service.CacheTestService; +import java.util.List; -import lombok.extern.slf4j.Slf4j; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; @SpringBootTest @TestInstance(TestInstance.Lifecycle.PER_CLASS) @@ -51,15 +49,17 @@ public void testCacheAndEvictMono() { */ @Test public void testCacheAndEvictFlux() { - List<TestModel> model = cacheTestService.getListFor("test1").collectList().block(); - List<TestModel> model2 = cacheTestService.getListFor("test1").collectList().block(); + List<TestModel> model = + cacheTestService.getListFor("test1").collectList().block(); + List<TestModel> model2 = + cacheTestService.getListFor("test1").collectList().block(); assertArrayEquals(model.toArray(), model2.toArray()); cacheTestService.evictListFor("test1").block(); // If not evicted with above call, this will return the same object model2 = cacheTestService.getListFor("test1").collectList().block(); - for(int i = model.size() - 1; i >= 0; i--) { + for (int i = model.size() - 1; i >= 0; i--) { assertNotEquals(model.get(i), model2.get(i)); } } @@ -86,8 +86,10 @@ public void testEvictAll() { */ @Test public void testExpression() { - TestModel model = cacheTestService.getObjectForWithKey(ArgumentModel.of("test1")).block(); - TestModel model2 = cacheTestService.getObjectForWithKey(ArgumentModel.of("test1")).block(); + TestModel model = + cacheTestService.getObjectForWithKey(ArgumentModel.of("test1")).block(); + TestModel model2 = + cacheTestService.getObjectForWithKey(ArgumentModel.of("test1")).block(); assertEquals(model, model2); cacheTestService.evictObjectForWithKey("test1").block(); @@ -106,7 +108,7 @@ public void measurePerformance() { TestModel model1 = cacheTestService.getObjectFor("test1").block(); long initialTime = System.nanoTime(); int count = 100; - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { cacheTestService.getObjectFor("test1").block(); } long finalTime = System.nanoTime();
bda53ce421faa889a2624632eab177782ef0f9fb
2024-02-12 06:29:17
yatinappsmith
ci: Trigger auto-analysis for cypress runs (#30659)
false
Trigger auto-analysis for cypress runs (#30659)
ci
diff --git a/.github/workflows/test-build-docker-image.yml b/.github/workflows/test-build-docker-image.yml index 0ca0c30b85ba..15adab6ce96a 100644 --- a/.github/workflows/test-build-docker-image.yml +++ b/.github/workflows/test-build-docker-image.yml @@ -201,6 +201,32 @@ jobs: SLACK_FOOTER: "Push Workflow" SLACK_MESSAGE: ${{steps.slack_notification.outputs.slack_message}} + # Dump github context for future use + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJSON(github) }} + run: | + echo "$GITHUB_CONTEXT" + echo ${{ github.repository }} + + # This step triggers an external workflow for automated analysis of Cypress test runs. + - name: Invoke Automated analysis workflow + run: | + curl --location --request POST ${{secrets.CYPRESS_WORKFLOW_API}} \ + --header 'x-appsmith-key: ${{ secrets.CYPRESS_WORKFLOW_KEY }}' \ + --header 'Content-Type: application/json' \ + --data-raw '{ "workflow_id" : ${{ github.run_id }} , + "commit_id" : "${{ github.sha }}" , + "repo" : "${{ github.event.repository.full_name }}" , + "task" : "${{ github.job }}" , + "workflow_type" : "${{ github.event_name }}", + "workflow_name" : "${{ github.workflow }}", + "job_id" : "", + "job_data": { + "ci_test_result_sample_data" : "sample_data" + } + }' + # Force save the CI failed spec list into a cache - name: Store the combined run result for CI if: needs.ci-test.result != 'success'
eb54d7d325d2a6510454d5d0dc57d24bb41d7a04
2022-02-12 15:10:52
Anagh Hegde
fix: Remove default error fields for git-sync related analytics for success events (#11097)
false
Remove default error fields for git-sync related analytics for success events (#11097)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java index 1d722d10044f..f4cfb745b750 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java @@ -2242,17 +2242,20 @@ private Mono<Application> addAnalyticsForGitOperation(String eventName, ? "" : GitUtils.getGitProviderName(application.getGitApplicationMetadata().getRemoteUrl()); + Map<String, Object> analyticsProps = new HashMap<>(Map.of("applicationId", defaultApplicationId, + "organizationId", defaultIfNull(application.getOrganizationId(), ""), + "branchApplicationId", defaultIfNull(application.getId(), ""), + "isRepoPrivate", defaultIfNull(isRepoPrivate, ""), + "gitHostingProvider", defaultIfNull(gitHostingProvider, "") + )); + return sessionUserService.getCurrentUser() .map(user -> { - final Map<String, Object> analyticsProps = Map.of( - "applicationId", defaultApplicationId, - "organizationId", defaultIfNull(application.getOrganizationId(), ""), - "branchApplicationId", defaultIfNull(application.getId(), ""), - "errorMessage", defaultIfNull(errorMessage, ""), - "errorType", defaultIfNull(errorType, ""), - "isRepoPrivate", defaultIfNull(isRepoPrivate, ""), - "gitHostingProvider", defaultIfNull(gitHostingProvider, "") - ); + // Do not include the error data points in the map for success states + if(!StringUtils.isEmptyOrNull(errorMessage) || !StringUtils.isEmptyOrNull(errorType)) { + analyticsProps.put("errorMessage", errorMessage); + analyticsProps.put("errorType", errorType); + } analyticsService.sendEvent(eventName, user.getUsername(), analyticsProps); return application; });
6f4543039517cf13589a3de3c9275866d007997d
2022-09-13 11:56:37
NandanAnantharamu
test: updated test and dsl (#16656)
false
updated test and dsl (#16656)
test
diff --git a/app/client/cypress/fixtures/tableV2NewDslWithPagination.json b/app/client/cypress/fixtures/tableV2NewDslWithPagination.json index cfda5996f7f3..2a7f865dd500 100644 --- a/app/client/cypress/fixtures/tableV2NewDslWithPagination.json +++ b/app/client/cypress/fixtures/tableV2NewDslWithPagination.json @@ -2,170 +2,287 @@ "dsl": { "widgetName": "MainContainer", "backgroundColor": "none", - "rightColumn": 1224, - "snapColumns": 16, + "rightColumn": 4896, + "snapColumns": 64, "detachFromLayout": true, "widgetId": "0", "topRow": 0, - "bottomRow": 1280, + "bottomRow": 1130, "containerStyle": "none", - "snapRows": 33, + "snapRows": 125, "parentRowSpace": 1, "type": "CANVAS_WIDGET", "canExtend": true, - "version": 8, + "version": 60, "minHeight": 1292, + "dynamicTriggerPathList": [], "parentColumnSpace": 1, "dynamicBindingPathList": [], "leftColumn": 0, - "children": [{ - "isVisible": true, - "isVisiblePagination": true, - "isVisibleSearch": true, - "isVisibleFilter": true, - "label": "Data", - "widgetName": "Table1", - "searchKey": "", - "tableData": "{{[\n {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 2736212,\n \"email\": \"[email protected]\",\n \"userName\": \"Lindsay Ferguson\",\n \"productName\": \"Tuna Salad\",\n \"orderAmount\": 9.99\n },\n {\n \"id\": 6788734,\n \"email\": \"[email protected]\",\n \"userName\": \"Tobias Funke\",\n \"productName\": \"Beef steak\",\n \"orderAmount\": 19.99\n },\n {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 2736212,\n \"email\": \"[email protected]\",\n \"userName\": \"Lindsay Ferguson\",\n \"productName\": \"Tuna Salad\",\n \"orderAmount\": 9.99\n },\n {\n \"id\": 6788734,\n \"email\": \"[email protected]\",\n \"userName\": \"Tobias Funke\",\n \"productName\": \"Beef steak\",\n \"orderAmount\": 19.99\n }\n]}}", - "type": "TABLE_WIDGET_V2", - "isLoading": false, - "parentColumnSpace": 74, - "parentRowSpace": 40, - "leftColumn": 2, - "rightColumn": 10, - "topRow": 12, - "bottomRow": 19, - "parentId": "0", - "widgetId": "sb070qr2ir", - "dynamicBindingPathList": [], - "columnOrder": [ - "id", - "email", - "userName", - "productName", - "orderAmount" - ], - "aliasMap": { - "id": "id", - "email": "email", - "userName": "userName", - "productName": "productName", - "orderAmount": "orderAmount" - }, - "childStylesheet": { - "button": { - "buttonColor": "{{appsmith.theme.colors.primaryColor}}", - "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", - "boxShadow": "none" + "children": [ + { + "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", + "isVisibleDownload": true, + "iconSVG": "/static/media/icon.db8a9cbd2acd22a31ea91cc37ea2a46c.svg", + "topRow": 83, + "isSortable": true, + "type": "TABLE_WIDGET_V2", + "inlineEditingSaveOption": "ROW_LEVEL", + "animateLoading": true, + "dynamicBindingPathList": [ + { + "key": "accentColor" + }, + { + "key": "borderRadius" + }, + { + "key": "boxShadow" + }, + { + "key": "childStylesheet.button.buttonColor" + }, + { + "key": "childStylesheet.button.borderRadius" + }, + { + "key": "childStylesheet.menuButton.menuColor" + }, + { + "key": "childStylesheet.menuButton.borderRadius" + }, + { + "key": "childStylesheet.iconButton.buttonColor" + }, + { + "key": "childStylesheet.iconButton.borderRadius" + }, + { + "key": "childStylesheet.editActions.saveButtonColor" + }, + { + "key": "childStylesheet.editActions.saveBorderRadius" + }, + { + "key": "childStylesheet.editActions.discardButtonColor" + }, + { + "key": "childStylesheet.editActions.discardBorderRadius" + }, + { + "key": "tableData" + }, + { + "key": "primaryColumns.id.computedValue" + }, + { + "key": "primaryColumns.email.computedValue" + }, + { + "key": "primaryColumns.userName.computedValue" + }, + { + "key": "primaryColumns.productName.computedValue" + }, + { + "key": "primaryColumns.orderAmount.computedValue" + } + ], + "leftColumn": 16, + "delimiter": ",", + "defaultSelectedRowIndex": 0, + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "isVisibleFilters": true, + "isVisible": true, + "enableClientSideSearch": true, + "version": 1, + "totalRecordsCount": 0, + "isLoading": false, + "childStylesheet": { + "button": { + "buttonColor": "{{appsmith.theme.colors.primaryColor}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "boxShadow": "none" + }, + "menuButton": { + "menuColor": "{{appsmith.theme.colors.primaryColor}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "boxShadow": "none" + }, + "iconButton": { + "buttonColor": "{{appsmith.theme.colors.primaryColor}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "boxShadow": "none" + }, + "editActions": { + "saveButtonColor": "{{appsmith.theme.colors.primaryColor}}", + "saveBorderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "discardButtonColor": "{{appsmith.theme.colors.primaryColor}}", + "discardBorderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}" + } }, - "menuButton": { - "menuColor": "{{appsmith.theme.colors.primaryColor}}", - "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", - "boxShadow": "none" + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "defaultSelectedRowIndices": [ + 0 + ], + "widgetName": "Table1", + "defaultPageSize": 0, + "columnOrder": [ + "id", + "email", + "userName", + "productName", + "orderAmount" + ], + "dynamicPropertyPathList": [], + "displayName": "Table", + "bottomRow": 111, + "columnWidthMap": { + "task": 245, + "step": 62, + "status": 75 }, - "iconButton": { - "menuColor": "{{appsmith.theme.colors.primaryColor}}", - "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", - "boxShadow": "none" - } - }, - "primaryColumns": { - "id": { - "index": 0, - "width": 150, - "id": "id", - "alias": "id", - "originalId": "id", - "horizontalAlignment": "LEFT", - "verticalAlignment": "CENTER", - "columnType": "text", - "textColor": "#4E5D78", - "textSize": "PARAGRAPH", - "fontStyle": "NORMAL", - "enableFilter": true, - "enableSort": true, - "isVisible": true, - "isDerived": false, - "label": "id", - "computedValue": "" + "parentRowSpace": 10, + "hideCard": false, + "parentColumnSpace": 9.96875, + "dynamicTriggerPathList": [], + "primaryColumns": { + "id": { + "allowCellWrapping": false, + "index": 0, + "width": 150, + "originalId": "id", + "id": "id", + "alias": "id", + "horizontalAlignment": "LEFT", + "verticalAlignment": "CENTER", + "columnType": "text", + "textSize": "0.875rem", + "enableFilter": true, + "enableSort": true, + "isVisible": true, + "isDisabled": false, + "isCellEditable": false, + "isEditable": false, + "isCellVisible": true, + "isDerived": false, + "label": "id", + "isSaveVisible": true, + "isDiscardVisible": true, + "computedValue": "{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow[\"id\"]))}}" + }, + "email": { + "allowCellWrapping": false, + "index": 1, + "width": 150, + "originalId": "email", + "id": "email", + "alias": "email", + "horizontalAlignment": "LEFT", + "verticalAlignment": "CENTER", + "columnType": "text", + "textSize": "0.875rem", + "enableFilter": true, + "enableSort": true, + "isVisible": true, + "isDisabled": false, + "isCellEditable": false, + "isEditable": false, + "isCellVisible": true, + "isDerived": false, + "label": "email", + "isSaveVisible": true, + "isDiscardVisible": true, + "computedValue": "{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow[\"email\"]))}}" + }, + "userName": { + "allowCellWrapping": false, + "index": 2, + "width": 150, + "originalId": "userName", + "id": "userName", + "alias": "userName", + "horizontalAlignment": "LEFT", + "verticalAlignment": "CENTER", + "columnType": "text", + "textSize": "0.875rem", + "enableFilter": true, + "enableSort": true, + "isVisible": true, + "isDisabled": false, + "isCellEditable": false, + "isEditable": false, + "isCellVisible": true, + "isDerived": false, + "label": "userName", + "isSaveVisible": true, + "isDiscardVisible": true, + "computedValue": "{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow[\"userName\"]))}}" + }, + "productName": { + "allowCellWrapping": false, + "index": 3, + "width": 150, + "originalId": "productName", + "id": "productName", + "alias": "productName", + "horizontalAlignment": "LEFT", + "verticalAlignment": "CENTER", + "columnType": "text", + "textSize": "0.875rem", + "enableFilter": true, + "enableSort": true, + "isVisible": true, + "isDisabled": false, + "isCellEditable": false, + "isEditable": false, + "isCellVisible": true, + "isDerived": false, + "label": "productName", + "isSaveVisible": true, + "isDiscardVisible": true, + "computedValue": "{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow[\"productName\"]))}}" + }, + "orderAmount": { + "allowCellWrapping": false, + "index": 4, + "width": 150, + "originalId": "orderAmount", + "id": "orderAmount", + "alias": "orderAmount", + "horizontalAlignment": "LEFT", + "verticalAlignment": "CENTER", + "columnType": "text", + "textSize": "0.875rem", + "enableFilter": true, + "enableSort": true, + "isVisible": true, + "isDisabled": false, + "isCellEditable": false, + "isEditable": false, + "isCellVisible": true, + "isDerived": false, + "label": "orderAmount", + "isSaveVisible": true, + "isDiscardVisible": true, + "computedValue": "{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow[\"orderAmount\"]))}}" + } }, - "email": { - "index": 1, - "width": 150, - "id": "email", - "alias": "email", - "originalId": "email", - "horizontalAlignment": "LEFT", - "verticalAlignment": "CENTER", - "columnType": "text", - "textColor": "#4E5D78", - "textSize": "PARAGRAPH", - "fontStyle": "NORMAL", - "enableFilter": true, - "enableSort": true, - "isVisible": true, - "isDerived": false, - "label": "email", - "computedValue": "" - }, - "userName": { - "index": 2, - "width": 150, - "id": "userName", - "alias": "userName", - "originalId": "userName", - "horizontalAlignment": "LEFT", - "verticalAlignment": "CENTER", - "columnType": "text", - "textColor": "#4E5D78", - "textSize": "PARAGRAPH", - "fontStyle": "NORMAL", - "enableFilter": true, - "enableSort": true, - "isVisible": true, - "isDerived": false, - "label": "userName", - "computedValue": "" - }, - "productName": { - "index": 3, - "width": 150, - "id": "productName", - "alias": "productName", - "originalId": "productName", - "horizontalAlignment": "LEFT", - "verticalAlignment": "CENTER", - "columnType": "text", - "textColor": "#4E5D78", - "textSize": "PARAGRAPH", - "fontStyle": "NORMAL", - "enableFilter": true, - "enableSort": true, - "isVisible": true, - "isDerived": false, - "label": "productName", - "computedValue": "" - }, - "orderAmount": { - "index": 4, - "width": 150, - "id": "orderAmount", - "alias": "orderAmount", - "originalId": "orderAmount", - "horizontalAlignment": "LEFT", - "verticalAlignment": "CENTER", - "columnType": "text", - "textColor": "#4E5D78", - "textSize": "PARAGRAPH", - "fontStyle": "NORMAL", - "enableFilter": true, - "enableSort": true, - "isVisible": true, - "isDerived": false, - "label": "orderAmount", - "computedValue": "" - } + "key": "rxs6wup9fz", + "isDeprecated": false, + "rightColumn": 50, + "textSize": "0.875rem", + "widgetId": "8o3mdylmxa", + "tableData": "{{[\n {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 2736212,\n \"email\": \"[email protected]\",\n \"userName\": \"Lindsay Ferguson\",\n \"productName\": \"Tuna Salad\",\n \"orderAmount\": 9.99\n },\n {\n \"id\": 6788734,\n \"email\": \"[email protected]\",\n \"userName\": \"Tobias Funke\",\n \"productName\": \"Beef steak\",\n \"orderAmount\": 19.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n }\n]}}", + "label": "Data", + "searchKey": "", + "parentId": "0", + "renderMode": "CANVAS", + "horizontalAlignment": "LEFT", + "isVisibleSearch": true, + "isVisiblePagination": true, + "verticalAlignment": "CENTER" } - }] + ] } } \ No newline at end of file diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV1/Table_Widget_Add_button_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV1/Table_Widget_Add_button_spec.js index 506c5f80d768..ab6f5c4967eb 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV1/Table_Widget_Add_button_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV1/Table_Widget_Add_button_spec.js @@ -190,7 +190,7 @@ describe("Table Widget property pane feature validation", function() { const color1 = "rgb(255, 255, 0)"; cy.get(widgetsPage.menuColor) .clear() - .click() + .click({force:true}) .type(color1); cy.get(widgetsPage.tableBtn).should("have.css", "background-color", color1); @@ -198,7 +198,7 @@ describe("Table Widget property pane feature validation", function() { const color2 = "rgb(255, 0, 0)"; cy.get(widgetsPage.menuColor) .clear() - .click() + .click({force:true}) // following wait is required to reproduce #9526 .wait(500) .type(color2); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_PropertyPane_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_PropertyPane_spec.js index be2b3d822910..9f05e35c5f74 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_PropertyPane_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_PropertyPane_spec.js @@ -240,7 +240,7 @@ describe("Table Widget V2 property pane feature validation", function() { .children() .contains("URL") .click(); - cy.get(".t--property-control-visible span.bp3-control-indicator").click(); + // cy.get(".t--property-control-visible span.bp3-control-indicator").click(); cy.wait("@updateLayout"); cy.moveToStyleTab(); // Verifying Center Alignment
afb5bfcd700beceed72628736fad2988076ddc6e
2021-09-23 19:07:39
Shrikant Sharat Kandula
ci: The package job needs prelude (#7768)
false
The package job needs prelude (#7768)
ci
diff --git a/.github/workflows/github-release.yml b/.github/workflows/github-release.yml index 71b58fe31a20..fb06da6cd591 100644 --- a/.github/workflows/github-release.yml +++ b/.github/workflows/github-release.yml @@ -179,7 +179,7 @@ jobs: path: app/rts/dist/ package: - needs: [buildClient, buildServer, buildRts] + needs: [prelude, buildClient, buildServer, buildRts] runs-on: ubuntu-latest
db614c3a31955ae3fe4983c075412131eef1fb59
2023-05-22 09:50:47
Parthvi
test: fix SwitchBranch_Spec flaky test (#23573)
false
fix SwitchBranch_Spec flaky test (#23573)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/SwitchBranches_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/SwitchBranches_spec.js index d430f4f9e6ac..633ab0228288 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/SwitchBranches_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/SwitchBranches_spec.js @@ -220,6 +220,7 @@ describe("Git sync:", function () { cy.wait(400); cy.get(gitSyncLocators.branchListItem).contains("master").click(); cy.wait(4000); + _.entityExplorer.NavigateToSwitcher("Widgets"); cy.get(`.t--entity.page`) .contains("Page1") .closest(".t--entity")
228af868612d28ebdc40af49d99a0196c12f31fd
2024-09-11 16:50:55
Ankita Kinger
feat: Action redesign: Updating the config for Firestore plugin to use sections and zones format (#36097)
false
Action redesign: Updating the config for Firestore plugin to use sections and zones format (#36097)
feat
diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/addToCollection.json b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/addToCollection.json index 00c1dee01838..c8394db1e544 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/addToCollection.json +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/addToCollection.json @@ -1,32 +1,50 @@ { + "controlType": "SECTION_V2", "identifier": "ADD_TO_COLLECTION", - "controlType": "SECTION", "conditionals": { "show": "{{actionConfiguration.formData.command.data === 'ADD_TO_COLLECTION'}}" }, "children": [ { - "label": "Collection/Document path", - "configProperty": "actionConfiguration.formData.path.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": true, - "initialValue": "" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "ADD-TO-COLLECTION-Z1", + "children": [ + { + "label": "Collection/Document path", + "configProperty": "actionConfiguration.formData.path.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": true, + "initialValue": "" + } + ] }, { - "label": "Body", - "configProperty": "actionConfiguration.formData.body.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "initialValue": "", - "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "ADD-TO-COLLECTION-Z2", + "children": [ + { + "label": "Body", + "configProperty": "actionConfiguration.formData.body.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "initialValue": "", + "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + } + ] }, { - "label": "Timestamp Path", - "configProperty": "actionConfiguration.formData.timestampValuePath.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "initialValue": "", - "placeholderText": "[ \"checkinLog.timestampKey\" ]" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "ADD-TO-COLLECTION-Z3", + "children": [ + { + "label": "Timestamp Path", + "configProperty": "actionConfiguration.formData.timestampValuePath.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "initialValue": "", + "placeholderText": "[ \"checkinLog.timestampKey\" ]" + } + ] } ] } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/createDocument.json b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/createDocument.json index 2da8632fd281..18fc12a2f3b5 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/createDocument.json +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/createDocument.json @@ -1,32 +1,50 @@ { + "controlType": "SECTION_V2", "identifier": "CREATE_DOCUMENT", - "controlType": "SECTION", "conditionals": { "show": "{{actionConfiguration.formData.command.data === 'CREATE_DOCUMENT'}}" }, "children": [ { - "label": "Collection Name", - "configProperty": "actionConfiguration.formData.path.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": true, - "initialValue": "" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "CREATE-DOCUMENT-Z1", + "children": [ + { + "label": "Collection Name", + "configProperty": "actionConfiguration.formData.path.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": true, + "initialValue": "" + } + ] }, { - "label": "Body", - "configProperty": "actionConfiguration.formData.body.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "initialValue": "", - "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "CREATE-DOCUMENT-Z2", + "children": [ + { + "label": "Body", + "configProperty": "actionConfiguration.formData.body.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "initialValue": "", + "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + } + ] }, { - "label": "Timestamp Path", - "configProperty": "actionConfiguration.formData.timestampValuePath.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "initialValue": "", - "placeholderText": "[ \"checkinLog.timestampKey\" ]" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "CREATE-DOCUMENT-Z3", + "children": [ + { + "label": "Timestamp Path", + "configProperty": "actionConfiguration.formData.timestampValuePath.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "initialValue": "", + "placeholderText": "[ \"checkinLog.timestampKey\" ]" + } + ] } ] } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/deleteDocument.json b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/deleteDocument.json index 651fc4cd2943..5943ec682a37 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/deleteDocument.json +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/deleteDocument.json @@ -1,18 +1,24 @@ { + "controlType": "SECTION_V2", "identifier": "DELETE_DOCUMENT", - "controlType": "SECTION", "conditionals": { "show": "{{actionConfiguration.formData.command.data === 'DELETE_DOCUMENT'}}" }, "children": [ { - "label": "Collection/Document path", - "configProperty": "actionConfiguration.formData.path.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": true, - "placeholderText": "collection/{{Table1.selectedRow._ref}}", - "initialValue": "" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "DELETE-DOCUMENT-Z1", + "children": [ + { + "label": "Collection/Document path", + "configProperty": "actionConfiguration.formData.path.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": true, + "placeholderText": "collection/{{Table1.selectedRow._ref}}", + "initialValue": "" + } + ] } ] } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/getCollection.json b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/getCollection.json index ef11956f380e..b1e5d07b5364 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/getCollection.json +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/getCollection.json @@ -1,101 +1,131 @@ { + "controlType": "SECTION_V2", "identifier": "GET_COLLECTION", - "controlType": "SECTION", "conditionals": { "show": "{{actionConfiguration.formData.command.data === 'GET_COLLECTION'}}" }, "children": [ { - "label": "Collection Name", - "configProperty": "actionConfiguration.formData.path.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": true, - "initialValue": "" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "GET-COLLECTION-Z1", + "children": [ + { + "label": "Collection Name", + "configProperty": "actionConfiguration.formData.path.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": true, + "initialValue": "" + } + ] }, { - "label": "Where", - "configProperty": "actionConfiguration.formData.where.data", - "nestedLevels": 1, - "controlType": "WHERE_CLAUSE", - "-subtitle": "Array of Objects", - "-tooltipText": "Array of Objects", - "-alternateViewTypes": ["json"], - "logicalTypes": [ + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "GET-COLLECTION-Z2", + "children": [ { - "label": "AND", - "value": "AND" + "label": "Where", + "configProperty": "actionConfiguration.formData.where.data", + "nestedLevels": 1, + "controlType": "WHERE_CLAUSE", + "-subtitle": "Array of Objects", + "-tooltipText": "Array of Objects", + "-alternateViewTypes": ["json"], + "logicalTypes": [ + { + "label": "AND", + "value": "AND" + } + ], + "comparisonTypes": [ + { + "label": "==", + "value": "EQ" + }, + { + "label": "<", + "value": "LT" + }, + { + "label": "<=", + "value": "LTE" + }, + { + "label": ">=", + "value": "GTE" + }, + { + "label": ">", + "value": "GT" + }, + { + "label": "in", + "value": "IN" + }, + { + "label": "Contains", + "value": "ARRAY_CONTAINS" + }, + { + "label": "Contains Any", + "value": "ARRAY_CONTAINS_ANY" + } + ] } - ], - "comparisonTypes": [ - { - "label": "==", - "value": "EQ" - }, - { - "label": "<", - "value": "LT" - }, - { - "label": "<=", - "value": "LTE" - }, - { - "label": ">=", - "value": "GTE" - }, - { - "label": ">", - "value": "GT" - }, + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "GET-COLLECTION-Z3", + "children": [ { - "label": "in", - "value": "IN" - }, + "label": "Order By", + "configProperty": "actionConfiguration.formData.orderBy.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": false, + "initialValue": "", + "placeholderText": "[\"ascKey\", \"-descKey\"]" + } + ] + }, + { + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "GET-COLLECTION-Z4", + "children": [ { - "label": "Contains", - "value": "ARRAY_CONTAINS" + "label": "Start After", + "configProperty": "actionConfiguration.formData.next.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": false, + "initialValue": "", + "palceholderText": "" }, { - "label": "Contains Any", - "value": "ARRAY_CONTAINS_ANY" + "label": "End Before", + "configProperty": "actionConfiguration.formData.prev.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": false, + "initialValue": "" } ] }, { - "label": "Order By", - "configProperty": "actionConfiguration.formData.orderBy.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": false, - "initialValue": "", - "placeholderText": "[\"ascKey\", \"-descKey\"]" - }, - { - "label": "Start After", - "configProperty": "actionConfiguration.formData.next.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": false, - "initialValue": "", - "palceholderText": "" - }, - { - "label": "End Before", - "configProperty": "actionConfiguration.formData.prev.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": false, - "initialValue": "" - }, - { - "label": "Limit", - "configProperty": "actionConfiguration.formData.limitDocuments.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": false, - "palceholderText": "{{Table1.pageSize}}", - "initialValue": "10" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "GET-COLLECTION-Z5", + "children": [ + { + "label": "Limit", + "configProperty": "actionConfiguration.formData.limitDocuments.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": false, + "palceholderText": "{{Table1.pageSize}}", + "initialValue": "10" + } + ] } ] } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/getDocument.json b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/getDocument.json index 2f1aa00bfc35..8422d805738e 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/getDocument.json +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/getDocument.json @@ -1,17 +1,23 @@ { + "controlType": "SECTION_V2", "identifier": "GET_DOCUMENT", - "controlType": "SECTION", "conditionals": { "show": "{{actionConfiguration.formData.command.data === 'GET_DOCUMENT'}}" }, "children": [ { - "label": "Collection/Document path", - "configProperty": "actionConfiguration.formData.path.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": true, - "initialValue": "" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "GET-DOCUMENT-Z1", + "children": [ + { + "label": "Collection/Document path", + "configProperty": "actionConfiguration.formData.path.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": true, + "initialValue": "" + } + ] } ] } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/root.json b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/root.json index e15b769264c8..c0986810e99b 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/root.json +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/root.json @@ -1,43 +1,49 @@ { "editor": [ { - "controlType": "SECTION", + "controlType": "SECTION_V2", "identifier": "SELECTOR", "children": [ { - "label": "Command", - "description": "Choose method you would like to use", - "configProperty": "actionConfiguration.formData.command.data", - "controlType": "DROP_DOWN", - "initialValue": "GET_COLLECTION", - "options": [ + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SELECTOR-Z1", + "children": [ { - "label": "List Documents", - "value": "GET_COLLECTION" - }, - { - "label": "Create document", - "value": "CREATE_DOCUMENT" - }, - { - "label": "Update document", - "value": "UPDATE_DOCUMENT" - }, - { - "label": "Delete document", - "value": "DELETE_DOCUMENT" - }, - { - "label": "Get Document", - "value": "GET_DOCUMENT" - }, - { - "label": "Upsert Document", - "value": "SET_DOCUMENT" - }, - { - "label": "Add document to collection", - "value": "ADD_TO_COLLECTION" + "label": "Command", + "description": "Choose method you would like to use", + "configProperty": "actionConfiguration.formData.command.data", + "controlType": "DROP_DOWN", + "initialValue": "GET_COLLECTION", + "options": [ + { + "label": "List Documents", + "value": "GET_COLLECTION" + }, + { + "label": "Create document", + "value": "CREATE_DOCUMENT" + }, + { + "label": "Update document", + "value": "UPDATE_DOCUMENT" + }, + { + "label": "Delete document", + "value": "DELETE_DOCUMENT" + }, + { + "label": "Get Document", + "value": "GET_DOCUMENT" + }, + { + "label": "Upsert Document", + "value": "SET_DOCUMENT" + }, + { + "label": "Add document to collection", + "value": "ADD_TO_COLLECTION" + } + ] } ] } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/setDocument.json b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/setDocument.json index a874402b7f94..25dd8b0da1f5 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/setDocument.json +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/setDocument.json @@ -1,32 +1,50 @@ { + "controlType": "SECTION_V2", "identifier": "SET_DOCUMENT", - "controlType": "SECTION", "conditionals": { "show": "{{actionConfiguration.formData.command.data === 'SET_DOCUMENT'}}" }, "children": [ { - "label": "Collection/Document path", - "configProperty": "actionConfiguration.formData.path.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": true, - "initialValue": "" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SET-DOCUMENT-Z1", + "children": [ + { + "label": "Collection/Document path", + "configProperty": "actionConfiguration.formData.path.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": true, + "initialValue": "" + } + ] }, { - "label": "Body", - "configProperty": "actionConfiguration.formData.body.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "initialValue": "", - "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "SET-DOCUMENT-Z2", + "children": [ + { + "label": "Body", + "configProperty": "actionConfiguration.formData.body.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "initialValue": "", + "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + } + ] }, { - "label": "Timestamp Path", - "configProperty": "actionConfiguration.formData.timestampValuePath.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "initialValue": "", - "placeholderText": "[ \"checkinLog.timestampKey\" ]" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "SET-DOCUMENT-Z3", + "children": [ + { + "label": "Timestamp Path", + "configProperty": "actionConfiguration.formData.timestampValuePath.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "initialValue": "", + "placeholderText": "[ \"checkinLog.timestampKey\" ]" + } + ] } ] } diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/updateDocument.json b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/updateDocument.json index 6bb8ef57d3af..3cdbda305dc0 100644 --- a/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/updateDocument.json +++ b/app/server/appsmith-plugins/firestorePlugin/src/main/resources/editor/updateDocument.json @@ -1,41 +1,59 @@ { + "controlType": "SECTION_V2", "identifier": "UPDATE_DOCUMENT", - "controlType": "SECTION", "conditionals": { "show": "{{actionConfiguration.formData.command.data === 'UPDATE_DOCUMENT'}}" }, "children": [ { - "label": "Collection/Document path", - "configProperty": "actionConfiguration.formData.path.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": true, - "initialValue": "" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "UPDATE-DOCUMENT-Z1", + "children": [ + { + "label": "Collection/Document path", + "configProperty": "actionConfiguration.formData.path.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": true, + "initialValue": "" + } + ] }, { - "label": "Body", - "configProperty": "actionConfiguration.formData.body.data", - "controlType": "QUERY_DYNAMIC_TEXT", - "initialValue": "", - "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + "controlType": "SINGLE_COLUMN_ZONE", + "identifier": "UPDATE-DOCUMENT-Z2", + "children": [ + { + "label": "Body", + "configProperty": "actionConfiguration.formData.body.data", + "controlType": "QUERY_DYNAMIC_TEXT", + "initialValue": "", + "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + } + ] }, { - "label": "Delete Key Path", - "configProperty": "actionConfiguration.formData.deleteKeyPath.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "isRequired": true, - "initialValue": "", - "placeholderText": "[\"userKey.nestedNamekey\"]" - }, - { - "label": "Timestamp Path", - "configProperty": "actionConfiguration.formData.timestampValuePath.data", - "controlType": "QUERY_DYNAMIC_INPUT_TEXT", - "evaluationSubstitutionType": "TEMPLATE", - "initialValue": "", - "placeholderText": "[ \"checkinLog.timestampKey\" ]" + "controlType": "DOUBLE_COLUMN_ZONE", + "identifier": "UPDATE-DOCUMENT-Z3", + "children": [ + { + "label": "Delete Key Path", + "configProperty": "actionConfiguration.formData.deleteKeyPath.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "isRequired": true, + "initialValue": "", + "placeholderText": "[\"userKey.nestedNamekey\"]" + }, + { + "label": "Timestamp Path", + "configProperty": "actionConfiguration.formData.timestampValuePath.data", + "controlType": "QUERY_DYNAMIC_INPUT_TEXT", + "evaluationSubstitutionType": "TEMPLATE", + "initialValue": "", + "placeholderText": "[ \"checkinLog.timestampKey\" ]" + } + ] } ] }
cef5bed7f6138469fbca239ade2d94f4ec8233d9
2022-06-09 11:41:24
Tolulope Adetula
fix: empty commit
false
empty commit
fix
diff --git a/app/client/cypress.env.json b/app/client/cypress.env.json index de4d4271039f..f117283226d1 100644 --- a/app/client/cypress.env.json +++ b/app/client/cypress.env.json @@ -1,5 +1,7 @@ { "MySQL":1, "Mongo":1, - "Edition": 0 + "Edition": 0, + "USERNAME": "[email protected]", + "PASSWORD":"password" } diff --git a/app/client/src/pages/Editor/index.tsx b/app/client/src/pages/Editor/index.tsx index 3348fb4acf03..9ec49d264a30 100644 --- a/app/client/src/pages/Editor/index.tsx +++ b/app/client/src/pages/Editor/index.tsx @@ -14,6 +14,7 @@ import { getIsEditorLoading, getIsPublishingApplication, getPublishingError, + selectCurrentApplicationIcon, } from "selectors/editorSelectors"; import { initEditor, @@ -76,6 +77,7 @@ type EditorProps = { collabStartSharingPointerEvent: (pageId: string) => void; collabStopSharingPointerEvent: (pageId?: string) => void; pageLevelSocketRoomId: string; + currentAppIcon?: string; }; type Props = EditorProps & RouteComponentProps<BuilderRouteParams>; @@ -253,6 +255,7 @@ const mapStateToProps = (state: AppState) => ({ currentPageId: getCurrentPageId(state), isPageLevelSocketConnected: getIsPageLevelSocketConnected(state), loadingGuidedTour: loading(state), + currentAppIcon: selectCurrentApplicationIcon(state), }); const mapDispatchToProps = (dispatch: any) => { diff --git a/app/client/src/selectors/editorSelectors.tsx b/app/client/src/selectors/editorSelectors.tsx index fc434306e3fc..0e68d6cd6e9a 100644 --- a/app/client/src/selectors/editorSelectors.tsx +++ b/app/client/src/selectors/editorSelectors.tsx @@ -138,6 +138,9 @@ export const getCurrentApplicationId = (state: AppState) => export const selectCurrentApplicationSlug = (state: AppState) => state.ui.applications.currentApplication?.slug || PLACEHOLDER_APP_SLUG; +export const selectCurrentApplicationIcon = (state: AppState) => + state.ui.applications.currentApplication?.icon; + export const selectApplicationVersion = (state: AppState) => state.ui.applications.currentApplication?.applicationVersion || ApplicationVersion.DEFAULT;
e128b2daf351586fb37d5a81cd79b4abcc2aa9a3
2022-05-04 13:28:57
rahulramesha
feat: new Widget Copy paste experience (#12906)
false
new Widget Copy paste experience (#12906)
feat
diff --git a/app/client/cypress/fixtures/WidgetCopyPaste.json b/app/client/cypress/fixtures/WidgetCopyPaste.json new file mode 100644 index 000000000000..50569b707b3f --- /dev/null +++ b/app/client/cypress/fixtures/WidgetCopyPaste.json @@ -0,0 +1,149 @@ +{ + "dsl": { + "widgetName": "MainContainer", + "backgroundColor": "none", + "rightColumn": 1936, + "snapColumns": 64, + "detachFromLayout": true, + "widgetId": "0", + "topRow": 0, + "bottomRow": 1160, + "containerStyle": "none", + "snapRows": 116, + "parentRowSpace": 1, + "type": "CANVAS_WIDGET", + "canExtend": true, + "version": 54, + "minHeight": 1170, + "parentColumnSpace": 1, + "dynamicBindingPathList": [], + "leftColumn": 0, + "children": [ + { + "boxShadow": "NONE", + "widgetName": "Container1", + "borderColor": "transparent", + "isCanvas": true, + "displayName": "Container", + "iconSVG": "/static/media/icon.1977dca3.svg", + "topRow": 18, + "bottomRow": 58, + "parentRowSpace": 10, + "type": "CONTAINER_WIDGET", + "hideCard": false, + "animateLoading": true, + "parentColumnSpace": 30.0625, + "leftColumn": 6, + "children": [ + { + "widgetName": "Canvas1", + "rightColumn": 721.5, + "detachFromLayout": true, + "displayName": "Canvas", + "widgetId": "79a7avach5", + "containerStyle": "none", + "topRow": 0, + "bottomRow": 400, + "parentRowSpace": 1, + "isVisible": true, + "type": "CANVAS_WIDGET", + "canExtend": false, + "version": 1, + "hideCard": true, + "parentId": "drqlbbf2jm", + "minHeight": 400, + "renderMode": "CANVAS", + "isLoading": false, + "parentColumnSpace": 1, + "leftColumn": 0, + "children": [], + "key": "wv7g2n64td" + } + ], + "borderWidth": "0", + "key": "t9ac12itzf", + "backgroundColor": "#FFFFFF", + "rightColumn": 30, + "widgetId": "drqlbbf2jm", + "containerStyle": "card", + "isVisible": true, + "version": 1, + "parentId": "0", + "renderMode": "CANVAS", + "isLoading": false, + "borderRadius": "0" + }, + { + "widgetName": "Chart1", + "allowScroll": false, + "displayName": "Chart", + "iconSVG": "/static/media/icon.6adbe31e.svg", + "topRow": 20, + "bottomRow": 52, + "parentRowSpace": 10, + "type": "CHART_WIDGET", + "hideCard": false, + "chartData": { + "0jqgz3wqpx": { + "seriesName": "Sales", + "data": [ + { + "x": "Product1", + "y": 20000 + }, + { + "x": "Product2", + "y": 22000 + }, + { + "x": "Product3", + "y": 32000 + } + ] + } + }, + "animateLoading": true, + "parentColumnSpace": 30.0625, + "leftColumn": 35, + "customFusionChartConfig": { + "type": "column2d", + "dataSource": { + "chart": { + "caption": "Sales Report", + "xAxisName": "Product Line", + "yAxisName": "Revenue($)", + "theme": "fusion" + }, + "data": [ + { + "label": "Product1", + "value": 20000 + }, + { + "label": "Product2", + "value": 22000 + }, + { + "label": "Product3", + "value": 32000 + } + ] + } + }, + "key": "5dh7y0hcpk", + "rightColumn": 59, + "widgetId": "mxhtzoaizs", + "isVisible": true, + "version": 1, + "parentId": "0", + "labelOrientation": "auto", + "renderMode": "CANVAS", + "isLoading": false, + "yAxisName": "Revenue($)", + "chartName": "Sales Report", + "xAxisName": "Product Line", + "chartType": "COLUMN_CHART" + } + ] + } +} \ No newline at end of file diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/WidgetCopyPaste/WidgetCopyPaste_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/WidgetCopyPaste/WidgetCopyPaste_spec.js new file mode 100644 index 000000000000..5234504354a5 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/WidgetCopyPaste/WidgetCopyPaste_spec.js @@ -0,0 +1,108 @@ +const widgetsPage = require("../../../../locators/Widgets.json"); +const commonLocators = require("../../../../locators/commonlocators.json"); +const explorer = require("../../../../locators/explorerlocators.json"); +const dsl = require("../../../../fixtures/WidgetCopyPaste.json"); + +describe("Widget Copy paste", function() { + const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl"; + before(() => { + cy.addDsl(dsl); + }); + + it("when non Layout widget is selected, it should place below the widget selected", function() { + // Selection + cy.get(`#${dsl.dsl.children[1].widgetId}`).click({ + ctrlKey: true, + }); + cy.get(`div[data-testid='t--selected']`).should("have.length", 1); + + //copy + cy.get("body").type(`{${modifierKey}}{c}`); + cy.get(commonLocators.toastmsg).contains("Copied"); + + //paste + cy.get("body").type(`{${modifierKey}}{v}`); + cy.get(widgetsPage.chartWidget).should("have.length", 2); + + // verify the position + cy.get(widgetsPage.chartWidget) + .eq(0) + .then((element) => { + const elementTop = parseFloat(element.css("top")); + const elementHeight = parseFloat(element.css("height")); + const pastedWidgetTop = + (elementTop + elementHeight + 10).toString() + "px"; + cy.get(widgetsPage.chartWidget) + .eq(1) + .invoke("attr", "style") + .should("contain", `left: ${element.css("left")}`) + .should("contain", `top: ${pastedWidgetTop}`); + }); + }); + + it("when Layout widget is selected, it should place it inside the layout widget", function() { + cy.get(`#div-selection-0`).click({ + force: true, + }); + + // Selection + cy.get(`#${dsl.dsl.children[0].widgetId}`).click({ + ctrlKey: true, + }); + cy.get(`div[data-testid='t--selected']`).should("have.length", 1); + + //paste + cy.get("body").type(`{${modifierKey}}{v}`); + + cy.get(`#${dsl.dsl.children[0].widgetId}`) + .find(widgetsPage.chartWidget) + .should("have.length", 1); + }); + + it("when widget inside the layout widget is selected, then it should paste inside the layout widget below the selected widget", function() { + cy.get(`#div-selection-0`).click({ + force: true, + }); + + // Selection + cy.get(`#${dsl.dsl.children[0].widgetId}`) + .find(widgetsPage.chartWidget) + .click({ + ctrlKey: true, + }); + cy.get(`div[data-testid='t--selected']`).should("have.length", 1); + + //paste + cy.get("body").type(`{${modifierKey}}{v}`); + cy.get(`#${dsl.dsl.children[0].widgetId}`) + .find(widgetsPage.chartWidget) + .should("have.length", 2); + }); + + it("when modal is open, it should paste inside the modal", () => { + //add modal widget + cy.get(explorer.addWidget).click(); + cy.dragAndDropToCanvas("modalwidget", { x: 300, y: 700 }); + cy.get(".t--modal-widget").should("exist"); + + //paste + cy.get("body").type(`{${modifierKey}}{v}`); + cy.get(".t--modal-widget") + .find(widgetsPage.chartWidget) + .should("have.length", 1); + }); + + it("when widget Inside a modal is selected, it should paste inside the modal", () => { + //verify modal and selected widget + cy.get(".t--modal-widget").should("exist"); + cy.get(".t--modal-widget") + .find(`div[data-testid='t--selected']`) + .should("have.length", 1); + + //paste + cy.get("body").type(`{${modifierKey}}{v}`); + cy.get(".t--modal-widget") + .find(widgetsPage.chartWidget) + .should("have.length", 2); + }); +}); diff --git a/app/client/src/actions/widgetActions.tsx b/app/client/src/actions/widgetActions.tsx index 1855f1189b1e..db4609c3d5fb 100644 --- a/app/client/src/actions/widgetActions.tsx +++ b/app/client/src/actions/widgetActions.tsx @@ -103,11 +103,15 @@ export const copyWidget = (isShortcut: boolean) => { }; }; -export const pasteWidget = (groupWidgets = false) => { +export const pasteWidget = ( + groupWidgets = false, + mouseLocation: { x: number; y: number }, +) => { return { type: ReduxActionTypes.PASTE_COPIED_WIDGET_INIT, payload: { groupWidgets: groupWidgets, + mouseLocation, }, }; }; diff --git a/app/client/src/components/designSystems/appsmith/PositionedContainer.tsx b/app/client/src/components/designSystems/appsmith/PositionedContainer.tsx index acffc2b0afe6..fd67df21aa51 100644 --- a/app/client/src/components/designSystems/appsmith/PositionedContainer.tsx +++ b/app/client/src/components/designSystems/appsmith/PositionedContainer.tsx @@ -11,6 +11,7 @@ import WidgetFactory from "utils/WidgetFactory"; import { isEqual, memoize } from "lodash"; import { getReflowSelector } from "selectors/widgetReflowSelectors"; import { AppState } from "reducers"; +import { POSITIONED_WIDGET } from "constants/componentClassNameConstants"; const PositionedWidget = styled.div<{ zIndexOnHover: number }>` &:hover { @@ -44,8 +45,7 @@ export function PositionedContainer(props: PositionedContainerProps) { const containerClassName = useMemo(() => { return ( generateClassName(props.widgetId) + - " positioned-widget " + - `t--widget-${props.widgetType + ` ${POSITIONED_WIDGET} t--widget-${props.widgetType .split("_") .join("") .toLowerCase()}` diff --git a/app/client/src/constants/componentClassNameConstants.ts b/app/client/src/constants/componentClassNameConstants.ts new file mode 100644 index 000000000000..fb79f4050530 --- /dev/null +++ b/app/client/src/constants/componentClassNameConstants.ts @@ -0,0 +1,13 @@ +export function getStickyCanvasName(widgetId: string) { + return `div-selection-${widgetId}`; +} + +export function getSlidingCanvasName(widgetId: string) { + return `canvas-selection-${widgetId}`; +} + +export function getBaseWidgetClassName(id?: string) { + return `appsmith_widget_${id}`; +} + +export const POSITIONED_WIDGET = "positioned-widget"; diff --git a/app/client/src/pages/Editor/GlobalHotKeys.test.tsx b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.test.tsx similarity index 92% rename from app/client/src/pages/Editor/GlobalHotKeys.test.tsx rename to app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.test.tsx index 345fb07217e4..3c399a951f5f 100644 --- a/app/client/src/pages/Editor/GlobalHotKeys.test.tsx +++ b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.test.tsx @@ -7,7 +7,7 @@ import { } from "test/factories/WidgetFactoryUtils"; import { act, render, fireEvent, waitFor } from "test/testUtils"; import GlobalHotKeys from "./GlobalHotKeys"; -import MainContainer from "./MainContainer"; +import MainContainer from "../MainContainer"; import { MemoryRouter } from "react-router-dom"; import * as utilities from "selectors/editorSelectors"; import store from "store"; @@ -56,7 +56,7 @@ describe("Canvas Hot Keys", () => { rootSaga: mockGenerator, })); - // only the deafault exports are mocked to avoid overriding utilities exported out of them. defaults are marked to avoid worker initiation and page api calls in tests. + // only the default exports are mocked to avoid overriding utilities exported out of them. defaults are marked to avoid worker initiation and page api calls in tests. jest.mock("sagas/EvaluationsSaga", () => ({ ...jest.requireActual("sagas/EvaluationsSaga"), default: mockGenerator, @@ -84,7 +84,11 @@ describe("Canvas Hot Keys", () => { initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]} > <MockApplication> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <UpdatedMainContainer dsl={dsl} /> </GlobalHotKeys> </MockApplication> @@ -204,7 +208,11 @@ describe("Canvas Hot Keys", () => { initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]} > <MockApplication> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <UpdatedMainContainer dsl={dsl} /> </GlobalHotKeys> </MockApplication> @@ -246,7 +254,11 @@ describe("Canvas Hot Keys", () => { initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]} > <MockApplication> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <UpdatedMainContainer dsl={dsl} /> </GlobalHotKeys> </MockApplication> @@ -331,7 +343,11 @@ describe("Canvas Hot Keys", () => { initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]} > <MockApplication> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <UpdatedMainContainer dsl={dsl} /> </GlobalHotKeys> </MockApplication> @@ -388,7 +404,11 @@ describe("Cut/Copy/Paste hotkey", () => { }); const component = render( <MockPageDSL dsl={dsl}> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <MockCanvas /> </GlobalHotKeys> </MockPageDSL>, @@ -469,7 +489,11 @@ describe("Cut/Copy/Paste hotkey", () => { }); const component = render( <MockPageDSL dsl={dsl}> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <MockCanvas /> </GlobalHotKeys> </MockPageDSL>, @@ -540,7 +564,11 @@ describe("Undo/Redo hotkey", () => { const dispatchSpy = jest.spyOn(store, "dispatch"); const component = render( <MockPageDSL> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <MockCanvas /> </GlobalHotKeys> </MockPageDSL>, @@ -566,7 +594,11 @@ describe("Undo/Redo hotkey", () => { const dispatchSpy = jest.spyOn(store, "dispatch"); const component = render( <MockPageDSL> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <MockCanvas /> </GlobalHotKeys> </MockPageDSL>, @@ -592,7 +624,11 @@ describe("Undo/Redo hotkey", () => { const dispatchSpy = jest.spyOn(store, "dispatch"); const component = render( <MockPageDSL> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <MockCanvas /> </GlobalHotKeys> </MockPageDSL>, @@ -628,7 +664,11 @@ describe("cmd + s hotkey", () => { pauseOnHover={false} transition={Slide} /> - <GlobalHotKeys> + <GlobalHotKeys + getMousePosition={() => { + return { x: 0, y: 0 }; + }} + > <div /> </GlobalHotKeys> </>, diff --git a/app/client/src/pages/Editor/GlobalHotKeys.tsx b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx similarity index 97% rename from app/client/src/pages/Editor/GlobalHotKeys.tsx rename to app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx index c873597ee001..1445839b619a 100644 --- a/app/client/src/pages/Editor/GlobalHotKeys.tsx +++ b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx @@ -55,7 +55,7 @@ import { commentModeSelector } from "selectors/commentsSelectors"; type Props = { copySelectedWidget: () => void; - pasteCopiedWidget: () => void; + pasteCopiedWidget: (mouseLocation: { x: number; y: number }) => void; deleteSelectedWidget: () => void; cutSelectedWidget: () => void; groupSelectedWidget: () => void; @@ -80,6 +80,7 @@ type Props = { isExplorerPinned: boolean; setExplorerPinnedAction: (shouldPinned: boolean) => void; showCommitModal: () => void; + getMousePosition: () => { x: number; y: number }; }; @HotkeysTarget @@ -215,7 +216,9 @@ class GlobalHotKeys extends React.Component<Props> { group="Canvas" label="Paste Widget" onKeyDown={() => { - this.props.pasteCopiedWidget(); + this.props.pasteCopiedWidget( + this.props.getMousePosition() || { x: 0, y: 0 }, + ); }} /> <Hotkey @@ -420,7 +423,8 @@ const mapStateToProps = (state: AppState) => ({ const mapDispatchToProps = (dispatch: any) => { return { copySelectedWidget: () => dispatch(copyWidget(true)), - pasteCopiedWidget: () => dispatch(pasteWidget()), + pasteCopiedWidget: (mouseLocation: { x: number; y: number }) => + dispatch(pasteWidget(false, mouseLocation)), deleteSelectedWidget: () => dispatch(deleteSelectedWidget(true)), cutSelectedWidget: () => dispatch(cutWidget()), groupSelectedWidget: () => dispatch(groupWidgets()), diff --git a/app/client/src/pages/Editor/GlobalHotKeys/index.tsx b/app/client/src/pages/Editor/GlobalHotKeys/index.tsx new file mode 100644 index 000000000000..4685d4240ba0 --- /dev/null +++ b/app/client/src/pages/Editor/GlobalHotKeys/index.tsx @@ -0,0 +1,16 @@ +import GlobalHotKeys from "./GlobalHotKeys"; +import React from "react"; +import { useMouseLocation } from "./useMouseLocation"; + +//HOC to track user's mouse location, separated out so that it doesn't render the component on every mouse move +function HotKeysHOC(props: any) { + const getMousePosition = useMouseLocation(); + + return ( + <GlobalHotKeys {...props} getMousePosition={getMousePosition}> + {props.children} + </GlobalHotKeys> + ); +} + +export default HotKeysHOC; diff --git a/app/client/src/pages/Editor/GlobalHotKeys/useMouseLocation.tsx b/app/client/src/pages/Editor/GlobalHotKeys/useMouseLocation.tsx new file mode 100644 index 000000000000..a9a4015230d8 --- /dev/null +++ b/app/client/src/pages/Editor/GlobalHotKeys/useMouseLocation.tsx @@ -0,0 +1,26 @@ +import { useEffect, useRef } from "react"; + +export const useMouseLocation = () => { + const mousePosition = useRef<{ x: number; y: number }>({ + x: 0, + y: 0, + }); + + const setMousePosition = (e: any) => { + if (e) { + mousePosition.current = { x: e.clientX, y: e.clientY }; + } + }; + + useEffect(() => { + window.addEventListener("mousemove", setMousePosition); + + () => { + window.removeEventListener("mousemove", setMousePosition); + }; + }, []); + + return function() { + return mousePosition.current; + }; +}; diff --git a/app/client/src/pages/Editor/GuidedTour/useComputeCurrentStep.ts b/app/client/src/pages/Editor/GuidedTour/useComputeCurrentStep.ts index df58874a9388..8cf03e0b1507 100644 --- a/app/client/src/pages/Editor/GuidedTour/useComputeCurrentStep.ts +++ b/app/client/src/pages/Editor/GuidedTour/useComputeCurrentStep.ts @@ -28,6 +28,7 @@ import { countryInputSelector, imageWidgetSelector, } from "selectors/onboardingSelectors"; +import { getBaseWidgetClassName } from "constants/componentClassNameConstants"; import { GUIDED_TOUR_STEPS, Steps } from "./constants"; import { hideIndicator, highlightSection, showIndicator } from "./utils"; @@ -230,11 +231,11 @@ function useComputeCurrentStep(showInfoMessage: boolean) { // Highlight the selected row and the NameInput widget highlightSection( "selected-row", - `appsmith_widget_${isTableWidgetBound}`, + getBaseWidgetClassName(isTableWidgetBound), "class", ); highlightSection( - `appsmith_widget_${nameInputWidgetId}`, + getBaseWidgetClassName(nameInputWidgetId), undefined, "class", ); diff --git a/app/client/src/pages/Editor/WidgetsMultiSelectBox.tsx b/app/client/src/pages/Editor/WidgetsMultiSelectBox.tsx index 454f109a704c..c3e02fcde14e 100644 --- a/app/client/src/pages/Editor/WidgetsMultiSelectBox.tsx +++ b/app/client/src/pages/Editor/WidgetsMultiSelectBox.tsx @@ -25,6 +25,7 @@ import WidgetFactory from "utils/WidgetFactory"; import { AppState } from "reducers"; import { useWidgetDragResize } from "utils/hooks/dragResizeHooks"; import { commentModeSelector } from "selectors/commentsSelectors"; +import { POSITIONED_WIDGET } from "constants/componentClassNameConstants"; const WidgetTypes = WidgetFactory.widgetTypes; const StyledSelectionBox = styled.div` @@ -239,7 +240,7 @@ function WidgetsMultiSelectBox(props: { const { height, left, top, width } = useMemo(() => { if (shouldRender) { const widgetClasses = selectedWidgetIDs - .map((id) => `.${generateClassName(id)}.positioned-widget`) + .map((id) => `.${generateClassName(id)}.${POSITIONED_WIDGET}`) .join(","); const elements = document.querySelectorAll<HTMLElement>(widgetClasses); diff --git a/app/client/src/pages/common/CanvasArenas/CanvasSelectionArena.tsx b/app/client/src/pages/common/CanvasArenas/CanvasSelectionArena.tsx index ae129d1f6e5f..37d74407f06e 100644 --- a/app/client/src/pages/common/CanvasArenas/CanvasSelectionArena.tsx +++ b/app/client/src/pages/common/CanvasArenas/CanvasSelectionArena.tsx @@ -23,6 +23,10 @@ import { getIsDraggingForSelection } from "selectors/canvasSelectors"; import { commentModeSelector } from "selectors/commentsSelectors"; import { StickyCanvasArena } from "./StickyCanvasArena"; import { getAbsolutePixels } from "utils/helpers"; +import { + getSlidingCanvasName, + getStickyCanvasName, +} from "constants/componentClassNameConstants"; export interface SelectedArenaDimensions { top: number; @@ -482,10 +486,10 @@ export function CanvasSelectionArena({ return shouldShow ? ( <StickyCanvasArena canExtend={canExtend} - canvasId={`canvas-selection-${widgetId}`} + canvasId={getSlidingCanvasName(widgetId)} canvasPadding={canvasPadding} getRelativeScrollingParent={getNearestParentCanvas} - id={`div-selection-${widgetId}`} + id={getStickyCanvasName(widgetId)} ref={canvasRef} showCanvas={shouldShow} snapColSpace={snapColumnSpace} diff --git a/app/client/src/sagas/WidgetOperationSagas.tsx b/app/client/src/sagas/WidgetOperationSagas.tsx index e9018f3e2c9d..019b02108286 100644 --- a/app/client/src/sagas/WidgetOperationSagas.tsx +++ b/app/client/src/sagas/WidgetOperationSagas.tsx @@ -48,11 +48,13 @@ import { } from "constants/WidgetConstants"; import { getCopiedWidgets, saveCopiedWidgets } from "utils/storage"; import { generateReactKey } from "utils/generators"; -import { flashElementsById } from "utils/helpers"; import AnalyticsUtil from "utils/AnalyticsUtil"; import log from "loglevel"; import { navigateToCanvas } from "pages/Editor/Explorer/Widgets/utils"; -import { getCurrentPageId } from "selectors/editorSelectors"; +import { + getCurrentPageId, + getWidgetSpacesSelectorForContainer, +} from "selectors/editorSelectors"; import { selectMultipleWidgetsInitAction } from "actions/widgetSelectionActions"; import { getDataTree } from "selectors/dataTreeSelectors"; @@ -92,6 +94,22 @@ import { getParentWidgetIdForGrouping, isCopiedModalWidget, purgeOrphanedDynamicPaths, + getReflowedPositions, + NewPastePositionVariables, + getContainerIdForCanvas, + getSnappedGrid, + getNewPositionsForCopiedWidgets, + getVerticallyAdjustedPositions, + getOccupiedSpacesFromProps, + changeIdsOfPastePositions, + getCanvasIdForContainer, + getMousePositions, + getPastePositionMapFromMousePointer, + getBoundariesFromSelectedWidgets, + WIDGET_PASTE_PADDING, + getWidgetsFromIds, + getDefaultCanvas, + isDropTarget, } from "./WidgetOperationUtils"; import { getSelectedWidgets } from "selectors/ui"; import { widgetSelectionSagas } from "./WidgetSelectionSagas"; @@ -102,7 +120,16 @@ import widgetDeletionSagas from "./WidgetDeletionSagas"; import { getReflow } from "selectors/widgetReflowSelectors"; import { widgetReflow } from "reducers/uiReducers/reflowReducer"; import { stopReflowAction } from "actions/reflowActions"; -import { collisionCheckPostReflow } from "utils/reflowHookUtils"; +import { + collisionCheckPostReflow, + getBottomRowAfterReflow, +} from "utils/reflowHookUtils"; +import { PrevReflowState, ReflowDirection, SpaceMap } from "reflow/reflowTypes"; +import { WidgetSpace } from "constants/CanvasEditorConstants"; +import { reflow } from "reflow"; +import { getBottomMostRow } from "reflow/reflowUtils"; +import { flashElementsById } from "utils/helpers"; +import { getSlidingCanvasName } from "constants/componentClassNameConstants"; export function* resizeSaga(resizeAction: ReduxAction<WidgetResize>) { try { @@ -739,7 +766,10 @@ function* copyWidgetSaga(action: ReduxAction<{ isShortcut: boolean }>) { * @param parentId * @param canvasWidgets * @param parentBottomRow - * @param persistColumnPosition + * @param newPastingPositionMap + * @param shouldPersistColumnPosition + * @param isThereACollision + * @param shouldGroup * @returns */ export function calculateNewWidgetPosition( @@ -747,6 +777,7 @@ export function calculateNewWidgetPosition( parentId: string, canvasWidgets: { [widgetId: string]: FlattenedWidgetProps }, parentBottomRow?: number, + newPastingPositionMap?: SpaceMap, shouldPersistColumnPosition = false, isThereACollision = false, shouldGroup = false, @@ -756,6 +787,20 @@ export function calculateNewWidgetPosition( leftColumn: number; rightColumn: number; } { + if ( + !shouldGroup && + newPastingPositionMap && + newPastingPositionMap[widget.widgetId] + ) { + const newPastingPosition = newPastingPositionMap[widget.widgetId]; + return { + topRow: newPastingPosition.top, + bottomRow: newPastingPosition.bottom, + leftColumn: newPastingPosition.left, + rightColumn: newPastingPosition.right, + }; + } + const nextAvailableRow = parentBottomRow ? parentBottomRow : nextAvailableRowInContainer(parentId, canvasWidgets); @@ -779,10 +824,335 @@ export function calculateNewWidgetPosition( }; } +/** + * Method to provide the new positions where the widgets can be pasted. + * It will return an empty object if it doesn't have any selected widgets, or if the mouse is outside the canvas. + * + * @param copiedWidgetGroups Contains information on the copied widgets + * @param mouseLocation location of the mouse in absolute pixels + * @param copiedTotalWidth total width of the copied widgets + * @param copiedTopMostRow top row of the top most copied widget + * @param copiedLeftMostColumn left column of the left most copied widget + * @returns + */ +const getNewPositions = function*( + copiedWidgetGroups: CopiedWidgetGroup[], + mouseLocation: { x: number; y: number }, + copiedTotalWidth: number, + copiedTopMostRow: number, + copiedLeftMostColumn: number, +) { + const selectedWidgetIDs: string[] = yield select(getSelectedWidgets); + const canvasWidgets: CanvasWidgetsReduxState = yield select(getWidgets); + const selectedWidgets = getWidgetsFromIds(selectedWidgetIDs, canvasWidgets); + + //if the copied widget is a modal widget, then it has to paste on the main container + if ( + copiedWidgetGroups.length === 1 && + copiedWidgetGroups[0].list[0] && + copiedWidgetGroups[0].list[0].type === "MODAL_WIDGET" + ) + return {}; + + //if multiple widgets are selected or if a single non-layout widget is selected, + // then call the method to calculate and return positions based on selected widgets. + if ( + !( + selectedWidgets.length === 1 && + isDropTarget(selectedWidgets[0].type, true) + ) && + selectedWidgets.length > 0 + ) { + const newPastingPositionDetails: NewPastePositionVariables = yield call( + getNewPositionsBasedOnSelectedWidgets, + copiedWidgetGroups, + selectedWidgets, + canvasWidgets, + copiedTotalWidth, + copiedTopMostRow, + copiedLeftMostColumn, + ); + return newPastingPositionDetails; + } + + //if a layout widget is selected or mouse is on the main canvas + // then call the method to calculate and return positions mouse positions. + const newPastingPositionDetails: NewPastePositionVariables = yield call( + getNewPositionsBasedOnMousePositions, + copiedWidgetGroups, + mouseLocation, + selectedWidgets, + canvasWidgets, + copiedTotalWidth, + copiedTopMostRow, + copiedLeftMostColumn, + ); + return newPastingPositionDetails; +}; + +/** + * Calculates the new positions of the pasting widgets, based on the selected widgets + * The new positions will be just below the selected widgets + * + * @param copiedWidgetGroups Contains information on the copied widgets + * @param selectedWidgets array of selected widgets + * @param canvasWidgets canvas widgets from the DSL + * @param copiedTotalWidth total width of the copied widgets + * @param copiedTopMostRow top row of the top most copied widget + * @param copiedLeftMostColumn left column of the left most copied widget + * @returns + */ +function* getNewPositionsBasedOnSelectedWidgets( + copiedWidgetGroups: CopiedWidgetGroup[], + selectedWidgets: WidgetProps[], + canvasWidgets: CanvasWidgetsReduxState, + copiedTotalWidth: number, + copiedTopMostRow: number, + copiedLeftMostColumn: number, +) { + //get Parent canvasId + const parentId = selectedWidgets[0].parentId || ""; + + // get the Id of the container widget based on the canvasId + const containerId = getContainerIdForCanvas(parentId); + + const containerWidget = canvasWidgets[containerId]; + const canvasDOM = document.querySelector( + `#${getSlidingCanvasName(parentId)}`, + ); + + if (!canvasDOM || !containerWidget) return {}; + + const rect = canvasDOM.getBoundingClientRect(); + + // get Grid values such as snapRowSpace and snapColumnSpace + const { snapGrid } = getSnappedGrid(containerWidget, rect.width); + + const selectedWidgetsArray = selectedWidgets.length ? selectedWidgets : []; + //from selected widgets get some information required for position calculation + const { + leftMostColumn: selectedLeftMostColumn, + maxThickness, + topMostRow: selectedTopMostRow, + totalWidth, + } = getBoundariesFromSelectedWidgets(selectedWidgetsArray); + + // calculation of left most column of where widgets are to be pasted + let pasteLeftMostColumn = + selectedLeftMostColumn - (copiedTotalWidth - totalWidth) / 2; + + pasteLeftMostColumn = Math.round(pasteLeftMostColumn); + + // conditions to adjust to the edges of the boundary, so that it doesn't go out of canvas + if (pasteLeftMostColumn < 0) pasteLeftMostColumn = 0; + if ( + pasteLeftMostColumn + copiedTotalWidth > + GridDefaults.DEFAULT_GRID_COLUMNS + ) + pasteLeftMostColumn = GridDefaults.DEFAULT_GRID_COLUMNS - copiedTotalWidth; + + // based on the above calculation get the new Positions that are aligned to the top left of selected widgets + // i.e., the top of the selected widgets will be equal to the top of copied widgets and both are horizontally centered + const newPositionsForCopiedWidgets = getNewPositionsForCopiedWidgets( + copiedWidgetGroups, + copiedTopMostRow, + selectedTopMostRow, + copiedLeftMostColumn, + pasteLeftMostColumn, + ); + + // with the new positions, calculate the map of new position, which are moved down to the point where + // it doesn't overlap with any of the selected widgets. + const newPastingPositionMap = getVerticallyAdjustedPositions( + newPositionsForCopiedWidgets, + getOccupiedSpacesFromProps(selectedWidgetsArray), + maxThickness, + ); + + if (!newPastingPositionMap) return {}; + + const gridProps = { + parentColumnSpace: snapGrid.snapColumnSpace, + parentRowSpace: snapGrid.snapRowSpace, + maxGridColumns: GridDefaults.DEFAULT_GRID_COLUMNS, + }; + + const reflowSpacesSelector = getWidgetSpacesSelectorForContainer(parentId); + const widgetSpaces: WidgetSpace[] = yield select(reflowSpacesSelector) || []; + + // Ids of each pasting are changed just for reflow + const newPastePositions = changeIdsOfPastePositions(newPastingPositionMap); + + const { movementMap: reflowedMovementMap } = reflow( + newPastePositions, + newPastePositions, + widgetSpaces, + ReflowDirection.BOTTOM, + gridProps, + true, + false, + { prevSpacesMap: {} } as PrevReflowState, + ); + + // calculate the new bottom most row of the canvas + const bottomMostRow = getBottomRowAfterReflow( + reflowedMovementMap, + getBottomMostRow(newPastePositions), + widgetSpaces, + gridProps, + ); + + return { + bottomMostRow: + (bottomMostRow + GridDefaults.CANVAS_EXTENSION_OFFSET) * + gridProps.parentRowSpace, + gridProps, + newPastingPositionMap, + reflowedMovementMap, + canvasId: parentId, + }; +} + +/** + * Calculates the new positions of the pasting widgets, based on the mouse position + * If the mouse position is on the canvas it the top left of the new positions aligns itself to the mouse position + * returns a empty object if the mouse is out of canvas + * + * @param copiedWidgetGroups Contains information on the copied widgets + * @param mouseLocation location of the mouse in absolute pixels + * @param selectedWidgets array of selected widgets + * @param canvasWidgets canvas widgets from the DSL + * @param copiedTotalWidth total width of the copied widgets + * @param copiedTopMostRow top row of the top most copied widget + * @param copiedLeftMostColumn left column of the left most copied widget + * @returns + */ +function* getNewPositionsBasedOnMousePositions( + copiedWidgetGroups: CopiedWidgetGroup[], + mouseLocation: { x: number; y: number }, + selectedWidgets: WidgetProps[], + canvasWidgets: CanvasWidgetsReduxState, + copiedTotalWidth: number, + copiedTopMostRow: number, + copiedLeftMostColumn: number, +) { + let { canvasDOM, canvasId, containerWidget } = getDefaultCanvas( + canvasWidgets, + ); + + //if the selected widget is a layout widget then change the pasting canvas. + if (selectedWidgets.length === 1 && isDropTarget(selectedWidgets[0].type)) { + containerWidget = selectedWidgets[0]; + ({ canvasDOM, canvasId } = getCanvasIdForContainer(containerWidget)); + } + + if (!canvasDOM || !containerWidget || !canvasId) return {}; + + const canvasRect = canvasDOM.getBoundingClientRect(); + + // get Grid values such as snapRowSpace and snapColumnSpace + const { padding, snapGrid } = getSnappedGrid( + containerWidget, + canvasRect.width, + ); + + // get mouse positions in terms of grid rows and columns of the pasting canvas + const mousePositions = getMousePositions( + canvasRect, + canvasId, + snapGrid, + padding, + mouseLocation, + ); + + if (!snapGrid || !mousePositions) return {}; + + const reflowSpacesSelector = getWidgetSpacesSelectorForContainer(canvasId); + const widgetSpaces: WidgetSpace[] = yield select(reflowSpacesSelector) || []; + + let mouseTopRow = mousePositions.top; + let mouseLeftColumn = mousePositions.left; + + // if the mouse position is on another widget on the canvas, then new positions are below it. + for (const widgetSpace of widgetSpaces) { + if ( + widgetSpace.top < mousePositions.top && + widgetSpace.left < mousePositions.left && + widgetSpace.bottom > mousePositions.top && + widgetSpace.right > mousePositions.left + ) { + mouseTopRow = widgetSpace.bottom + WIDGET_PASTE_PADDING; + mouseLeftColumn = + widgetSpace.left - + (copiedTotalWidth - (widgetSpace.right - widgetSpace.left)) / 2; + break; + } + } + + mouseLeftColumn = Math.round(mouseLeftColumn); + + // adjust the top left based on the edges of the canvas + if (mouseLeftColumn < 0) mouseLeftColumn = 0; + if (mouseLeftColumn + copiedTotalWidth > GridDefaults.DEFAULT_GRID_COLUMNS) + mouseLeftColumn = GridDefaults.DEFAULT_GRID_COLUMNS - copiedTotalWidth; + + // get the new Pasting positions of the widgets based on the adjusted mouse top-left + const newPastingPositionMap = getPastePositionMapFromMousePointer( + copiedWidgetGroups, + copiedTopMostRow, + mouseTopRow, + copiedLeftMostColumn, + mouseLeftColumn, + ); + + const gridProps = { + parentColumnSpace: snapGrid.snapColumnSpace, + parentRowSpace: snapGrid.snapRowSpace, + maxGridColumns: GridDefaults.DEFAULT_GRID_COLUMNS, + }; + + // Ids of each pasting are changed just for reflow + const newPastePositions = changeIdsOfPastePositions(newPastingPositionMap); + + const { movementMap: reflowedMovementMap } = reflow( + newPastePositions, + newPastePositions, + widgetSpaces, + ReflowDirection.BOTTOM, + gridProps, + true, + false, + { prevSpacesMap: {} } as PrevReflowState, + ); + + // calculate the new bottom most row of the canvas. + const bottomMostRow = getBottomRowAfterReflow( + reflowedMovementMap, + getBottomMostRow(newPastePositions), + widgetSpaces, + gridProps, + ); + + return { + bottomMostRow: + (bottomMostRow + GridDefaults.CANVAS_EXTENSION_OFFSET) * + gridProps.parentRowSpace, + gridProps, + newPastingPositionMap, + reflowedMovementMap, + canvasId, + }; +} + /** * this saga create a new widget from the copied one to store */ -function* pasteWidgetSaga(action: ReduxAction<{ groupWidgets: boolean }>) { +function* pasteWidgetSaga( + action: ReduxAction<{ + groupWidgets: boolean; + mouseLocation: { x: number; y: number }; + }>, +) { let copiedWidgetGroups: CopiedWidgetGroup[] = yield getCopiedWidgets(); const shouldGroup: boolean = action.payload.groupWidgets; @@ -836,14 +1206,36 @@ function* pasteWidgetSaga(action: ReduxAction<{ groupWidgets: boolean }>) { ) return; - const { topMostWidget } = getBoundaryWidgetsFromCopiedGroups( - copiedWidgetGroups, - ); + const { + leftMostWidget, + topMostWidget, + totalWidth: copiedTotalWidth, + } = getBoundaryWidgetsFromCopiedGroups(copiedWidgetGroups); + const nextAvailableRow: number = nextAvailableRowInContainer( pastingIntoWidgetId, widgets, ); + // new pasting positions, the variables are undefined if the positions cannot be calculated, + // then it pastes the regular way at the bottom of the canvas + const { + bottomMostRow, + canvasId, + gridProps, + newPastingPositionMap, + reflowedMovementMap, + }: NewPastePositionVariables = yield call( + getNewPositions, + copiedWidgetGroups, + action.payload.mouseLocation, + copiedTotalWidth, + topMostWidget.topRow, + leftMostWidget.leftColumn, + ); + + if (canvasId) pastingIntoWidgetId = canvasId; + yield all( copiedWidgetGroups.map((copiedWidgets) => call(function*() { @@ -883,6 +1275,7 @@ function* pasteWidgetSaga(action: ReduxAction<{ groupWidgets: boolean }>) { pastingIntoWidgetId, widgets, nextAvailableRow, + newPastingPositionMap, true, isThereACollision, shouldGroup, @@ -1002,7 +1395,7 @@ function* pasteWidgetSaga(action: ReduxAction<{ groupWidgets: boolean }>) { ...widgets, [pastingIntoWidgetId]: { ...widgets[pastingIntoWidgetId], - bottomRow: parentBottomRow, + bottomRow: Math.max(parentBottomRow, bottomMostRow || 0), children: parentChildren, }, }; @@ -1064,9 +1457,19 @@ function* pasteWidgetSaga(action: ReduxAction<{ groupWidgets: boolean }>) { ), ); - yield put(updateAndSaveLayout(widgets)); + //calculate the new positions of the reflowed widgets + const reflowedWidgets = getReflowedPositions( + widgets, + gridProps, + reflowedMovementMap, + ); + + yield put(updateAndSaveLayout(reflowedWidgets)); - flashElementsById(newlyCreatedWidgetIds, 100); + //if pasting at the bottom of the canvas, then flash it. + if (shouldGroup || !newPastingPositionMap) { + flashElementsById(newlyCreatedWidgetIds, 100); + } yield put(selectMultipleWidgetsInitAction(newlyCreatedWidgetIds)); } diff --git a/app/client/src/sagas/WidgetOperationUtils.test.ts b/app/client/src/sagas/WidgetOperationUtils.test.ts index a084d3dd8d14..126fa671eb75 100644 --- a/app/client/src/sagas/WidgetOperationUtils.test.ts +++ b/app/client/src/sagas/WidgetOperationUtils.test.ts @@ -1,5 +1,7 @@ +import { OccupiedSpace } from "constants/CanvasEditorConstants"; import { get } from "lodash"; import { WidgetProps } from "widgets/BaseWidget"; +import { FlattenedWidgetProps } from "widgets/constants"; import { handleIfParentIsListWidgetWhilePasting, handleSpecificCasesWhilePasting, @@ -7,6 +9,15 @@ import { checkIfPastingIntoListWidget, updateListWidgetPropertiesOnChildDelete, purgeOrphanedDynamicPaths, + getBoundariesFromSelectedWidgets, + getSnappedGrid, + changeIdsOfPastePositions, + getVerticallyAdjustedPositions, + getNewPositionsForCopiedWidgets, + CopiedWidgetGroup, + getPastePositionMapFromMousePointer, + getReflowedPositions, + getWidgetsFromIds, } from "./WidgetOperationUtils"; describe("WidgetOperationSaga", () => { @@ -622,4 +633,349 @@ describe("WidgetOperationSaga", () => { const result = purgeOrphanedDynamicPaths((input as any) as WidgetProps); expect(result).toStrictEqual(expected); }); + it("should return boundaries of selected Widgets", () => { + const selectedWidgets = ([ + { + id: "1234", + topRow: 10, + leftColumn: 20, + rightColumn: 45, + bottomRow: 40, + }, + { + id: "1233", + topRow: 45, + leftColumn: 30, + rightColumn: 60, + bottomRow: 70, + }, + ] as any) as WidgetProps[]; + expect(getBoundariesFromSelectedWidgets(selectedWidgets)).toEqual({ + totalWidth: 40, + maxThickness: 30, + topMostRow: 10, + leftMostColumn: 20, + }); + }); + describe("test getSnappedGrid", () => { + it("should return snapGrids for a ContainerWidget", () => { + const canvasWidget = ({ + widgetId: "1234", + type: "CONTAINER_WIDGET", + noPad: true, + } as any) as WidgetProps; + expect(getSnappedGrid(canvasWidget, 250)).toEqual({ + padding: 4, + snapGrid: { + snapColumnSpace: 3.78125, + snapRowSpace: 10, + }, + }); + }); + it("should return snapGrids for non ContainerWidget", () => { + const canvasWidget = ({ + widgetId: "1234", + type: "LIST_WIDGET", + noPad: false, + } as any) as WidgetProps; + expect(getSnappedGrid(canvasWidget, 250)).toEqual({ + padding: 10, + snapGrid: { + snapColumnSpace: 3.59375, + snapRowSpace: 10, + }, + }); + }); + }); + it("should test changeIdsOfPastePositions", () => { + const newPastingPositionMap = { + "1234": { + id: "1234", + left: 10, + right: 20, + top: 10, + bottom: 20, + }, + "1235": { + id: "1235", + left: 11, + right: 22, + top: 11, + bottom: 22, + }, + }; + expect(changeIdsOfPastePositions(newPastingPositionMap)).toEqual([ + { + id: "1", + left: 10, + right: 20, + top: 10, + bottom: 20, + }, + { + id: "2", + left: 11, + right: 22, + top: 11, + bottom: 22, + }, + ]); + }); + + it("should offset widgets vertically so that it doesn't overlap with selected widgets", () => { + const selectedWidgets = [ + { + id: "1234", + top: 10, + left: 20, + right: 45, + bottom: 40, + }, + { + id: "1233", + top: 45, + left: 30, + right: 60, + bottom: 70, + }, + { + id: "1235", + topRow: 80, + left: 10, + right: 50, + bottom: 100, + }, + ] as OccupiedSpace[]; + const copiedWidgets = ([ + { + id: "1234", + top: 10, + left: 20, + right: 45, + bottom: 40, + }, + { + id: "1233", + top: 45, + left: 30, + right: 60, + bottom: 70, + }, + ] as any) as OccupiedSpace[]; + expect( + getVerticallyAdjustedPositions(copiedWidgets, selectedWidgets, 30), + ).toEqual({ + "1234": { + id: "1234", + top: 71, + left: 20, + right: 45, + bottom: 101, + }, + "1233": { + id: "1233", + top: 106, + left: 30, + right: 60, + bottom: 131, + }, + }); + }); + it("should test getNewPositionsForCopiedWidgets", () => { + const copiedGroups = ([ + { + widgetId: "1234", + list: [ + { + topRow: 10, + leftColumn: 20, + rightColumn: 45, + bottomRow: 40, + }, + ], + }, + { + widgetId: "1235", + list: [ + { + topRow: 45, + leftColumn: 25, + rightColumn: 40, + bottomRow: 80, + }, + ], + }, + ] as any) as CopiedWidgetGroup[]; + expect( + getNewPositionsForCopiedWidgets(copiedGroups, 10, 40, 20, 10), + ).toEqual([ + { + id: "1234", + top: 40, + left: 10, + right: 35, + bottom: 70, + }, + { + id: "1235", + top: 75, + left: 15, + right: 30, + bottom: 110, + }, + ]); + }); + it("should test getPastePositionMapFromMousePointer", () => { + const copiedGroups = ([ + { + widgetId: "1234", + list: [ + { + topRow: 10, + leftColumn: 20, + rightColumn: 45, + bottomRow: 40, + }, + ], + }, + { + widgetId: "1235", + list: [ + { + topRow: 45, + leftColumn: 25, + rightColumn: 40, + bottomRow: 80, + }, + ], + }, + ] as any) as CopiedWidgetGroup[]; + expect( + getPastePositionMapFromMousePointer(copiedGroups, 10, 40, 20, 10), + ).toEqual({ + "1234": { + id: "1234", + top: 40, + left: 10, + right: 35, + bottom: 70, + }, + "1235": { + id: "1235", + top: 75, + left: 15, + right: 30, + bottom: 110, + }, + }); + }); + it("should test getReflowedPositions", () => { + const widgets = { + "1234": { + widgetId: "1234", + topRow: 40, + leftColumn: 10, + rightColumn: 35, + bottomRow: 70, + } as FlattenedWidgetProps, + "1233": { + widgetId: "1233", + topRow: 45, + leftColumn: 30, + rightColumn: 60, + bottomRow: 70, + } as FlattenedWidgetProps, + "1235": { + widgetId: "1235", + topRow: 75, + leftColumn: 15, + rightColumn: 30, + bottomRow: 110, + } as FlattenedWidgetProps, + }; + + const gridProps = { + parentRowSpace: 10, + parentColumnSpace: 10, + maxGridColumns: 64, + }; + + const reflowingWidgets = { + "1234": { + X: 30, + width: 200, + }, + "1235": { + X: 40, + width: 250, + Y: 50, + height: 250, + }, + }; + + expect(getReflowedPositions(widgets, gridProps, reflowingWidgets)).toEqual({ + "1234": { + widgetId: "1234", + topRow: 40, + leftColumn: 13, + rightColumn: 33, + bottomRow: 70, + }, + "1233": { + widgetId: "1233", + topRow: 45, + leftColumn: 30, + rightColumn: 60, + bottomRow: 70, + }, + "1235": { + widgetId: "1235", + topRow: 80, + leftColumn: 19, + rightColumn: 44, + bottomRow: 105, + }, + }); + }); + it("should test getWidgetsFromIds", () => { + const widgets = { + "1234": { + widgetId: "1234", + topRow: 40, + leftColumn: 10, + rightColumn: 35, + bottomRow: 70, + } as FlattenedWidgetProps, + "1233": { + widgetId: "1233", + topRow: 45, + leftColumn: 30, + rightColumn: 60, + bottomRow: 70, + } as FlattenedWidgetProps, + "1235": { + widgetId: "1235", + topRow: 75, + leftColumn: 15, + rightColumn: 30, + bottomRow: 110, + } as FlattenedWidgetProps, + }; + expect(getWidgetsFromIds(["1235", "1234", "1237"], widgets)).toEqual([ + { + widgetId: "1235", + topRow: 75, + leftColumn: 15, + rightColumn: 30, + bottomRow: 110, + }, + { + widgetId: "1234", + topRow: 40, + leftColumn: 10, + rightColumn: 35, + bottomRow: 70, + }, + ]); + }); }); diff --git a/app/client/src/sagas/WidgetOperationUtils.ts b/app/client/src/sagas/WidgetOperationUtils.ts index a170a36118f1..d2b2b3c95d92 100644 --- a/app/client/src/sagas/WidgetOperationUtils.ts +++ b/app/client/src/sagas/WidgetOperationUtils.ts @@ -6,10 +6,12 @@ import { } from "./selectors"; import _, { isString, remove } from "lodash"; import { + CONTAINER_GRID_PADDING, GridDefaults, MAIN_CONTAINER_WIDGET_ID, RenderModes, WidgetType, + WIDGET_PADDING, } from "constants/WidgetConstants"; import { all, call } from "redux-saga/effects"; import { DataTree } from "entities/DataTree/dataTreeFactory"; @@ -31,6 +33,15 @@ import { import { getNextEntityName } from "utils/AppsmithUtils"; import WidgetFactory from "utils/WidgetFactory"; import { getParentWithEnhancementFn } from "./WidgetEnhancementHelpers"; +import { OccupiedSpace } from "constants/CanvasEditorConstants"; +import { areIntersecting } from "utils/WidgetPropsUtils"; +import { GridProps, ReflowedSpaceMap, SpaceMap } from "reflow/reflowTypes"; +import { + getBaseWidgetClassName, + getSlidingCanvasName, + getStickyCanvasName, + POSITIONED_WIDGET, +} from "constants/componentClassNameConstants"; export interface CopiedWidgetGroup { widgetId: string; @@ -38,6 +49,16 @@ export interface CopiedWidgetGroup { list: WidgetProps[]; } +export type NewPastePositionVariables = { + bottomMostRow?: number; + gridProps?: GridProps; + newPastingPositionMap?: SpaceMap; + reflowedMovementMap?: ReflowedSpaceMap; + canvasId?: string; +}; + +export const WIDGET_PASTE_PADDING = 1; + /** * checks if triggerpaths contains property path passed * @@ -310,6 +331,8 @@ export const getParentWidgetIdForPasting = function*( if (childWidget && childWidget.type === "CANVAS_WIDGET") { newWidgetParentId = childWidget.widgetId; } + } else if (selectedWidget && selectedWidget.type === "CANVAS_WIDGET") { + newWidgetParentId = selectedWidget.widgetId; } return newWidgetParentId; }; @@ -365,7 +388,7 @@ export const checkIfPastingIntoListWidget = function( }; /** - * get top, left, right, bottom most widgets from copied groups when pasting + * get top, left, right, bottom most widgets and and totalWidth from copied groups when pasting * * @param copiedWidgetGroups * @returns @@ -385,15 +408,43 @@ export const getBoundaryWidgetsFromCopiedGroups = function( const bottomMostWidget = copiedWidgetGroups.sort( (a, b) => b.list[0].bottomRow - a.list[0].bottomRow, )[0].list[0]; - return { topMostWidget, leftMostWidget, rightMostWidget, bottomMostWidget, + totalWidth: rightMostWidget.rightColumn - leftMostWidget.leftColumn, }; }; +/** + * get totalWidth, maxThickness, topMostRow and leftMostColumn from selected Widgets + * + * @param selectedWidgets + * @returns + */ +export function getBoundariesFromSelectedWidgets( + selectedWidgets: WidgetProps[], +) { + const topMostWidget = selectedWidgets.sort((a, b) => a.topRow - b.topRow)[0]; + const leftMostWidget = selectedWidgets.sort( + (a, b) => a.leftColumn - b.leftColumn, + )[0]; + const rightMostWidget = selectedWidgets.sort( + (a, b) => b.rightColumn - a.rightColumn, + )[0]; + const thickestWidget = selectedWidgets.sort( + (a, b) => b.bottomRow - b.topRow - a.bottomRow + a.topRow, + )[0]; + + return { + totalWidth: rightMostWidget.rightColumn - leftMostWidget.leftColumn, + maxThickness: thickestWidget.bottomRow - thickestWidget.topRow, + topMostRow: topMostWidget.topRow, + leftMostColumn: leftMostWidget.leftColumn, + }; +} + /** * ------------------------------------------------------------------------------- * OPERATION = PASTING @@ -432,6 +483,442 @@ export const getSelectedWidgetWhenPasting = function*() { return selectedWidget; }; +/** + * calculates mouse positions in terms of grid values + * + * @param canvasRect canvas DOM rect + * @param canvasId Id of the canvas widget + * @param snapGrid grid parameters + * @param padding padding inside of widget + * @param mouseLocation mouse Location in terms of absolute pixel values + * @returns + */ +export function getMousePositions( + canvasRect: DOMRect, + canvasId: string, + snapGrid: { snapRowSpace: number; snapColumnSpace: number }, + padding: number, + mouseLocation?: { x: number; y: number }, +) { + //check if the mouse location is inside of the container widget + if ( + !mouseLocation || + !( + canvasRect.top < mouseLocation.y && + canvasRect.left < mouseLocation.x && + canvasRect.bottom > mouseLocation.y && + canvasRect.right > mouseLocation.x + ) + ) + return; + + //get DOM of the overall canvas including it's total scroll height + const stickyCanvasDOM = document.querySelector( + `#${getStickyCanvasName(canvasId)}`, + ); + if (!stickyCanvasDOM) return; + + const rect = stickyCanvasDOM.getBoundingClientRect(); + + // get mouse position relative to the canvas. + const relativeMouseLocation = { + y: mouseLocation.y - rect.top - padding, + x: mouseLocation.x - rect.left - padding, + }; + + return { + top: Math.floor(relativeMouseLocation.y / snapGrid.snapRowSpace), + left: Math.floor(relativeMouseLocation.x / snapGrid.snapColumnSpace), + }; +} + +/** + * This method calculates the snap Grid dimensions. + * + * @param LayoutWidget + * @param canvasWidth + * @returns + */ +export function getSnappedGrid(LayoutWidget: WidgetProps, canvasWidth: number) { + let padding = (CONTAINER_GRID_PADDING + WIDGET_PADDING) * 2; + if ( + LayoutWidget.widgetId === MAIN_CONTAINER_WIDGET_ID || + LayoutWidget.type === "CONTAINER_WIDGET" + ) { + //For MainContainer and any Container Widget padding doesn't exist coz there is already container padding. + padding = CONTAINER_GRID_PADDING * 2; + } + if (LayoutWidget.noPad) { + // Widgets like ListWidget choose to have no container padding so will only have widget padding + padding = WIDGET_PADDING * 2; + } + const width = canvasWidth - padding; + return { + snapGrid: { + snapRowSpace: GridDefaults.DEFAULT_GRID_ROW_HEIGHT, + snapColumnSpace: canvasWidth + ? width / GridDefaults.DEFAULT_GRID_COLUMNS + : 0, + }, + padding: padding / 2, + }; +} + +/** + * method to return default canvas, + * It is MAIN_CONTAINER_WIDGET_ID by default or + * if a modal is open, then default canvas is a Modal's canvas + * + * @param canvasWidgets + * @returns + */ +export function getDefaultCanvas(canvasWidgets: CanvasWidgetsReduxState) { + const containerDOM = document.querySelector(".t--modal-widget"); + //if a modal is open, then get it's canvas Id + if (containerDOM && containerDOM.id && canvasWidgets[containerDOM.id]) { + const containerWidget = canvasWidgets[containerDOM.id]; + const { canvasDOM, canvasId } = getCanvasIdForContainer(containerWidget); + return { + canvasId, + canvasDOM, + containerWidget, + }; + } else { + //default canvas is set as MAIN_CONTAINER_WIDGET_ID + return { + canvasId: MAIN_CONTAINER_WIDGET_ID, + containerWidget: canvasWidgets[MAIN_CONTAINER_WIDGET_ID], + canvasDOM: document.querySelector( + `#${getSlidingCanvasName(MAIN_CONTAINER_WIDGET_ID)}`, + ), + }; + } +} + +/** + * This method returns the Id of the parent widget of the canvas widget + * + * @param canvasId + * @returns + */ +export function getContainerIdForCanvas(canvasId: string) { + if (canvasId === MAIN_CONTAINER_WIDGET_ID) return canvasId; + + const selector = `#${getSlidingCanvasName(canvasId)}`; + const canvasDOM = document.querySelector(selector); + if (!canvasDOM) return ""; + //check for positionedWidget parent + let containerDOM = canvasDOM.closest(`.${POSITIONED_WIDGET}`); + //if positioned widget parent is not found, most likely is a modal widget + if (!containerDOM) containerDOM = canvasDOM.closest(".t--modal-widget"); + + return containerDOM ? containerDOM.id : ""; +} + +/** + * This method returns Id of the child canvas inside of the Layout Widget + * + * @param layoutWidget + * @returns + */ +export function getCanvasIdForContainer(layoutWidget: WidgetProps) { + const selector = + layoutWidget.type === "MODAL_WIDGET" + ? `.${getBaseWidgetClassName(layoutWidget.widgetId)}` + : `.${POSITIONED_WIDGET}.${getBaseWidgetClassName( + layoutWidget.widgetId, + )}`; + const containerDOM = document.querySelector(selector); + if (!containerDOM) return {}; + const canvasDOM = containerDOM.getElementsByTagName("canvas"); + + return { + canvasId: canvasDOM ? canvasDOM[0]?.id.split("-")[2] : undefined, + canvasDOM: canvasDOM[0], + }; +} + +/** + * This method returns array of occupiedSpaces with changes Ids + * + * @param newPastingPositionMap + * @returns + */ +export function changeIdsOfPastePositions(newPastingPositionMap: SpaceMap) { + const newPastePositions = []; + const newPastingPositionArray = Object.values(newPastingPositionMap); + let count = 1; + for (const position of newPastingPositionArray) { + newPastePositions.push({ + ...position, + id: count.toString(), + }); + count++; + } + + return newPastePositions; +} + +/** + * Iterates over the selected widgets to find the next available space below the selected widgets + * where in the new pasting positions dont overlap with the selected widgets + * + * @param copiedSpaces + * @param selectedSpaces + * @param thickness + * @returns + */ +export function getVerticallyAdjustedPositions( + copiedSpaces: OccupiedSpace[], + selectedSpaces: OccupiedSpace[], + thickness: number, +) { + let verticalOffset = thickness; + + const newPastingPositionMap: SpaceMap = {}; + + //iterate over the widgets to calculate verticalOffset + //TODO: find a better way to do this. + for (let i = 0; i < copiedSpaces.length; i++) { + const copiedSpace = { + ...copiedSpaces[i], + top: copiedSpaces[i].top + verticalOffset, + bottom: copiedSpaces[i].bottom + verticalOffset, + }; + + for (let j = 0; j < selectedSpaces.length; j++) { + const selectedSpace = selectedSpaces[j]; + if (areIntersecting(copiedSpace, selectedSpace)) { + const increment = selectedSpace.bottom - copiedSpace.top; + if (increment > 0) { + verticalOffset += increment; + i = 0; + j = 0; + break; + } else return; + } + } + } + + verticalOffset += WIDGET_PASTE_PADDING; + + // offset the pasting positions down + for (const copiedSpace of copiedSpaces) { + newPastingPositionMap[copiedSpace.id] = { + ...copiedSpace, + top: copiedSpace.top + verticalOffset, + bottom: copiedSpace.bottom + verticalOffset, + }; + } + + return newPastingPositionMap; +} + +/** + * Simple method to convert widget props to occupied spaces + * + * @param widgets + * @returns + */ +export function getOccupiedSpacesFromProps( + widgets: WidgetProps[], +): OccupiedSpace[] { + const occupiedSpaces = []; + for (const widget of widgets) { + const currentSpace = { + id: widget.widgetId, + top: widget.topRow, + left: widget.leftColumn, + bottom: widget.bottomRow, + right: widget.rightColumn, + } as OccupiedSpace; + occupiedSpaces.push(currentSpace); + } + + return occupiedSpaces; +} + +/** + * Method that adjusts the positions of copied spaces using, + * the top-left of copied widgets and top left of where it should be placed + * + * @param copiedWidgetGroups + * @param copiedTopMostRow + * @param selectedTopMostRow + * @param copiedLeftMostColumn + * @param pasteLeftMostColumn + * @returns + */ +export function getNewPositionsForCopiedWidgets( + copiedWidgetGroups: CopiedWidgetGroup[], + copiedTopMostRow: number, + selectedTopMostRow: number, + copiedLeftMostColumn: number, + pasteLeftMostColumn: number, +): OccupiedSpace[] { + const copiedSpacePositions = []; + + // the logic is that, when subtracted by top-left of copied widget, the new position's top-left will be zero + // by adding the selectedTopMostRow or pasteLeftMostColumn, copied widget's top row is aligned there + + const leftOffSet = copiedLeftMostColumn - pasteLeftMostColumn; + const topOffSet = copiedTopMostRow - selectedTopMostRow; + + for (const copiedWidgetGroup of copiedWidgetGroups) { + const copiedWidget = copiedWidgetGroup.list[0]; + + const currentSpace = { + id: copiedWidgetGroup.widgetId, + top: copiedWidget.topRow - topOffSet, + left: copiedWidget.leftColumn - leftOffSet, + bottom: copiedWidget.bottomRow - topOffSet, + right: copiedWidget.rightColumn - leftOffSet, + } as OccupiedSpace; + + copiedSpacePositions.push(currentSpace); + } + + return copiedSpacePositions; +} + +/** + * Method that adjusts the positions of copied spaces using, + * the top-left of copied widgets and top left of where it should be placed + * + * @param copiedWidgetGroups + * @param copiedTopMostRow + * @param mouseTopRow + * @param copiedLeftMostColumn + * @param mouseLeftColumn + * @returns + */ +export function getPastePositionMapFromMousePointer( + copiedWidgetGroups: CopiedWidgetGroup[], + copiedTopMostRow: number, + mouseTopRow: number, + copiedLeftMostColumn: number, + mouseLeftColumn: number, +): SpaceMap { + const newPastingPositionMap: SpaceMap = {}; + + // the logic is that, when subtracted by top-left of copied widget, the new position's top-left will be zero + // by adding the selectedTopMostRow or pasteLeftMostColumn, copied widget's top row is aligned there + + const leftOffSet = copiedLeftMostColumn - mouseLeftColumn; + const topOffSet = copiedTopMostRow - mouseTopRow; + + for (const copiedWidgetGroup of copiedWidgetGroups) { + const copiedWidget = copiedWidgetGroup.list[0]; + + newPastingPositionMap[copiedWidgetGroup.widgetId] = { + id: copiedWidgetGroup.widgetId, + top: copiedWidget.topRow - topOffSet, + left: copiedWidget.leftColumn - leftOffSet, + bottom: copiedWidget.bottomRow - topOffSet, + right: copiedWidget.rightColumn - leftOffSet, + type: copiedWidget.type, + } as OccupiedSpace; + } + + return newPastingPositionMap; +} + +/** + * Take the canvas widgets and move them with the reflowed values + * + * + * @param widgets + * @param gridProps + * @param reflowingWidgets + * @returns + */ +export function getReflowedPositions( + widgets: { + [widgetId: string]: FlattenedWidgetProps; + }, + gridProps?: GridProps, + reflowingWidgets?: ReflowedSpaceMap, +) { + const currentWidgets: { + [widgetId: string]: FlattenedWidgetProps; + } = { ...widgets }; + + const reflowWidgetKeys = Object.keys(reflowingWidgets || {}); + + // if there are no reflowed widgets return the original widgets + if (!reflowingWidgets || !gridProps || reflowWidgetKeys.length <= 0) + return widgets; + + for (const reflowedWidgetId of reflowWidgetKeys) { + const reflowWidget = reflowingWidgets[reflowedWidgetId]; + const canvasWidget = { ...currentWidgets[reflowedWidgetId] }; + + let { bottomRow, leftColumn, rightColumn, topRow } = canvasWidget; + + // adjust the positions with respect to the reflowed positions + if (reflowWidget.X !== undefined && reflowWidget.width !== undefined) { + leftColumn = Math.round( + canvasWidget.leftColumn + reflowWidget.X / gridProps.parentColumnSpace, + ); + rightColumn = Math.round( + leftColumn + reflowWidget.width / gridProps.parentColumnSpace, + ); + } + + if (reflowWidget.Y !== undefined && reflowWidget.height !== undefined) { + topRow = Math.round( + canvasWidget.topRow + reflowWidget.Y / gridProps.parentRowSpace, + ); + bottomRow = Math.round( + topRow + reflowWidget.height / gridProps.parentRowSpace, + ); + } + + currentWidgets[reflowedWidgetId] = { + ...canvasWidget, + topRow, + leftColumn, + bottomRow, + rightColumn, + }; + } + + return currentWidgets; +} + +/** + * method to return array of widget properties from widgetsIds, without any undefined values + * + * @param widgetsIds + * @param canvasWidgets + * @returns array of widgets properties + */ +export function getWidgetsFromIds( + widgetsIds: string[], + canvasWidgets: CanvasWidgetsReduxState, +) { + const widgets = []; + for (const currentId of widgetsIds) { + if (canvasWidgets[currentId]) widgets.push(canvasWidgets[currentId]); + } + + return widgets; +} + +/** + * Check if it is drop target Including the CANVAS_WIDGET + * + * @param type + * @returns + */ +export function isDropTarget(type: WidgetType, includeCanvasWidget = false) { + const isLayoutWidget = !!WidgetFactory.widgetConfigMap.get(type)?.isCanvas; + + if (includeCanvasWidget) return isLayoutWidget || type === "CANVAS_WIDGET"; + + return isLayoutWidget; +} + /** * group copied widgets into a container * diff --git a/app/client/src/utils/generators.tsx b/app/client/src/utils/generators.tsx index ea18eede87f1..660693c10650 100644 --- a/app/client/src/utils/generators.tsx +++ b/app/client/src/utils/generators.tsx @@ -1,5 +1,6 @@ import { WidgetType } from "constants/WidgetConstants"; import generate from "nanoid/generate"; +import { getBaseWidgetClassName } from "../constants/componentClassNameConstants"; const ALPHANUMERIC = "1234567890abcdefghijklmnopqrstuvwxyz"; // const ALPHABET = "abcdefghijklmnopqrstuvwxyz"; @@ -16,7 +17,7 @@ export const generateReactKey = ({ // 2. Property pane reference for positioning // 3. Table widget filter pan reference for positioning export const generateClassName = (seed?: string) => { - return `appsmith_widget_${seed}`; + return getBaseWidgetClassName(seed); }; export const getCanvasClassName = () => "canvas"; diff --git a/app/client/src/widgets/BaseInputWidget/component/index.tsx b/app/client/src/widgets/BaseInputWidget/component/index.tsx index bb452af4c151..ff80dca59583 100644 --- a/app/client/src/widgets/BaseInputWidget/component/index.tsx +++ b/app/client/src/widgets/BaseInputWidget/component/index.tsx @@ -27,6 +27,7 @@ import { InputTypes } from "../constants"; import ErrorTooltip from "components/editorComponents/ErrorTooltip"; import Icon from "components/ads/Icon"; import { InputType } from "widgets/InputWidget/constants"; +import { getBaseWidgetClassName } from "constants/componentClassNameConstants"; import { LabelPosition } from "components/constants"; import LabelWithTooltip, { labelLayoutStyles, @@ -331,7 +332,7 @@ class BaseInputComponent extends React.Component< componentDidMount() { if (isNumberInputType(this.props.inputHTMLType) && this.props.onStep) { const element = document.querySelector<HTMLDivElement>( - `.appsmith_widget_${this.props.widgetId} .bp3-button-group`, + `.${getBaseWidgetClassName(this.props.widgetId)} .bp3-button-group`, ); if (element !== null && element.childNodes) { @@ -350,7 +351,7 @@ class BaseInputComponent extends React.Component< componentWillUnmount() { if (isNumberInputType(this.props.inputHTMLType) && this.props.onStep) { const element = document.querySelector<HTMLDivElement>( - `.appsmith_widget_${this.props.widgetId} .bp3-button-group`, + `.${getBaseWidgetClassName(this.props.widgetId)} .bp3-button-group`, ); if (element !== null && element.childNodes) { diff --git a/app/client/src/widgets/InputWidget/component/index.tsx b/app/client/src/widgets/InputWidget/component/index.tsx index 541ee5ab914a..a068f73116af 100644 --- a/app/client/src/widgets/InputWidget/component/index.tsx +++ b/app/client/src/widgets/InputWidget/component/index.tsx @@ -36,6 +36,7 @@ import ISDCodeDropdown, { import ErrorTooltip from "components/editorComponents/ErrorTooltip"; import Icon from "components/ads/Icon"; import { limitDecimalValue, getSeparators } from "./utilities"; +import { getBaseWidgetClassName } from "constants/componentClassNameConstants"; import { LabelPosition } from "components/constants"; import LabelWithTooltip, { labelLayoutStyles, @@ -298,7 +299,7 @@ class InputComponent extends React.Component< componentDidMount() { if (this.props.inputType === InputTypes.CURRENCY) { const element: any = document.querySelectorAll( - `.appsmith_widget_${this.props.widgetId} .bp3-button`, + `.${getBaseWidgetClassName(this.props.widgetId)} .bp3-button`, ); if (element !== null) { element[0].addEventListener("click", this.onIncrementButtonClick); @@ -313,7 +314,7 @@ class InputComponent extends React.Component< this.props.inputType !== prevProps.inputType ) { const element: any = document.querySelectorAll( - `.appsmith_widget_${this.props.widgetId} .bp3-button`, + `.${getBaseWidgetClassName(this.props.widgetId)} .bp3-button`, ); if (element !== null) { element[0].addEventListener("click", this.onIncrementButtonClick); @@ -325,7 +326,7 @@ class InputComponent extends React.Component< componentWillUnmount() { if (this.props.inputType === InputTypes.CURRENCY) { const element: any = document.querySelectorAll( - `.appsmith_widget_${this.props.widgetId} .bp3-button`, + `.${getBaseWidgetClassName(this.props.widgetId)} .bp3-button`, ); if (element !== null) { element[0].removeEventListener("click", this.onIncrementButtonClick); diff --git a/app/client/src/widgets/ModalWidget/component/index.tsx b/app/client/src/widgets/ModalWidget/component/index.tsx index 12de4f608849..afeca158cfbf 100644 --- a/app/client/src/widgets/ModalWidget/component/index.tsx +++ b/app/client/src/widgets/ModalWidget/component/index.tsx @@ -122,6 +122,7 @@ export type ModalComponentProps = { resizeModal?: (dimensions: UIElementSize) => void; maxWidth?: number; minSize?: number; + widgetId: string; widgetName: string; }; @@ -198,6 +199,7 @@ export default function ModalComponent(props: ModalComponentProps) { }; const getResizableContent = () => { + //id for Content is required for Copy Paste inside the modal return ( <Resizable allowResize @@ -215,6 +217,7 @@ export default function ModalComponent(props: ModalComponentProps) { > <Content className={`${getCanvasClassName()} ${props.className}`} + id={props.widgetId} ref={modalContentRef} scroll={props.scrollContents} > diff --git a/app/client/src/widgets/ModalWidget/widget/index.tsx b/app/client/src/widgets/ModalWidget/widget/index.tsx index b0a27bdd8dce..94355fafcb99 100644 --- a/app/client/src/widgets/ModalWidget/widget/index.tsx +++ b/app/client/src/widgets/ModalWidget/widget/index.tsx @@ -198,6 +198,7 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> { portalContainer={portalContainer} resizeModal={this.onModalResize} scrollContents={!!this.props.shouldScrollContents} + widgetId={this.props.widgetId} widgetName={this.props.widgetName} width={this.getModalWidth(this.props.width)} >
3d8650db4de60116834fde1c09b326801c18e14a
2022-12-13 14:49:22
Sangeeth Sivan
fix: publishing an app removes page permissions (#18865)
false
publishing an app removes page permissions (#18865)
fix
diff --git a/app/client/src/sagas/ApplicationSagas.tsx b/app/client/src/sagas/ApplicationSagas.tsx index e920e254b2dc..d4abb32cd2b8 100644 --- a/app/client/src/sagas/ApplicationSagas.tsx +++ b/app/client/src/sagas/ApplicationSagas.tsx @@ -1,5 +1,6 @@ import { ApplicationPayload, + Page, ReduxAction, ReduxActionErrorTypes, ReduxActionTypes, @@ -93,7 +94,7 @@ import { getDefaultPageId as selectDefaultPageId } from "./selectors"; import PageApi from "api/PageApi"; import { identity, merge, pickBy } from "lodash"; import { checkAndGetPluginFormConfigsSaga } from "./PluginSagas"; -import { getPluginForm } from "selectors/entitiesSelector"; +import { getPageList, getPluginForm } from "selectors/entitiesSelector"; import { getConfigInitialValues } from "components/formControls/utils"; import DatasourcesApi from "api/DatasourcesApi"; import { resetApplicationWidgets } from "actions/pageActions"; @@ -227,6 +228,11 @@ export function* fetchAppAndPagesSaga( ); const isValidResponse: boolean = yield call(validateResponse, response); if (isValidResponse) { + const prevPagesState: Page[] = yield select(getPageList); + const pagePermissionsMap = prevPagesState.reduce((acc, page) => { + acc[page.pageId] = page.userPermissions ?? []; + return acc; + }, {} as Record<string, string[]>); yield put({ type: ReduxActionTypes.FETCH_APPLICATION_SUCCESS, payload: { ...response.data.application, pages: response.data.pages }, @@ -242,7 +248,9 @@ export function* fetchAppAndPagesSaga( isHidden: !!page.isHidden, slug: page.slug, customSlug: page.customSlug, - userPermissions: page.userPermissions, + userPermissions: page.userPermissions + ? page.userPermissions + : pagePermissionsMap[page.id], })), applicationId: response.data.application?.id, }, diff --git a/app/client/src/sagas/PageSagas.tsx b/app/client/src/sagas/PageSagas.tsx index d1993fe9ab3f..a700130623b2 100644 --- a/app/client/src/sagas/PageSagas.tsx +++ b/app/client/src/sagas/PageSagas.tsx @@ -133,6 +133,7 @@ import { getSelectedWidgets } from "selectors/ui"; import { checkAndLogErrorsIfCyclicDependency } from "./helper"; import { LOCAL_STORAGE_KEYS } from "utils/localStorage"; import { generateAutoHeightLayoutTreeAction } from "actions/autoHeightActions"; +import { getPageList } from "selectors/entitiesSelector"; const WidgetTypes = WidgetFactory.widgetTypes; @@ -153,6 +154,11 @@ export function* fetchPageListSaga( : PageApi.fetchPageListViewMode; const response: FetchPageListResponse = yield call(apiCall, applicationId); const isValidResponse: boolean = yield validateResponse(response); + const prevPagesState: Page[] = yield select(getPageList); + const pagePermissionsMap = prevPagesState.reduce((acc, page) => { + acc[page.pageId] = page.userPermissions ?? []; + return acc; + }, {} as Record<string, string[]>); if (isValidResponse) { const workspaceId = response.data.workspaceId; const pages: Page[] = response.data.pages.map((page) => ({ @@ -161,7 +167,9 @@ export function* fetchPageListSaga( isDefault: page.isDefault, isHidden: !!page.isHidden, slug: page.slug, - userPermissions: page.userPermissions, + userPermissions: page.userPermissions + ? page.userPermissions + : pagePermissionsMap[page.id], })); yield put({ type: ReduxActionTypes.SET_CURRENT_WORKSPACE_ID,
97c86afd35ca552d32d0bc04d5138e0d3a29227a
2022-10-07 11:47:04
Dhruvik Neharia
feat: Video Widget Reskinning (#17355)
false
Video Widget Reskinning (#17355)
feat
diff --git a/app/client/src/widgets/VideoWidget/index.ts b/app/client/src/widgets/VideoWidget/index.ts index 4ea1ef482e02..6b02911553a3 100644 --- a/app/client/src/widgets/VideoWidget/index.ts +++ b/app/client/src/widgets/VideoWidget/index.ts @@ -15,6 +15,7 @@ export const CONFIG = { autoPlay: false, version: 1, animateLoading: true, + backgroundColor: "#000", }, properties: { derived: Widget.getDerivedPropertiesMap(),
028070eeb2fd83ae176cdca5e2f8a8622908ca03
2020-09-23 19:36:50
devrk96
feature: Variable addition in light and dark theme (#677)
false
Variable addition in light and dark theme (#677)
feature
diff --git a/app/client/src/components/ads/AppIcon.tsx b/app/client/src/components/ads/AppIcon.tsx index 296b00da1e31..c8f920bb0047 100644 --- a/app/client/src/components/ads/AppIcon.tsx +++ b/app/client/src/components/ads/AppIcon.tsx @@ -14,7 +14,7 @@ import { ReactComponent as FlightIcon } from "assets/icons/ads/flight.svg"; import styled from "styled-components"; import { Size } from "./Button"; -import { CommonComponentProps } from "./common"; +import { CommonComponentProps, Classes } from "./common"; export const AppIconCollection = [ "bag", @@ -72,7 +72,7 @@ const IconWrapper = styled.a<AppIconProps & { styledProps: cssAttributes }>` width: ${props => props.styledProps.width}px; height: ${props => props.styledProps.height}px; path { - fill: ${props => props.theme.colors.blackShades[7]}; + fill: ${props => props.theme.colors.appIcon.normal}; } } `; @@ -133,6 +133,7 @@ const AppIcon = (props: AppIconProps) => { <IconWrapper data-cy={props.cypressSelector} {...props} + className={Classes.APP_ICON} styledProps={styledProps} > {returnIcon} diff --git a/app/client/src/components/ads/Button.tsx b/app/client/src/components/ads/Button.tsx index cccc465e0320..94b41d35393d 100644 --- a/app/client/src/components/ads/Button.tsx +++ b/app/client/src/components/ads/Button.tsx @@ -81,19 +81,19 @@ const stateStyles = ( bgColorPrimary = props.theme.colors[props.variant].darkest; borderColorPrimary = props.theme.colors[props.variant].darkest; } - txtColorPrimary = props.theme.colors.blackShades[6]; + txtColorPrimary = props.theme.colors.button.disabledText; break; case Category.secondary: if (props.variant) { bgColorSecondary = props.theme.colors[props.variant].darkest; borderColorSecondary = props.theme.colors[props.variant].darker; } - txtColorSecondary = props.theme.colors.blackShades[6]; + txtColorSecondary = props.theme.colors.button.disabledText; break; case Category.tertiary: bgColorTertiary = props.theme.colors.tertiary.darker; borderColorTertiary = props.theme.colors.tertiary.dark; - txtColorTertiary = props.theme.colors.blackShades[6]; + txtColorTertiary = props.theme.colors.button.disabledText; break; } } else if (state === "main") { diff --git a/app/client/src/components/ads/Checkbox.tsx b/app/client/src/components/ads/Checkbox.tsx index 19e6400bec1c..abcd03a07195 100644 --- a/app/client/src/components/ads/Checkbox.tsx +++ b/app/client/src/components/ads/Checkbox.tsx @@ -19,16 +19,16 @@ const Checkmark = styled.span<{ background-color: ${props => props.isChecked ? props.disabled - ? props.theme.colors.blackShades[3] + ? props.theme.colors.checkbox.disabled : props.theme.colors.info.main : "transparent"}; border: 2px solid ${props => props.isChecked ? props.disabled - ? props.theme.colors.blackShades[3] + ? props.theme.colors.checkbox.disabled : props.theme.colors.info.main - : props.theme.colors.blackShades[4]}; + : props.theme.colors.checkbox.unchecked}; &::after { content: ""; @@ -40,7 +40,9 @@ const Checkmark = styled.span<{ height: 11px; border: solid ${props => - props.disabled ? "#565656" : props.theme.colors.blackShades[9]}; + props.disabled + ? props.theme.colors.checkbox.disabledCheck + : props.theme.colors.checkbox.normalCheck}; border-width: 0 2px 2px 0; transform: rotate(45deg); } @@ -57,7 +59,7 @@ const StyledCheckbox = styled.label<{ font-size: ${props => props.theme.typography.p1.fontSize}px; line-height: ${props => props.theme.typography.p1.lineHeight}px; letter-spacing: ${props => props.theme.typography.p1.letterSpacing}px; - color: ${props => props.theme.colors.blackShades[7]}; + color: ${props => props.theme.colors.checkbox.labelColor}; padding-left: ${props => props.theme.spaces[12] - 2}px; input { diff --git a/app/client/src/components/ads/ColorSelector.tsx b/app/client/src/components/ads/ColorSelector.tsx index c033ecea44e8..b58c50a3b82b 100644 --- a/app/client/src/components/ads/ColorSelector.tsx +++ b/app/client/src/components/ads/ColorSelector.tsx @@ -29,7 +29,8 @@ const ColorBox = styled.div<{ selected: string; color: string }>` position: relative; &:hover { - box-shadow: 0px 0px 0px ${props => props.theme.spaces[1] - 1}px #353535; + box-shadow: 0px 0px 0px ${props => props.theme.spaces[1] - 1}px + ${props => props.theme.colors.colorSelector.shadow}; } &:last-child { @@ -45,8 +46,8 @@ const ColorBox = styled.div<{ selected: string; color: string }>` top: ${props.theme.spaces[1] - 1}px width: ${props.theme.spaces[2] - 1}px height: ${props.theme.spaces[4] - 1}px - border: 1.5px solid ${props.theme.colors.blackShades[9]}; - border-width: 0 1.5px 1.5px 0; + border: 2px solid ${props.theme.colors.colorSelector.checkmark}; + border-width: 0 2px 2px 0; transform: rotate(45deg); }` : ` diff --git a/app/client/src/components/ads/Dropdown.tsx b/app/client/src/components/ads/Dropdown.tsx index fa98463c94c5..c55df20e19dc 100644 --- a/app/client/src/components/ads/Dropdown.tsx +++ b/app/client/src/components/ads/Dropdown.tsx @@ -27,8 +27,8 @@ const Selected = styled.div<{ isOpen: boolean; disabled?: boolean }>` ${props => props.theme.spaces[6]}px; background: ${props => props.disabled - ? props.theme.colors.blackShades[2] - : props.theme.colors.blackShades[0]}; + ? props.theme.colors.dropdown.header.disabledText + : props.theme.colors.dropdown.header.disabledBg}; display: flex; align-items: center; justify-content: space-between; @@ -47,15 +47,15 @@ const Selected = styled.div<{ isOpen: boolean; disabled?: boolean }>` .${Classes.TEXT} { ${props => props.disabled - ? `color: ${props.theme.colors.blackShades[6]}` - : `color: ${props.theme.colors.blackShades[7]}`}; + ? `color: ${props.theme.colors.dropdown.text}` + : `color: ${props.theme.colors.dropdown.disabledText}`}; } `; const DropdownWrapper = styled.div` margin-top: ${props => props.theme.spaces[2] - 1}px; - background: ${props => props.theme.colors.blackShades[3]}; - box-shadow: 0px 12px 28px rgba(0, 0, 0, 0.6); + background: ${props => props.theme.colors.dropdown.menuBg}; + box-shadow: 0px 12px 28px ${props => props.theme.colors.dropdown.menuShadow}; width: 100%; `; @@ -66,10 +66,14 @@ const OptionWrapper = styled.div<{ selected: boolean }>` display: flex; align-items: center; ${props => - props.selected ? `background: ${props.theme.colors.blackShades[4]}` : null}; + props.selected + ? `background: ${props.theme.colors.dropdown.selected.bg}` + : null}; .${Classes.TEXT} { ${props => - props.selected ? `color: ${props.theme.colors.blackShades[9]}` : null}; + props.selected + ? `color: ${props.theme.colors.dropdown.selected.text}` + : null}; } .${Classes.ICON} { margin-right: ${props => props.theme.spaces[5]}px; @@ -77,20 +81,20 @@ const OptionWrapper = styled.div<{ selected: boolean }>` path { ${props => props.selected - ? `fill: ${props.theme.colors.blackShades[8]}` - : `fill: ${props.theme.colors.blackShades[6]}`}; + ? `fill: ${props.theme.colors.dropdown.selected.icon}` + : `fill: ${props.theme.colors.dropdown.icon}`}; } } } &:hover { .${Classes.TEXT} { - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.dropdown.selected.text}; } .${Classes.ICON} { svg { path { - fill: ${props => props.theme.colors.blackShades[8]}; + fill: ${props => props.theme.colors.dropdown.selected.icon}; } } } @@ -100,7 +104,7 @@ const OptionWrapper = styled.div<{ selected: boolean }>` const LabelWrapper = styled.div<{ label?: string }>` display: flex; flex-direction: column; - align-item: flex-start; + align-items: flex-start; ${props => props.label diff --git a/app/client/src/components/ads/EditableText.tsx b/app/client/src/components/ads/EditableText.tsx index 0b855cc4ca60..4a6c8426bb5e 100644 --- a/app/client/src/components/ads/EditableText.tsx +++ b/app/client/src/components/ads/EditableText.tsx @@ -3,7 +3,7 @@ import { EditableText as BlueprintEditableText } from "@blueprintjs/core"; import styled from "styled-components"; import Text, { TextType } from "./Text"; import Spinner from "./Spinner"; -import { hexToRgba, Classes, CommonComponentProps } from "./common"; +import { Classes, CommonComponentProps } from "./common"; import { noop } from "lodash"; import Icon, { IconSize } from "./Icon"; import { getThemeDetails } from "selectors/themeSelectors"; @@ -55,9 +55,9 @@ const editModeBgcolor = ( theme: any, ): string => { if ((isInvalid && isEditing) || savingState === SavingState.ERROR) { - return hexToRgba(theme.colors.danger.main, 0.08); + return theme.colors.editableText.dangerBg; } else if (!isInvalid && isEditing) { - return theme.colors.blackShades[2]; + return theme.colors.editableText.bg; } else { return "transparent"; } @@ -89,7 +89,7 @@ const TextContainer = styled.div<{ &&& .bp3-editable-text-content { cursor: pointer; - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.editableText.color}; overflow: hidden; text-overflow: ellipsis; ${props => (props.isEditing ? "display: none" : "display: block")}; @@ -99,7 +99,7 @@ const TextContainer = styled.div<{ border: none; outline: none; height: ${props => props.theme.spaces[13] + 3}px; - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.editableText.color}; min-width: 100%; border-radius: ${props => props.theme.spaces[0]}px; } diff --git a/app/client/src/components/ads/Icon.tsx b/app/client/src/components/ads/Icon.tsx index 7550f46194a6..5db54588aaa8 100644 --- a/app/client/src/components/ads/Icon.tsx +++ b/app/client/src/components/ads/Icon.tsx @@ -101,7 +101,7 @@ const IconWrapper = styled.span<IconProps>` width: ${props => sizeHandler(props.size)}px; height: ${props => sizeHandler(props.size)}px; path { - fill: ${props => props.theme.colors.blackShades[6]}; + fill: ${props => props.theme.colors.icon.normal}; } } visibility: ${props => (props.invisible ? "hidden" : "visible")}; @@ -109,14 +109,14 @@ const IconWrapper = styled.span<IconProps>` &:hover { cursor: pointer; path { - fill: ${props => props.theme.colors.blackShades[8]}; + fill: ${props => props.theme.colors.icon.hover}; } } &:active { cursor: pointer; path { - fill: ${props => props.theme.colors.blackShades[9]}; + fill: ${props => props.theme.colors.icon.active}; } } `; diff --git a/app/client/src/components/ads/IconSelector.tsx b/app/client/src/components/ads/IconSelector.tsx index 57a8214b9a79..0dc17980fb0e 100644 --- a/app/client/src/components/ads/IconSelector.tsx +++ b/app/client/src/components/ads/IconSelector.tsx @@ -2,7 +2,7 @@ import React, { useState, useEffect } from "react"; import styled from "styled-components"; import AppIcon, { AppIconName, AppIconCollection } from "./AppIcon"; import { Size } from "./Button"; -import { CommonComponentProps } from "./common"; +import { CommonComponentProps, Classes } from "./common"; type IconSelectorProps = CommonComponentProps & { onSelect?: (icon: AppIconName) => void; @@ -28,7 +28,7 @@ const IconBox = styled.div<{ selectedColor?: string }>` justify-content: center; align-items: center; background-color: ${props => - props.selectedColor || props.theme.colors.blackShades[2]}; + props.selectedColor || props.theme.colors.appIcon.background}; margin: 0 ${props => props.theme.spaces[2]}px ${props => props.theme.spaces[2]}px 0; position: relative; @@ -36,6 +36,17 @@ const IconBox = styled.div<{ selectedColor?: string }>` &:nth-child(6n) { margin-right: ${props => props.theme.spaces[0]}px; } + + ${props => + props.selectedColor + ? `.${Classes.APP_ICON} { + svg { + path { + fill: #fff; + } + } + }` + : null}; `; const IconSelector = (props: IconSelectorProps) => { diff --git a/app/client/src/components/ads/Menu.tsx b/app/client/src/components/ads/Menu.tsx index d19971d87c9a..6ace64786b7a 100644 --- a/app/client/src/components/ads/Menu.tsx +++ b/app/client/src/components/ads/Menu.tsx @@ -1,5 +1,5 @@ import React, { ReactNode } from "react"; -import { CommonComponentProps, Classes } from "./common"; +import { CommonComponentProps } from "./common"; import styled from "styled-components"; import { Popover } from "@blueprintjs/core/lib/esm/components/popover/popover"; import { Position } from "@blueprintjs/core/lib/esm/common/position"; @@ -14,18 +14,12 @@ type MenuProps = CommonComponentProps & { const MenuWrapper = styled.div` width: 234px; - background: ${props => props.theme.colors.blackShades[3]}; - box-shadow: 0px 12px 28px rgba(0, 0, 0, 0.75); + background: ${props => props.theme.colors.menu.background}; + box-shadow: 0px 12px 28px ${props => props.theme.colors.menu.shadow}; `; const MenuOption = styled.div` - color: ${props => props.theme.colors.blackShades[6]}; font-family: ${props => props.theme.fonts[3]}; - .${Classes.ICON} { - path { - fill: ${props => props.theme.colors.blackShades[6]}; - } - } `; const Menu = (props: MenuProps) => { @@ -36,6 +30,7 @@ const Menu = (props: MenuProps) => { onOpening={props.onOpening} onClosing={props.onClosing} className={props.className} + portalClassName={props.className} data-cy={props.cypressSelector} > {props.target} diff --git a/app/client/src/components/ads/MenuDivider.tsx b/app/client/src/components/ads/MenuDivider.tsx index b8ba4aef299c..98bc9894ee35 100644 --- a/app/client/src/components/ads/MenuDivider.tsx +++ b/app/client/src/components/ads/MenuDivider.tsx @@ -3,7 +3,7 @@ import styled from "styled-components"; const MenuDivider = styled.div` margin: ${props => props.theme.spaces[1]}px ${props => props.theme.spaces[6]}px; - border-top: 1px solid #404040; + border-top: 1px solid ${props => props.theme.colors.menuBorder}; `; export default MenuDivider; diff --git a/app/client/src/components/ads/MenuItem.tsx b/app/client/src/components/ads/MenuItem.tsx index 917107f0e498..08f763eec513 100644 --- a/app/client/src/components/ads/MenuItem.tsx +++ b/app/client/src/components/ads/MenuItem.tsx @@ -18,21 +18,31 @@ const ItemRow = styled.a<{ disabled?: boolean }>` justify-content: space-between; text-decoration: none; padding: 0px ${props => props.theme.spaces[6]}px; + .${Classes.TEXT} { + color: ${props => props.theme.colors.menuItem.normalText}; + } + .${Classes.ICON} { + svg { + path { + fill: ${props => props.theme.colors.menuItem.normalIcon}; + } + } + } height: 38px; ${props => !props.disabled ? ` &:hover { - cursor: pointer; text-decoration: none; - background-color: ${props.theme.colors.blackShades[4]}; + cursor: pointer; + background-color: ${props.theme.colors.menuItem.hoverBg}; .${Classes.TEXT} { - color: ${props.theme.colors.blackShades[9]}; + color: ${props.theme.colors.menuItem.hoverText}; } .${Classes.ICON} { path { - fill: ${props.theme.colors.blackShades[9]}; + fill: ${props.theme.colors.menuItem.hoverIcon}; } } }` diff --git a/app/client/src/components/ads/Radio.tsx b/app/client/src/components/ads/Radio.tsx index d79b2b63bcc2..f853383df0b2 100644 --- a/app/client/src/components/ads/Radio.tsx +++ b/app/client/src/components/ads/Radio.tsx @@ -44,7 +44,7 @@ const Radio = styled.label<{ font-weight: ${props => props.theme.typography.p1.fontWeight}; line-height: ${props => props.theme.typography.p1.lineHeight}px; letter-spacing: ${props => props.theme.typography.p1.letterSpacing}px; - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.radio.text}; ${props => props.rows && props.rows > 0 ? `flex-basis: calc(100% / ${props.rows})` @@ -71,7 +71,7 @@ const Radio = styled.label<{ height: ${props => props.theme.spaces[8]}px; background-color: transparent; border: ${props => props.theme.spaces[1] - 2}px solid - ${props => props.theme.colors.blackShades[4]}; + ${props => props.theme.colors.radio.border}; border-radius: 50%; margin-top: ${props => props.theme.spaces[0]}px; } diff --git a/app/client/src/components/ads/RectangularSwitcher.tsx b/app/client/src/components/ads/RectangularSwitcher.tsx index 03dd1ce2cf49..506a0f0dca6c 100644 --- a/app/client/src/components/ads/RectangularSwitcher.tsx +++ b/app/client/src/components/ads/RectangularSwitcher.tsx @@ -30,7 +30,7 @@ const StyledSwitch = styled.label<{ cursor: pointer; top: 0; left: 0; - border: 1px solid ${props => props.theme.colors.blackShades[5]}; + border: 1px solid ${props => props.theme.colors.switch.border}; background-color: ${props => props.theme.colors.info.main}; width: 78px; height: 26px; @@ -43,7 +43,7 @@ const StyledSwitch = styled.label<{ width: 36px; height: 20px; top: 2px; - background-color: ${props.theme.colors.blackShades[0]}; + background-color: ${props.theme.colors.switch.bg}; left: ${props.value && !props.firstRender ? "38px" : "2px"}; transition: ${props.firstRender ? "0.4s" : "none"}; } @@ -54,17 +54,20 @@ const StyledSwitch = styled.label<{ } input:checked + .slider:before { - background-color: ${props => props.theme.colors.blackShades[0]}; + background-color: ${props => props.theme.colors.switch.hover.bg}; } input:hover + .slider { - border: 1px solid ${props => props.theme.colors.blackShades[7]}; + border: 1px solid ${props => props.theme.colors.switch.hover.border}; } `; const Light = styled.div<{ value: boolean }>` .${Classes.TEXT} { - color: ${props => (props.value ? "#FFFFFF" : "#939090")}; + color: ${props => + props.value + ? props.theme.colors.switch.lightText + : props.theme.colors.switch.darkText}; font-size: 10px; line-height: 12px; letter-spacing: -0.171429px; @@ -75,11 +78,11 @@ const Light = styled.div<{ value: boolean }>` `; const Dark = styled.div<{ value: boolean }>` - .${Classes.TEXT} { + &&&& .${Classes.TEXT} { font-size: 10px; line-height: 12px; letter-spacing: -0.171429px; - color: ${props => (!props.value ? "#FFFFFF" : "#939090")}; + color: ${props => props.theme.colors.switch.lightText}; } position: absolute; top: 3px; diff --git a/app/client/src/components/ads/SearchInput.tsx b/app/client/src/components/ads/SearchInput.tsx index c3b43c3030fb..9aa36d2f98c2 100644 --- a/app/client/src/components/ads/SearchInput.tsx +++ b/app/client/src/components/ads/SearchInput.tsx @@ -41,10 +41,10 @@ const StyledInput = styled.input< letter-spacing: ${props => props.theme.typography.p1.letterSpacing}px; text-overflow: ellipsis; - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.searchInput.text}; &::placeholder { - color: ${props => props.theme.colors.blackShades[5]}; + color: ${props => props.theme.colors.searchInput.placeholder}; } `; @@ -61,12 +61,14 @@ const InputWrapper = styled.div<{ ${props => props.theme.spaces[6]}px; width: ${props => (props.fill ? "100%" : "210px")}; background-color: ${props => - props.variant === SearchVariant.SEAMLESS ? "transparent" : "#262626"}; + props.variant === SearchVariant.SEAMLESS + ? "transparent" + : props.theme.colors.searchInput.bg}; ${props => props.variant === SearchVariant.BACKGROUND ? props.isFocused || props.value ? `box-shadow: 0px 1px 0px ${props.theme.colors.info.main}` - : `box-shadow: 0px 1px 0px ${props.theme.colors.blackShades[4]}` + : `box-shadow: 0px 1px 0px ${props.theme.colors.searchInput.border}` : null} `; @@ -82,8 +84,8 @@ const SearchIcon = styled.div<{ circle { stroke: ${props => props.isFocused || props.value - ? props.theme.colors.blackShades[7] - : props.theme.colors.blackShades[5]}; + ? props.theme.colors.searchInput.icon.focused + : props.theme.colors.searchInput.icon.normal}; } } } diff --git a/app/client/src/components/ads/Spinner.tsx b/app/client/src/components/ads/Spinner.tsx index 2f40c640a1cb..737af40a2388 100644 --- a/app/client/src/components/ads/Spinner.tsx +++ b/app/client/src/components/ads/Spinner.tsx @@ -31,7 +31,7 @@ const SvgContainer = styled.svg<SpinnerProp>` `; const SvgCircle = styled.circle` - stroke: ${props => props.theme.colors.blackShades[9]}; + stroke: ${props => props.theme.colors.spinner}; stroke-linecap: round; animation: ${dash} 1.5s ease-in-out infinite; stroke-width: ${props => props.theme.spaces[1]}px; diff --git a/app/client/src/components/ads/Table.tsx b/app/client/src/components/ads/Table.tsx index aadb9a33062d..ae371e134b43 100644 --- a/app/client/src/components/ads/Table.tsx +++ b/app/client/src/components/ads/Table.tsx @@ -12,7 +12,7 @@ const Styles = styled.div` thead { tr { - background-color: ${props => props.theme.colors.blackShades[2]}; + background-color: ${props => props.theme.colors.table.headerBg}; th:first-child { padding: 0 ${props => props.theme.spaces[9]}px; @@ -21,7 +21,7 @@ const Styles = styled.div` th { padding: ${props => props.theme.spaces[5]}px 0; text-align: left; - color: ${props => props.theme.colors.blackShades[5]}; + color: ${props => props.theme.colors.table.headerText}; font-weight: ${props => props.theme.fontWeights[1]}; font-size: ${props => props.theme.typography.h6.fontSize}px; line-height: ${props => props.theme.typography.h6.lineHeight}px; @@ -33,11 +33,11 @@ const Styles = styled.div` } &:hover { - color: ${props => props.theme.colors.blackShades[7]}; + color: ${props => props.theme.colors.table.hover.headerColor}; cursor: pointer; svg { path { - fill: ${props => props.theme.colors.blackShades[7]}; + fill: ${props => props.theme.colors.table.hover.headerColor}; } } } @@ -48,33 +48,33 @@ const Styles = styled.div` tbody { tr { td:first-child { - color: ${props => props.theme.colors.blackShades[7]}; + color: ${props => props.theme.colors.table.rowTitle}; padding: 0 ${props => props.theme.spaces[9]}px; font-weight: ${props => props.theme.fontWeights[1]}; } td { padding: ${props => props.theme.spaces[4]}px 0; - color: ${props => props.theme.colors.blackShades[6]}; + color: ${props => props.theme.colors.table.rowData}; font-size: ${props => props.theme.typography.p1.fontSize}px; line-height: ${props => props.theme.typography.p1.lineHeight}px; letter-spacing: ${props => props.theme.typography.p1.letterSpacing}px; font-weight: normal; - border-bottom: 1px solid ${props => props.theme.colors.blackShades[3]}; + border-bottom: 1px solid ${props => props.theme.colors.table.border}; } &:hover { - background-color: ${props => props.theme.colors.blackShades[4]}; + background-color: ${props => props.theme.colors.table.hover.rowBg}; .${Classes.ICON} { path { - fill: ${props => props.theme.colors.blackShades[9]}; + fill: ${props => props.theme.colors.table.hover.rowTitle}; } } td:first-child { - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.table.hover.rowTitle}; } td { - color: ${props => props.theme.colors.blackShades[7]}; + color: ${props => props.theme.colors.table.hover.rowData}; } } } diff --git a/app/client/src/components/ads/TableDropdown.tsx b/app/client/src/components/ads/TableDropdown.tsx index 00d74ae7b85c..9b14f0520670 100644 --- a/app/client/src/components/ads/TableDropdown.tsx +++ b/app/client/src/components/ads/TableDropdown.tsx @@ -1,5 +1,5 @@ import React, { useState } from "react"; -import { CommonComponentProps, hexToRgba, Classes } from "./common"; +import { CommonComponentProps, Classes } from "./common"; import { ReactComponent as DownArrow } from "assets/icons/ads/down_arrow.svg"; import Text, { TextType } from "./Text"; import styled from "styled-components"; @@ -36,10 +36,10 @@ const OptionsWrapper = styled.div` width: 200px; display: flex; flex-direction: column; - background-color: ${props => props.theme.colors.blackShades[3]}; + background-color: ${props => props.theme.colors.tableDropdown.bg}; box-shadow: ${props => props.theme.spaces[0]}px ${props => props.theme.spaces[5]}px ${props => props.theme.spaces[13] - 2}px - ${props => hexToRgba(props.theme.colors.blackShades[0], 0.75)}; + ${props => props.theme.colors.tableDropdown.shadow}; `; const DropdownOption = styled.div<{ @@ -51,7 +51,7 @@ const DropdownOption = styled.div<{ cursor: pointer; ${props => props.isSelected - ? `background-color: ${props.theme.colors.blackShades[4]}` + ? `background-color: ${props.theme.colors.tableDropdown.selectedBg}` : null}; .${Classes.TEXT}:last-child { @@ -60,7 +60,7 @@ const DropdownOption = styled.div<{ &:hover { .${Classes.TEXT} { - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.tableDropdown.selectedText}; } } `; diff --git a/app/client/src/components/ads/Tabs.tsx b/app/client/src/components/ads/Tabs.tsx index 0e79d959e912..f159b2103483 100644 --- a/app/client/src/components/ads/Tabs.tsx +++ b/app/client/src/components/ads/Tabs.tsx @@ -30,10 +30,10 @@ const TabsWrapper = styled.div<{ shouldOverflow?: boolean }>` display: flex; align-items: center; border-bottom: ${props => props.theme.spaces[1] - 2}px solid - ${props => props.theme.colors.blackShades[3]}; - color: ${props => props.theme.colors.blackShades[6]}; + ${props => props.theme.colors.tabs.border}; + color: ${props => props.theme.colors.tabs.normal}; path { - fill: ${props => props.theme.colors.blackShades[6]}; + fill: ${props => props.theme.colors.tabs.normal}; } ${props => props.shouldOverflow && @@ -57,17 +57,17 @@ const TabsWrapper = styled.div<{ shouldOverflow?: boolean }>` position: relative; } .react-tabs__tab:hover { - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.tabs.hover}; path { - fill: ${props => props.theme.colors.blackShades[9]}; + fill: ${props => props.theme.colors.tabs.hover}; } } .react-tabs__tab--selected { - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.tabs.hover}; background-color: transparent; path { - fill: ${props => props.theme.colors.blackShades[9]}; + fill: ${props => props.theme.colors.tabs.hover}; } &::after { @@ -93,7 +93,7 @@ const TabsWrapper = styled.div<{ shouldOverflow?: boolean }>` box-shadow: none; border-color: transparent; path { - fill: ${props => props.theme.colors.blackShades[9]}; + fill: ${props => props.theme.colors.tabs.hover}; } } `; diff --git a/app/client/src/components/ads/Text.tsx b/app/client/src/components/ads/Text.tsx index fda263932070..b657ca2c325b 100644 --- a/app/client/src/components/ads/Text.tsx +++ b/app/client/src/components/ads/Text.tsx @@ -38,16 +38,16 @@ const typeSelector = (props: TextProps & ThemeProp): string => { let color = ""; switch (props.type) { case TextType.P1: - color = props.theme.colors.blackShades[6]; + color = props.theme.colors.text.normal; break; case TextType.P2: - color = props.theme.colors.blackShades[6]; + color = props.theme.colors.text.normal; break; case TextType.P3: - color = props.theme.colors.blackShades[6]; + color = props.theme.colors.text.normal; break; default: - color = props.theme.colors.blackShades[7]; + color = props.theme.colors.text.heading; break; } return color; @@ -70,7 +70,7 @@ const Text = styled.span.attrs((props: TextProps) => ({ letter-spacing: ${props => props.theme.typography[props.type].letterSpacing}px; color: ${props => - props.highlight ? props.theme.colors.blackShades[9] : typeSelector(props)}; + props.highlight ? props.theme.colors.text.hightlight : typeSelector(props)}; text-transform: ${props => (props.case ? props.case : "none")}; `; diff --git a/app/client/src/components/ads/TextInput.tsx b/app/client/src/components/ads/TextInput.tsx index 92c040cef18b..b2bc1d87e637 100644 --- a/app/client/src/components/ads/TextInput.tsx +++ b/app/client/src/components/ads/TextInput.tsx @@ -52,14 +52,14 @@ const boxStyles = ( isValid: boolean, theme: any, ): boxReturnType => { - let bgColor = theme.colors.blackShades[0]; - let color = theme.colors.blackShades[9]; - let borderColor = theme.colors.blackShades[0]; + let bgColor = theme.colors.textInput.normal.bg; + let color = theme.colors.textInput.normal.text; + let borderColor = theme.colors.textInput.normal.border; if (props.disabled) { - bgColor = theme.colors.blackShades[2]; - color = theme.colors.blackShades[6]; - borderColor = theme.colors.blackShades[2]; + bgColor = theme.colors.textInput.disable.bg; + color = theme.colors.textInput.disable.text; + borderColor = theme.colors.textInput.disable.border; } if (!isValid) { bgColor = hexToRgba(theme.colors.danger.main, 0.1); @@ -83,7 +83,7 @@ const StyledInput = styled.input< color: ${props => props.inputStyle.color}; &::placeholder { - color: ${props => props.theme.colors.blackShades[5]}; + color: ${props => props.theme.colors.textInput.placeholder}; } &:focus { border: 1px solid diff --git a/app/client/src/components/ads/Toggle.tsx b/app/client/src/components/ads/Toggle.tsx index b44475462c20..edb7f9a21e87 100644 --- a/app/client/src/components/ads/Toggle.tsx +++ b/app/client/src/components/ads/Toggle.tsx @@ -29,8 +29,8 @@ const StyledToggle = styled.label<{ left: 0; background-color: ${props => props.isLoading - ? props.theme.colors.blackShades[3] - : props.theme.colors.blackShades[4]}; + ? props.theme.colors.toggle.disable.off + : props.theme.colors.toggle.bg}; transition: 0.4s; width: 46px; height: 23px; @@ -56,8 +56,8 @@ const StyledToggle = styled.label<{ left: 2px; background-color: ${ props.disabled && !props.value - ? lighten(props.theme.colors.tertiary.dark, 16) - : props.theme.colors.blackShades[9] + ? props.theme.colors.toggle.disabledSlider.off + : props.theme.colors.toggle.disabledSlider.on }; box-shadow: ${ props.value @@ -93,21 +93,21 @@ const StyledToggle = styled.label<{ input:focus + .slider { background-color: ${props => props.value - ? lighten(props.theme.colors.info.main, 12) - : lighten(props.theme.colors.blackShades[3], 16)}; + ? props.theme.colors.toggle.hover.on + : props.theme.colors.toggle.hover.off}; } input:disabled + .slider { cursor: not-allowed; background-color: ${props => props.value && !props.isLoading - ? darken(props.theme.colors.info.darker, 20) - : props.theme.colors.tertiary.dark}; + ? props.theme.colors.toggle.disable.on + : props.theme.colors.toggle.disable.off}; } .${Classes.SPINNER} { circle { - stroke: ${props => props.theme.colors.blackShades[6]}; + stroke: ${props => props.theme.colors.toggle.spinner}; } } `; diff --git a/app/client/src/components/ads/Tooltip.tsx b/app/client/src/components/ads/Tooltip.tsx index 1d1a3f5af1f9..e17ed0570639 100644 --- a/app/client/src/components/ads/Tooltip.tsx +++ b/app/client/src/components/ads/Tooltip.tsx @@ -19,21 +19,24 @@ const TooltipWrapper = styled.div<{ variant?: Variant }>` border-radius: 0px; background-color: ${props => props.variant === "dark" - ? props.theme.colors.blackShades[0] - : props.theme.colors.blackShades[8]}; + ? props.theme.colors.tooltip.darkBg + : props.theme.colors.tooltip.lightBg}; } div.${Classes.POPOVER_ARROW} { display: block; } .${Classes.TOOLTIP} { - box-shadow: 0px 12px 20px rgba(0, 0, 0, 0.35);a + box-shadow: 0px 12px 20px rgba(0, 0, 0, 0.35); } - .${Classes.TOOLTIP} .${CsClasses.BP3_POPOVER_ARROW_BORDER}, - &&&& .${Classes.TOOLTIP} .${CsClasses.BP3_POPOVER_ARROW_FILL} { + .${Classes.TOOLTIP} + .${CsClasses.BP3_POPOVER_ARROW_BORDER}, + &&&& + .${Classes.TOOLTIP} + .${CsClasses.BP3_POPOVER_ARROW_FILL} { fill: ${props => props.variant === "dark" - ? props.theme.colors.blackShades[0] - : props.theme.colors.blackShades[8]}; + ? props.theme.colors.tooltip.darkBg + : props.theme.colors.tooltip.lightBg}; } `; diff --git a/app/client/src/constants/DefaultTheme.tsx b/app/client/src/constants/DefaultTheme.tsx index e3b1ea8987de..ed5a76292f99 100644 --- a/app/client/src/constants/DefaultTheme.tsx +++ b/app/client/src/constants/DefaultTheme.tsx @@ -429,25 +429,226 @@ export const largeButton = css` letter-spacing: ${props => props.theme.typography.btnLarge.letterSpacing}px; `; -export const dark = { - blackShades: [ - // "#090707", - "#1A191C", - "#232324", - "#262626", - "#2B2B2B", - "#404040", - "#6D6D6D", - "#9F9F9F", - "#D4D4D4", - "#E9E9E9", - "#FFFFFF", - ], +const darkShades = [ + "#1A191C", + "#232324", + "#262626", + "#2B2B2B", + "#404040", + "#6D6D6D", + "#9F9F9F", + "#D4D4D4", + "#E9E9E9", + "#FFFFFF", +] as const; + +const lightShades = [ + "#FAFAFA", + "#F7F7F7", + "#F0F0F0", + "#E8E8E8", + "#C5C5C5", + "#A9A7A7", + "#939090", + "#716E6E", + "#4B4848", + "#302D2D", + "#090707", + "#FFFFFF", +] as const; + +type ColorPalette = typeof darkShades[number] | typeof lightShades[number]; + +type buttonVariant = { + main: string; + light: string; + dark: string; + darker: string; + darkest: string; +}; + +type ColorType = { + button: { + disabledText: ColorPalette; + }; + tertiary: buttonVariant; + info: buttonVariant; + success: buttonVariant; + warning: buttonVariant; + danger: buttonVariant; + homepageBackground: string; + card: { + hoverBG: Color; + hoverBGOpacity: number; + hoverBorder: ColorPalette; + targetBg: string; + iconColor: ColorPalette; + }; + appCardColors: string[]; + text: { + normal: ColorPalette; + heading: ColorPalette; + hightlight: ColorPalette; + }; + icon: { + normal: ColorPalette; + hover: ColorPalette; + active: ColorPalette; + }; + appIcon: { + normal: ColorPalette; + background: ColorPalette; + }; + menu: { + background: ColorPalette; + shadow: string; + }; + menuItem: { + normalText: ColorPalette; + normalIcon: ColorPalette; + hoverIcon: ColorPalette; + hoverText: ColorPalette; + hoverBg: ColorPalette; + }; + colorSelector: { + shadow: string; + checkmark: ColorPalette; + }; + checkbox: { + disabled: ColorPalette; + unchecked: ColorPalette; + disabledCheck: string; + normalCheck: ColorPalette; + labelColor: ColorPalette; + }; + dropdown: { + header: { + text: ColorPalette; + disabled: ColorPalette; + bg: ColorPalette; + disabledBg: ColorPalette; + }; + menuBg: ColorPalette; + menuShadow: string; + selected: { + text: ColorPalette; + bg: ColorPalette; + icon: ColorPalette; + }; + icon: ColorPalette; + }; + toggle: { + bg: ColorPalette; + hover: { + on: string; + off: string; + }; + disable: { + on: string; + off: ColorPalette; + }; + disabledSlider: { + on: ColorPalette; + off: string; + }; + spinner: ColorPalette; + }; + textInput: { + disable: { + bg: ColorPalette; + text: ColorPalette; + border: ColorPalette; + }; + normal: { + bg: ColorPalette; + text: ColorPalette; + border: ColorPalette; + }; + placeholder: ColorPalette; + }; + menuBorder: ColorPalette; + editableText: { + color: ColorPalette; + bg: string; + dangerBg: string; + }; + radio: { + disable: string; + border: ColorPalette; + }; + searchInput: { + placeholder: ColorPalette; + text: ColorPalette; + border: ColorPalette; + bg: ColorPalette; + icon: { + focused: ColorPalette; + normal: ColorPalette; + }; + }; + spinner: ColorPalette; + tableDropdown: { + bg: ColorPalette; + selectedBg: ColorPalette; + selectedText: ColorPalette; + shadow: string; + }; + tabs: { + normal: ColorPalette; + hover: ColorPalette; + border: ColorPalette; + }; + settingHeading: ColorPalette; + table: { + headerBg: ColorPalette; + headerText: ColorPalette; + rowData: ColorPalette; + rowTitle: ColorPalette; + border: ColorPalette; + hover: { + headerColor: ColorPalette; + rowBg: ColorPalette; + rowTitle: ColorPalette; + rowData: ColorPalette; + }; + }; + applications: { + bg: ColorPalette; + textColor: ColorPalette; + orgColor: ColorPalette; + iconColor: ColorPalette; + hover: { + bg: ColorPalette; + textColor: ColorPalette; + orgColor: ColorPalette; + }; + }; + switch: { + border: ColorPalette; + bg: ColorPalette; + hover: { + border: ColorPalette; + bg: ColorPalette; + }; + lightText: ColorPalette; + darkText: ColorPalette; + }; + queryTemplate: { + bg: ColorPalette; + color: ColorPalette; + }; +}; + +export const dark: ColorType = { + button: { + disabledText: darkShades[6], + }, tertiary: { main: "#D4D4D4", light: "#FFFFFF", dark: "#2B2B2B", darker: "#202021", + darkest: "#1A191C", }, info: { main: "#CB4810", @@ -481,6 +682,9 @@ export const dark = { card: { hoverBG: Colors.BLACK, hoverBGOpacity: 0.5, + hoverBorder: darkShades[4], + targetBg: "rgba(0, 0, 0, 0.1)", + iconColor: darkShades[9], }, appCardColors: [ "#4F70FD", @@ -493,34 +697,174 @@ export const dark = { "#A8D76C", "#6C4CF1", ], + text: { + normal: darkShades[6], + heading: darkShades[7], + hightlight: darkShades[9], + }, + icon: { + normal: darkShades[6], + hover: darkShades[8], + active: darkShades[9], + }, + appIcon: { + normal: darkShades[9], + background: darkShades[1], + }, + menu: { + background: darkShades[3], + shadow: "rgba(0, 0, 0, 0.75)", + }, + menuItem: { + normalText: darkShades[7], + normalIcon: darkShades[6], + hoverIcon: darkShades[8], + hoverText: darkShades[9], + hoverBg: darkShades[4], + }, + colorSelector: { + shadow: "#353535", + checkmark: darkShades[9], + }, + checkbox: { + disabled: darkShades[3], + unchecked: darkShades[4], + disabledCheck: "#565656", + normalCheck: darkShades[9], + labelColor: darkShades[7], + }, + dropdown: { + header: { + text: darkShades[7], + disabled: darkShades[6], + bg: darkShades[2], + disabledBg: darkShades[0], + }, + menuBg: darkShades[3], + menuShadow: "rgba(0, 0, 0, 0.6)", + selected: { + text: darkShades[9], + bg: darkShades[4], + icon: darkShades[8], + }, + icon: darkShades[6], + }, + toggle: { + bg: darkShades[4], + hover: { + on: "#F56426", + off: "#5E5E5E", + }, + disable: { + on: "#3D2219", + off: darkShades[3], + }, + disabledSlider: { + on: darkShades[9], + off: "#565656", + }, + spinner: darkShades[6], + }, + textInput: { + disable: { + bg: darkShades[2], + text: darkShades[6], + border: darkShades[2], + }, + normal: { + bg: darkShades[0], + text: darkShades[9], + border: darkShades[0], + }, + placeholder: darkShades[5], + }, + menuBorder: darkShades[4], + editableText: { + color: darkShades[9], + bg: darkShades[1], + dangerBg: "rgba(226, 44, 44, 0.08)", + }, + radio: { + disable: "#565656", + border: darkShades[4], + }, + searchInput: { + placeholder: darkShades[5], + text: darkShades[9], + border: darkShades[4], + bg: darkShades[2], + icon: { + focused: darkShades[7], + normal: darkShades[5], + }, + }, + spinner: darkShades[6], + tableDropdown: { + bg: darkShades[3], + selectedBg: darkShades[4], + selectedText: darkShades[9], + shadow: "rgba(0, 0, 0, 0.75)", + }, + tabs: { + normal: darkShades[6], + hover: darkShades[9], + border: darkShades[3], + }, + settingHeading: darkShades[9], + table: { + headerBg: darkShades[2], + headerText: darkShades[5], + rowData: darkShades[6], + rowTitle: darkShades[7], + border: darkShades[3], + hover: { + headerColor: darkShades[7], + rowBg: darkShades[4], + rowTitle: darkShades[9], + rowData: darkShades[7], + }, + }, + applications: { + bg: darkShades[1], + textColor: darkShades[7], + orgColor: darkShades[7], + iconColor: darkShades[7], + hover: { + bg: darkShades[4], + textColor: darkShades[8], + orgColor: darkShades[9], + }, + }, + switch: { + border: darkShades[5], + bg: darkShades[0], + hover: { + border: darkShades[7], + bg: darkShades[0], + }, + lightText: darkShades[9], + darkText: darkShades[6], + }, + queryTemplate: { + bg: darkShades[3], + color: darkShades[7], + }, }; -export const light = { - blackShades: [ - "#FAFAFA", - "#F7F7F7", - "#F0F0F0", - "#E8E8E8", - "#C5C5C5", - // "#EFEFEF", - // "#E7E7E7", - "#A9A7A7", - "#939090", - "#716E6E", - "#4B4848", - // "#4B4848", - "#302D2D", - // "#161414" - ], +export const light: ColorType = { + button: { + disabledText: lightShades[6], + }, tertiary: { main: "#716E6E", light: "#090707", - dark: "#F0F0F0", + dark: "#F7F7F7", darker: "#E8E8E8", + darkest: "#939090", }, info: { main: "#F86A2B", - light: "#FB773C", + light: "#DC5B21", dark: "#BF4109", darker: "#FEEDE5", darkest: "#F7EBE6", @@ -550,6 +894,9 @@ export const light = { card: { hoverBG: Colors.WHITE, hoverBGOpacity: 0.7, + hoverBorder: lightShades[2], + targetBg: "rgba(0, 0, 0, 0.1)", + iconColor: lightShades[11], }, appCardColors: [ "#4266FD", @@ -562,6 +909,158 @@ export const light = { "#B0E968", "#9177FF", ], + text: { + normal: lightShades[8], + heading: lightShades[9], + hightlight: lightShades[11], + }, + icon: { + normal: lightShades[4], + hover: lightShades[8], + active: lightShades[9], + }, + appIcon: { + normal: lightShades[7], + background: lightShades[1], + }, + menu: { + background: lightShades[11], + shadow: "rgba(0, 0, 0, 0.32)", + }, + menuItem: { + normalText: lightShades[8], + normalIcon: lightShades[6], + hoverIcon: lightShades[8], + hoverText: lightShades[10], + hoverBg: lightShades[2], + }, + colorSelector: { + shadow: lightShades[3], + checkmark: lightShades[11], + }, + checkbox: { + disabled: lightShades[3], + unchecked: lightShades[4], + disabledCheck: lightShades[6], + normalCheck: lightShades[11], + labelColor: lightShades[9], + }, + dropdown: { + header: { + text: lightShades[9], + disabled: darkShades[6], + bg: lightShades[2], + disabledBg: lightShades[1], + }, + menuBg: lightShades[11], + menuShadow: "rgba(0, 0, 0, 0.32)", + selected: { + text: lightShades[9], + bg: lightShades[2], + icon: lightShades[8], + }, + icon: lightShades[7], + }, + toggle: { + bg: lightShades[4], + hover: { + on: "#E4500E", + off: lightShades[5], + }, + disable: { + on: "#FDE0D2", + off: lightShades[3], + }, + disabledSlider: { + off: lightShades[11], + on: lightShades[11], + }, + spinner: lightShades[6], + }, + textInput: { + disable: { + bg: lightShades[1], + text: darkShades[6], + border: lightShades[1], + }, + normal: { + bg: lightShades[2], + text: lightShades[9], + border: lightShades[2], + }, + placeholder: lightShades[6], + }, + menuBorder: lightShades[3], + editableText: { + color: lightShades[10], + bg: "rgba(247, 247, 247, 0.8)", + dangerBg: "rgba(242, 43, 43, 0.06)", + }, + radio: { + disable: lightShades[4], + border: lightShades[3], + }, + searchInput: { + placeholder: lightShades[6], + text: lightShades[10], + border: lightShades[3], + bg: lightShades[1], + icon: { + focused: lightShades[7], + normal: lightShades[5], + }, + }, + spinner: lightShades[6], + tableDropdown: { + bg: lightShades[11], + selectedBg: lightShades[2], + selectedText: lightShades[9], + shadow: "rgba(0, 0, 0, 0.32)", + }, + tabs: { + normal: lightShades[6], + hover: lightShades[10], + border: lightShades[3], + }, + settingHeading: lightShades[9], + table: { + headerBg: lightShades[1], + headerText: lightShades[6], + rowData: lightShades[7], + rowTitle: lightShades[9], + border: lightShades[3], + hover: { + headerColor: lightShades[9], + rowBg: lightShades[2], + rowTitle: lightShades[10], + rowData: lightShades[9], + }, + }, + applications: { + bg: lightShades[2], + textColor: lightShades[7], + orgColor: lightShades[7], + iconColor: lightShades[7], + hover: { + bg: lightShades[3], + textColor: lightShades[8], + orgColor: lightShades[9], + }, + }, + switch: { + border: lightShades[5], + bg: lightShades[11], + hover: { + border: lightShades[7], + bg: lightShades[11], + }, + lightText: lightShades[11], + darkText: lightShades[6], + }, + queryTemplate: { + bg: lightShades[3], + color: lightShades[7], + }, }; export const theme: Theme = { @@ -664,6 +1163,10 @@ export const theme: Theme = { }, drawerWidth: "80%", colors: { + tooltip: { + lightBg: lightShades[0], + darkBg: lightShades[10], + }, callout: { note: { dark: { @@ -686,9 +1189,6 @@ export const theme: Theme = { }, }, }, - radio: { - disabled: "#565656", - }, appBackground: "#EFEFEF", primaryOld: Colors.GREEN, primaryDarker: Colors.JUNGLE_GREEN, diff --git a/app/client/src/pages/Applications/ApplicationCard.tsx b/app/client/src/pages/Applications/ApplicationCard.tsx index 0a19d29bc389..10247c950f9e 100644 --- a/app/client/src/pages/Applications/ApplicationCard.tsx +++ b/app/client/src/pages/Applications/ApplicationCard.tsx @@ -40,6 +40,7 @@ import { getThemeDetails } from "selectors/themeSelectors"; import { useSelector } from "react-redux"; import { UpdateApplicationPayload } from "api/ApplicationApi"; import { getIsSavingAppName } from "selectors/applicationSelectors"; +import { Classes as CsClasses } from "components/ads/common"; type NameWrapperProps = { hasReadPermission: boolean; @@ -57,7 +58,7 @@ const NameWrapper = styled((props: HTMLDivProps & NameWrapperProps) => ( props.showOverlay && ` { - background-color: ${props.theme.colors.blackShades[4]}; + background-color: ${props.theme.colors.card.hoverBorder}}; justify-content: center; align-items: center; @@ -125,6 +126,14 @@ const Wrapper = styled( .bp3-card { border-radius: 0; } + .${CsClasses.APP_ICON} { + margin: 0 auto; + svg { + path { + fill: #fff; + } + } + } `; const ApplicationImage = styled.div` @@ -193,13 +202,16 @@ const ContextDropdownWrapper = styled.div` position: absolute; top: -6px; right: -3px; -`; -const StyledAppIcon = styled(AppIcon)` - margin: 0 auto; - svg { - path { - fill: #fff; + .${Classes.POPOVER_TARGET} { + span { + background: ${props => props.theme.colors.card.targetBg}; + + svg { + path { + fill: ${props => props.theme.colors.card.iconColor}; + } + } } } `; @@ -379,7 +391,7 @@ export const ApplicationCard = (props: ApplicationCardProps) => { hasReadPermission={hasReadPermission} backgroundColor={colorCode} > - <StyledAppIcon size={Size.large} name={appIcon} /> + <AppIcon size={Size.large} name={appIcon} /> {/* <Initials>{initials}</Initials> */} {showOverlay && ( <div className="overlay"> diff --git a/app/client/src/pages/Applications/index.tsx b/app/client/src/pages/Applications/index.tsx index d94b50c3e00a..24ec19411a80 100644 --- a/app/client/src/pages/Applications/index.tsx +++ b/app/client/src/pages/Applications/index.tsx @@ -174,8 +174,8 @@ const textIconStyles = (props: { color: string; hover: string }) => { const NewWorkspaceWrapper = styled.div` ${props => { return `${textIconStyles({ - color: props.theme.colors.blackShades[7], - hover: props.theme.colors.blackShades[8], + color: props.theme.colors.applications.textColor, + hover: props.theme.colors.applications.hover.textColor, })}`; }} `; @@ -184,7 +184,7 @@ const ApplicationAddCardWrapper = styled(Card)` display: flex; flex-direction: column; // justify-content: center; - background: ${props => props.theme.colors.blackShades[2]}; + background: ${props => props.theme.colors.applications.bg}; align-items: center; width: ${props => props.theme.card.minWidth}px; height: ${props => props.theme.card.minHeight}px; @@ -205,12 +205,12 @@ const ApplicationAddCardWrapper = styled(Card)` } cursor: pointer; &:hover { - background: ${props => props.theme.colors.blackShades[4]}; + background: ${props => props.theme.colors.applications.hover.bg}; } ${props => { return `${textIconStyles({ - color: props.theme.colors.blackShades[7], - hover: props.theme.colors.blackShades[8], + color: props.theme.colors.applications.textColor, + hover: props.theme.colors.applications.hover.textColor, })}`; }} `; @@ -260,8 +260,8 @@ const OrgNameWrapper = styled.div<{ disabled?: boolean }>` cursor: ${props => (!props.disabled ? "pointer" : "inherit")}; ${props => { const color = props.disabled - ? props.theme.colors.blackShades[7] - : props.theme.colors.blackShades[9]; + ? props.theme.colors.applications.orgColor + : props.theme.colors.applications.hover.orgColor[9]; return `${textIconStyles({ color: color, hover: color, @@ -271,6 +271,7 @@ ${props => { .${Classes.ICON} { display: ${props => (!props.disabled ? "inline" : "none")};; margin-left: 8px; + color: ${props => props.theme.colors.applications.iconColor}; } `; @@ -405,41 +406,48 @@ const ApplicationsSection = () => { )} </OrgDropDown> <ApplicationCardsWrapper key={organization.id}> - <FormDialogComponent - permissions={organization.userPermissions} - permissionRequired={PERMISSION_TYPE.CREATE_APPLICATION} - trigger={ - <PaddingWrapper> - <ApplicationAddCardWrapper> - <Icon - className="t--create-app-popup" - name={"plus"} - size={IconSize.LARGE} - ></Icon> - <CreateNewLabel - type={TextType.H4} - className="createnew" - // cypressSelector={"t--create-new-app"} - > - Create New - </CreateNewLabel> - </ApplicationAddCardWrapper> - </PaddingWrapper> - } - Form={CreateApplicationForm} - orgId={organization.id} - title={"Create Application"} - /> + {isPermitted( + organization.userPermissions, + PERMISSION_TYPE.CREATE_APPLICATION, + ) && ( + <PaddingWrapper> + <FormDialogComponent + permissions={organization.userPermissions} + permissionRequired={PERMISSION_TYPE.CREATE_APPLICATION} + trigger={ + <ApplicationAddCardWrapper> + <Icon + className="t--create-app-popup" + name={"plus"} + size={IconSize.LARGE} + ></Icon> + <CreateNewLabel + type={TextType.H4} + className="createnew" + // cypressSelector={"t--create-new-app"} + > + Create New + </CreateNewLabel> + </ApplicationAddCardWrapper> + } + Form={CreateApplicationForm} + orgId={organization.id} + title={"Create Application"} + /> + </PaddingWrapper> + )} {applications.map((application: any) => { return ( application.pages?.length > 0 && ( - <ApplicationCard - key={application.id} - application={application} - delete={deleteApplication} - update={updateApplicationDispatch} - duplicate={duplicateApplicationDispatch} - /> + <PaddingWrapper> + <ApplicationCard + key={application.id} + application={application} + delete={deleteApplication} + update={updateApplicationDispatch} + duplicate={duplicateApplicationDispatch} + /> + </PaddingWrapper> ) ); })} diff --git a/app/client/src/pages/Editor/Explorer/Datasources/QueryTemplates.tsx b/app/client/src/pages/Editor/Explorer/Datasources/QueryTemplates.tsx index 6084d899a11f..653dde148e71 100644 --- a/app/client/src/pages/Editor/Explorer/Datasources/QueryTemplates.tsx +++ b/app/client/src/pages/Editor/Explorer/Datasources/QueryTemplates.tsx @@ -15,13 +15,13 @@ import { ExplorerURLParams } from "../helpers"; import { QUERY_EDITOR_URL_WITH_SELECTED_PAGE_ID } from "constants/routes"; const Container = styled.div` - background-color: ${props => props.theme.colors.blackShades[3]}; + background-color: ${props => props.theme.colors.queryTemplate.bg}; color: ${props => props.theme.colors.textOnDarkBG}; width: 250px; `; const TemplateType = styled.div` - color: ${props => props.theme.colors.blackShades[7]}; + color: ${props => props.theme.colors.queryTemplate.color}; padding: 8px; &:hover { cursor: pointer; diff --git a/app/client/src/pages/common/ProfileDropdown.tsx b/app/client/src/pages/common/ProfileDropdown.tsx index d663794afa17..af0d0e680ceb 100644 --- a/app/client/src/pages/common/ProfileDropdown.tsx +++ b/app/client/src/pages/common/ProfileDropdown.tsx @@ -1,10 +1,10 @@ -import React from "react"; +import React, { Fragment } from "react"; import { CommonComponentProps } from "components/ads/common"; import { getInitialsAndColorCode } from "utils/AppsmithUtils"; import { useSelector } from "react-redux"; import { getThemeDetails } from "selectors/themeSelectors"; import Text, { TextType } from "components/ads/Text"; -import styled from "styled-components"; +import styled, { createGlobalStyle } from "styled-components"; import { Position } from "@blueprintjs/core"; import Menu from "components/ads/Menu"; import ThemeSwitcher from "./ThemeSwitcher"; @@ -32,6 +32,14 @@ const ProfileImage = styled.div<{ backgroundColor?: string }>` background-color: ${props => props.backgroundColor}; `; +const ProfileMenuStyle = createGlobalStyle` + .profile-menu { + .bp3-popover .bp3-popover-content{ + margin-top: 2px; + } + } +`; + export default function ProfileDropdown(props: TagProps) { const themeDetails = useSelector(getThemeDetails); @@ -41,27 +49,31 @@ export default function ProfileDropdown(props: TagProps) { ); return ( - <Menu - position={Position.BOTTOM} - target={ - <ProfileImage backgroundColor={initialsAndColorCode[1]}> - <Text type={TextType.H6} highlight> - {initialsAndColorCode[0]} - </Text> - </ProfileImage> - } - > - <ThemeSwitcher /> - <MenuDivider /> - <MenuItem - icon="logout" - text="Sign Out" - onSelect={() => - getOnSelectAction(DropdownOnSelectActions.DISPATCH, { - type: ReduxActionTypes.LOGOUT_USER_INIT, - }) + <Fragment> + <ProfileMenuStyle /> + <Menu + className="profile-menu" + position={Position.BOTTOM} + target={ + <ProfileImage backgroundColor={initialsAndColorCode[1]}> + <Text type={TextType.H6} highlight> + {initialsAndColorCode[0]} + </Text> + </ProfileImage> } - /> - </Menu> + > + <ThemeSwitcher /> + <MenuDivider /> + <MenuItem + icon="logout" + text="Sign Out" + onSelect={() => + getOnSelectAction(DropdownOnSelectActions.DISPATCH, { + type: ReduxActionTypes.LOGOUT_USER_INIT, + }) + } + /> + </Menu> + </Fragment> ); } diff --git a/app/client/src/pages/organization/General.tsx b/app/client/src/pages/organization/General.tsx index 111a3dd1ca1b..525d2f4ff0a6 100644 --- a/app/client/src/pages/organization/General.tsx +++ b/app/client/src/pages/organization/General.tsx @@ -27,7 +27,7 @@ const SettingWrapper = styled.div` `; export const SettingsHeading = styled(Text)` - color: ${props => props.theme.colors.blackShades[9]}; + color: ${props => props.theme.colors.settingHeading}; display: inline-block; margin-top: 25px; margin-bottom: 32px;
ba70a6367584f523d04501b5050cfcfac675a465
2023-09-20 12:19:48
Nilesh Sarupriya
fix: pick changes present in release
false
pick changes present in release
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/VisualTests/JSEditorSaveAndAutoIndent_spec.js b/app/client/cypress/e2e/Regression/ClientSide/VisualTests/JSEditorSaveAndAutoIndent_spec.js index 9cd38dd21a9a..335d92f05d20 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/VisualTests/JSEditorSaveAndAutoIndent_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/VisualTests/JSEditorSaveAndAutoIndent_spec.js @@ -1,6 +1,6 @@ import * as _ from "../../../../support/Objects/ObjectsCore"; -describe.skip("JS Editor Save and Auto-indent: Visual tests", () => { +describe("JS Editor Save and Auto-indent: Visual tests", () => { it("1. Auto indents and saves the code when Ctrl/Cmd+s is pressed", () => { _.jsEditor.CreateJSObject( `export default { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/CodeScanner/CodeScanner1_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/CodeScanner/CodeScanner1_spec.ts index bdaca3706ba3..9ce99a7ab90f 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/CodeScanner/CodeScanner1_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/CodeScanner/CodeScanner1_spec.ts @@ -3,7 +3,6 @@ const widgetsPage = require("../../../../../locators/Widgets.json"); const commonlocators = require("../../../../../locators/commonlocators.json"); const publish = require("../../../../../locators/publishWidgetspage.json"); import * as _ from "../../../../../support/Objects/ObjectsCore"; - const widgetName = "codescannerwidget"; const codeScannerVideoOnPublishPage = `${publish.codescannerwidget} ${commonlocators.codeScannerVideo}`; const codeScannerDisabledSVGIconOnPublishPage = `${publish.codescannerwidget} ${commonlocators.codeScannerDisabledSVGIcon}`; diff --git a/app/client/cypress/e2e/Sanity/Datasources/RestApiOAuth2Validation_spec.js b/app/client/cypress/e2e/Sanity/Datasources/RestApiOAuth2Validation_spec.js deleted file mode 100644 index e69de29bb2d1..000000000000
5510cd4c523f90d5109161e4d9b1223354ae956e
2023-11-02 15:55:24
ashit-rath
chore: Refactor URLAssembly to throw error on missing pageId for app route resolution only (#28527)
false
Refactor URLAssembly to throw error on missing pageId for app route resolution only (#28527)
chore
diff --git a/app/client/src/RouteParamsMiddleware.ts b/app/client/src/RouteParamsMiddleware.ts deleted file mode 100644 index 3eba48065b74..000000000000 --- a/app/client/src/RouteParamsMiddleware.ts +++ /dev/null @@ -1,128 +0,0 @@ -import type { - ApplicationPayload, - Page, - ReduxAction, -} from "@appsmith/constants/ReduxActionConstants"; -import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; -import type { UpdatePageResponse } from "api/PageApi"; -import type { - ApplicationURLParams, - PageURLParams, -} from "@appsmith/entities/URLRedirect/URLAssembly"; -import urlBuilder from "@appsmith/entities/URLRedirect/URLAssembly"; -import type { Middleware } from "redux"; - -const routeParamsMiddleware: Middleware = - () => (next: any) => (action: ReduxAction<any>) => { - let appParams: ApplicationURLParams = {}; - let pageParams: PageURLParams[] = []; - switch (action.type) { - case ReduxActionTypes.IMPORT_APPLICATION_SUCCESS: - case ReduxActionTypes.IMPORT_TEMPLATE_TO_WORKSPACE_SUCCESS: - case ReduxActionTypes.FETCH_APPLICATION_SUCCESS: { - const application: ApplicationPayload = action.payload; - const { pages } = application; - appParams = { - applicationId: application.id, - applicationSlug: application.slug, - applicationVersion: application.applicationVersion, - }; - pageParams = pages.map((page) => ({ - pageSlug: page.slug, - pageId: page.id, - customSlug: page.customSlug, - })); - break; - } - case ReduxActionTypes.FORK_APPLICATION_SUCCESS: - case ReduxActionTypes.CREATE_APPLICATION_SUCCESS: { - const application: ApplicationPayload = action.payload.application; - const { pages } = application; - appParams = { - applicationId: application.id, - applicationSlug: application.slug, - applicationVersion: application.applicationVersion, - }; - pageParams = pages.map((page) => ({ - pageSlug: page.slug, - pageId: page.id, - customSlug: page.customSlug, - })); - break; - } - case ReduxActionTypes.CURRENT_APPLICATION_NAME_UPDATE: { - const application = action.payload; - appParams = { - applicationId: application.id, - applicationSlug: application.slug, - applicationVersion: application.applicationVersion, - }; - break; - } - case ReduxActionTypes.FETCH_PAGE_LIST_SUCCESS: { - const pages: Page[] = action.payload.pages; - pageParams = pages.map((page) => ({ - pageSlug: page.slug, - pageId: page.pageId, - customSlug: page.customSlug, - })); - break; - } - case ReduxActionTypes.UPDATE_PAGE_SUCCESS: { - const page: UpdatePageResponse = action.payload; - pageParams = [ - { - pageSlug: page.slug, - pageId: page.id, - customSlug: page.customSlug, - }, - ]; - break; - } - case ReduxActionTypes.CREATE_PAGE_SUCCESS: { - const page: Page = action.payload; - pageParams = [ - { - pageSlug: page.slug, - pageId: page.pageId, - customSlug: page.customSlug, - }, - ]; - break; - } - case ReduxActionTypes.GENERATE_TEMPLATE_PAGE_SUCCESS: { - const { page } = action.payload; - urlBuilder.updateURLParams(null, [ - { - pageSlug: page.slug, - pageId: page.id, - customSlug: page.customSlug, - }, - ]); - break; - } - case ReduxActionTypes.UPDATE_APPLICATION_SUCCESS: - const application = action.payload; - appParams = { - applicationId: application.id, - applicationSlug: application.slug, - applicationVersion: application.applicationVersion, - }; - break; - case ReduxActionTypes.CLONE_PAGE_SUCCESS: - const { pageId, pageSlug } = action.payload; - pageParams = [ - { - pageId, - pageSlug, - }, - ]; - break; - default: - break; - } - urlBuilder.updateURLParams(appParams, pageParams); - return next(action); - }; - -export default routeParamsMiddleware; diff --git a/app/client/src/ce/RouteParamsMiddleware.ts b/app/client/src/ce/RouteParamsMiddleware.ts new file mode 100644 index 000000000000..91ac86e8343f --- /dev/null +++ b/app/client/src/ce/RouteParamsMiddleware.ts @@ -0,0 +1,132 @@ +import type { + ApplicationPayload, + Page, + ReduxAction, +} from "@appsmith/constants/ReduxActionConstants"; +import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; +import type { UpdatePageResponse } from "api/PageApi"; +import type { + ApplicationURLParams, + PageURLParams, +} from "@appsmith/entities/URLRedirect/URLAssembly"; +import urlBuilder from "@appsmith/entities/URLRedirect/URLAssembly"; +import type { Middleware } from "redux"; + +export const handler = (action: ReduxAction<any>) => { + let appParams: ApplicationURLParams = {}; + let pageParams: PageURLParams[] = []; + switch (action.type) { + case ReduxActionTypes.IMPORT_APPLICATION_SUCCESS: + case ReduxActionTypes.IMPORT_TEMPLATE_TO_WORKSPACE_SUCCESS: + case ReduxActionTypes.FETCH_APPLICATION_SUCCESS: { + const application: ApplicationPayload = action.payload; + const { pages } = application; + appParams = { + applicationId: application.id, + applicationSlug: application.slug, + applicationVersion: application.applicationVersion, + }; + pageParams = pages.map((page) => ({ + pageSlug: page.slug, + pageId: page.id, + customSlug: page.customSlug, + })); + break; + } + case ReduxActionTypes.FORK_APPLICATION_SUCCESS: + case ReduxActionTypes.CREATE_APPLICATION_SUCCESS: { + const application: ApplicationPayload = action.payload.application; + const { pages } = application; + appParams = { + applicationId: application.id, + applicationSlug: application.slug, + applicationVersion: application.applicationVersion, + }; + pageParams = pages.map((page) => ({ + pageSlug: page.slug, + pageId: page.id, + customSlug: page.customSlug, + })); + break; + } + case ReduxActionTypes.CURRENT_APPLICATION_NAME_UPDATE: { + const application = action.payload; + appParams = { + applicationId: application.id, + applicationSlug: application.slug, + applicationVersion: application.applicationVersion, + }; + break; + } + case ReduxActionTypes.FETCH_PAGE_LIST_SUCCESS: { + const pages: Page[] = action.payload.pages; + pageParams = pages.map((page) => ({ + pageSlug: page.slug, + pageId: page.pageId, + customSlug: page.customSlug, + })); + break; + } + case ReduxActionTypes.UPDATE_PAGE_SUCCESS: { + const page: UpdatePageResponse = action.payload; + pageParams = [ + { + pageSlug: page.slug, + pageId: page.id, + customSlug: page.customSlug, + }, + ]; + break; + } + case ReduxActionTypes.CREATE_PAGE_SUCCESS: { + const page: Page = action.payload; + pageParams = [ + { + pageSlug: page.slug, + pageId: page.pageId, + customSlug: page.customSlug, + }, + ]; + break; + } + case ReduxActionTypes.GENERATE_TEMPLATE_PAGE_SUCCESS: { + const { page } = action.payload; + urlBuilder.updateURLParams(null, [ + { + pageSlug: page.slug, + pageId: page.id, + customSlug: page.customSlug, + }, + ]); + break; + } + case ReduxActionTypes.UPDATE_APPLICATION_SUCCESS: + const application = action.payload; + appParams = { + applicationId: application.id, + applicationSlug: application.slug, + applicationVersion: application.applicationVersion, + }; + break; + case ReduxActionTypes.CLONE_PAGE_SUCCESS: + const { pageId, pageSlug } = action.payload; + pageParams = [ + { + pageId, + pageSlug, + }, + ]; + break; + default: + break; + } + urlBuilder.updateURLParams(appParams, pageParams); +}; + +const routeParamsMiddleware: Middleware = + () => (next: any) => (action: ReduxAction<any>) => { + handler(action); + return next(action); + }; + +export default routeParamsMiddleware; diff --git a/app/client/src/ce/entities/URLRedirect/URLAssembly.test.ts b/app/client/src/ce/entities/URLRedirect/URLAssembly.test.ts index 27fa5b3407a7..ac4c667aaa31 100644 --- a/app/client/src/ce/entities/URLRedirect/URLAssembly.test.ts +++ b/app/client/src/ce/entities/URLRedirect/URLAssembly.test.ts @@ -93,8 +93,6 @@ describe("URLBuilder", () => { }; URLBuilder.prototype.generateBasePath = jest.fn((pageId, mode) => { - expect(pageId).toBe(testPageId); // Ensure the overridden pageId is used - expect(mode).toBe(testMode); return `mockedBasePath/${pageId}/${mode}`; }); @@ -109,6 +107,14 @@ describe("URLBuilder", () => { "mockedBasePath/testPageId/EDIT/testSuffix?param1=value1&param2=value2&branch=testBranch#testHash", ); }); + + it("should throw an error when pageId is missing", () => { + urlBuilder.setCurrentPageId(null); + + expect(() => { + urlBuilder.build({}, APP_MODE.EDIT); + }).toThrow(URIError); + }); }); describe(".getQueryStringfromObject", () => { diff --git a/app/client/src/ce/entities/URLRedirect/URLAssembly.ts b/app/client/src/ce/entities/URLRedirect/URLAssembly.ts index ee54d0427651..7bb7e389468d 100644 --- a/app/client/src/ce/entities/URLRedirect/URLAssembly.ts +++ b/app/client/src/ce/entities/URLRedirect/URLAssembly.ts @@ -244,16 +244,18 @@ export class URLBuilder { } resolveEntityIdForApp(builderParams: URLBuilderParams) { - return { - entityId: builderParams.pageId || this.currentPageId, - entityType: "pageId", - }; + const pageId = builderParams.pageId || this.currentPageId; + + if (!pageId) { + throw new URIError( + "Missing pageId. If you are trying to set href inside a react component use the 'useHref' hook.", + ); + } + + return pageId; } - resolveEntityId(builderParams: URLBuilderParams): { - entityId?: string | null; - entityType: string; - } { + resolveEntityId(builderParams: URLBuilderParams): string { return this.resolveEntityIdForApp(builderParams); } @@ -272,13 +274,7 @@ export class URLBuilder { suffix, } = builderParams; - const { entityId, entityType } = this.resolveEntityId(builderParams); - - if (!entityId) { - throw new URIError( - `Missing ${entityType}. If you are trying to set href inside a react component use the 'useHref' hook.`, - ); - } + const entityId = this.resolveEntityId(builderParams); const basePath = this.generateBasePath(entityId, mode); diff --git a/app/client/src/ee/RouteParamsMiddleware.ts b/app/client/src/ee/RouteParamsMiddleware.ts new file mode 100644 index 000000000000..b4d88262ae45 --- /dev/null +++ b/app/client/src/ee/RouteParamsMiddleware.ts @@ -0,0 +1,3 @@ +export * from "ce/RouteParamsMiddleware"; +import { default as CE_RouteParamsMiddleware } from "ce/RouteParamsMiddleware"; +export default CE_RouteParamsMiddleware; diff --git a/app/client/src/store.ts b/app/client/src/store.ts index 98e0e5a2be46..7ec2f3b4b6e9 100644 --- a/app/client/src/store.ts +++ b/app/client/src/store.ts @@ -7,7 +7,7 @@ import { rootSaga } from "@appsmith/sagas"; import { composeWithDevTools } from "redux-devtools-extension/logOnlyInProduction"; import * as Sentry from "@sentry/react"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; -import routeParamsMiddleware from "RouteParamsMiddleware"; +import routeParamsMiddleware from "@appsmith/RouteParamsMiddleware"; const sagaMiddleware = createSagaMiddleware(); const ignoredSentryActionTypes = [
8940726ed113333e5f7b7456fd9c1f6c46aae74e
2022-08-17 19:10:10
Aman Agarwal
fix: rts fat container docker image (#16092)
false
rts fat container docker image (#16092)
fix
diff --git a/Dockerfile b/Dockerfile index 675316af2c4d..7699bdc24c83 100644 --- a/Dockerfile +++ b/Dockerfile @@ -59,7 +59,7 @@ COPY ${PLUGIN_JARS} backend/plugins/ COPY ./app/client/build editor/ # Add RTS - Application Layer -COPY ./app/rts/package.json ./app/rts/dist/* rts/ +COPY ./app/rts/package.json ./app/rts/dist rts/ COPY ./app/rts/node_modules rts/node_modules # Nginx & MongoDB config template - Configuration layer
ecf0b9bd2aab1efa2d787f9f8ecc5c8c9c30c677
2023-10-25 19:09:18
Anagh Hegde
fix: Add support for jackson with java time modules (#28347)
false
Add support for jackson with java time modules (#28347)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateServiceImpl.java index b215c32a879b..edee6d4ca83b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationTemplateServiceImpl.java @@ -7,6 +7,7 @@ import com.appsmith.server.services.ce.ApplicationTemplateServiceCEImpl; import com.appsmith.server.solutions.ApplicationPermission; import com.appsmith.server.solutions.ReleaseNotesService; +import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -24,7 +25,8 @@ public ApplicationTemplateServiceImpl( UserDataService userDataService, ApplicationService applicationService, ResponseUtils responseUtils, - ApplicationPermission applicationPermission) { + ApplicationPermission applicationPermission, + ObjectMapper objectMapper) { super( cloudServicesConfig, releaseNotesService, @@ -34,6 +36,7 @@ public ApplicationTemplateServiceImpl( userDataService, applicationService, responseUtils, - applicationPermission); + applicationPermission, + objectMapper); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java index 28f81aeffb4d..011d927956c6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java @@ -56,6 +56,8 @@ public class ApplicationTemplateServiceCEImpl implements ApplicationTemplateServ private final ResponseUtils responseUtils; private final ApplicationPermission applicationPermission; + private final ObjectMapper objectMapper; + public ApplicationTemplateServiceCEImpl( CloudServicesConfig cloudServicesConfig, ReleaseNotesService releaseNotesService, @@ -65,7 +67,8 @@ public ApplicationTemplateServiceCEImpl( UserDataService userDataService, ApplicationService applicationService, ResponseUtils responseUtils, - ApplicationPermission applicationPermission) { + ApplicationPermission applicationPermission, + ObjectMapper objectMapper) { this.cloudServicesConfig = cloudServicesConfig; this.releaseNotesService = releaseNotesService; this.importApplicationService = importApplicationService; @@ -75,6 +78,7 @@ public ApplicationTemplateServiceCEImpl( this.applicationService = applicationService; this.responseUtils = responseUtils; this.applicationPermission = applicationPermission; + this.objectMapper = objectMapper; } @Override @@ -337,7 +341,7 @@ private Mono<ApplicationTemplate> uploadCommunityTemplateToCS(CommunityTemplateU String authHeader = "Authorization"; String payload; try { - ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); + ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter(); payload = ow.writeValueAsString(communityTemplate); } catch (Exception e) { return Mono.error(e); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationTemplateServiceUnitTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationTemplateServiceUnitTest.java index 543dab378730..6b9f492f79f1 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationTemplateServiceUnitTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationTemplateServiceUnitTest.java @@ -95,7 +95,8 @@ public void initialize() { userDataService, applicationService, responseUtils, - applicationPermission); + applicationPermission, + objectMapper); } private ApplicationTemplate create(String id, String title) {
e6793a7bbbd809e32e224a0b05f16d4239b731c5
2023-08-23 23:25:56
Keyur Paralkar
test: creates data source from ted server instead of mock db (#26585)
false
creates data source from ted server instead of mock db (#26585)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/server_side_filtering_spec_1.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/server_side_filtering_spec_1.ts index a281060b6adb..8c2addab7262 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/server_side_filtering_spec_1.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/server_side_filtering_spec_1.ts @@ -33,7 +33,9 @@ describe("Table widget v2: test server side filtering", function () { oneClickBindingLocator.otherActionSelector("Connect new datasource"), ); - dataSources.CreateMockDB("Users").then(($createdMockUsers) => { + dataSources.CreateDataSource("MySql"); + + cy.get("@dsName").then(($dsName) => { dataSources.CreateQueryAfterDSSaved(); cy.wait(500); @@ -42,14 +44,14 @@ describe("Table widget v2: test server side filtering", function () { expandLoadMoreOptions(); agHelper.GetNClick( - oneClickBindingLocator.datasourceSelector($createdMockUsers), + oneClickBindingLocator.datasourceSelector($dsName as unknown as string), ); agHelper.Sleep(3000); //for tables to populate for CI runs agHelper.GetNClick(oneClickBindingLocator.tableOrSpreadsheetDropdown); agHelper.GetNClick( - oneClickBindingLocator.tableOrSpreadsheetDropdownOption("public.users"), + oneClickBindingLocator.tableOrSpreadsheetDropdownOption("employees"), ); agHelper.GetNClick(oneClickBindingLocator.connectData); @@ -69,7 +71,7 @@ describe("Table widget v2: test server side filtering", function () { // set execute select SQL query action on table filter update: propPane.SelectPlatformFunction("onTableFilterUpdate", "Execute a query"); - agHelper.GetNClickByContains(".single-select", "Select_public_users1"); + agHelper.GetNClickByContains(".single-select", "Select_employees1"); agHelper.GetNClick(propPane._actionAddCallback("success")); agHelper.GetNClick(locators._dropDownValue("Show alert")); agHelper.EnterActionValue("Message", ALERT_SUCCESS_MSG); @@ -79,7 +81,7 @@ describe("Table widget v2: test server side filtering", function () { table.ReadTableRowColumnData(0, 0, "v2").then(($cellData) => { expect(Number($cellData)).to.greaterThan(-1); }); - table.OpenNFilterTable("id", "greater than", "10"); + table.OpenNFilterTable("employeeNumber", "greater than", "1000"); agHelper.WaitUntilToastDisappear(ALERT_SUCCESS_MSG); table.CloseFilter(); table.ReadTableRowColumnData(0, 0, "v2").then(($cellData) => { @@ -101,12 +103,12 @@ describe("Table widget v2: test server side filtering", function () { it("4. should test that data is filtered client-side when serverside filtering is turned off", () => { propPane.TogglePropertyState("serversidefiltering", "Off"); - table.OpenNFilterTable("id", "is equal to", "4"); + table.OpenNFilterTable("employeeNumber", "is equal to", "1002"); table.CloseFilter(); // check first row table.ReadTableRowColumnData(0, 0, "v2").then(($cellData) => { - expect($cellData).to.eq("4"); + expect($cellData).to.eq("1002"); }); }); });
5af238b771aec45812511f9c4d85a4c733d6445d
2024-01-30 14:12:50
Rudraprasad Das
fix: trigger issue with git settings (#30731)
false
trigger issue with git settings (#30731)
fix
diff --git a/app/client/cypress/support/Pages/GitSync.ts b/app/client/cypress/support/Pages/GitSync.ts index ce570b523d0e..88976e1fc324 100644 --- a/app/client/cypress/support/Pages/GitSync.ts +++ b/app/client/cypress/support/Pages/GitSync.ts @@ -183,7 +183,8 @@ export class GitSync { private remoteUrlInput = "[data-testid='git-connect-remote-url-input']"; private addedDeployKeyCheckbox = "[data-testid='t--added-deploy-key-checkbox']"; - private startUsingGitButton = "[data-testid='t--start-using-git-button']"; + private startUsingGitButton = + "[data-testid='t--git-success-modal-start-using-git-cta']"; private existingRepoCheckbox = "[data-testid='t--existing-repo-checkbox']"; CreateNConnectToGitV2( diff --git a/app/client/src/entities/GitSync.ts b/app/client/src/entities/GitSync.ts index 6b8d46bde215..12397a010a62 100644 --- a/app/client/src/entities/GitSync.ts +++ b/app/client/src/entities/GitSync.ts @@ -2,7 +2,6 @@ export enum GitSyncModalTab { GIT_CONNECTION = "GIT_CONNECTION", DEPLOY = "DEPLOY", MERGE = "MERGE", - SETTINGS = "SETTINGS", } export interface GitConfig { diff --git a/app/client/src/pages/Editor/gitSync/DisconnectGitModal.tsx b/app/client/src/pages/Editor/gitSync/DisconnectGitModal.tsx index 771584e38e04..d624973b47e9 100644 --- a/app/client/src/pages/Editor/gitSync/DisconnectGitModal.tsx +++ b/app/client/src/pages/Editor/gitSync/DisconnectGitModal.tsx @@ -8,6 +8,7 @@ import { useDispatch, useSelector } from "react-redux"; import { revokeGit, setDisconnectingGitApplication, + setGitSettingsModalOpenAction, setIsDisconnectGitModalOpen, setIsGitSyncModalOpen, } from "actions/gitSyncActions"; @@ -36,6 +37,7 @@ import { Space } from "./components/StyledComponents"; import { GitSyncModalTab } from "entities/GitSync"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; +import { GitSettingsTab } from "reducers/uiReducers/gitSyncReducer"; function DisconnectGitModal() { const isGitConnectV2Enabled = useFeatureFlag( @@ -50,14 +52,21 @@ function DisconnectGitModal() { const handleClickOnBack = useCallback(() => { dispatch(setIsDisconnectGitModalOpen(false)); - dispatch( - setIsGitSyncModalOpen({ - isOpen: true, - tab: isGitConnectV2Enabled - ? GitSyncModalTab.SETTINGS - : GitSyncModalTab.GIT_CONNECTION, - }), - ); + if (isGitConnectV2Enabled) { + dispatch( + setGitSettingsModalOpenAction({ + open: true, + tab: GitSettingsTab.GENERAL, + }), + ); + } else { + dispatch( + setIsGitSyncModalOpen({ + isOpen: true, + tab: GitSyncModalTab.GIT_CONNECTION, + }), + ); + } dispatch(setDisconnectingGitApplication({ id: "", name: "" })); }, [dispatch]); diff --git a/app/client/src/pages/Editor/gitSync/Tabs/ConnectionSuccess.tsx b/app/client/src/pages/Editor/gitSync/Tabs/ConnectionSuccess.tsx index e4cadf77cb22..94c99d2343e8 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/ConnectionSuccess.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/ConnectionSuccess.tsx @@ -91,6 +91,11 @@ function ConnectionSuccess() { }; const handleOpenSettings = () => { + dispatch( + setIsGitSyncModalOpen({ + isOpen: false, + }), + ); dispatch( setGitSettingsModalOpenAction({ open: true, @@ -136,14 +141,18 @@ function ConnectionSuccess() { return ( <> <Button - data-testid="t--start-using-git-button" + data-testid="t--git-success-modal-start-using-git-cta" kind="secondary" onClick={handleStartGit} size="md" > {createMessage(START_USING_GIT)} </Button> - <Button onClick={handleOpenSettings} size="md"> + <Button + data-testid="t--git-success-modal-open-settings-cta" + onClick={handleOpenSettings} + size="md" + > {createMessage(OPEN_GIT_SETTINGS)} </Button> </> @@ -152,11 +161,15 @@ function ConnectionSuccess() { return ( <> - <ModalBody> + <ModalBody data-testid="t--git-success-modal-body"> <Container> <TitleContainer> <StyledIcon color="#059669" name="oval-check" size="lg" /> - <TitleText kind="heading-s" renderAs="h3"> + <TitleText + data-testid="t--git-success-modal-title" + kind="heading-s" + renderAs="h3" + > {createMessage(GIT_CONNECT_SUCCESS_TITLE)} </TitleText> </TitleContainer> diff --git a/app/client/src/pages/Editor/gitSync/Tabs/__tests__/ConnectionSuccess.test.tsx b/app/client/src/pages/Editor/gitSync/Tabs/__tests__/ConnectionSuccess.test.tsx new file mode 100644 index 000000000000..1325813f659d --- /dev/null +++ b/app/client/src/pages/Editor/gitSync/Tabs/__tests__/ConnectionSuccess.test.tsx @@ -0,0 +1,93 @@ +import React from "react"; +import { render } from "@testing-library/react"; +import ConnectionSuccess from "../ConnectionSuccess"; + +import configureStore from "redux-mock-store"; +import { Provider } from "react-redux"; +import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; +import { GitSettingsTab } from "reducers/uiReducers/gitSyncReducer"; + +const initialState = { + ui: { + applications: { + currentApplication: { + gitApplicationMetadata: { + branchName: "master", + defaultBranchName: "master", + remoteUrl: "[email protected]:delmuerto/book-app-ld.git", + browserSupportedRemoteUrl: "https://github.com/delmuerto/book-app-ld", + isRepoPrivate: true, + repoName: "book-app-ld", + defaultApplicationId: "xxx", + lastCommittedAt: "2024-01-25T12:36:40Z", + }, + }, + }, + }, +}; +const mockStore = configureStore(); + +const dispatch = jest.fn(); +jest.mock("react-redux", () => { + const originalModule = jest.requireActual("react-redux"); + return { + ...originalModule, + useDispatch: () => dispatch, + }; +}); + +describe("Connection Success Modal", () => { + it("is rendered properly", () => { + const store = mockStore(initialState); + const { queryByTestId } = render( + <Provider store={store}> + <ConnectionSuccess /> + </Provider>, + ); + expect(queryByTestId("t--git-success-modal-body")).toBeTruthy(); + expect( + queryByTestId("t--git-success-modal-start-using-git-cta"), + ).toBeTruthy(); + expect( + queryByTestId("t--git-success-modal-open-settings-cta"), + ).toBeTruthy(); + }); + + it("go to settings cta button is working", () => { + const store = mockStore(initialState); + const { queryByTestId } = render( + <Provider store={store}> + <ConnectionSuccess /> + </Provider>, + ); + expect(dispatch).toHaveBeenNthCalledWith(1, { + type: ReduxActionTypes.FETCH_BRANCHES_INIT, + }); + queryByTestId("t--git-success-modal-open-settings-cta")?.click(); + expect(dispatch).toHaveBeenNthCalledWith(3, { + type: ReduxActionTypes.SET_IS_GIT_SYNC_MODAL_OPEN, + payload: { isOpen: false }, + }); + expect(dispatch).toHaveBeenNthCalledWith(4, { + type: ReduxActionTypes.GIT_SET_SETTINGS_MODAL_OPEN, + payload: { open: true, tab: GitSettingsTab.GENERAL }, + }); + }); + + it("start using git cta button is working", () => { + const store = mockStore(initialState); + const { queryByTestId } = render( + <Provider store={store}> + <ConnectionSuccess /> + </Provider>, + ); + expect(dispatch).toHaveBeenNthCalledWith(1, { + type: ReduxActionTypes.FETCH_BRANCHES_INIT, + }); + queryByTestId("t--git-success-modal-start-using-git-cta")?.click(); + expect(dispatch).toHaveBeenNthCalledWith(3, { + type: ReduxActionTypes.SET_IS_GIT_SYNC_MODAL_OPEN, + payload: { isOpen: false }, + }); + }); +}); diff --git a/app/client/src/pages/Editor/gitSync/components/BranchList.tsx b/app/client/src/pages/Editor/gitSync/components/BranchList.tsx index 516e3d693185..9dad11ebaf07 100644 --- a/app/client/src/pages/Editor/gitSync/components/BranchList.tsx +++ b/app/client/src/pages/Editor/gitSync/components/BranchList.tsx @@ -27,9 +27,6 @@ import BranchListHotkeys from "./BranchListHotkeys"; import { createMessage, FIND_OR_CREATE_A_BRANCH, - // GO_TO_SETTINGS, - // LEARN_MORE, - // NOW_PROTECT_BRANCH, SWITCH_BRANCHES, SYNC_BRANCHES, } from "@appsmith/constants/messages"; @@ -40,7 +37,6 @@ import { Button, SearchInput, Text, - // Callout, } from "design-system"; import { get } from "lodash"; import { @@ -381,32 +377,6 @@ export default function BranchList(props: { {loading && <BranchesLoading />} {!loading && ( <ListContainer> - {/* keeping it commented for future use */} - {/* <Callout - isClosable - links={[ - { - children: createMessage(GO_TO_SETTINGS), - onClick: () => { - props.setIsPopupOpen?.(false); - dispatch( - setIsGitSyncModalOpen({ - isOpen: true, - tab: GitSyncModalTab.SETTINGS, - }), - ); - }, - }, - { - children: createMessage(LEARN_MORE), - to: "https://docs.appsmith.com/advanced-concepts/version-control-with-git", - target: "_blank", - }, - ]} - style={{ width: 300 }} - > - {createMessage(NOW_PROTECT_BRANCH)} - </Callout> */} <Space size={5} /> {isCreateNewBranchInputValid && ( <CreateNewBranch
7ab05c4a10dd952153303e46140c6a572e0ba281
2022-06-21 03:36:44
Tolulope Adetula
fix: failing tests
false
failing tests
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/MultiSelect_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/MultiSelect_spec.js index 1253f5dcbc3d..64647cec7cba 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/MultiSelect_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/MultiSelect_spec.js @@ -31,37 +31,7 @@ describe("MultiSelect Widget Functionality", function() { .first() .should("have.text", "Option 3"); }); - it("Selects value with enter in default value", () => { - cy.testJsontext( - "defaultvalue", - '[\n {\n "label": "Option 3",\n "value": "3"\n }\n]', - ); - cy.get(formWidgetsPage.multiselectwidgetv2) - .find(".rc-select-selection-item-content") - .first() - .should("have.text", "Option 3"); - }); - it("Dropdown Functionality To Validate Options", function() { - cy.get(".rc-select-selector").click({ force: true }); - cy.dropdownMultiSelectDynamic("Option 2"); - }); - it("Dropdown Functionality To Unchecked Visible Widget", function() { - cy.togglebarDisable(commonlocators.visibleCheckbox); - cy.PublishtheApp(); - cy.get(publish.multiselectwidgetv2 + " " + ".rc-select-selector").should( - "not.exist", - ); - cy.get(publish.backToEditor).click(); - }); - it("Dropdown Functionality To Check Visible Widget", function() { - cy.openPropertyPane("multiselectwidgetv2"); - cy.togglebar(commonlocators.visibleCheckbox); - cy.PublishtheApp(); - cy.get(publish.multiselectwidgetv2 + " " + ".rc-select-selector").should( - "be.visible", - ); - cy.get(publish.backToEditor).click(); - }); + it("Dropdown Functionality To Check Allow select all option", function() { // select all option is not enable cy.get(formWidgetsPage.multiselectwidgetv2) @@ -114,6 +84,37 @@ describe("MultiSelect Widget Functionality", function() { // Check if isDirty is set to false cy.get(".t--widget-textwidget").should("contain", "false"); }); + it("Selects value with enter in default value", () => { + cy.testJsontext( + "defaultvalue", + '[\n {\n "label": "Option 3",\n "value": "3"\n }\n]', + ); + cy.get(formWidgetsPage.multiselectwidgetv2) + .find(".rc-select-selection-item-content") + .first() + .should("have.text", "Option 3"); + }); + it("Dropdown Functionality To Validate Options", function() { + cy.get(".rc-select-selector").click({ force: true }); + cy.dropdownMultiSelectDynamic("Option 2"); + }); + it("Dropdown Functionality To Unchecked Visible Widget", function() { + cy.togglebarDisable(commonlocators.visibleCheckbox); + cy.PublishtheApp(); + cy.get(publish.multiselectwidgetv2 + " " + ".rc-select-selector").should( + "not.exist", + ); + cy.get(publish.backToEditor).click(); + }); + it("Dropdown Functionality To Check Visible Widget", function() { + cy.openPropertyPane("multiselectwidgetv2"); + cy.togglebar(commonlocators.visibleCheckbox); + cy.PublishtheApp(); + cy.get(publish.multiselectwidgetv2 + " " + ".rc-select-selector").should( + "be.visible", + ); + cy.get(publish.backToEditor).click(); + }); }); afterEach(() => { // put your clean up code if any diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Multi_Select_Tree_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Multi_Select_Tree_spec.js index 0627ee03ca6e..8d53c111936f 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Multi_Select_Tree_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Multi_Select_Tree_spec.js @@ -9,6 +9,32 @@ describe("MultiSelectTree Widget Functionality", function() { cy.addDsl(dsl); }); + it("Check isDirty meta property", function() { + cy.get(explorer.addWidget).click(); + cy.dragAndDropToCanvas("textwidget", { x: 300, y: 500 }); + cy.openPropertyPane("textwidget"); + cy.updateCodeInput( + ".t--property-control-text", + `{{MultiSelectTree1.isDirty}}`, + ); + // Change defaultValue + cy.openPropertyPane("multiselecttreewidget"); + cy.testJsontext("defaultvalue", "GREEN\n"); + // Check if isDirty is set to false + cy.get(".t--widget-textwidget").should("contain", "false"); + // Interact with UI + cy.get(formWidgetsPage.treeSelectInput) + .first() + .click({ force: true }); + cy.treeMultiSelectDropdown("Red"); + // Check if isDirty is set to true + cy.get(".t--widget-textwidget").should("contain", "true"); + // Reset isDirty by changing defaultValue + cy.testJsontext("defaultvalue", "BLUE\n"); + // Check if isDirty is set to false + cy.get(".t--widget-textwidget").should("contain", "false"); + }); + it("Selects value with enter in default value", () => { cy.openPropertyPane("multiselecttreewidget"); cy.testJsontext("defaultvalue", "RED\n"); @@ -43,32 +69,6 @@ describe("MultiSelectTree Widget Functionality", function() { ).should("be.visible"); cy.get(publish.backToEditor).click(); }); - - it("Check isDirty meta property", function() { - cy.get(explorer.addWidget).click(); - cy.dragAndDropToCanvas("textwidget", { x: 300, y: 500 }); - cy.openPropertyPane("textwidget"); - cy.updateCodeInput( - ".t--property-control-text", - `{{MultiSelectTree1.isDirty}}`, - ); - // Change defaultValue - cy.openPropertyPane("multiselecttreewidget"); - cy.testJsontext("defaultvalue", "GREEN\n"); - // Check if isDirty is set to false - cy.get(".t--widget-textwidget").should("contain", "false"); - // Interact with UI - cy.get(formWidgetsPage.treeSelectInput) - .first() - .click({ force: true }); - cy.treeMultiSelectDropdown("Red"); - // Check if isDirty is set to true - cy.get(".t--widget-textwidget").should("contain", "true"); - // Reset isDirty by changing defaultValue - cy.testJsontext("defaultvalue", "BLUE\n"); - // Check if isDirty is set to false - cy.get(".t--widget-textwidget").should("contain", "false"); - }); }); afterEach(() => { // put your clean up code if any diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Single_Select_Tree_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Single_Select_Tree_spec.js index a4de78b0db09..f126e4d75c6d 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Single_Select_Tree_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Single_Select_Tree_spec.js @@ -7,6 +7,34 @@ describe("Single Select Widget Functionality", function() { before(() => { cy.addDsl(dsl); }); + + it("Check isDirty meta property", function() { + cy.openPropertyPane("textwidget"); + cy.updateCodeInput( + ".t--property-control-text", + `{{SingleSelectTree1.isDirty}}`, + ); + // Change defaultText + cy.openPropertyPane("singleselecttreewidget"); + cy.updateCodeInput(".t--property-control-defaultvalue", "GREEN"); + // Check if isDirty is reset to false + cy.get(".t--widget-textwidget").should("contain", "false"); + // Interact with UI + cy.get(formWidgetsPage.treeSelectInput) + .last() + .click({ force: true }); + cy.get(formWidgetsPage.treeSelectFilterInput) + .click() + .type("light"); + cy.treeSelectDropdown("Light Blue"); + // Check if isDirty is set to true + cy.get(".t--widget-textwidget").should("contain", "true"); + // Change defaultText + cy.openPropertyPane("singleselecttreewidget"); + cy.updateCodeInput(".t--property-control-defaultvalue", "RED"); + // Check if isDirty is reset to false + cy.get(".t--widget-textwidget").should("contain", "false"); + }); it("Selects value with enter in default value", () => { cy.openPropertyPane("singleselecttreewidget"); cy.testJsontext("defaultvalue", "RED\n"); @@ -41,35 +69,6 @@ describe("Single Select Widget Functionality", function() { ).should("be.visible"); cy.get(publish.backToEditor).click(); }); - - it("Check isDirty meta property", function() { - cy.openPropertyPane("textwidget"); - cy.updateCodeInput( - ".t--property-control-text", - `{{SingleSelectTree1.isDirty}}`, - ); - // Change defaultText - cy.openPropertyPane("singleselecttreewidget"); - cy.updateCodeInput(".t--property-control-defaultvalue", "GREEN"); - cy.closePropertyPane(); - // Check if isDirty is reset to false - cy.get(".t--widget-textwidget").should("contain", "false"); - // Interact with UI - cy.get(formWidgetsPage.treeSelectInput) - .last() - .click({ force: true }); - cy.get(formWidgetsPage.treeSelectFilterInput) - .click() - .type("light"); - cy.treeSelectDropdown("Light Blue"); - // Check if isDirty is set to true - cy.get(".t--widget-textwidget").should("contain", "true"); - // Change defaultText - cy.openPropertyPane("singleselecttreewidget"); - cy.updateCodeInput(".t--property-control-defaultvalue", "RED"); - // Check if isDirty is reset to false - cy.get(".t--widget-textwidget").should("contain", "false"); - }); }); afterEach(() => { // put your clean up code if any
aca4457a328333e8f0d80c2c32f6370445937104
2021-08-25 19:41:15
ashit-rath
fix: RTE crash on defaultText change (#6789)
false
RTE crash on defaultText change (#6789)
fix
diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index f6425916bb96..a75d6ef2ce58 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -381,24 +381,31 @@ class CodeEditor extends Component<Props, State> { const entityInformation: FieldEntityInformation = { expectedType: expected?.autocompleteDataType, }; + if (dataTreePath) { const { entityName, propertyPath } = getEntityNameAndPropertyPath( dataTreePath, ); entityInformation.entityName = entityName; const entity = dynamicData[entityName]; - if (entity && "ENTITY_TYPE" in entity) { - const entityType = entity.ENTITY_TYPE; - if ( - entityType === ENTITY_TYPE.WIDGET || - entityType === ENTITY_TYPE.ACTION - ) { - entityInformation.entityType = entityType; + + if (entity) { + if ("ENTITY_TYPE" in entity) { + const entityType = entity.ENTITY_TYPE; + if ( + entityType === ENTITY_TYPE.WIDGET || + entityType === ENTITY_TYPE.ACTION + ) { + entityInformation.entityType = entityType; + } } + + if (isActionEntity(entity)) + entityInformation.entityId = entity.actionId; + if (isWidgetEntity(entity)) + entityInformation.entityId = entity.widgetId; + entityInformation.propertyPath = propertyPath; } - if (isActionEntity(entity)) entityInformation.entityId = entity.actionId; - if (isWidgetEntity(entity)) entityInformation.entityId = entity.widgetId; - entityInformation.propertyPath = propertyPath; } return entityInformation; };
f939ebbe8a4864bd48c840444d368e8ce8c9eedb
2021-10-08 22:21:24
Sheetal Patel
chore: Fixing yoda conditions in the code (#8297)
false
Fixing yoda conditions in the code (#8297)
chore
diff --git a/app/server/scripts/node/acl-migration.js b/app/server/scripts/node/acl-migration.js index 7519a42b08d4..cadc589be2b9 100644 --- a/app/server/scripts/node/acl-migration.js +++ b/app/server/scripts/node/acl-migration.js @@ -338,7 +338,7 @@ async function purgeSuperUser(db, isSilent) { async function runChecks(db) { for (const collection of await db.collections()) { - if (0 !== await collection.countDocuments({ "policies.users": SUPER_EMAIL })) { + if (await collection.countDocuments({ "policies.users": SUPER_EMAIL }) !== 0 ) { console.error(`Super user lives on in the '${collection.collectionName}' collection.`); } }
9e9c1490e6708df383eae748ec0a347dd15b2d8f
2023-06-07 10:20:50
balajisoundar
fix: connect datasource size issue in the generate page form (#24073)
false
connect datasource size issue in the generate page form (#24073)
fix
diff --git a/app/client/src/pages/Editor/GeneratePage/components/DataSourceOption.tsx b/app/client/src/pages/Editor/GeneratePage/components/DataSourceOption.tsx index 7fa07d042605..9ec6995df266 100644 --- a/app/client/src/pages/Editor/GeneratePage/components/DataSourceOption.tsx +++ b/app/client/src/pages/Editor/GeneratePage/components/DataSourceOption.tsx @@ -8,7 +8,7 @@ import type { } from "design-system-old"; import { Classes, Text, TextType } from "design-system-old"; import _ from "lodash"; -import { Tooltip, Button } from "design-system"; +import { Tooltip, Icon } from "design-system"; import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; // ---------- Helpers and constants ---------- @@ -63,6 +63,12 @@ export const DatasourceImage = styled.img` width: 16px; `; +const CreateIconWrapper = styled.div` + margin: 0px 8px 0px 0px; + cursor: pointer; + height: 16px; +`; + interface DataSourceOptionType extends RenderDropdownOptionType { dataTestid: string; optionWidth: string; @@ -116,7 +122,9 @@ function DataSourceOption({ width={optionWidth} > {isConnectNewDataSourceBtn ? ( - <Button isIconButton kind="tertiary" size="md" startIcon="plus" /> + <CreateIconWrapper> + <Icon name="plus" size="md" /> + </CreateIconWrapper> ) : pluginImages[(dropdownOption as DropdownOption)?.data?.pluginId] ? ( <ImageWrapper> <DatasourceImage
0c406b0d02afc5d38b99e606d157e389fdeecb56
2024-11-07 11:25:49
Rahul Barwal
feat: Enhance date validation logic and add tests for timePrecision in DatePickerWidget2 (#37218)
false
Enhance date validation logic and add tests for timePrecision in DatePickerWidget2 (#37218)
feat
diff --git a/app/client/src/widgets/DatePickerWidget2/widget/derived.js b/app/client/src/widgets/DatePickerWidget2/widget/derived.js index cda0937f7e31..e3ace7250e46 100644 --- a/app/client/src/widgets/DatePickerWidget2/widget/derived.js +++ b/app/client/src/widgets/DatePickerWidget2/widget/derived.js @@ -1,31 +1,50 @@ /* eslint-disable @typescript-eslint/no-unused-vars*/ export default { isValidDate: (props, moment, _) => { - const minDate = new Date(props.minDate); - const maxDate = new Date(props.maxDate); - const selectedDate = - props.selectedDate !== "" - ? moment(new Date(props.selectedDate)) - : props.selectedDate; - let dateValid = true; - - if (!!props.minDate && !!props.maxDate) { - dateValid = !!selectedDate - ? selectedDate.isBetween(minDate, maxDate) - : !props.isRequired; - } else if (!!props.minDate) { - dateValid = !!selectedDate - ? selectedDate.isAfter(minDate) - : !props.isRequired; - } else if (!!props.maxDate) { - dateValid = !!selectedDate - ? selectedDate.isBefore(maxDate) - : !props.isRequired; - } else { - dateValid = props.isRequired ? !!selectedDate : true; + if (!props.selectedDate && !props.isRequired) { + return true; } - return dateValid; + const minDate = props.minDate ? new Date(props.minDate) : null; + const maxDate = props.maxDate ? new Date(props.maxDate) : null; + const selectedDate = props.selectedDate + ? moment(new Date(props.selectedDate)) + : props.selectedDate; + + if (!selectedDate) { + return !props.isRequired; + } + + let granularity, + inclusivity = "[]"; + + switch (props.timePrecision) { + case "None": + granularity = "day"; + break; + case "second": + case "minute": + case "millisecond": + granularity = props.timePrecision; + break; + default: + granularity = undefined; + inclusivity = undefined; + } + + if (minDate && maxDate) { + return selectedDate.isBetween(minDate, maxDate, granularity, inclusivity); + } + + if (minDate) { + return selectedDate.isSameOrAfter(minDate, granularity); + } + + if (maxDate) { + return selectedDate.isSameOrBefore(maxDate, granularity); + } + + return true; }, // }; diff --git a/app/client/src/widgets/DatePickerWidget2/widget/derived.test.js b/app/client/src/widgets/DatePickerWidget2/widget/derived.test.js index 820d4f2e10e4..f52aaf962c60 100644 --- a/app/client/src/widgets/DatePickerWidget2/widget/derived.test.js +++ b/app/client/src/widgets/DatePickerWidget2/widget/derived.test.js @@ -86,4 +86,124 @@ describe("Validates Derived Properties", () => { expect(result).toStrictEqual(false); }); + describe("timePrecision", () => { + it("should fail when selectedDate minute is outside bounds", () => { + const { isValidDate } = derivedProperty; + const input = { + isRequired: true, + maxDate: "2021-12-01T05:49:00.000Z", + minDate: "2021-12-01T05:48:00.000Z", + selectedDate: "2021-12-01T05:50:00.000Z", + timePrecision: "minute", + }; + + let result = isValidDate(input, moment, _); + + expect(result).toStrictEqual(false); + }); + + it("timePrecision: minute -> date is valid even if selectedDate is over by seconds", () => { + const { isValidDate } = derivedProperty; + const input = { + isRequired: true, + maxDate: "2121-12-31T18:29:00.000Z", + minDate: "2021-12-01T05:49:28.753Z", + selectedDate: "2021-12-01T05:49:24.753Z", + timePrecision: "minute", + }; + + let result = isValidDate(input, moment, _); + + expect(result).toStrictEqual(true); + }); + + it("timePrecision: second -> date is valid even if selectedDate is over by milliseconds", () => { + const { isValidDate } = derivedProperty; + const input = { + isRequired: true, + maxDate: "2121-12-31T18:29:00.000Z", + minDate: "2021-12-01T05:49:24.753Z", + selectedDate: "2021-12-01T05:49:24.751Z", + timePrecision: "second", + }; + + let result = isValidDate(input, moment, _); + + expect(result).toStrictEqual(true); + }); + + it("timePrecision: millisecond", () => { + const { isValidDate } = derivedProperty; + const input = { + isRequired: true, + maxDate: "2121-12-31T18:29:00.000Z", + minDate: "2021-12-01T05:49:24.752Z", + selectedDate: "2021-12-01T05:49:24.753Z", + timePrecision: "millisecond", + }; + + let result = isValidDate(input, moment, _); + + expect(result).toStrictEqual(true); + }); + + describe("timePrecision: None", () => { + it("date is same as minDate", () => { + const { isValidDate } = derivedProperty; + const input = { + isRequired: true, + maxDate: "2121-12-31T18:29:00.000Z", + minDate: "2021-12-01T00:00:00.000Z", + selectedDate: "2021-12-01T00:00:00.000Z", + timePrecision: "None", + }; + + let result = isValidDate(input, moment, _); + + expect(result).toStrictEqual(true); + }); + it("date is same as maxDate", () => { + const { isValidDate } = derivedProperty; + const input = { + isRequired: true, + maxDate: "2021-12-01T00:00:00.000Z", + minDate: "1991-12-31T18:29:00.000Z", + selectedDate: "2021-12-01T00:00:00.000Z", + timePrecision: "None", + }; + + let result = isValidDate(input, moment, _); + + expect(result).toStrictEqual(true); + }); + it("date is between minDate and maxDate", () => { + const { isValidDate } = derivedProperty; + const input = { + isRequired: true, + maxDate: "2121-12-31T18:29:00.000Z", + minDate: "1920-12-31T18:30:00.000Z", + selectedDate: "2021-12-01T05:49:24.753Z", + timePrecision: "None", + }; + + let result = isValidDate(input, moment, _); + + expect(result).toStrictEqual(true); + }); + it("date is out of bounds", () => { + const { isValidDate } = derivedProperty; + const input = { + isRequired: true, + maxDate: "2021-12-31T18:29:00.000Z", + minDate: "1920-12-31T18:30:00.000Z", + selectedDate: "2022-12-01T05:49:24.753Z", + timePrecision: "None", + }; + + let result = isValidDate(input, moment, _); + + expect(result).toStrictEqual(false); + }); + }); + }); });
0c258e20bb15035412b90733b93279d491189994
2023-10-04 18:07:26
Nayan
fix: Stop updating action when datasource name is updated (#27668)
false
Stop updating action when datasource name is updated (#27668)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java index daa93bea45d1..f9b9d21ac7e7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java @@ -277,29 +277,10 @@ public Mono<Datasource> updateDatasource( // This is meant to be an update for just the datasource - like a renamed return datasourceMono .map(datasourceInDb -> { - // check whether name is going to be updated - boolean isRenamed = StringUtils.hasLength(datasource.getName()) - && !datasource.getName().equals(datasourceInDb.getName()); copyNestedNonNullProperties(datasource, datasourceInDb); - return Tuples.of(datasourceInDb, isRenamed); - }) - .flatMap(tuples -> { - Datasource datasourceInDb = tuples.getT1(); - boolean isRenamed = tuples.getT2(); - return validateAndSaveDatasourceToRepository(datasourceInDb).flatMap(savedDatasource -> { - if (isRenamed) { - /* - if name updated, we've to set the updatedAt date for the related actions. - Because in git file system, actions are mapped with a datasource by the name. - If updatedAt changed, git will remap the updated actions with new datasource name. - */ - return newActionRepository - .updateDatasourceNameInActions(savedDatasource) - .thenReturn(savedDatasource); - } - return Mono.just(savedDatasource); - }); + return datasourceInDb; }) + .flatMap(this::validateAndSaveDatasourceToRepository) .map(savedDatasource -> { // not required by client side in order to avoid updating it to a null storage, // one alternative is that we find and send datasourceStorages along, but that is an expensive call diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java index d3d2807556cc..b1493ac79a70 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java @@ -11,6 +11,7 @@ import org.springframework.transaction.TransactionException; import org.springframework.util.CollectionUtils; +import java.time.Instant; import java.util.Map; import java.util.Set; @@ -131,4 +132,15 @@ public static boolean isPageNameInUpdatedList(ApplicationJson applicationJson, S } return pageName != null && updatedPageNames.contains(pageName); } + + public static boolean isDatasourceUpdatedSinceLastCommit( + Map<String, Instant> datasourceNameToUpdatedAtMap, + ActionDTO actionDTO, + Instant applicationLastCommittedAt) { + String datasourceName = actionDTO.getDatasource().getId(); + Instant datasourceUpdatedAt = datasourceName != null ? datasourceNameToUpdatedAtMap.get(datasourceName) : null; + return datasourceUpdatedAt != null + && applicationLastCommittedAt != null + && datasourceUpdatedAt.isAfter(applicationLastCommittedAt); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java index ee1a842fa516..c3bda9cc5a79 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java @@ -1,6 +1,5 @@ package com.appsmith.server.repositories.ce; -import com.appsmith.external.models.Datasource; import com.appsmith.server.acl.AclPermission; import com.appsmith.server.domains.NewAction; import com.appsmith.server.dtos.PluginTypeAndCountDTO; @@ -82,8 +81,6 @@ Flux<NewAction> findAllNonJsActionsByNameAndPageIdsAndViewMode( Mono<UpdateResult> archiveDeletedUnpublishedActions(String applicationId, AclPermission permission); - Mono<UpdateResult> updateDatasourceNameInActions(Datasource datasource); - Flux<PluginTypeAndCountDTO> countActionsByPluginType(String applicationId); Flux<NewAction> findAllByApplicationIdsWithoutPermission(List<String> applicationIds, List<String> includeFields); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java index f516eb219a9a..840c0dfe6b92 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java @@ -1,6 +1,5 @@ package com.appsmith.server.repositories.ce; -import com.appsmith.external.models.Datasource; import com.appsmith.external.models.PluginType; import com.appsmith.external.models.QActionConfiguration; import com.appsmith.external.models.QBranchAwareDomain; @@ -644,31 +643,4 @@ public Flux<NewAction> findAllByApplicationIdsWithoutPermission( Criteria applicationCriteria = Criteria.where(FieldName.APPLICATION_ID).in(applicationIds); return queryAll(List.of(applicationCriteria), includeFields, null, null, NO_RECORD_LIMIT); } - - /** - * Sets the datasource.name and updatedAt fields of newAction as per the provided datasource. The actions which - * have unpublishedAction.datasource.id same as the provided datasource.id will be updated. - * @param datasource The datasource object - * @return result of the multi update query - */ - @Override - public Mono<UpdateResult> updateDatasourceNameInActions(Datasource datasource) { - String unpublishedActionDatasourceIdFieldPath = String.format( - "%s.%s.%s", - fieldName(QNewAction.newAction.unpublishedAction), - fieldName(QNewAction.newAction.unpublishedAction.datasource), - fieldName(QNewAction.newAction.unpublishedAction.datasource.id)); - - String unpublishedActionDatasourceNameFieldPath = String.format( - "%s.%s.%s", - fieldName(QNewAction.newAction.unpublishedAction), - fieldName(QNewAction.newAction.unpublishedAction.datasource), - fieldName(QNewAction.newAction.unpublishedAction.datasource.name)); - - Criteria criteria = where(unpublishedActionDatasourceIdFieldPath).is(datasource.getId()); - Update update = new Update(); - update.set(FieldName.UPDATED_AT, datasource.getUpdatedAt()); - update.set(unpublishedActionDatasourceNameFieldPath, datasource.getName()); - return updateByCriteria(List.of(criteria), update, null); - } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java index 0d4b79f4a246..00d0e816b92b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java @@ -175,6 +175,7 @@ public Mono<ApplicationJson> exportApplicationById( ApplicationJson applicationJson = new ApplicationJson(); Map<String, String> pluginMap = new HashMap<>(); Map<String, String> datasourceIdToNameMap = new HashMap<>(); + Map<String, Instant> datasourceNameToUpdatedAtMap = new HashMap<>(); Map<String, String> pageIdToNameMap = new HashMap<>(); Map<String, String> actionIdToNameMap = new HashMap<>(); Map<String, String> collectionIdToNameMap = new HashMap<>(); @@ -397,8 +398,11 @@ public Mono<ApplicationJson> exportApplicationById( .flatMapMany(tuple2 -> { List<Datasource> datasourceList = tuple2.getT1(); String environmentId = tuple2.getT2(); - datasourceList.forEach(datasource -> - datasourceIdToNameMap.put(datasource.getId(), datasource.getName())); + datasourceList.forEach(datasource -> { + datasourceIdToNameMap.put(datasource.getId(), datasource.getName()); + datasourceNameToUpdatedAtMap.put(datasource.getName(), datasource.getUpdatedAt()); + }); + List<DatasourceStorage> storageList = datasourceList.stream() .map(datasource -> { DatasourceStorage storage = @@ -578,6 +582,10 @@ public Mono<ApplicationJson> exportApplicationById( : null; // TODO: check whether resource updated after last commit - move to a function String pageName = actionDTO.getPageId(); + // we've replaced the datasource id with datasource name in previous step + boolean isDatasourceUpdated = ImportExportUtils.isDatasourceUpdatedSinceLastCommit( + datasourceNameToUpdatedAtMap, actionDTO, applicationLastCommittedAt); + boolean isPageUpdated = ImportExportUtils.isPageNameInUpdatedList(applicationJson, pageName); Instant newActionUpdatedAt = newAction.getUpdatedAt(); @@ -585,6 +593,7 @@ public Mono<ApplicationJson> exportApplicationById( || isServerSchemaMigrated || applicationLastCommittedAt == null || isPageUpdated + || isDatasourceUpdated || newActionUpdatedAt == null || applicationLastCommittedAt.isBefore(newActionUpdatedAt); if (isNewActionUpdated && newActionName != null) { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ImportExportUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ImportExportUtilsTest.java index b2a7924917a1..cd0e40bb5509 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ImportExportUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/ImportExportUtilsTest.java @@ -1,5 +1,7 @@ package com.appsmith.server.helpers; +import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.Datasource; import com.appsmith.server.constants.FieldName; import com.appsmith.server.dtos.ApplicationJson; import com.appsmith.server.exceptions.AppsmithError; @@ -8,6 +10,7 @@ import org.junit.jupiter.api.Test; import org.springframework.data.mongodb.MongoTransactionException; +import java.time.Instant; import java.util.Map; import java.util.Set; @@ -47,4 +50,36 @@ void isPageNameInUpdatedList() { Assertions.assertFalse(ImportExportUtils.isPageNameInUpdatedList(applicationJson, "")); Assertions.assertFalse(ImportExportUtils.isPageNameInUpdatedList(applicationJson, null)); } + + @Test + public void isDatasourceUpdatedSinceLastCommit() { + Map<String, Instant> map = Map.of("Datasource1", Instant.now()); + ActionDTO actionDTO = new ActionDTO(); + actionDTO.setDatasource(new Datasource()); + // should return true if datasource has no id set + Assertions.assertFalse(ImportExportUtils.isDatasourceUpdatedSinceLastCommit( + map, actionDTO, Instant.now().minusSeconds(10))); + + actionDTO.getDatasource().setName("Datasource1"); + // should return false if datasource has name set but no id + Assertions.assertFalse(ImportExportUtils.isDatasourceUpdatedSinceLastCommit( + map, actionDTO, Instant.now().minusSeconds(10))); + + actionDTO.getDatasource().setId("Datasource2"); + // should return false if datasource id does not exist in the map + Assertions.assertFalse(ImportExportUtils.isDatasourceUpdatedSinceLastCommit( + map, actionDTO, Instant.now().minusSeconds(10))); + + actionDTO.getDatasource().setId("Datasource1"); + // should return true if datasource has name set but no id + Assertions.assertTrue(ImportExportUtils.isDatasourceUpdatedSinceLastCommit( + map, actionDTO, Instant.now().minusSeconds(10))); + + // should return false if datasource was modified before last commit + Assertions.assertFalse(ImportExportUtils.isDatasourceUpdatedSinceLastCommit( + map, actionDTO, Instant.now().plusSeconds(10))); + + // should return false if last commit date is null + Assertions.assertFalse(ImportExportUtils.isDatasourceUpdatedSinceLastCommit(map, actionDTO, null)); + } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImplTest.java index 07e63cc47da6..e8382a337a98 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImplTest.java @@ -19,11 +19,8 @@ import reactor.util.function.Tuple2; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.ArrayList; -import java.util.Collection; import java.util.List; -import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -293,47 +290,4 @@ public void archiveDeletedUnpublishedActions_WhenApplicationIdMatchesAndDeletedF }) .verifyComplete(); } - - @Test - public void updateDatasourceNameInActions_WhenDatasourceIdMatched_MatchedObjectsUpdated() { - String uniqueString = UUID.randomUUID().toString(); - String datasourceOne = "ds-1-" + uniqueString, datasourceTwo = "ds-2-" + uniqueString; - String applicationId = "app-" + uniqueString; - - List<NewAction> newActions = List.of( - createActionWithDatasource(applicationId, datasourceOne), - createActionWithDatasource(applicationId, datasourceOne), - createActionWithDatasource(applicationId, datasourceTwo)); - - Datasource datasource = new Datasource(); - datasource.setId(datasourceOne); - datasource.setUpdatedAt(Instant.now().minusSeconds(60 * 60)); // 1 hour ago - - Mono<Map<String, Collection<NewAction>>> newActionsByDatasourceIdMapMono = newActionRepository - .saveAll(newActions) - .then(newActionRepository.updateDatasourceNameInActions(datasource)) - .thenMany(newActionRepository.findByApplicationId(applicationId)) - .collectMultimap((newAction -> - newAction.getUnpublishedAction().getDatasource().getId())); - - StepVerifier.create(newActionsByDatasourceIdMapMono) - .assertNext(multiMap -> { - assertThat(multiMap.size()).isEqualTo(2); - assertThat(multiMap.get(datasourceOne).size()).isEqualTo(2); - assertThat(multiMap.get(datasourceTwo).size()).isEqualTo(1); - - multiMap.get(datasourceOne).forEach(newAction -> { - long diffInMinutes = - datasource.getUpdatedAt().until(newAction.getUpdatedAt(), ChronoUnit.MINUTES); - assertThat(diffInMinutes).isEqualTo(0); - }); - - multiMap.get(datasourceTwo).forEach(newAction -> { - long diffInMinutes = - datasource.getUpdatedAt().until(newAction.getUpdatedAt(), ChronoUnit.MINUTES); - assertThat(diffInMinutes).isGreaterThan(50); // should be at least 50 minutes ago - }); - }) - .verifyComplete(); - } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java index 17b4d160a69a..3ac17236f285 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java @@ -21,7 +21,6 @@ import com.appsmith.server.datasources.base.DatasourceService; import com.appsmith.server.datasourcestorages.base.DatasourceStorageService; import com.appsmith.server.domains.Application; -import com.appsmith.server.domains.NewAction; import com.appsmith.server.domains.PermissionGroup; import com.appsmith.server.domains.Plugin; import com.appsmith.server.domains.User; @@ -57,13 +56,11 @@ import reactor.test.StepVerifier; import reactor.util.function.Tuple2; -import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.UUID; import static com.appsmith.server.acl.AclPermission.DELETE_DATASOURCES; import static com.appsmith.server.acl.AclPermission.EXECUTE_DATASOURCES; @@ -2028,50 +2025,4 @@ public void verifyTestDatasourceWithoutSavedDatasource() { }) .verifyComplete(); } - - @Test - @WithUserDetails(value = "api_user") - public void updateDatasource_WhenNameUpdated_ActionUpdatedDateModified() { - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) - .thenReturn(Mono.just(new MockPluginExecutor())); - - String uniqueString = UUID.randomUUID().toString(); - String applicationId = "app_" + uniqueString; - - Workspace toCreate = new Workspace(); - toCreate.setName("workspace_" + uniqueString); - - Workspace workspace = workspaceService.create(toCreate).block(); - String workspaceId = workspace.getId(); - - Datasource datasource = createDatasource("D", workspaceId); - - // create a new action for this datasource - ActionDTO actionDTO = new ActionDTO(); - actionDTO.setDatasource(datasource); - NewAction newAction = new NewAction(); - newAction.setApplicationId(applicationId); - newAction.setUnpublishedAction(actionDTO); - - Mono<NewAction> createActionMono = newActionRepository.save(newAction); - Datasource updateDto = new Datasource(); - updateDto.setName(datasource.getName() + "#1"); - Mono<Datasource> updateDatasourceMono = - datasourceService.updateDatasource(datasource.getId(), updateDto, defaultEnvironmentId, true); - - Mono<Tuple2<NewAction, Datasource>> tuple2Mono = createActionMono - .delayElement(Duration.ofSeconds(1)) - .then(updateDatasourceMono) - .then(newActionRepository.findByApplicationId(applicationId).last()) - .zipWhen(action -> datasourceService.findById( - action.getUnpublishedAction().getDatasource().getId())); - - StepVerifier.create(tuple2Mono) - .assertNext(tuples -> { - NewAction action = tuples.getT1(); - Datasource updatedDatasource = tuples.getT2(); - assertThat(action.getUpdatedAt()).isEqualTo(updatedDatasource.getUpdatedAt()); - }) - .verifyComplete(); - } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java index 9c33e45d888d..0f09a9dfbf0f 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java @@ -4864,4 +4864,89 @@ public void exportApplicationByWhen_WhenGitConnectedAndPageRenamed_QueriesAreInU }) .verifyComplete(); } + + @Test + @WithUserDetails("api_user") + public void exportApplicationByWhen_WhenGitConnectedAndDatasourceRenamed_QueriesAreInUpdatedResources() { + // create an application + Application testApplication = new Application(); + final String appName = UUID.randomUUID().toString(); + testApplication.setName(appName); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setClientSchemaVersion(JsonSchemaVersions.clientVersion); + testApplication.setServerSchemaVersion(JsonSchemaVersions.serverVersion); + + Mono<ApplicationJson> applicationJsonMono = applicationPageService + .createApplication(testApplication, workspaceId) + .flatMap(application -> { + // add a datasource to the workspace + Datasource ds1 = new Datasource(); + ds1.setName("DS_FOR_RENAME_TEST"); + ds1.setWorkspaceId(workspaceId); + ds1.setPluginId(installedPlugin.getId()); + final DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); + datasourceConfiguration.setUrl("http://example.org/get"); + datasourceConfiguration.setHeaders(List.of(new Property("X-Answer", "42"))); + + HashMap<String, DatasourceStorageDTO> storages1 = new HashMap<>(); + storages1.put( + defaultEnvironmentId, + new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration)); + ds1.setDatasourceStorages(storages1); + return datasourceService.create(ds1).zipWith(Mono.just(application)); + }) + .flatMap(objects -> { + Datasource datasource = objects.getT1(); + Application application = objects.getT2(); + + // create an action with the datasource + ActionDTO action = new ActionDTO(); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(datasource); + action.setName("MyAction"); + action.setPageId(application.getPages().get(0).getId()); + return layoutActionService.createAction(action).thenReturn(objects); + }) + .flatMap(objects -> { + Application application = objects.getT2(); + // set git meta data for the application and set a last commit date + GitApplicationMetadata gitApplicationMetadata = new GitApplicationMetadata(); + // add buffer of 5 seconds so that the last commit date is definitely after the last updated date + gitApplicationMetadata.setLastCommittedAt(Instant.now()); + application.setGitApplicationMetadata(gitApplicationMetadata); + return applicationRepository.save(application).thenReturn(objects); + }) + .delayElement(Duration.ofMillis( + 100)) // to make sure the last commit date is definitely after the last updated date + .flatMap(objects -> { + // rename the datasource + Datasource datasource = objects.getT1(); + Application application = objects.getT2(); + datasource.setName("DS_FOR_RENAME_TEST_RENAMED"); + return datasourceService + .save(datasource) + .then(importExportApplicationService.exportApplicationById( + application.getId(), SerialiseApplicationObjective.VERSION_CONTROL)); + }); + + // verify that the exported json has the updated page name, and the queries are in the updated resources + StepVerifier.create(applicationJsonMono) + .assertNext(applicationJson -> { + Map<String, Set<String>> updatedResources = applicationJson.getUpdatedResources(); + assertThat(updatedResources).isNotNull(); + Set<String> updatedActionNames = updatedResources.get(FieldName.ACTION_LIST); + assertThat(updatedActionNames).isNotNull(); + + // action should be present in the updated resources although action not updated but datasource is + assertThat(updatedActionNames.size()).isEqualTo(1); + updatedActionNames.forEach(actionName -> { + assertThat(actionName).contains("MyAction"); + }); + }) + .verifyComplete(); + } }
e27c6bdea74e8417ec2a4f9eb3156aec1c5263a9
2023-09-22 18:56:11
Pawan Kumar
chore: Remove side label in WDS components (#27566)
false
Remove side label in WDS components (#27566)
chore
diff --git a/app/client/packages/design-system/headless/src/components/Checkbox/src/CheckboxGroup.tsx b/app/client/packages/design-system/headless/src/components/Checkbox/src/CheckboxGroup.tsx index b0c426efae44..bdec0fc03f73 100644 --- a/app/client/packages/design-system/headless/src/components/Checkbox/src/CheckboxGroup.tsx +++ b/app/client/packages/design-system/headless/src/components/Checkbox/src/CheckboxGroup.tsx @@ -8,17 +8,15 @@ import type { SpectrumCheckboxGroupProps } from "@react-types/checkbox"; import { Field } from "@design-system/headless"; import { CheckboxGroupContext } from "./context"; -import type { LabelProps } from "@design-system/headless"; export type CheckboxGroupRef = DOMRef<HTMLDivElement>; + export interface CheckboxGroupProps extends Omit< SpectrumCheckboxGroupProps, - keyof StyleProps | "includeNecessityIndicatorInAccessibilityName" + keyof StyleProps | "labelPosition" | "labelAlign" | "isEmphasized" > { className?: string; - /** label width for the width, only used in side position */ - labelWidth?: LabelProps["labelWidth"]; } const _CheckboxGroup = (props: CheckboxGroupProps, ref: CheckboxGroupRef) => { diff --git a/app/client/packages/design-system/headless/src/components/Field/src/Field.tsx b/app/client/packages/design-system/headless/src/components/Field/src/Field.tsx index 9880f03f2d77..7b5a68ecfdf7 100644 --- a/app/client/packages/design-system/headless/src/components/Field/src/Field.tsx +++ b/app/client/packages/design-system/headless/src/components/Field/src/Field.tsx @@ -12,6 +12,8 @@ export type FieldProps = Omit< | "necessityIndicator" | "isRequired" | "showErrorIcon" + | "labelPosition" + | "labelAlign" | keyof StyleProps > & { fieldType?: "field" | "field-group"; @@ -27,8 +29,6 @@ const _Field = (props: FieldProps, ref: FieldRef) => { errorMessageProps = {}, isDisabled, label, - labelAlign, - labelPosition = "top", labelProps, validationState, wrapperClassName, @@ -57,12 +57,7 @@ const _Field = (props: FieldProps, ref: FieldRef) => { const labelAndContextualHelp = ( <div data-field-label-wrapper=""> {label && ( - <Label - {...labelProps} - elementType={elementType} - labelAlign={labelAlign} - labelPosition={labelPosition} - > + <Label {...labelProps} elementType={elementType}> {label} </Label> )} @@ -74,11 +69,9 @@ const _Field = (props: FieldProps, ref: FieldRef) => { <div {...wrapperProps} className={wrapperClassName} - data-align={labelAlign} data-disabled={isDisabled ? "" : undefined} data-field="" data-field-type={fieldType} - data-position={labelPosition} ref={ref} > {labelAndContextualHelp} diff --git a/app/client/packages/design-system/headless/src/components/Field/src/Label.tsx b/app/client/packages/design-system/headless/src/components/Field/src/Label.tsx index d5180484cdec..c2afce9f9d9c 100644 --- a/app/client/packages/design-system/headless/src/components/Field/src/Label.tsx +++ b/app/client/packages/design-system/headless/src/components/Field/src/Label.tsx @@ -4,26 +4,22 @@ import { filterDOMProps } from "@react-aria/utils"; import type { DOMRef, StyleProps } from "@react-types/shared"; import type { SpectrumLabelProps } from "@react-types/label"; -export interface LabelProps - extends Omit< - SpectrumLabelProps, - | "necessityIndicator" - | "includeNecessityIndicatorInAccessibilityName" - | "isRequired" - | keyof StyleProps - > { - isEmphasized?: boolean; - labelWidth?: string; -} +export type LabelProps = Omit< + SpectrumLabelProps, + | "necessityIndicator" + | "includeNecessityIndicatorInAccessibilityName" + | "isRequired" + | keyof StyleProps + | "labelPosition" + | "labelAlign" +>; const _Label = (props: LabelProps, ref: DOMRef<HTMLLabelElement>) => { const { children, - labelPosition = "top", - labelAlign = labelPosition === "side" ? "start" : null, - htmlFor, - for: labelFor, elementType: ElementType = "label", + for: labelFor, + htmlFor, onClick, ...otherProps } = props; @@ -32,9 +28,7 @@ const _Label = (props: LabelProps, ref: DOMRef<HTMLLabelElement>) => { return ( <ElementType - data-align={labelAlign} data-field-label="" - data-position={labelPosition} {...filterDOMProps(otherProps)} htmlFor={ElementType === "label" ? labelFor || htmlFor : undefined} onClick={onClick} diff --git a/app/client/packages/design-system/headless/src/components/Radio/src/RadioGroup.tsx b/app/client/packages/design-system/headless/src/components/Radio/src/RadioGroup.tsx index 725fedd55a00..4da12687c738 100644 --- a/app/client/packages/design-system/headless/src/components/Radio/src/RadioGroup.tsx +++ b/app/client/packages/design-system/headless/src/components/Radio/src/RadioGroup.tsx @@ -8,16 +8,14 @@ import type { SpectrumRadioGroupProps } from "@react-types/radio"; import { RadioContext } from "./context"; import { Field } from "@design-system/headless"; -import type { LabelProps } from "@design-system/headless"; export type RadioGroupRef = DOMRef<HTMLDivElement>; export interface RadioGroupProps extends Omit< SpectrumRadioGroupProps, - keyof StyleProps | "includeNecessityIndicatorInAccessibilityName" + keyof StyleProps | "labelPosition" | "labelAlign" | "isEmphasized" > { className?: string; - labelWidth?: LabelProps["labelWidth"]; } const _RadioGroup = (props: RadioGroupProps, ref: RadioGroupRef) => { diff --git a/app/client/packages/design-system/headless/src/components/TextInput/src/types.ts b/app/client/packages/design-system/headless/src/components/TextInput/src/types.ts index 4d6861b7b3c6..8a19c9b75f32 100644 --- a/app/client/packages/design-system/headless/src/components/TextInput/src/types.ts +++ b/app/client/packages/design-system/headless/src/components/TextInput/src/types.ts @@ -1,12 +1,18 @@ -import type { StyleProps } from "@react-types/shared"; +import type { PressEvents, StyleProps } from "@react-types/shared"; import type { SpectrumTextFieldProps } from "@react-types/textfield"; import type { TextInputBaseProps } from "../../TextInputBase"; export type OmitedSpectrumTextFieldProps = Omit< SpectrumTextFieldProps, - keyof StyleProps | "icon" | "isQuiet" | "necessityIndicator" ->; + | keyof StyleProps + | "icon" + | "isQuiet" + | "necessityIndicator" + | "labelPosition" + | "labelAlign" +> & + PressEvents; export interface TextInputProps extends OmitedSpectrumTextFieldProps, diff --git a/app/client/packages/design-system/headless/src/components/TextInputBase/src/types.ts b/app/client/packages/design-system/headless/src/components/TextInputBase/src/types.ts index c87d1d18f9d8..3f885d63973b 100644 --- a/app/client/packages/design-system/headless/src/components/TextInputBase/src/types.ts +++ b/app/client/packages/design-system/headless/src/components/TextInputBase/src/types.ts @@ -1,14 +1,9 @@ import type { RefObject } from "react"; import type { TextFieldAria } from "@react-aria/textfield"; -import type { PressEvents, StyleProps } from "@react-types/shared"; + import type { OmitedSpectrumTextFieldProps } from "../../TextInput"; -export interface TextInputBaseProps - extends Omit< - OmitedSpectrumTextFieldProps, - "onChange" | "icon" | keyof StyleProps - >, - PressEvents { +export interface TextInputBaseProps extends OmitedSpectrumTextFieldProps { /** classname for the input element */ inputClassName?: string; /** indicates if the component is textarea */ diff --git a/app/client/packages/design-system/widgets/src/components/CheckboxGroup/src/CheckboxGroup.tsx b/app/client/packages/design-system/widgets/src/components/CheckboxGroup/src/CheckboxGroup.tsx index 2c0d9ed09aed..4c75fc47c4c1 100644 --- a/app/client/packages/design-system/widgets/src/components/CheckboxGroup/src/CheckboxGroup.tsx +++ b/app/client/packages/design-system/widgets/src/components/CheckboxGroup/src/CheckboxGroup.tsx @@ -18,7 +18,9 @@ const _CheckboxGroup = ( ref: HeadlessCheckboxGroupRef, ) => { const { errorMessage, label, ...rest } = props; - const wrappedErrorMessage = errorMessage && <Text>{errorMessage}</Text>; + const wrappedErrorMessage = errorMessage && ( + <Text variant="footnote">{errorMessage}</Text> + ); const wrappedLabel = label && <Text>{label}</Text>; return ( diff --git a/app/client/packages/design-system/widgets/src/components/SwitchGroup/stories/SwitchGroup.stories.mdx b/app/client/packages/design-system/widgets/src/components/SwitchGroup/stories/SwitchGroup.stories.mdx index 8e36b5ba7a25..0cfbf8376530 100644 --- a/app/client/packages/design-system/widgets/src/components/SwitchGroup/stories/SwitchGroup.stories.mdx +++ b/app/client/packages/design-system/widgets/src/components/SwitchGroup/stories/SwitchGroup.stories.mdx @@ -48,30 +48,6 @@ Switch Group is a group of checkboxes that can be selected together. {Template.bind({})} </Story> -# Emphasized - -<Story - args={{ - isEmphasized: true, - }} - name="Is Emphasised" -> - {Template.bind({})} -</Story> - -# Label Position and Alignment - -<Story - args={{ - labelPosition: "side", - labelWidth: "100px", - errorMessage: "This is a description", - }} - name="Label Position - Side" -> - {Template.bind({})} -</Story> - # Is Disabled <Story diff --git a/app/client/packages/design-system/widgets/src/components/TextArea/stories/TextArea.stories.mdx b/app/client/packages/design-system/widgets/src/components/TextArea/stories/TextArea.stories.mdx index 5b76ac65b85c..2754185f22e1 100644 --- a/app/client/packages/design-system/widgets/src/components/TextArea/stories/TextArea.stories.mdx +++ b/app/client/packages/design-system/widgets/src/components/TextArea/stories/TextArea.stories.mdx @@ -37,29 +37,6 @@ TextArea is a component that is similar to the native textarea element, but with {Template.bind({})} </Story> -## Label Position - -<Story - name="Label Position - Top" - args={{ - placeholder: "Label Position - Top", - labelPosition: "top", - }} -> - {Template.bind({})} -</Story> - -<Story - name="Label Position - Side" - args={{ - placeholder: "Label Position - Side", - labelPosition: "side", - labelWidth: "100px", - }} -> - {Template.bind({})} -</Story> - ## Disabled <Story diff --git a/app/client/packages/design-system/widgets/src/components/TextInput/stories/TextInput.stories.mdx b/app/client/packages/design-system/widgets/src/components/TextInput/stories/TextInput.stories.mdx index 76b5d0495553..75fceb9db21f 100644 --- a/app/client/packages/design-system/widgets/src/components/TextInput/stories/TextInput.stories.mdx +++ b/app/client/packages/design-system/widgets/src/components/TextInput/stories/TextInput.stories.mdx @@ -61,30 +61,6 @@ TextInput is a component that allows users to input text. {Template.bind({})} </Story> -## Label Position - -<Story - name="Label Position - Top" - args={{ - placeholder: "Label Position - Top", - labelPosition: "top", - description: "This is a description", - }} -> - {Template.bind({})} -</Story> - -<Story - name="Label Position - Side" - args={{ - placeholder: "Label Position - Side", - labelPosition: "side", - description: "This is a description", - }} -> - {Template.bind({})} -</Story> - ## Prefix and Suffix <Story diff --git a/app/client/packages/design-system/widgets/src/components/testing/ComplexForm.tsx b/app/client/packages/design-system/widgets/src/components/testing/ComplexForm.tsx index 91d5bf1fe5f0..3a9e6db57585 100644 --- a/app/client/packages/design-system/widgets/src/components/testing/ComplexForm.tsx +++ b/app/client/packages/design-system/widgets/src/components/testing/ComplexForm.tsx @@ -37,7 +37,7 @@ export const ComplexForm = () => { </Switch> </SwitchGroup> - <CheckboxGroup isEmphasized label="Dishes"> + <CheckboxGroup label="Dishes"> <Checkbox value="Hamburger">Hamburger</Checkbox> <Checkbox value="French fries">French fries</Checkbox> <Checkbox value="Coca-Cola">Coca-Cola</Checkbox> diff --git a/app/client/src/widgets/BaseInputWidgetV2/component/types.ts b/app/client/src/widgets/BaseInputWidgetV2/component/types.ts index 90953b369813..acedc03362d5 100644 --- a/app/client/src/widgets/BaseInputWidgetV2/component/types.ts +++ b/app/client/src/widgets/BaseInputWidgetV2/component/types.ts @@ -22,9 +22,6 @@ export interface BaseInputComponentProps extends ComponentProps { // label props label: string; - labelWidth?: number; - labelAlign?: TextInputProps["labelAlign"]; - labelPosition?: TextInputProps["labelPosition"]; // validation props validationStatus?: TextInputProps["validationState"]; diff --git a/app/client/src/widgets/BaseInputWidgetV2/widget/contentConfig.ts b/app/client/src/widgets/BaseInputWidgetV2/widget/contentConfig.ts index 38162cef7c90..08455656a3cf 100644 --- a/app/client/src/widgets/BaseInputWidgetV2/widget/contentConfig.ts +++ b/app/client/src/widgets/BaseInputWidgetV2/widget/contentConfig.ts @@ -1,9 +1,6 @@ -import { Alignment } from "@blueprintjs/core"; -import { LabelPosition } from "components/constants"; import { ValidationTypes } from "constants/WidgetValidation"; import type { BaseInputWidgetProps } from "./types"; -import { isAutoLayout } from "layoutSystems/autolayout/utils/flexWidgetUtils"; export const propertyPaneContentConfig = [ { @@ -19,63 +16,6 @@ export const propertyPaneContentConfig = [ isTriggerProperty: false, validation: { type: ValidationTypes.TEXT }, }, - { - helpText: "Sets the label position of the widget", - propertyName: "labelPosition", - label: "Position", - controlType: "ICON_TABS", - fullWidth: true, - hidden: isAutoLayout, - options: [ - { label: "Auto", value: LabelPosition.Auto }, - { label: "Left", value: LabelPosition.Left }, - { label: "Top", value: LabelPosition.Top }, - ], - defaultValue: LabelPosition.Top, - isBindProperty: false, - isTriggerProperty: false, - validation: { type: ValidationTypes.TEXT }, - }, - { - helpText: "Sets the label alignment of the widget", - propertyName: "labelAlignment", - label: "Alignment", - controlType: "LABEL_ALIGNMENT_OPTIONS", - fullWidth: false, - options: [ - { - startIcon: "align-left", - value: Alignment.LEFT, - }, - { - startIcon: "align-right", - value: Alignment.RIGHT, - }, - ], - isBindProperty: false, - isTriggerProperty: false, - validation: { type: ValidationTypes.TEXT }, - hidden: (props: BaseInputWidgetProps) => props.labelPosition !== "side", - dependencies: ["labelPosition"], - }, - { - helpText: "Sets the label width of the widget as the number of columns", - propertyName: "labelWidth", - label: "Width (in columns)", - controlType: "NUMERIC_INPUT", - isJSConvertible: true, - isBindProperty: true, - isTriggerProperty: false, - min: 0, - validation: { - type: ValidationTypes.NUMBER, - params: { - natural: true, - }, - }, - hidden: (props: BaseInputWidgetProps) => props.labelPosition !== "side", - dependencies: ["labelPosition"], - }, ], }, { diff --git a/app/client/src/widgets/BaseInputWidgetV2/widget/types.ts b/app/client/src/widgets/BaseInputWidgetV2/widget/types.ts index ada125ab0467..365f56b55c89 100644 --- a/app/client/src/widgets/BaseInputWidgetV2/widget/types.ts +++ b/app/client/src/widgets/BaseInputWidgetV2/widget/types.ts @@ -1,7 +1,5 @@ import type { WidgetProps } from "widgets/BaseWidget"; -import type { BaseInputComponentProps } from "../component/types"; - export interface BaseInputWidgetProps extends WidgetProps { text: string; isDisabled?: boolean; @@ -19,9 +17,6 @@ export interface BaseInputWidgetProps extends WidgetProps { // label Props label: string; - labelPosition?: BaseInputComponentProps["labelPosition"]; - labelAlignment?: BaseInputComponentProps["labelAlign"]; - labelWidth?: BaseInputComponentProps["labelWidth"]; // misc tooltip?: string; diff --git a/app/client/src/widgets/InputWidgetV3/widget/index.tsx b/app/client/src/widgets/InputWidgetV3/widget/index.tsx index 4a840e51f8c6..4fdf672c5f75 100644 --- a/app/client/src/widgets/InputWidgetV3/widget/index.tsx +++ b/app/client/src/widgets/InputWidgetV3/widget/index.tsx @@ -291,8 +291,6 @@ class InputWidget extends BaseInputWidget<InputWidgetProps, WidgetState> { isDisabled={this.props.isDisabled} isLoading={this.props.isLoading} label={this.props.label} - labelAlign={this.props.labelAlignment} - labelPosition={this.props.labelPosition} maxChars={this.props.maxChars} maxNum={this.props.maxNum} minNum={this.props.minNum}
49e0bbfc85dbbc5cb41db311cf7b431c49f0028a
2023-07-31 19:40:14
Aishwarya-U-R
test: Cypress | Fix Datasources/MockDBs_Spec.ts (#25796)
false
Cypress | Fix Datasources/MockDBs_Spec.ts (#25796)
test
diff --git a/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts b/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts index d72c36b6c927..87ed2a7713ae 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts +++ b/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts @@ -15,6 +15,7 @@ describe( it("1. Create Query from Mock Mongo DB & verify active queries count", () => { dataSources.CreateMockDB("Movies").then((mockDBName) => { dsName = mockDBName; + cy.log("Mock DB Name: " + mockDBName); // delay is introduced so that structure fetch is complete before moving to query creation // feat: #25320, new query created for mock db movies, will be populated with default values @@ -26,7 +27,7 @@ describe( assertHelper.AssertNetworkStatus("@trigger"); dataSources.ValidateNSelectDropdown("Commands", "Find document(s)"); dataSources.ValidateNSelectDropdown("Collection", "movies"); - dataSources.RunQueryNVerifyResponseViews(1, false); + dataSources.RunQueryNVerifyResponseViews(2, false); dataSources.NavigateToActiveTab(); agHelper .GetText(dataSources._queriesOnPageText(mockDBName)) @@ -37,7 +38,7 @@ describe( entityExplorer.CreateNewDsQuery(mockDBName); dataSources.ValidateNSelectDropdown("Commands", "Find document(s)"); dataSources.ValidateNSelectDropdown("Collection", "movies"); - dataSources.RunQueryNVerifyResponseViews(1, false); + dataSources.RunQueryNVerifyResponseViews(2, false); dataSources.NavigateToActiveTab(); agHelper .GetText(dataSources._queriesOnPageText(mockDBName)) @@ -50,6 +51,7 @@ describe( it("2. Create Query from Mock Postgres DB & verify active queries count", () => { dataSources.CreateMockDB("Users").then((mockDBName) => { dsName = mockDBName; + cy.log("Mock DB Name: " + mockDBName); assertHelper.AssertNetworkStatus("@getDatasourceStructure", 200); dataSources.CreateQueryAfterDSSaved();
9eba768a9072f7aff678a191c69a13aab818bdd0
2024-03-18 12:48:54
Apeksha Bhosale
chore: added tag module for module related tests (#31790)
false
added tag module for module related tests (#31790)
chore
diff --git a/app/client/cypress/tags.js b/app/client/cypress/tags.js index f88d438cf74f..94224a2ccb35 100644 --- a/app/client/cypress/tags.js +++ b/app/client/cypress/tags.js @@ -63,5 +63,6 @@ module.exports = { "@tag.Authentication", "@tag.MainContainer", "@tag.Visual", + "@tag.Module", ], };
1cafbca76705dd168d48d951661c5e6196dece82
2020-12-15 10:34:51
Pawan Kumar
fix: The search in the multi select is not showing + Multi select dropdown stops functioning if default value is undefined (#2057)
false
The search in the multi select is not showing + Multi select dropdown stops functioning if default value is undefined (#2057)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/Binding/Binding_Table_Widget_DefaultSearch_Input_widget_spec.js b/app/client/cypress/integration/Smoke_TestSuite/Binding/Binding_Table_Widget_DefaultSearch_Input_widget_spec.js index 82241bd5ada8..021c8a797d9c 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/Binding/Binding_Table_Widget_DefaultSearch_Input_widget_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/Binding/Binding_Table_Widget_DefaultSearch_Input_widget_spec.js @@ -1,7 +1,5 @@ const commonlocators = require("../../../locators/commonlocators.json"); -const formWidgetsPage = require("../../../locators/FormWidgets.json"); const dsl = require("../../../fixtures/formInputTableDsl.json"); -const pages = require("../../../locators/Pages.json"); const widgetsPage = require("../../../locators/Widgets.json"); const publish = require("../../../locators/publishWidgetspage.json"); const testdata = require("../../../fixtures/testdata.json"); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ExplorerTests/Entity_Explorer_Query_Datasource_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ExplorerTests/Entity_Explorer_Query_Datasource_spec.js index e5bbff18cfe4..70cc78687e84 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ExplorerTests/Entity_Explorer_Query_Datasource_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ExplorerTests/Entity_Explorer_Query_Datasource_spec.js @@ -52,6 +52,7 @@ describe("Entity explorer tests related to query and datasource", function() { 200, ); + /* eslint-disable */ cy.wait(2000); cy.go("back"); diff --git a/app/client/cypress/integration/Smoke_TestSuite/FormWidgets/Dropdown_spec.js b/app/client/cypress/integration/Smoke_TestSuite/FormWidgets/Dropdown_spec.js index 0e28f706c11e..e6386ee26150 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/FormWidgets/Dropdown_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/FormWidgets/Dropdown_spec.js @@ -14,7 +14,7 @@ describe("Dropdown Widget Functionality", function() { cy.openPropertyPane("dropdownwidget"); cy.testJsontext("options", JSON.stringify(data.input)); - cy.testJsontext("defaultoption", "Not an option"); + cy.testJsontext("defaultoption", "{{ undefined }}"); cy.get(formWidgetsPage.dropdownWidget) .find(widgetLocators.dropdownSingleSelect) diff --git a/app/client/cypress/integration/Smoke_TestSuite/FormWidgets/Input_spec.js b/app/client/cypress/integration/Smoke_TestSuite/FormWidgets/Input_spec.js index c3a9696f1c5d..9870301748d0 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/FormWidgets/Input_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/FormWidgets/Input_spec.js @@ -2,8 +2,6 @@ const commonlocators = require("../../../locators/commonlocators.json"); const dsl = require("../../../fixtures/newFormDsl.json"); const widgetsPage = require("../../../locators/Widgets.json"); const publish = require("../../../locators/publishWidgetspage.json"); -const pages = require("../../../locators/Pages.json"); -const explorer = require("../../../locators/explorerlocators.json"); describe("Input Widget Functionality", function() { before(() => { diff --git a/app/client/src/components/designSystems/blueprint/DropdownComponent.tsx b/app/client/src/components/designSystems/blueprint/DropdownComponent.tsx index 7cc1e4c35c76..50acb43e2d4d 100644 --- a/app/client/src/components/designSystems/blueprint/DropdownComponent.tsx +++ b/app/client/src/components/designSystems/blueprint/DropdownComponent.tsx @@ -181,8 +181,8 @@ const StyledMultiDropDown = styled(MultiDropDown)<{ .${Classes.TAG_INPUT_VALUES} { margin-top: 0; overflow: hidden; + display: flex; height: ${props => props.height - WIDGET_PADDING * 2 - 2}px; - display: initial; } .${Classes.TAG} { @@ -216,8 +216,9 @@ const StyledMultiDropDown = styled(MultiDropDown)<{ .${Classes.INPUT_GHOST} { flex: 0 0 auto; margin: 0; - width: 1px; + display: flex; height: 26px; + flex: 1; } } } @@ -297,6 +298,7 @@ class DropDownComponent extends React.Component<DropDownComponentProps> { : undefined, }), disabled: this.props.disabled, + fill: true, rightElement: <Icon icon={IconNames.CHEVRON_DOWN} />, }} hideCloseButtonIndex={hideCloseButtonIndex}
8b63b2029e0e36f991b789da96801895376bf766
2021-09-02 23:56:30
Rishabh Saxena
fix: bottom padding at the api editor (#7074)
false
bottom padding at the api editor (#7074)
fix
diff --git a/app/client/src/components/editorComponents/ApiResponseView.tsx b/app/client/src/components/editorComponents/ApiResponseView.tsx index 3980f9cbb48b..bb50fd17cefc 100644 --- a/app/client/src/components/editorComponents/ApiResponseView.tsx +++ b/app/client/src/components/editorComponents/ApiResponseView.tsx @@ -73,7 +73,7 @@ const ResponseTabWrapper = styled.div` `; const TabbedViewWrapper = styled.div<{ isCentered: boolean }>` - height: calc(100% - 30px); + height: 100%; &&& { ul.react-tabs__tab-list { @@ -93,6 +93,12 @@ const TabbedViewWrapper = styled.div<{ isCentered: boolean }>` } ` : null} + + & { + .react-tabs__tab-panel { + height: calc(100% - 32px); + } + } `; const SectionDivider = styled.div` @@ -112,7 +118,7 @@ const Flex = styled.div` `; const NoResponseContainer = styled.div` - height: 100%; + flex: 1; width: 100%; display: flex; align-items: center; @@ -153,8 +159,8 @@ const InlineButton = styled(Button)` `; const HelpSection = styled.div` - margin-bottom: 5px; - margin-top: 10px; + padding-bottom: 5px; + padding-top: 10px; `; interface ReduxStateProps { @@ -188,6 +194,16 @@ const StatusCodeText = styled(BaseText)<{ code: string }>` props.code.startsWith("2") ? props.theme.colors.primaryOld : Colors.RED}; `; +const ResponseDataContainer = styled.div` + flex: 1; + overflow: auto; + display: flex; + flex-direction: column; + & .CodeEditorTarget { + overflow: hidden; + } +`; + function ApiResponseView(props: Props) { const { match: { @@ -222,13 +238,14 @@ function ApiResponseView(props: Props) { const initialIndex = useSelector(getActionTabsInitialIndex); const [selectedIndex, setSelectedIndex] = useState(initialIndex); const messages = response?.messages; + const tabs = [ { key: "body", title: "Response Body", panelComponent: ( <ResponseTabWrapper> - {messages && ( + {Array.isArray(messages) && messages.length > 0 && ( <HelpSection> {messages.map((msg, i) => ( <Callout fill key={i} text={msg} variant={Variant.warning} /> @@ -250,33 +267,35 @@ function ApiResponseView(props: Props) { variant={Variant.danger} /> )} - {_.isEmpty(response.statusCode) ? ( - <NoResponseContainer> - <Icon name="no-response" /> - <Text type={TextType.P1}> - {EMPTY_RESPONSE_FIRST_HALF()} - <InlineButton - isLoading={isRunning} - onClick={onRunClick} - size={Size.medium} - tag="button" - text="Run" - type="button" - /> - {EMPTY_RESPONSE_LAST_HALF()} - </Text> - </NoResponseContainer> - ) : ( - <ReadOnlyEditor - folding - height={"100%"} - input={{ - value: response.body - ? JSON.stringify(response.body, null, 2) - : "", - }} - /> - )} + <ResponseDataContainer> + {_.isEmpty(response.statusCode) ? ( + <NoResponseContainer> + <Icon name="no-response" /> + <Text type={TextType.P1}> + {EMPTY_RESPONSE_FIRST_HALF()} + <InlineButton + isLoading={isRunning} + onClick={onRunClick} + size={Size.medium} + tag="button" + text="Run" + type="button" + /> + {EMPTY_RESPONSE_LAST_HALF()} + </Text> + </NoResponseContainer> + ) : ( + <ReadOnlyEditor + folding + height={"100%"} + input={{ + value: response.body + ? JSON.stringify(response.body, null, 2) + : "", + }} + /> + )} + </ResponseDataContainer> </ResponseTabWrapper> ), }, diff --git a/app/client/src/pages/Editor/APIEditor/Form.tsx b/app/client/src/pages/Editor/APIEditor/Form.tsx index cbe3e6d899c3..8b20e7703801 100644 --- a/app/client/src/pages/Editor/APIEditor/Form.tsx +++ b/app/client/src/pages/Editor/APIEditor/Form.tsx @@ -190,7 +190,7 @@ const Link = styled.a` const Wrapper = styled.div` display: flex; flex-direction: row; - height: calc(100% - 126px); + height: calc(100% - 118px); position: relative; `; interface APIFormProps {
c93a8d84cfc86431373f530f5d5db8b8be9732b3
2025-03-11 17:32:46
Ashit Rath
chore: Changes to introduce UI module instance creation (#39562)
false
Changes to introduce UI module instance creation (#39562)
chore
diff --git a/app/client/src/ce/sagas/moduleInterfaceSagas.ts b/app/client/src/ce/sagas/moduleInterfaceSagas.ts new file mode 100644 index 000000000000..a0cd7b3cb0a8 --- /dev/null +++ b/app/client/src/ce/sagas/moduleInterfaceSagas.ts @@ -0,0 +1,21 @@ +/** + * ModuleInterfaceSagas + * + * Purpose: + * This saga file serves as a bridge between the Community Edition (CE) and Enterprise Edition (EE) + * module-related functionalities. It provides a clean interface layer that handles all interactions + * between core widget operations and module-specific features available in the enterprise version. + */ +import type { WidgetAddChild } from "actions/pageActions"; +import type { CanvasWidgetsReduxState } from "ee/reducers/entityReducers/canvasWidgetsReducer"; + +export interface HandleModuleWidgetCreationSagaPayload { + addChildPayload: WidgetAddChild; + widgets: CanvasWidgetsReduxState; +} + +export function* handleModuleWidgetCreationSaga( + props: HandleModuleWidgetCreationSagaPayload, +) { + return props.widgets; +} diff --git a/app/client/src/ee/sagas/moduleInterfaceSaga.ts b/app/client/src/ee/sagas/moduleInterfaceSaga.ts new file mode 100644 index 000000000000..edc2fb0b7f11 --- /dev/null +++ b/app/client/src/ee/sagas/moduleInterfaceSaga.ts @@ -0,0 +1,9 @@ +/** + * ModuleInterfaceSagas + * + * Purpose: + * This saga file serves as a bridge between the Community Edition (CE) and Enterprise Edition (EE) + * module-related functionalities. It provides a clean interface layer that handles all interactions + * between core widget operations and module-specific features available in the enterprise version. + */ +export * from "ce/sagas/moduleInterfaceSagas"; diff --git a/app/client/src/sagas/WidgetAdditionSagas.ts b/app/client/src/sagas/WidgetAdditionSagas.ts index a64c2eea38c8..d26d9bb9ab71 100644 --- a/app/client/src/sagas/WidgetAdditionSagas.ts +++ b/app/client/src/sagas/WidgetAdditionSagas.ts @@ -53,6 +53,7 @@ import { import { getPropertiesToUpdate } from "./WidgetOperationSagas"; import { getWidget, getWidgets } from "./selectors"; import { addBuildingBlockToCanvasSaga } from "./BuildingBlockSagas/BuildingBlockAdditionSagas"; +import { handleModuleWidgetCreationSaga } from "ee/sagas/moduleInterfaceSaga"; const WidgetTypes = WidgetFactory.widgetTypes; @@ -378,13 +379,18 @@ export function* getUpdateDslAfterCreatingChild( // some widgets need to update property of parent if the parent have CHILD_OPERATIONS // so here we are traversing up the tree till we get to MAIN_CONTAINER_WIDGET_ID // while traversing, if we find any widget which has CHILD_OPERATION, we will call the fn in it - const updatedWidgets: CanvasWidgetsReduxState = yield call( + let updatedWidgets: CanvasWidgetsReduxState = yield call( traverseTreeAndExecuteBlueprintChildOperations, parent, [addChildPayload.newWidgetId], widgets, ); + updatedWidgets = yield call(handleModuleWidgetCreationSaga, { + addChildPayload, + widgets: updatedWidgets, + }); + return updatedWidgets; } diff --git a/app/client/src/widgets/ContainerWidget/component/index.tsx b/app/client/src/widgets/ContainerWidget/component/index.tsx index 5a51c8ec8b2d..26b7c1f8a23d 100644 --- a/app/client/src/widgets/ContainerWidget/component/index.tsx +++ b/app/client/src/widgets/ContainerWidget/component/index.tsx @@ -29,7 +29,8 @@ const StyledContainerComponent = styled.div< ${(props) => props.shouldScrollContents && !props.$noScroll ? scrollCSS : ``} - opacity: ${(props) => (props.resizeDisabled ? "0.8" : "1")}; + opacity: ${(props) => + props.resizeDisabled && !props.forceFullOpacity ? "0.8" : "1"}; background: ${(props) => props.backgroundColor}; &:hover { @@ -53,6 +54,7 @@ interface ContainerWrapperProps { type: WidgetType; dropDisabled?: boolean; $noScroll: boolean; + forceFullOpacity?: boolean; } function ContainerComponentWrapper( @@ -133,6 +135,7 @@ function ContainerComponentWrapper( : "" }`} dropDisabled={props.dropDisabled} + forceFullOpacity={props.forceFullOpacity} onClick={props.onClick} onClickCapture={props.onClickCapture} onMouseOver={onMouseOver} @@ -153,6 +156,7 @@ function ContainerComponent(props: ContainerComponentProps) { <ContainerComponentWrapper $noScroll={!!props.noScroll} dropDisabled={props.dropDisabled} + forceFullOpacity={props.forceFullOpacity} onClick={props.onClick} onClickCapture={props.onClickCapture} resizeDisabled={props.resizeDisabled} @@ -184,6 +188,7 @@ function ContainerComponent(props: ContainerComponentProps) { $noScroll={!!props.noScroll} backgroundColor={props.backgroundColor} dropDisabled={props.dropDisabled} + forceFullOpacity={props.forceFullOpacity} onClick={props.onClick} onClickCapture={props.onClickCapture} resizeDisabled={props.resizeDisabled} @@ -223,6 +228,7 @@ export interface ContainerComponentProps extends WidgetStyleContainerProps { justifyContent?: string; alignItems?: string; dropDisabled?: boolean; + forceFullOpacity?: boolean; layoutSystemType?: LayoutSystemTypes; isListItemContainer?: boolean; } diff --git a/app/client/src/widgets/ContainerWidget/widget/index.tsx b/app/client/src/widgets/ContainerWidget/widget/index.tsx index 2d8faebd81f9..c757c1c18f62 100644 --- a/app/client/src/widgets/ContainerWidget/widget/index.tsx +++ b/app/client/src/widgets/ContainerWidget/widget/index.tsx @@ -416,6 +416,7 @@ export interface ContainerWidgetProps<T extends WidgetProps> shouldScrollContents?: boolean; noPad?: boolean; positioning?: Positioning; + forceFullOpacity?: boolean; // used to force full opacity for ui module instance meta widgets } export default ContainerWidget;
7a97640a07327999bfae4611be72f6a873d8669f
2022-02-23 09:51:50
Rishi Kumar Ray
chore: Update config label in Rest API datasource config page (#11107)
false
Update config label in Rest API datasource config page (#11107)
chore
diff --git a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx index 2e8f62b69241..7d5a55304bae 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx @@ -814,7 +814,7 @@ class DatasourceRestAPIEditor extends React.Component<Props> { value: "HEADER", }, ], - "Send client credentials with", + "Send client credentials with (on refresh token):", "", false, "",
349d5c8283693d1f17d6c35090b3106008b55375
2022-10-28 19:35:59
Satish Gandham
ci: Read environment variables right. (#17948)
false
Read environment variables right. (#17948)
ci
diff --git a/.github/workflows/client-build.yml b/.github/workflows/client-build.yml index 1e4c6a9c2e89..710ec2c4fae3 100644 --- a/.github/workflows/client-build.yml +++ b/.github/workflows/client-build.yml @@ -57,7 +57,7 @@ jobs: PGPASSWORD='${{secrets.APPSMITH_PERFORMANCE_DB_PASSWORD}}' psql -h '${{secrets.APPSMITH_PERFORMANCE_DB_HOST}}' \ -U aforce_admin -d perf-infra -c \ "INSERT INTO public.run_meta (gh_run_id, gh_run_attempt, pull_request_id, is_active) - VALUES ('${{env.GITHUB_RUN_ID}}', '${{env.GITHUB_RUN_ATTEMPT}}', '${{ inputs.pr }}', FALSE)" + VALUES ('${{github.run_id}}', '${{github.run_attempt}}', '${{ inputs.pr }}', FALSE)" # Checkout the code in the current branch in case the workflow is called because of a branch push event - name: Checkout the head commit of the branch
a6fe5047684991bb78f35847ee9b7b02e3b4d529
2022-04-06 15:46:36
Nikhil Nandagopal
feat: Updated CRUD Template (#12579)
false
Updated CRUD Template (#12579)
feat
diff --git a/app/client/cypress/locators/GeneratePage.json b/app/client/cypress/locators/GeneratePage.json index 141e6441c20a..3a12f4f2c291 100644 --- a/app/client/cypress/locators/GeneratePage.json +++ b/app/client/cypress/locators/GeneratePage.json @@ -8,7 +8,7 @@ "selectSearchColumnDropdown": "[data-cy=t--searchColumn-dropdown]", "generatePageFormSubmitBtn": "[data-cy=t--generate-page-form-submit]", "selectRowinTable": "//div[text()='CRUD User2']/ancestor::div[contains(@class,'tr')]", - "currentStatusField": "//div[@type='FORM_WIDGET']//span[text()='status:']//ancestor::div[contains(@class,'t--widget-textwidget')]/following-sibling::div[contains(@class, 't--widget-inputwidgetv2')][1]//input", + "currentStatusField": "//div[@type='FORM_WIDGET']//span[text()='Status']//ancestor::div[contains(@class,'t--widget-textwidget')]/following-sibling::div[contains(@class, 't--widget-inputwidgetv2')][1]//input", "updateBtn": "span:contains('Update')", "addRowIcon": "//span[@icon='add']/ancestor::div[1]", "idField": "//input[@placeholder='id']", @@ -20,7 +20,7 @@ "sortByDropdown": "span[name='dropdown']", "ascending": "//div[text()='Ascending']", "descending": "//div[text()='Descending']", - "currentNameField": "//div[@type='FORM_WIDGET']//span[text()='name:']//ancestor::div[contains(@class,'t--widget-textwidget')]/following-sibling::div[contains(@class, 't--widget-inputwidgetv2')][1]//input", + "currentNameField": "//div[@type='FORM_WIDGET']//span[text()='Name']//ancestor::div[contains(@class,'t--widget-textwidget')]/following-sibling::div[contains(@class, 't--widget-inputwidgetv2')][1]//input", "deleteofSelectedRow": "//div[@class='tr selected-row']//span[text()='Delete']", "confirmBtn": "span:contains('Confirm')", "deleteMenuItem": "//div[text()='Delete']/parent::a[contains(@class, 'single-select')]", diff --git a/app/server/appsmith-server/src/main/resources/CRUD-DB-Table-Template-Application.json b/app/server/appsmith-server/src/main/resources/CRUD-DB-Table-Template-Application.json index 40761d89486a..cc254bd60312 100644 --- a/app/server/appsmith-server/src/main/resources/CRUD-DB-Table-Template-Application.json +++ b/app/server/appsmith-server/src/main/resources/CRUD-DB-Table-Template-Application.json @@ -1 +1 @@ -{"editModeTheme":{"new":true,"isSystemTheme":true,"displayName":"Classic","name":"Classic"},"datasourceList":[{"isConfigured":true,"new":true,"invalids":[],"pluginId":"amazons3-plugin","isValid":true,"name":"AmazonS3 CRUD","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d704509528942","structure":{}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"Appsmith Release","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d704509528a53","structure":{}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"firestore-plugin","isValid":true,"name":"FBTemplateDB","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d70450952893f","structure":{}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"google-sheets-plugin","isValid":true,"name":"Google Sheet","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d704509528941","structure":{}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"postgres-plugin","isValid":true,"name":"Internal DB","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d70450952893c","structure":{"tables":[{"schema":"public","columns":[{"defaultValue":"nextval('aforce_roster_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"email","type":"text","isAutogenerated":false},{"name":"name","type":"text","isAutogenerated":false},{"name":"registration_date","type":"date","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"aforce_roster_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"aforce_heroes\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"aforce_heroes\" (\"email\", \"name\", \"registration_date\")\n VALUES ('', '', '2019-07-01');"},{"title":"UPDATE","body":"UPDATE public.\"aforce_heroes\" SET\n \"email\" = '',\n \"name\" = '',\n \"registration_date\" = '2019-07-01'\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"aforce_heroes\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.aforce_heroes","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('aforce_roster_id_seq1'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"date","type":"date","isAutogenerated":false},{"name":"hero_id","type":"int4","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"aforce_roster_pkey1","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"aforce_roster\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"aforce_roster\" (\"date\", \"hero_id\")\n VALUES ('2019-07-01', 1);"},{"title":"UPDATE","body":"UPDATE public.\"aforce_roster\" SET\n \"date\" = '2019-07-01',\n \"hero_id\" = 1\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"aforce_roster\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.aforce_roster","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('discord_messages_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"msg_id","type":"text","isAutogenerated":false},{"name":"created_at","type":"date","isAutogenerated":false},{"name":"author","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"discord_messages_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"discord_messages\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"discord_messages\" (\"msg_id\", \"created_at\", \"author\")\n VALUES ('', '2019-07-01', '');"},{"title":"UPDATE","body":"UPDATE public.\"discord_messages\" SET\n \"msg_id\" = '',\n \"created_at\" = '2019-07-01',\n \"author\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"discord_messages\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.discord_messages","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('email_issues_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"from","type":"text","isAutogenerated":false},{"name":"body","type":"text","isAutogenerated":false},{"name":"created_at","type":"timestamptz","isAutogenerated":false},{"name":"subject","type":"text","isAutogenerated":false},{"name":"is_tagged","type":"bool","isAutogenerated":false},{"name":"assignee","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"email_issues_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"email_issues\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"email_issues\" (\"from\", \"body\", \"created_at\", \"subject\", \"is_tagged\", \"assignee\")\n VALUES ('', '', TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET', '', '', '');"},{"title":"UPDATE","body":"UPDATE public.\"email_issues\" SET\n \"from\" = '',\n \"body\" = '',\n \"created_at\" = TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET',\n \"subject\" = '',\n \"is_tagged\" = '',\n \"assignee\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"email_issues\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.email_issues","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('github_issues_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"upvotes","type":"int4","isAutogenerated":false},{"name":"closed_date","type":"date","isAutogenerated":false},{"name":"created_date","type":"date","isAutogenerated":false},{"name":"assignee","type":"text","isAutogenerated":false},{"name":"state","type":"text","isAutogenerated":false},{"name":"issue_creator_id","type":"text","isAutogenerated":false},{"name":"title","type":"text","isAutogenerated":false},{"name":"issue_number","type":"int4","isAutogenerated":false},{"name":"label_arr","type":"_text","isAutogenerated":false},{"name":"total_reactions","type":"int4","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"github_issues_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"github_issues\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"github_issues\" (\"upvotes\", \"closed_date\", \"created_date\", \"assignee\", \"state\", \"issue_creator_id\", \"title\", \"issue_number\", \"label_arr\", \"total_reactions\")\n VALUES (1, '2019-07-01', '2019-07-01', '', '', '', '', 1, '', 1);"},{"title":"UPDATE","body":"UPDATE public.\"github_issues\" SET\n \"upvotes\" = 1,\n \"closed_date\" = '2019-07-01',\n \"created_date\" = '2019-07-01',\n \"assignee\" = '',\n \"state\" = '',\n \"issue_creator_id\" = '',\n \"title\" = '',\n \"issue_number\" = 1,\n \"label_arr\" = '',\n \"total_reactions\" = 1\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"github_issues\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.github_issues","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('issue_db_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"github_issue_id","type":"int4","isAutogenerated":false},{"name":"author","type":"text","isAutogenerated":false},{"name":"created_at","type":"timestamp","isAutogenerated":false},{"name":"title","type":"text","isAutogenerated":false},{"name":"description","type":"text","isAutogenerated":false},{"name":"labels","type":"_text","isAutogenerated":false},{"name":"type","type":"text","isAutogenerated":false},{"name":"state","type":"text","isAutogenerated":false},{"name":"answer","type":"text","isAutogenerated":false},{"name":"needs_docs","type":"bool","isAutogenerated":false},{"name":"link","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"issue_db_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"global_issues\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"global_issues\" (\"github_issue_id\", \"author\", \"created_at\", \"title\", \"description\", \"labels\", \"type\", \"state\", \"answer\", \"needs_docs\", \"link\")\n VALUES (1, '', TIMESTAMP '2019-07-01 10:00:00', '', '', '', '', '', '', '', '');"},{"title":"UPDATE","body":"UPDATE public.\"global_issues\" SET\n \"github_issue_id\" = 1,\n \"author\" = '',\n \"created_at\" = TIMESTAMP '2019-07-01 10:00:00',\n \"title\" = '',\n \"description\" = '',\n \"labels\" = '',\n \"type\" = '',\n \"state\" = '',\n \"answer\" = '',\n \"needs_docs\" = '',\n \"link\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"global_issues\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.global_issues","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('issue_upvote_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"link","type":"text","isAutogenerated":false},{"name":"comment","type":"text","isAutogenerated":false},{"name":"author","type":"text","isAutogenerated":false},{"name":"created_at","type":"timestamp","isAutogenerated":false},{"name":"issue_id","type":"int4","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"issue_upvote_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"issue_upvote\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"issue_upvote\" (\"link\", \"comment\", \"author\", \"created_at\", \"issue_id\")\n VALUES ('', '', '', TIMESTAMP '2019-07-01 10:00:00', 1);"},{"title":"UPDATE","body":"UPDATE public.\"issue_upvote\" SET\n \"link\" = '',\n \"comment\" = '',\n \"author\" = '',\n \"created_at\" = TIMESTAMP '2019-07-01 10:00:00',\n \"issue_id\" = 1\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"issue_upvote\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.issue_upvote","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('standup_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"name","type":"text","isAutogenerated":false},{"name":"yesterday","type":"text","isAutogenerated":false},{"name":"today","type":"text","isAutogenerated":false},{"name":"blocked","type":"text","isAutogenerated":false},{"name":"date","type":"date","isAutogenerated":false},{"name":"pod","type":"text","isAutogenerated":false},{"name":"dayrating","type":"int4","isAutogenerated":false},{"name":"restrating","type":"int4","isAutogenerated":false},{"name":"focusrating","type":"int4","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"standup_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"standup\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"standup\" (\"name\", \"yesterday\", \"today\", \"blocked\", \"date\", \"pod\", \"dayrating\", \"restrating\", \"focusrating\")\n VALUES ('', '', '', '', '2019-07-01', '', 1, 1, 1);"},{"title":"UPDATE","body":"UPDATE public.\"standup\" SET\n \"name\" = '',\n \"yesterday\" = '',\n \"today\" = '',\n \"blocked\" = '',\n \"date\" = '2019-07-01',\n \"pod\" = '',\n \"dayrating\" = 1,\n \"restrating\" = 1,\n \"focusrating\" = 1\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"standup\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.standup","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('support_tickets_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"description","type":"varchar","isAutogenerated":false},{"name":"created_at","type":"timestamptz","isAutogenerated":false},{"name":"author","type":"text","isAutogenerated":false},{"name":"user","type":"text","isAutogenerated":false},{"name":"comments","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"support_tickets_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"support_tickets\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"support_tickets\" (\"description\", \"created_at\", \"author\", \"user\", \"comments\")\n VALUES ('', TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET', '', '', '');"},{"title":"UPDATE","body":"UPDATE public.\"support_tickets\" SET\n \"description\" = '',\n \"created_at\" = TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET',\n \"author\" = '',\n \"user\" = '',\n \"comments\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"support_tickets\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.support_tickets","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('template_table_col1_seq'::regclass)","name":"col1","type":"int4","isAutogenerated":true},{"name":"col3","type":"text","isAutogenerated":false},{"name":"col4","type":"int4","isAutogenerated":false},{"name":"col5","type":"bool","isAutogenerated":false},{"name":"col2","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["col1"],"name":"template_table_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"template_table\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"template_table\" (\"col3\", \"col4\", \"col5\", \"col2\")\n VALUES ('', 1, '', '');"},{"title":"UPDATE","body":"UPDATE public.\"template_table\" SET\n \"col3\" = '',\n \"col4\" = 1,\n \"col5\" = '',\n \"col2\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"template_table\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.template_table","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('ticket_tags_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"ticket_id","type":"int4","isAutogenerated":false},{"name":"github_tag_id","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"ticket_tags_pkey","type":"primary key"},{"fromColumns":["ticket_id"],"name":"ticket_id_fk","toColumns":["support_tickets.id"],"type":"foreign key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"ticket_tags\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"ticket_tags\" (\"ticket_id\", \"github_tag_id\")\n VALUES (1, '');"},{"title":"UPDATE","body":"UPDATE public.\"ticket_tags\" SET\n \"ticket_id\" = 1,\n \"github_tag_id\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"ticket_tags\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.ticket_tags","type":"TABLE"}]}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"mongo-plugin","isValid":true,"name":"Mock_Mongo","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"5f7add8687af934ed846dd6a_61c43332e89bc475f3cae797","structure":{"tables":[{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"col1","type":"String","isAutogenerated":false},{"name":"col2","type":"String","isAutogenerated":false},{"name":"col3","type":"String","isAutogenerated":false},{"name":"col4","type":"String","isAutogenerated":false}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"col1\": \"test\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"template_table","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"template_table\",\n \"filter\": {\n \"col1\": \"test\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"template_table","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"template_table\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"col1\": \"new value\",\n \"col2\": \"new value\",\n \"col3\": \"new value\",\n \"col4\": \"new value\",\n}]"},"collection":"template_table","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"template_table\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"col1\": \"new value\",\n \"col2\": \"new value\",\n \"col3\": \"new value\",\n \"col4\": \"new value\",\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"col1\": \"new value\" } }"},"collection":"template_table","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"template_table\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"col1\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"template_table","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"template_table\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"template_table","type":"COLLECTION"},{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"createdAt","type":"Date","isAutogenerated":false},{"name":"email","type":"String","isAutogenerated":false},{"name":"name","type":"String","isAutogenerated":false},{"name":"role","type":"String","isAutogenerated":false},{"name":"status","type":"Object","isAutogenerated":false}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"email\": \"[email protected]\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"users","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"users\",\n \"filter\": {\n \"email\": \"[email protected]\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"users","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"users\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"email\": \"new value\",\n \"name\": \"new value\",\n \"role\": \"new value\",\n \"status\": {},\n}]"},"collection":"users","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"users\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"email\": \"new value\",\n \"name\": \"new value\",\n \"role\": \"new value\",\n \"status\": {},\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"email\": \"new value\" } }"},"collection":"users","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"users\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"email\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"users","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"users\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"users","type":"COLLECTION"},{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"createdAt","type":"Date","isAutogenerated":false},{"name":"currentLimit","type":"Integer","isAutogenerated":false},{"name":"featureName","type":"String","isAutogenerated":false},{"name":"key","type":"Integer","isAutogenerated":false},{"name":"limit","type":"Integer","isAutogenerated":false},{"name":"subscriptionId","type":"ObjectId","isAutogenerated":true}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"featureName\": \"Okuneva Inc\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"orgs","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"orgs\",\n \"filter\": {\n \"featureName\": \"Okuneva Inc\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"orgs","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"orgs\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"currentLimit\": 1,\n \"featureName\": \"new value\",\n \"key\": 1,\n \"limit\": 1,\n \"subscriptionId\": ObjectId(\"a_valid_object_id_hex\"),\n}]"},"collection":"orgs","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"orgs\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"currentLimit\": 1,\n \"featureName\": \"new value\",\n \"key\": 1,\n \"limit\": 1,\n \"subscriptionId\": ObjectId(\"a_valid_object_id_hex\"),\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"featureName\": \"new value\" } }"},"collection":"orgs","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"orgs\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"featureName\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"orgs","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"orgs\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"orgs","type":"COLLECTION"},{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"createdAt","type":"Date","isAutogenerated":false},{"name":"createdBy","type":"ObjectId","isAutogenerated":true},{"name":"domain","type":"String","isAutogenerated":false},{"name":"name","type":"String","isAutogenerated":false},{"name":"numUsers","type":"Integer","isAutogenerated":false},{"name":"orgId","type":"ObjectId","isAutogenerated":true}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"domain\": \"adolph.biz\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"apps","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"apps\",\n \"filter\": {\n \"domain\": \"adolph.biz\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"apps","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"apps\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"createdBy\": ObjectId(\"a_valid_object_id_hex\"),\n \"domain\": \"new value\",\n \"name\": \"new value\",\n \"numUsers\": 1,\n \"orgId\": ObjectId(\"a_valid_object_id_hex\"),\n}]"},"collection":"apps","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"apps\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"createdBy\": ObjectId(\"a_valid_object_id_hex\"),\n \"domain\": \"new value\",\n \"name\": \"new value\",\n \"numUsers\": 1,\n \"orgId\": ObjectId(\"a_valid_object_id_hex\"),\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"domain\": \"new value\" } }"},"collection":"apps","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"apps\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"domain\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"apps","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"apps\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"apps","type":"COLLECTION"},{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"createdAt","type":"Date","isAutogenerated":false},{"name":"currency","type":"String","isAutogenerated":false},{"name":"mrr","type":"String","isAutogenerated":false},{"name":"name","type":"String","isAutogenerated":false},{"name":"renewalDate","type":"Date","isAutogenerated":false},{"name":"status","type":"String","isAutogenerated":false},{"name":"statusOfApp","type":"Object","isAutogenerated":false}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"currency\": \"RUB\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"subscriptions","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"subscriptions\",\n \"filter\": {\n \"currency\": \"RUB\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"subscriptions","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"subscriptions\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"currency\": \"new value\",\n \"mrr\": \"new value\",\n \"name\": \"new value\",\n \"renewalDate\": new Date(\"2019-07-01\"),\n \"status\": \"new value\",\n \"statusOfApp\": {},\n}]"},"collection":"subscriptions","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"subscriptions\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"currency\": \"new value\",\n \"mrr\": \"new value\",\n \"name\": \"new value\",\n \"renewalDate\": new Date(\"2019-07-01\"),\n \"status\": \"new value\",\n \"statusOfApp\": {},\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"currency\": \"new value\" } }"},"collection":"subscriptions","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"subscriptions\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"currency\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"subscriptions","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"subscriptions\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"subscriptions","type":"COLLECTION"}]}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"redis-plugin","isValid":true,"name":"RedisTemplateApps","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d704509528943","structure":{}}],"actionList":[{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"SELECT * FROM public.template_table\nWHERE col2 like '%{{Table1.searchText || \"\"}}%'\nORDER BY {{col_select.selectedOptionValue}} {{order_select.selectedOptionValue}}\nLIMIT {{Table1.pageSize}}\nOFFSET {{(Table1.pageNo - 1) * Table1.pageSize}};","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","col_select.selectedOptionValue","Table1.pageSize","order_select.selectedOptionValue"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"pluginId":"postgres-plugin","id":"SQL_SelectQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"SELECT * FROM public.template_table\nWHERE col2 like '%{{Table1.searchText || \"\"}}%'\nORDER BY {{col_select.selectedOptionValue}} {{order_select.selectedOptionValue}}\nLIMIT {{Table1.pageSize}}\nOFFSET {{(Table1.pageNo - 1) * Table1.pageSize}};","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","col_select.selectedOptionValue","Table1.pageSize","order_select.selectedOptionValue"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531ef8"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"INSERT INTO public.template_table (\n\tcol1,\n\tcol2, \n\tcol3,\n\tcol4, \n\tcol5\n)\nVALUES (\n\t\t\t\t{{insert_col_input1.text}}, \n\t\t\t\t{{insert_col_input2.text}}, \n\t\t\t\t{{insert_col_input3.text}}, \n\t\t\t\t{{insert_col_input4.text}}, \n\t\t\t\t{{insert_col_input5.text}}\n);","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"postgres-plugin","id":"SQL_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"INSERT INTO public.template_table (\n\tcol1,\n\tcol2, \n\tcol3,\n\tcol4, \n\tcol5\n)\nVALUES (\n\t\t\t\t{{insert_col_input1.text}}, \n\t\t\t\t{{insert_col_input2.text}}, \n\t\t\t\t{{insert_col_input3.text}}, \n\t\t\t\t{{insert_col_input4.text}}, \n\t\t\t\t{{insert_col_input5.text}}\n);","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531ef9"},{"new":false,"pluginType":"SAAS","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"UPDATE","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"","key":"rowOffset"},{"value":"{\n\t \"rowIndex\": {{data_table.selectedRow.rowIndex}}, \n\t\t\"col1\": \"{{colInput1.text}}\", \n\t\t\"col2\": \"{{colInput2.text}}\", \n\t\t\"col3\": \"{{colInput3.text}}\", \n\t\t\"col4\": \"{{colInput4.text}}\"\n}","key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[9].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["colInput1.text","colInput4.text","data_table.selectedRow.rowIndex","colInput2.text","colInput3.text"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"google-sheets-plugin","id":"Google Sheets_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"UPDATE","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"","key":"rowOffset"},{"value":"{\n\t \"rowIndex\": {{data_table.selectedRow.rowIndex}}, \n\t\t\"col1\": \"{{colInput1.text}}\", \n\t\t\"col2\": \"{{colInput2.text}}\", \n\t\t\"col3\": \"{{colInput3.text}}\", \n\t\t\"col4\": \"{{colInput4.text}}\"\n}","key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[9].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["colInput1.text","colInput4.text","data_table.selectedRow.rowIndex","colInput2.text","colInput3.text"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efa"},{"new":false,"pluginType":"SAAS","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"APPEND","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"","key":"rowOffset"},{"value":"{ \n\t\t\"col1\": \"{{insert_col_input1.text}}\", \n\t\t\"col2\": \"{{insert_col_input2.text}}\", \n\t\t\"col3\": \"{{insert_col_input3.text}}\", \n\t\t\"col4\": \"{{insert_col_input4.text}}\",\n\t\t\"col5\": \"{{insert_col_input5.text}}\"\n}","key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[9].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"google-sheets-plugin","id":"Google Sheets_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"APPEND","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"","key":"rowOffset"},{"value":"{ \n\t\t\"col1\": \"{{insert_col_input1.text}}\", \n\t\t\"col2\": \"{{insert_col_input2.text}}\", \n\t\t\"col3\": \"{{insert_col_input3.text}}\", \n\t\t\"col4\": \"{{insert_col_input4.text}}\",\n\t\t\"col5\": \"{{insert_col_input5.text}}\"\n}","key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[9].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efb"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":100000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name}}","viewType":"component","componentData":"{{(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name}}"},"create":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"},"expiry":{"data":"5","viewType":"component","componentData":"5"}},"body":{"data":"{{FilePicker.files[this.params.fileIndex]}}","viewType":"component","componentData":"{{FilePicker.files[this.params.fileIndex]}}"},"command":{"data":"UPLOAD_FILE_FROM_BODY","viewType":"component","componentData":"UPLOAD_FILE_FROM_BODY"}}},"userPermissions":[],"pageId":"S3","invalids":["'Query timeout' field must be an integer between 0 and 60000"],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name","FilePicker.files[this.params.fileIndex]"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"CreateFile","name":"CreateFile","messages":[]},"pluginId":"amazons3-plugin","id":"S3_CreateFile","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":100000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name}}","viewType":"component","componentData":"{{(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name}}"},"create":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"},"expiry":{"data":"5","viewType":"component","componentData":"5"}},"body":{"data":"{{FilePicker.files[this.params.fileIndex]}}","viewType":"component","componentData":"{{FilePicker.files[this.params.fileIndex]}}"},"command":{"data":"UPLOAD_FILE_FROM_BODY","viewType":"component","componentData":"UPLOAD_FILE_FROM_BODY"}}},"userPermissions":[],"pageId":"S3","invalids":["'Query timeout' field must be an integer between 0 and 60000"],"dynamicBindingPathList":[{"key":"body"},{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name","FilePicker.files[this.params.fileIndex]"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"CreateFile","name":"CreateFile","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efc"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"path":"","paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"body":{"data":"{\n\t\"data\": \"\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"\"\n}"},"list":{"prefix":{"data":"{{search_input.text}}","viewType":"component","componentData":"{{search_input.text}}"},"where":{"data":{"condition":"AND","children":[{"condition":"EQ"}]},"viewType":"component","componentData":{"condition":"AND","children":[{"condition":"EQ"}]}},"expiry":{"data":"{{ 60 * 24 }}","viewType":"component","componentData":"{{ 60 * 24 }}"},"signedUrl":{"data":"YES","viewType":"component","componentData":"YES"},"unSignedUrl":{"data":"YES","viewType":"component","componentData":"YES"}},"command":{"data":"LIST","viewType":"component","componentData":"LIST"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.list.prefix.data"},{"key":"formData.list.expiry.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["60 * 24","search_input.text"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"ListFiles","name":"ListFiles","messages":[]},"pluginId":"amazons3-plugin","id":"S3_ListFiles","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"path":"","paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"body":{"data":"{\n\t\"data\": \"\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"\"\n}"},"list":{"prefix":{"data":"{{search_input.text}}","viewType":"component","componentData":"{{search_input.text}}"},"where":{"data":{"condition":"AND","children":[{"condition":"EQ"}]},"viewType":"component","componentData":{"condition":"AND","children":[{"condition":"EQ"}]}},"expiry":{"data":"{{ 60 * 24 }}","viewType":"component","componentData":"{{ 60 * 24 }}"},"signedUrl":{"data":"YES","viewType":"component","componentData":"YES"},"unSignedUrl":{"data":"YES","viewType":"component","componentData":"YES"}},"command":{"data":"LIST","viewType":"component","componentData":"LIST"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.list.prefix"},{"key":"formData.list.expiry"}],"confirmBeforeExecute":false,"jsonPathKeys":["60 * 24","search_input.text"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"ListFiles","name":"ListFiles","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efd"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/uepsj7o6a0hmiodonjr7xrcqj9pixe0s","headers":[{"value":"application/json","key":"content-type"}],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n\t\"app\": {{ {...get_exported_app.data, decryptedFields: undefined, datasourceList: get_exported_app.data.datasourceList.map((source) => { return {...source, structure: appsmith.store[source.pluginId] == undefined ? {}: appsmith.store[source.pluginId].data} } ) } }},\n\t\"branch\": \"{{branch_input.text}}\"\n} ","httpMethod":"POST","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":true,"jsonPathKeys":["{...get_exported_app.data, decryptedFields: undefined, datasourceList: get_exported_app.data.datasourceList.map((source) => { return {...source, structure: appsmith.store[source.pluginId] == undefined ? {}: appsmith.store[source.pluginId].data} } ) }","branch_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://hook.integromat.com"}},"validName":"update_template","name":"update_template","messages":[]},"pluginId":"restapi-plugin","id":"Admin_update_template","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/uepsj7o6a0hmiodonjr7xrcqj9pixe0s","headers":[{"value":"application/json","key":"content-type"}],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n\t\"app\": {{ {...get_exported_app.data, decryptedFields: undefined, datasourceList: get_exported_app.data.datasourceList.map((source) => { return {...source, structure: appsmith.store[source.pluginId] == undefined ? {}: appsmith.store[source.pluginId].data} } ) } }},\n\t\"branch\": \"{{branch_input.text}}\"\n}","httpMethod":"POST","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":true,"jsonPathKeys":["{...get_exported_app.data, decryptedFields: undefined, datasourceList: get_exported_app.data.datasourceList.map((source) => { return {...source, structure: appsmith.store[source.pluginId] == undefined ? {}: appsmith.store[source.pluginId].data} } ) }","branch_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://hook.integromat.com"}},"validName":"update_template","name":"update_template","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efe"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"path":"/api/v1/applications/export/61764fbeba7e887d03bc3631","headers":[],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"httpMethod":"GET","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_exported_app","name":"get_exported_app","messages":[]},"pluginId":"restapi-plugin","id":"Admin_get_exported_app","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"path":"/api/v1/applications/export/61764fbeba7e887d03bc3631","headers":[],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_exported_app","name":"get_exported_app","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531eff"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/datasources/{{this.params.id}}/structure","headers":[],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["this.params.id"],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_datasource_structure","name":"get_datasource_structure","messages":[]},"pluginId":"restapi-plugin","id":"Admin_get_datasource_structure","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/datasources/{{this.params.id}}/structure","headers":[],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["this.params.id"],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_datasource_structure","name":"get_datasource_structure","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f00"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"DELETE FROM public.template_table\n WHERE col1 = {{Table1.triggeredRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.triggeredRow.col1"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"postgres-plugin","id":"SQL_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"DELETE FROM public.template_table\n WHERE col1 = {{Table1.triggeredRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.triggeredRow.col1"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f01"},{"new":false,"pluginType":"SAAS","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"GET","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"{{data_table.pageSize}}","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"{{(data_table.pageNo - 1) * data_table.pageSize}}","key":"rowOffset"},{"key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"},{"value":[{}],"key":"where"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","(data_table.pageNo - 1) * data_table.pageSize"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"pluginId":"google-sheets-plugin","id":"Google Sheets_SelectQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"GET","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"{{data_table.pageSize}}","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"{{(data_table.pageNo - 1) * data_table.pageSize}}","key":"rowOffset"},{"key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"},{"value":[{}],"key":"where"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","(data_table.pageNo - 1) * data_table.pageSize"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f02"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"UPDATE public.template_table SET\n\t\tcol2 = '{{update_col_2.text}}',\n col3 = '{{update_col_3.text}}',\n col4 = '{{update_col_4.text}}',\n col5 = '{{update_col_5.text}}'\n WHERE col1 = {{Table1.selectedRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","Table1.selectedRow.col1","update_col_2.text","update_col_5.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"postgres-plugin","id":"SQL_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"UPDATE public.template_table SET\n\t\tcol2 = '{{update_col_2.text}}',\n col3 = '{{update_col_3.text}}',\n col4 = '{{update_col_4.text}}',\n col5 = '{{update_col_5.text}}'\n WHERE col1 = {{Table1.selectedRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","Table1.selectedRow.col1","update_col_2.text","update_col_5.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f03"},{"new":false,"pluginType":"SAAS","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"DELETE_ROW","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"{{data_table.pageSize}}","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"{{(data_table.pageNo - 1) * data_table.pageSize}}","key":"rowOffset"},{"key":"rowObject"},{"key":"rowObjects"},{"value":"{{data_table.triggeredRow.rowIndex}}","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[6].value"},{"key":"pluginSpecifiedTemplates[8].value"},{"key":"pluginSpecifiedTemplates[11].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","data_table.triggeredRow.rowIndex","(data_table.pageNo - 1) * data_table.pageSize"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"google-sheets-plugin","id":"Google Sheets_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"DELETE_ROW","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"{{data_table.pageSize}}","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"{{(data_table.pageNo - 1) * data_table.pageSize}}","key":"rowOffset"},{"key":"rowObject"},{"key":"rowObjects"},{"value":"{{data_table.triggeredRow.rowIndex}}","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[6].value"},{"key":"pluginSpecifiedTemplates[8].value"},{"key":"pluginSpecifiedTemplates[11].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","data_table.triggeredRow.rowIndex","(data_table.pageNo - 1) * data_table.pageSize"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f04"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{tableName_input.text}}\",\n \"datasourceId\": \"{{datasource_input.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]}}\",\n \"applicationId\" : \"{{datasource_input.text.split(\"applications/\")[1].split(\"/\")[0]}}\",\n\t\t\"searchColumn\": \"{{search_col_input.text}}\",\n\t\t\"columns\": \"{{select_cols_input.text}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["select_cols_input.text","datasource_input.text.split(\"applications/\")[1].split(\"/\")[0]","datasource_input.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]","search_col_input.text","tableName_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_sql_app","name":"generate_sql_app","messages":[]},"pluginId":"restapi-plugin","id":"Page Generator_generate_sql_app","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{tableName_input.text}}\",\n \"datasourceId\": \"{{datasource_input.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]}}\",\n \"applicationId\" : \"{{datasource_input.text.split(\"applications/\")[1].split(\"/\")[0]}}\",\n\t\t\"searchColumn\": \"{{search_col_input.text}}\",\n\t\t\"columns\": \"{{select_cols_input.text}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["select_cols_input.text","datasource_input.text.split(\"applications/\")[1].split(\"/\")[0]","datasource_input.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]","search_col_input.text","tableName_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_sql_app","name":"generate_sql_app","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f05"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"find":{"query":{"data":"{ col2: /{{data_table.searchText||\"\"}}/i }","viewType":"component","componentData":"{ col2: /{{data_table.searchText||\"\"}}/i }"},"limit":{"data":"{{data_table.pageSize}}","viewType":"component","componentData":"{{data_table.pageSize}}"},"skip":{"data":"{{(data_table.pageNo - 1) * data_table.pageSize}}","viewType":"component","componentData":"{{(data_table.pageNo - 1) * data_table.pageSize}}"},"sort":{"data":"{ \n{{key_select.selectedOptionValue}}: {{order_select.selectedOptionValue}} \n}","viewType":"component","componentData":"{ \n{{key_select.selectedOptionValue}}: {{order_select.selectedOptionValue}} \n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"FIND","viewType":"component","componentData":"FIND"},"smartSubstitution":{"data":false,"viewType":"component","componentData":false}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["key_select.selectedOptionValue","data_table.pageSize","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"FindQuery","name":"FindQuery","messages":[]},"pluginId":"mongo-plugin","id":"MongoDB_FindQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"find":{"query":{"data":"{ col2: /{{data_table.searchText||\"\"}}/i }","viewType":"component","componentData":"{ col2: /{{data_table.searchText||\"\"}}/i }"},"limit":{"data":"{{data_table.pageSize}}","viewType":"component","componentData":"{{data_table.pageSize}}"},"skip":{"data":"{{(data_table.pageNo - 1) * data_table.pageSize}}","viewType":"component","componentData":"{{(data_table.pageNo - 1) * data_table.pageSize}}"},"sort":{"data":"{ \n{{key_select.selectedOptionValue}}: {{order_select.selectedOptionValue}} \n}","viewType":"component","componentData":"{ \n{{key_select.selectedOptionValue}}: {{order_select.selectedOptionValue}} \n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"FIND","viewType":"component","componentData":"FIND"},"smartSubstitution":{"data":false,"viewType":"component","componentData":false}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["key_select.selectedOptionValue","data_table.pageSize","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"FindQuery","name":"FindQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f06"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"template_table/{{data_table.selectedRow._ref}}","paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"delete":{"query":{"data":"{ _id: ObjectId('{{data_table.triggeredRow._id}}') }","viewType":"component","componentData":"{ _id: ObjectId('{{data_table.triggeredRow._id}}') }"},"limit":{"data":"SINGLE","viewType":"component","componentData":"SINGLE"}},"command":{"data":"DELETE","viewType":"component","componentData":"DELETE"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow._ref","data_table.triggeredRow._id"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"mongo-plugin","id":"MongoDB_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"template_table/{{data_table.selectedRow._ref}}","paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"delete":{"query":{"data":"{ _id: ObjectId('{{data_table.triggeredRow._id}}') }","viewType":"component","componentData":"{ _id: ObjectId('{{data_table.triggeredRow._id}}') }"},"limit":{"data":"SINGLE","viewType":"component","componentData":"SINGLE"}},"command":{"data":"DELETE","viewType":"component","componentData":"DELETE"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow._ref","data_table.triggeredRow._id"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f07"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"updateMany":{"query":{"data":"{ _id: ObjectId('{{data_table.selectedRow._id}}') }","viewType":"component","componentData":"{ _id: ObjectId('{{data_table.selectedRow._id}}') }"},"limit":{"data":"SINGLE","viewType":"component","componentData":"SINGLE"},"update":{"data":"{\n \"col1\" : {{update_col_1.text}},\n\t\"col2\" : {{update_col_2.text}},\n \"col3\" : {{update_col_3.text}},\n \"col4\" : {{update_col_4.text}}\n}","viewType":"component","componentData":"{\n \"col1\" : {{update_col_1.text}},\n\t\"col2\" : {{update_col_2.text}},\n \"col3\" : {{update_col_3.text}},\n \"col4\" : {{update_col_4.text}}\n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"UPDATE","viewType":"component","componentData":"UPDATE"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","update_col_2.text","data_table.selectedRow._id","update_col_1.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"mongo-plugin","id":"MongoDB_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"updateMany":{"query":{"data":"{ _id: ObjectId('{{data_table.selectedRow._id}}') }","viewType":"component","componentData":"{ _id: ObjectId('{{data_table.selectedRow._id}}') }"},"limit":{"data":"SINGLE","viewType":"component","componentData":"SINGLE"},"update":{"data":"{\n \"col1\" : {{update_col_1.text}},\n\t\"col2\" : {{update_col_2.text}},\n \"col3\" : {{update_col_3.text}},\n \"col4\" : {{update_col_4.text}}\n}","viewType":"component","componentData":"{\n \"col1\" : {{update_col_1.text}},\n\t\"col2\" : {{update_col_2.text}},\n \"col3\" : {{update_col_3.text}},\n \"col4\" : {{update_col_4.text}}\n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"UPDATE","viewType":"component","componentData":"UPDATE"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","update_col_2.text","data_table.selectedRow._id","update_col_1.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f08"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"insert":{"documents":{"data":"{\n \"col1\": {{insert_col_input1.text}}, \n \"col2\": {{insert_col_input2.text}}, \n \"col3\": {{insert_col_input3.text}}, \n \"col4\": {{insert_col_input4.text}}\n}","viewType":"component","componentData":"{\n \"col1\": {{insert_col_input1.text}}, \n \"col2\": {{insert_col_input2.text}}, \n \"col3\": {{insert_col_input3.text}}, \n \"col4\": {{insert_col_input4.text}}\n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"INSERT","viewType":"component","componentData":"INSERT"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"mongo-plugin","id":"MongoDB_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"insert":{"documents":{"data":"{\n \"col1\": {{insert_col_input1.text}}, \n \"col2\": {{insert_col_input2.text}}, \n \"col3\": {{insert_col_input3.text}}, \n \"col4\": {{insert_col_input4.text}}\n}","viewType":"component","componentData":"{\n \"col1\": {{insert_col_input1.text}}, \n \"col2\": {{insert_col_input2.text}}, \n \"col3\": {{insert_col_input3.text}}, \n \"col4\": {{insert_col_input4.text}}\n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"INSERT","viewType":"component","componentData":"INSERT"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f09"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{collection_input.text}}\",\n \"datasourceId\": \"{{mongo_ds_url.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]}}\",\n \"applicationId\" : \"{{mongo_ds_url.text.split(\"applications/\")[1].split(\"/\")[0]}}\",\n\t\t\"searchColumn\" : \"{{search_keys_input.text}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["mongo_ds_url.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]","collection_input.text","search_keys_input.text","mongo_ds_url.text.split(\"applications/\")[1].split(\"/\")[0]"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_mongo_app","name":"generate_mongo_app","messages":[]},"pluginId":"restapi-plugin","id":"Page Generator_generate_mongo_app","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{collection_input.text}}\",\n \"datasourceId\": \"{{mongo_ds_url.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]}}\",\n \"applicationId\" : \"{{mongo_ds_url.text.split(\"applications/\")[1].split(\"/\")[0]}}\",\n\t\t\"searchColumn\" : \"{{search_keys_input.text}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["mongo_ds_url.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]","collection_input.text","search_keys_input.text","mongo_ds_url.text.split(\"applications/\")[1].split(\"/\")[0]"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_mongo_app","name":"generate_mongo_app","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0a"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{collection_input.text}}\",\n \"datasourceId\": \"{{gsheet_ds_input.text.split(\"datasources/\")[1].split(\"/\" || \"?\")[0]}}\",\n \"applicationId\" : \"{{gsheet_ds_input.text.split(\"applications/\")[1].split(\"/\")[0]}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["gsheet_ds_input.text.split(\"datasources/\")[1].split(\"/\" || \"?\")[0]","gsheet_ds_input.text.split(\"applications/\")[1].split(\"/\")[0]","collection_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_gsheet_app","name":"generate_gsheet_app","messages":[]},"pluginId":"restapi-plugin","id":"Page Generator_generate_gsheet_app","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{collection_input.text}}\",\n \"datasourceId\": \"{{gsheet_ds_input.text.split(\"datasources/\")[1].split(\"/\" || \"?\")[0]}}\",\n \"applicationId\" : \"{{gsheet_ds_input.text.split(\"applications/\")[1].split(\"/\")[0]}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["gsheet_ds_input.text.split(\"datasources/\")[1].split(\"/\" || \"?\")[0]","gsheet_ds_input.text.split(\"applications/\")[1].split(\"/\")[0]","collection_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_gsheet_app","name":"generate_gsheet_app","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0b"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{File_List.selectedItem.fileName}}","viewType":"component","componentData":"{{File_List.selectedItem.fileName}}"},"body":{"data":"{\n\t\"data\": \"null\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"null\"\n}"},"command":{"data":"DELETE_FILE","viewType":"component","componentData":"DELETE_FILE"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["File_List.selectedItem.fileName"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"DeleteFile","name":"DeleteFile","messages":[]},"pluginId":"amazons3-plugin","id":"S3_DeleteFile","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{File_List.selectedItem.fileName}}","viewType":"component","componentData":"{{File_List.selectedItem.fileName}}"},"body":{"data":"{\n\t\"data\": \"null\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"null\"\n}"},"command":{"data":"DELETE_FILE","viewType":"component","componentData":"DELETE_FILE"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["File_List.selectedItem.fileName"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"DeleteFile","name":"DeleteFile","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0c"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{File_List.selectedItem.fileName}}","viewType":"component","componentData":"{{File_List.selectedItem.fileName}}"},"read":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"}},"body":{"data":"{\n\t\"data\": \"\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"\"\n}"},"command":{"data":"READ_FILE","viewType":"component","componentData":"READ_FILE"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["File_List.selectedItem.fileName"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"ReadFile","name":"ReadFile","messages":[]},"pluginId":"amazons3-plugin","id":"S3_ReadFile","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{File_List.selectedItem.fileName}}","viewType":"component","componentData":"{{File_List.selectedItem.fileName}}"},"read":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"}},"body":{"data":"{\n\t\"data\": \"\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"\"\n}"},"command":{"data":"READ_FILE","viewType":"component","componentData":"READ_FILE"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["File_List.selectedItem.fileName"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"ReadFile","name":"ReadFile","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0d"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{update_file_name.text}}","viewType":"component","componentData":"{{update_file_name.text}}"},"create":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"},"expiry":{"data":"5","viewType":"component","componentData":"5"}},"body":{"data":"{\n\t\"data\": \"{{update_file_picker.files.length ? update_file_picker.files[0].data : \"\" }}\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"{{update_file_picker.files.length ? update_file_picker.files[0].data : \"\" }}\"\n}"},"command":{"data":"UPLOAD_FILE_FROM_BODY","viewType":"component","componentData":"UPLOAD_FILE_FROM_BODY"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_file_picker.files.length ? update_file_picker.files[0].data : \"\"","update_file_name.text"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"UpdateFile","name":"UpdateFile","messages":[]},"pluginId":"amazons3-plugin","id":"S3_UpdateFile","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{update_file_name.text}}","viewType":"component","componentData":"{{update_file_name.text}}"},"create":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"},"expiry":{"data":"5","viewType":"component","componentData":"5"}},"body":{"data":"{\n\t\"data\": \"{{update_file_picker.files.length ? update_file_picker.files[0].data : \"\" }}\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"{{update_file_picker.files.length ? update_file_picker.files[0].data : \"\" }}\"\n}"},"command":{"data":"UPLOAD_FILE_FROM_BODY","viewType":"component","componentData":"UPLOAD_FILE_FROM_BODY"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"body"},{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_file_picker.files.length ? update_file_picker.files[0].data : \"\"","update_file_name.text"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"UpdateFile","name":"UpdateFile","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0e"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"{{data_table.selectedRow._ref.path}}","viewType":"component","componentData":"{{data_table.selectedRow._ref.path}}"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"UPDATE","viewType":"component","componentData":"UPDATE"},"body":{"data":"{\n\t\"col1\": \"{{update_col_1.text}}\",\n\t\"col2\": \"{{update_col_2.text}}\",\n\t\"col3\": \"{{update_col_3.text}}\",\n\t\"col4\": \"{{update_col_4.text}}\",\n\t\"col5\": \"{{update_col_5.text}}\"\n}","viewType":"component","componentData":"{\n\t\"col1\": \"{{update_col_1.text}}\",\n\t\"col2\": \"{{update_col_2.text}}\",\n\t\"col3\": \"{{update_col_3.text}}\",\n\t\"col4\": \"{{update_col_4.text}}\",\n\t\"col5\": \"{{update_col_5.text}}\"\n}"},"command":{"data":"UPDATE_DOCUMENT","viewType":"component","componentData":"UPDATE_DOCUMENT"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","update_col_2.text","data_table.selectedRow._ref.path","update_col_1.text","update_col_5.text","data_table.selectedRow._id","update_col_4.text"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"firestore-plugin","id":"Firestore_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"{{data_table.selectedRow._ref.path}}","viewType":"component","componentData":"{{data_table.selectedRow._ref.path}}"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"UPDATE","viewType":"component","componentData":"UPDATE"},"body":{"data":"{\n\t\"col1\": \"{{update_col_1.text}}\",\n\t\"col2\": \"{{update_col_2.text}}\",\n\t\"col3\": \"{{update_col_3.text}}\",\n\t\"col4\": \"{{update_col_4.text}}\",\n\t\"col5\": \"{{update_col_5.text}}\"\n}","viewType":"component","componentData":"{\n\t\"col1\": \"{{update_col_1.text}}\",\n\t\"col2\": \"{{update_col_2.text}}\",\n\t\"col3\": \"{{update_col_3.text}}\",\n\t\"col4\": \"{{update_col_4.text}}\",\n\t\"col5\": \"{{update_col_5.text}}\"\n}"},"command":{"data":"UPDATE_DOCUMENT","viewType":"component","componentData":"UPDATE_DOCUMENT"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"body"},{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","update_col_2.text","data_table.selectedRow._ref.path","update_col_1.text","update_col_5.text","data_table.selectedRow._id","update_col_4.text"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0f"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"{{data_table.triggeredRow._ref.path}}","viewType":"component","componentData":"{{data_table.triggeredRow._ref.path}}"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"DELETE","viewType":"component","componentData":"DELETE"},"command":{"data":"DELETE_DOCUMENT","viewType":"component","componentData":"DELETE_DOCUMENT"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.triggeredRow._ref.path","data_table.selectedRow._id"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"firestore-plugin","id":"Firestore_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"{{data_table.triggeredRow._ref.path}}","viewType":"component","componentData":"{{data_table.triggeredRow._ref.path}}"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"DELETE","viewType":"component","componentData":"DELETE"},"command":{"data":"DELETE_DOCUMENT","viewType":"component","componentData":"DELETE_DOCUMENT"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.triggeredRow._ref.path","data_table.selectedRow._id"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f10"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"template_table","viewType":"component","componentData":"template_table"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"INSERT","viewType":"component","componentData":"INSERT"},"body":{"data":"{\n\t\"col1\": \"{{insert_col_input1.text}}\",\n\t\"col2\": \"{{insert_col_input2.text}}\",\n\t\"col3\": \"{{insert_col_input3.text}}\",\n\t\"col4\": \"{{insert_col_input4.text}}\",\n\t\"col5\": \"{{insert_col_input5.text}}\"\n}","viewType":"component","componentData":"{\n\t\"col1\": \"{{insert_col_input1.text}}\",\n\t\"col2\": \"{{insert_col_input2.text}}\",\n\t\"col3\": \"{{insert_col_input3.text}}\",\n\t\"col4\": \"{{insert_col_input4.text}}\",\n\t\"col5\": \"{{insert_col_input5.text}}\"\n}"},"command":{"data":"ADD_TO_COLLECTION","viewType":"component","componentData":"ADD_TO_COLLECTION"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"firestore-plugin","id":"Firestore_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"template_table","viewType":"component","componentData":"template_table"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"INSERT","viewType":"component","componentData":"INSERT"},"body":{"data":"{\n\t\"col1\": \"{{insert_col_input1.text}}\",\n\t\"col2\": \"{{insert_col_input2.text}}\",\n\t\"col3\": \"{{insert_col_input3.text}}\",\n\t\"col4\": \"{{insert_col_input4.text}}\",\n\t\"col5\": \"{{insert_col_input5.text}}\"\n}","viewType":"component","componentData":"{\n\t\"col1\": \"{{insert_col_input1.text}}\",\n\t\"col2\": \"{{insert_col_input2.text}}\",\n\t\"col3\": \"{{insert_col_input3.text}}\",\n\t\"col4\": \"{{insert_col_input4.text}}\",\n\t\"col5\": \"{{insert_col_input5.text}}\"\n}"},"command":{"data":"ADD_TO_COLLECTION","viewType":"component","componentData":"ADD_TO_COLLECTION"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f11"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{{SelectQuery.data[SelectQuery.data.length - 1]}}","viewType":"component","componentData":"{{SelectQuery.data[SelectQuery.data.length - 1]}}"},"timestampValuePath":{"data":"","viewType":"component","componentData":""},"path":{"data":"template_table","viewType":"component","componentData":"template_table"},"startAfter":{"data":"{{SelectQuery.data[SelectQuery.data.length - 1]}}","viewType":"component","componentData":"{{SelectQuery.data[SelectQuery.data.length - 1]}}"},"endBefore":{"data":"{{SelectQuery.data[0]}}","viewType":"component","componentData":"{{SelectQuery.data[0]}}"},"deleteKeyPath":{"data":"","viewType":"component","componentData":""},"prev":{"data":"{{SelectQuery.data[0]}}","viewType":"component","componentData":"{{SelectQuery.data[0]}}"},"orderBy":{"data":"[\"{{order_select.selectedOptionValue + key_select.selectedOptionValue}}\"]","viewType":"component","componentData":"[\"{{order_select.selectedOptionValue + key_select.selectedOptionValue}}\"]"},"where":{"viewType":"component"},"limitDocuments":{"data":"1","viewType":"component","componentData":"1"},"command":{"data":"GET_COLLECTION","viewType":"component","componentData":"GET_COLLECTION"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.startAfter.data"},{"key":"formData.endBefore.data"},{"key":"formData.orderBy.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["SelectQuery.data[SelectQuery.data.length - 1]","order_select.selectedOptionValue + key_select.selectedOptionValue","SelectQuery.data[0]"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"pluginId":"firestore-plugin","id":"Firestore_SelectQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{{SelectQuery.data[SelectQuery.data.length - 1]}}","viewType":"component","componentData":"{{SelectQuery.data[SelectQuery.data.length - 1]}}"},"timestampValuePath":{"data":"","viewType":"component","componentData":""},"path":{"data":"template_table","viewType":"component","componentData":"template_table"},"startAfter":{"data":"{{SelectQuery.data[SelectQuery.data.length - 1]}}","viewType":"component","componentData":"{{SelectQuery.data[SelectQuery.data.length - 1]}}"},"endBefore":{"data":"{{SelectQuery.data[0]}}","viewType":"component","componentData":"{{SelectQuery.data[0]}}"},"deleteKeyPath":{"data":"","viewType":"component","componentData":""},"prev":{"data":"{{SelectQuery.data[0]}}","viewType":"component","componentData":"{{SelectQuery.data[0]}}"},"orderBy":{"data":"[\"{{order_select.selectedOptionValue + key_select.selectedOptionValue}}\"]","viewType":"component","componentData":"[\"{{order_select.selectedOptionValue + key_select.selectedOptionValue}}\"]"},"where":{"viewType":"component"},"limitDocuments":{"data":"1","viewType":"component","componentData":"1"},"command":{"data":"GET_COLLECTION","viewType":"component","componentData":"GET_COLLECTION"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.startAfter"},{"key":"formData.endBefore"},{"key":"formData.orderBy"}],"confirmBeforeExecute":false,"jsonPathKeys":["SelectQuery.data[SelectQuery.data.length - 1]","order_select.selectedOptionValue + key_select.selectedOptionValue","SelectQuery.data[0]"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f12"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"keys *"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"FetchKeys","name":"FetchKeys","messages":[]},"pluginId":"redis-plugin","id":"Redis_FetchKeys","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"keys *"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"FetchKeys","name":"FetchKeys","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f13"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"set {{insert_key_input.text}} \"{{insert_value_input.text}}\""},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_key_input.text","insert_value_input.text"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"InsertKey","name":"InsertKey","messages":[]},"pluginId":"redis-plugin","id":"Redis_InsertKey","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"set {{insert_key_input.text}} \"{{insert_value_input.text}}\""},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_key_input.text","insert_value_input.text"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"InsertKey","name":"InsertKey","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f14"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"set {{data_table.selectedRow.result}} \"{{update_value_input.text}}\""},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_value_input.text","data_table.selectedRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"UpdateKey","name":"UpdateKey","messages":[]},"pluginId":"redis-plugin","id":"Redis_UpdateKey","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"set {{data_table.selectedRow.result}} \"{{update_value_input.text}}\""},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_value_input.text","data_table.selectedRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"UpdateKey","name":"UpdateKey","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f15"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"del {{data_table.triggeredRow.result}}"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.triggeredRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"DeleteKey","name":"DeleteKey","messages":[]},"pluginId":"redis-plugin","id":"Redis_DeleteKey","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"del {{data_table.triggeredRow.result}}"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.triggeredRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"DeleteKey","name":"DeleteKey","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f16"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"GET {{data_table.selectedRow.result}}"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"FetchValue","name":"FetchValue","messages":[]},"pluginId":"redis-plugin","id":"Redis_FetchValue","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"GET {{data_table.selectedRow.result}}"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"FetchValue","name":"FetchValue","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f17"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"DELETE FROM public.template_table\n WHERE \"col1\" = {{Table1.triggeredRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.triggeredRow.col1"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"postgres-plugin","id":"PostgreSQL_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"DELETE FROM public.template_table\n WHERE \"col1\" = {{Table1.triggeredRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.triggeredRow.col1"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f18"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"UPDATE public.template_table SET\n\t\t\"col2\" = '{{update_col_2.text}}',\n \"col3\" = '{{update_col_3.text}}',\n \"col4\" = '{{update_col_4.text}}',\n \"col5\" = '{{update_col_5.text}}'\n WHERE \"col1\" = {{Table1.selectedRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","Table1.selectedRow.col1","update_col_2.text","update_col_5.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"postgres-plugin","id":"PostgreSQL_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"UPDATE public.template_table SET\n\t\t\"col2\" = '{{update_col_2.text}}',\n \"col3\" = '{{update_col_3.text}}',\n \"col4\" = '{{update_col_4.text}}',\n \"col5\" = '{{update_col_5.text}}'\n WHERE \"col1\" = {{Table1.selectedRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","Table1.selectedRow.col1","update_col_2.text","update_col_5.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f19"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"SELECT * FROM public.template_table\nWHERE \"col2\" ilike '%{{Table1.searchText || \"\"}}%'\nORDER BY \"{{col_select.selectedOptionValue}}\" {{order_select.selectedOptionValue}}\nLIMIT {{Table1.pageSize}}\nOFFSET {{(Table1.pageNo - 1) * Table1.pageSize}};","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","col_select.selectedOptionValue","Table1.pageSize","order_select.selectedOptionValue"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"pluginId":"postgres-plugin","id":"PostgreSQL_SelectQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"SELECT * FROM public.template_table\nWHERE \"col2\" ilike '%{{Table1.searchText || \"\"}}%'\nORDER BY \"{{col_select.selectedOptionValue}}\" {{order_select.selectedOptionValue}}\nLIMIT {{Table1.pageSize}}\nOFFSET {{(Table1.pageNo - 1) * Table1.pageSize}};","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","col_select.selectedOptionValue","Table1.pageSize","order_select.selectedOptionValue"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f1a"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"INSERT INTO public.template_table (\n\t\"col1\",\n\t\"col2\", \n\t\"col3\",\n\t\"col4\", \n\t\"col5\"\n)\nVALUES (\n\t\t\t\t{{insert_col_input1.text}}, \n\t\t\t\t{{insert_col_input2.text}}, \n\t\t\t\t{{insert_col_input3.text}}, \n\t\t\t\t{{insert_col_input4.text}}, \n\t\t\t\t{{insert_col_input5.text}}\n);","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"postgres-plugin","id":"PostgreSQL_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"INSERT INTO public.template_table (\n\t\"col1\",\n\t\"col2\", \n\t\"col3\",\n\t\"col4\", \n\t\"col5\"\n)\nVALUES (\n\t\t\t\t{{insert_col_input1.text}}, \n\t\t\t\t{{insert_col_input2.text}}, \n\t\t\t\t{{insert_col_input3.text}}, \n\t\t\t\t{{insert_col_input4.text}}, \n\t\t\t\t{{insert_col_input5.text}}\n);","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f1b"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/users/me","headers":[{"value":"_hjid=41cedd95-19f9-438a-8b6e-f2c4d7fb086b; SL_C_23361dd035530_KEY=c370af0df0edf38360adbefbdc47d2b42ea137c9; SL_C_23361dd035530_VID=P3kBR7eMjg; ajs_anonymous_id=e6ef9c9b-3407-4374-81ab-6bafef26a4d1; [email protected]; intercom-id-y10e7138=50e190b7-b24e-4bef-b320-3c47a3c91006; amplitude_id_fef1e872c952688acd962d30aa545b9eappsmith.com=eyJkZXZpY2VJZCI6IjIxNWJlMWRkLTNjMGQtNDY5NS05YzRmLTFjYTM4MjNhNzM5NlIiLCJ1c2VySWQiOm51bGwsIm9wdE91dCI6ZmFsc2UsInNlc3Npb25JZCI6MTYzNjI1ODEwMjkyNCwibGFzdEV2ZW50VGltZSI6MTYzNjI1ODEwMzE3MywiZXZlbnRJZCI6NSwiaWRlbnRpZnlJZCI6MSwic2VxdWVuY2VOdW1iZXIiOjZ9; _ga=GA1.2.526957763.1633412376; _gid=GA1.2.1610516593.1636258104; _ga_0JZ9C3M56S=GS1.1.1636258103.3.1.1636258646.0; SESSION=09ae7c78-ca84-4a38-916a-f282893efb40; mp_70b8ea94d623dd857fb555a76d11f944_mixpanel=%7B%22distinct_id%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24device_id%22%3A%20%2217c91e75170277-051d4ff86c77bb-1d3b6650-168000-17c91e75171dc2%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22mp_lib%22%3A%20%22Segment%3A%20web%22%2C%22%24user_id%22%3A%20%22nidhi%40appsmith.com%22%2C%22mp_name_tag%22%3A%20%22nidhi%40appsmith.com%22%2C%22userId%22%3A%20%22nidhi%40appsmith.com%22%2C%22source%22%3A%20%22cloud%22%2C%22id%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24email%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24first_name%22%3A%20%22Nidhi%22%2C%22%24last_name%22%3A%20%22Nair%22%2C%22%24name%22%3A%20%22Nidhi%20Nair%22%7D; SL_C_23361dd035530_SID=3VIjO5jKCt; intercom-session-y10e7138=WnhwMVl4VmVIUDFPVkgxUDVidm8wOXUzNjZ2elJ0OWx2a21Qc3NCYk1zenNEa0dzMkswWFlpanM4YXNxY2pQYi0taFpkWkR6K0xLUFJyUVFRSkMwZ3pUUT09--376a7fef0d7774b3284b94fb4c1ea1c8e2305afe; _hjAbsoluteSessionInProgress=1","key":"Cookie"}],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_user","name":"get_user","messages":[]},"pluginId":"restapi-plugin","id":"Admin_get_user","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/users/me","headers":[{"value":"_hjid=41cedd95-19f9-438a-8b6e-f2c4d7fb086b; SL_C_23361dd035530_KEY=c370af0df0edf38360adbefbdc47d2b42ea137c9; SL_C_23361dd035530_VID=P3kBR7eMjg; ajs_anonymous_id=e6ef9c9b-3407-4374-81ab-6bafef26a4d1; [email protected]; intercom-id-y10e7138=50e190b7-b24e-4bef-b320-3c47a3c91006; amplitude_id_fef1e872c952688acd962d30aa545b9eappsmith.com=eyJkZXZpY2VJZCI6IjIxNWJlMWRkLTNjMGQtNDY5NS05YzRmLTFjYTM4MjNhNzM5NlIiLCJ1c2VySWQiOm51bGwsIm9wdE91dCI6ZmFsc2UsInNlc3Npb25JZCI6MTYzNjI1ODEwMjkyNCwibGFzdEV2ZW50VGltZSI6MTYzNjI1ODEwMzE3MywiZXZlbnRJZCI6NSwiaWRlbnRpZnlJZCI6MSwic2VxdWVuY2VOdW1iZXIiOjZ9; _ga=GA1.2.526957763.1633412376; _gid=GA1.2.1610516593.1636258104; _ga_0JZ9C3M56S=GS1.1.1636258103.3.1.1636258646.0; SESSION=09ae7c78-ca84-4a38-916a-f282893efb40; mp_70b8ea94d623dd857fb555a76d11f944_mixpanel=%7B%22distinct_id%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24device_id%22%3A%20%2217c91e75170277-051d4ff86c77bb-1d3b6650-168000-17c91e75171dc2%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22mp_lib%22%3A%20%22Segment%3A%20web%22%2C%22%24user_id%22%3A%20%22nidhi%40appsmith.com%22%2C%22mp_name_tag%22%3A%20%22nidhi%40appsmith.com%22%2C%22userId%22%3A%20%22nidhi%40appsmith.com%22%2C%22source%22%3A%20%22cloud%22%2C%22id%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24email%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24first_name%22%3A%20%22Nidhi%22%2C%22%24last_name%22%3A%20%22Nair%22%2C%22%24name%22%3A%20%22Nidhi%20Nair%22%7D; SL_C_23361dd035530_SID=3VIjO5jKCt; intercom-session-y10e7138=WnhwMVl4VmVIUDFPVkgxUDVidm8wOXUzNjZ2elJ0OWx2a21Qc3NCYk1zenNEa0dzMkswWFlpanM4YXNxY2pQYi0taFpkWkR6K0xLUFJyUVFRSkMwZ3pUUT09--376a7fef0d7774b3284b94fb4c1ea1c8e2305afe; _hjAbsoluteSessionInProgress=1","key":"Cookie"}],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_user","name":"get_user","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb773acd5d7045095322ff"}],"clientSchemaVersion":1,"publishedDefaultPageName":"PostgreSQL","unpublishedDefaultPageName":"PostgreSQL","publishedTheme":{"new":true,"isSystemTheme":true,"displayName":"Classic","name":"Classic"},"invisibleActionFields":{"Admin_get_exported_app":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Admin_get_datasource_structure":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_UpdateFile":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"PostgreSQL_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"SQL_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_UpdateKey":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_FetchValue":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"PostgreSQL_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Page Generator_generate_mongo_app":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_DeleteKey":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Admin_get_user":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Firestore_SelectQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"SQL_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"MongoDB_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_ListFiles":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Firestore_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Google Sheets_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"MongoDB_FindQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"SQL_SelectQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"MongoDB_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"PostgreSQL_SelectQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Page Generator_generate_sql_app":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Google Sheets_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Page Generator_generate_gsheet_app":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"MongoDB_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Firestore_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Google Sheets_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_DeleteFile":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_CreateFile":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_FetchKeys":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"PostgreSQL_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Admin_update_template":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Google Sheets_SelectQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Firestore_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_ReadFile":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_InsertKey":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"SQL_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false}},"serverSchemaVersion":3,"unpublishedLayoutmongoEscapedWidgets":{"MongoDB":["data_table"]},"pageList":[{"publishedPage":{"name":"SQL","userPermissions":[],"layouts":[{"new":false,"id":"SQL","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","col_select.selectedOptionValue","Table1.pageSize","order_select.selectedOptionValue"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"SQL_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":890,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":900,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Table1","columnOrder":["col1","col2","col3","col4","col5","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","fontStyle":"","textColor":"","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"isRequired":false,"widgetName":"col_select","isFilterable":true,"rightColumn":22,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"asmgosgxjm","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{SelectQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"col1","parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":7,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n\t{\n\t\t\"label\": \"col1\",\n\t\t\"value\": \"col1\"\n\t},\n\t{\n\t\t\"label\": \"col2\",\n\t\t\"value\": \"col2\"\n\t},\n\t{\n\t\t\"label\": \"col3\",\n\t\t\"value\": \"col3\"\n\t}\n]","onOptionChange":"{{SelectQuery.run()}}","isDisabled":false},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"isRequired":false,"widgetName":"order_select","isFilterable":true,"rightColumn":33,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"10v8a19m25","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{SelectQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"ASC","parentColumnSpace":19.75,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":22,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"Ascending\",\n \"value\": \"ASC\"\n },\n {\n \"label\": \"Descending\",\n \"value\": \"DESC\"\n }\n]","onOptionChange":"{{SelectQuery.run()}}","isDisabled":false},{"widgetName":"Text16","rightColumn":64,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"2jj0197tff","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"kby34l9nbb","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => SelectQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text24","rightColumn":19,"textAlign":"RIGHT","widgetId":"9t3vdjd5xj","topRow":33,"bottomRow":37,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col1","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"l6pr59rote","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col2","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"or3u23jovu","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col3","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"t19g4rkxdg","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col4","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"wxfh7xr2ti","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":33,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col5","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"0l0coczf07","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{!!Table1.selectedRow.col1}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"update_col_5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"7no1xvf1tz","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col5}}"},{"widgetName":"update_col_4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"xg884qff60","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col4}}"},{"widgetName":"update_col_3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"lidt630yxv","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col3}}"},{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":42,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":42,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03b365","widgetId":"twwgpz5wfu","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Row: {{Table1.selectedRow.col1}}"},{"widgetName":"Text17","rightColumn":18,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text18","rightColumn":18,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text19","rightColumn":18,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text20","rightColumn":18,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"update_col_2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"culdocx5yg","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col2}}"}]}]}]}}],"slug":"sql","isHidden":false},"new":true,"unpublishedPage":{"name":"SQL","userPermissions":[],"layouts":[{"new":false,"id":"SQL","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","col_select.selectedOptionValue","Table1.pageSize","order_select.selectedOptionValue"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"SQL_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1431,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":940,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":52,"minHeight":1970,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":880,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Table1","columnOrder":["col1","col2","col3","col4","col5","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","fontStyle":"","textColor":"","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"widgetName":"Text16","rightColumn":64,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"2jj0197tff","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"kby34l9nbb","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"widgetName":"col_select","isFilterable":true,"dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Select","iconSVG":"/static/media/icon.bd99caba.svg","labelText":"","topRow":5,"bottomRow":9,"parentRowSpace":10,"type":"SELECT_WIDGET","serverSideFiltering":false,"hideCard":false,"defaultOptionValue":"col1","animateLoading":true,"parentColumnSpace":22.375,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":9,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n\t{\n\t\t\"label\": \"col1\",\n\t\t\"value\": \"col1\"\n\t},\n\t{\n\t\t\"label\": \"col2\",\n\t\t\"value\": \"col2\"\n\t},\n\t{\n\t\t\"label\": \"col3\",\n\t\t\"value\": \"col3\"\n\t},\n\t{\n\t\t\"label\": \"col4\",\n\t\t\"value\": \"col4\"\n\t}\n]","placeholderText":"Select option","isDisabled":false,"key":"52ieik6s6e","isRequired":false,"rightColumn":22,"widgetId":"1sa3136slm","isVisible":"{{SelectQuery.data.length > 0}}","version":1,"parentId":"59rw5mx0bq","renderMode":"CANVAS","isLoading":false,"onOptionChange":"{{SelectQuery.run()}}"},{"widgetName":"order_select","isFilterable":true,"dynamicPropertyPathList":[{"key":"isVisible"},{"key":"onOptionChange"}],"displayName":"Select","iconSVG":"/static/media/icon.bd99caba.svg","labelText":"","topRow":5,"bottomRow":9,"parentRowSpace":10,"type":"SELECT_WIDGET","serverSideFiltering":false,"hideCard":false,"defaultOptionValue":"ASC","animateLoading":true,"parentColumnSpace":22.375,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":23,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"Ascending\",\n \"value\": \"ASC\"\n },\n {\n \"label\": \"Descending\",\n \"value\": \"DESC\"\n }\n]","placeholderText":"Select option","isDisabled":false,"key":"52ieik6s6e","isRequired":false,"rightColumn":36,"widgetId":"vy6pgd3mwy","isVisible":"{{SelectQuery.data.length > 0}}","version":1,"parentId":"59rw5mx0bq","renderMode":"CANVAS","isLoading":false,"onOptionChange":"{{SelectQuery.run()}}"}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => SelectQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text24","rightColumn":19,"textAlign":"RIGHT","widgetId":"9t3vdjd5xj","topRow":33,"bottomRow":37,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col1","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"l6pr59rote","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col2","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"or3u23jovu","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col3","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"t19g4rkxdg","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col4","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"wxfh7xr2ti","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":33,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col5","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"0l0coczf07","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{!!Table1.selectedRow.col1}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"update_col_5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"7no1xvf1tz","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col5}}"},{"widgetName":"update_col_4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"xg884qff60","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col4}}"},{"widgetName":"update_col_3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"lidt630yxv","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col3}}"},{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":42,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":42,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03b365","widgetId":"twwgpz5wfu","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Row: {{Table1.selectedRow.col1}}"},{"widgetName":"Text17","rightColumn":18,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text18","rightColumn":18,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text19","rightColumn":18,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text20","rightColumn":18,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"update_col_2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"culdocx5yg","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col2}}"}]}]}]}}],"slug":"sql","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc0"},{"publishedPage":{"name":"Google Sheets","userPermissions":[],"layouts":[{"new":false,"id":"Google Sheets","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"SAAS","jsonPathKeys":["data_table.pageSize","(data_table.pageNo - 1) * data_table.pageSize"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"Google Sheets_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":940,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":900,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["col1","col2","col3","col4","rowIndex","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":6,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"}],"dynamicBindingPathList":[{"key":"tableData"},{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"primaryColumns.rowIndex.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col1.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"rowIndex":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex))}}","textSize":"PARAGRAPH","index":4,"isVisible":false,"label":"rowIndex","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"rowIndex","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{deleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"step":62,"status":75,"col1":140}},{"widgetName":"Text16","rightColumn":39,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"typ9jslblf","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"8b67sbqskr","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":18.8828125,"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text11","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Alert"},{"widgetName":"Button1","rightColumn":48,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":16,"bottomRow":20,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"delete_button","rightColumn":64,"onClick":"{{(function () {\nDeleteQuery.run(() =>{ showAlert('Row successfully deleted!','success');\tSelectQuery.run();\n}, () => showAlert('Something went wrong! Please check debugger for more info.','error'));\ncloseModal('Delete_Modal');\n})()}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":16,"bottomRow":20,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":60,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"hqtpvn9ut2","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"ipc9o3ksyi","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"hqtpvn9ut2","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"FormButton1","rightColumn":63,"onClick":"{{(function () {\nInsertQuery.run(() =>{ \t\tshowAlert('Item successfully inserted!','success');\ncloseModal('Insert_Modal');\nSelectQuery.run();\n}, (error) => showAlert(error,'error'));\n})()}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"s2jtkzz2ub","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ipc9o3ksyi","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"FormButton2","rightColumn":45,"isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"396envygmb","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ipc9o3ksyi","isLoading":false,"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text21","rightColumn":18,"textAlign":"RIGHT","widgetId":"vwgogtczul","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":18,"textAlign":"RIGHT","widgetId":"t2a63abehn","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":18,"textAlign":"RIGHT","widgetId":"0xqhj661rj","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":18,"textAlign":"RIGHT","widgetId":"mxztke60bg","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text24","rightColumn":18,"textAlign":"RIGHT","widgetId":"2xn45kukrz","topRow":33,"bottomRow":37,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"Text13","rightColumn":35,"textAlign":"LEFT","widgetId":"iuydklwdo3","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"ipc9o3ksyi","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col1}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"bazceo5528","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col2}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"144pojmxdg","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col3}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"guxxq17lmt","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col4}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"qdbr1z5udr","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":33,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col5}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"5a4k7u41d4","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{data_table.selectedRowIndex >= 0}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"colInput4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":28,"bottomRow":32,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"kxy5v10os2","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col4}}"},{"widgetName":"colInput3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":21,"bottomRow":25,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"9ddk5zsnlj","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col3}}"},{"widgetName":"colInput2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":14,"bottomRow":18,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"7ac4gdtkcc","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col2}}"},{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => SelectQuery.run(), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":42,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Row Index: {{data_table.selectedRow.rowIndex}}"},{"widgetName":"col_text_1","rightColumn":17,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":7,"bottomRow":11,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"col_text_2","rightColumn":17,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":14,"bottomRow":18,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"col_text_3","rightColumn":17,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":21,"bottomRow":25,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"col_text_4","rightColumn":17,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":28,"bottomRow":32,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"colInput1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":7,"bottomRow":11,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"p2sugbwwx3","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col1}}"}]}]}]}}],"slug":"google-sheets","isHidden":false},"new":true,"unpublishedPage":{"name":"Google Sheets","userPermissions":[],"layouts":[{"new":false,"id":"Google Sheets","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"SAAS","confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","(data_table.pageNo - 1) * data_table.pageSize"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"Google Sheets_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":940,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":53,"minHeight":900,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["col1","col2","col3","col4","rowIndex","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":6,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"}],"dynamicBindingPathList":[{"key":"tableData"},{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"primaryColumns.rowIndex.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col1.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"rowIndex":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex))}}","textSize":"PARAGRAPH","index":4,"isVisible":false,"label":"rowIndex","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"rowIndex","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{deleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"step":62,"status":75,"col1":140}},{"widgetName":"Text16","rightColumn":39,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"typ9jslblf","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"8b67sbqskr","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":18.8828125,"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text11","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Alert"},{"widgetName":"Button1","rightColumn":48,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":16,"bottomRow":20,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"delete_button","rightColumn":64,"onClick":"{{(function () {\nDeleteQuery.run(() =>{ showAlert('Row successfully deleted!','success');\tSelectQuery.run();\n}, () => showAlert('Something went wrong! Please check debugger for more info.','error'));\ncloseModal('Delete_Modal');\n})()}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":16,"bottomRow":20,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":60,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"hqtpvn9ut2","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"ipc9o3ksyi","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"hqtpvn9ut2","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"FormButton1","rightColumn":63,"onClick":"{{(function () {\nInsertQuery.run(() =>{ \t\tshowAlert('Item successfully inserted!','success');\ncloseModal('Insert_Modal');\nSelectQuery.run();\n}, (error) => showAlert(error,'error'));\n})()}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"s2jtkzz2ub","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ipc9o3ksyi","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"FormButton2","rightColumn":45,"isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"396envygmb","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ipc9o3ksyi","isLoading":false,"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text21","rightColumn":18,"textAlign":"RIGHT","widgetId":"vwgogtczul","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":18,"textAlign":"RIGHT","widgetId":"t2a63abehn","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":18,"textAlign":"RIGHT","widgetId":"0xqhj661rj","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":18,"textAlign":"RIGHT","widgetId":"mxztke60bg","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text24","rightColumn":18,"textAlign":"RIGHT","widgetId":"2xn45kukrz","topRow":33,"bottomRow":37,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ipc9o3ksyi","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"Text13","rightColumn":35,"textAlign":"LEFT","widgetId":"iuydklwdo3","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"ipc9o3ksyi","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col1}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"bazceo5528","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col2}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"144pojmxdg","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col3}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"guxxq17lmt","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col4}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"qdbr1z5udr","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":33,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"placeholderText"}],"labelStyle":"","inputType":"TEXT","placeholderText":"{{data_table.tableData[0].col5}}","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"5a4k7u41d4","isVisible":true,"label":"","version":2,"parentId":"ipc9o3ksyi","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{data_table.selectedRowIndex >= 0}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"colInput4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":28,"bottomRow":32,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"kxy5v10os2","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col4}}"},{"widgetName":"colInput3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":21,"bottomRow":25,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"9ddk5zsnlj","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col3}}"},{"widgetName":"colInput2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":14,"bottomRow":18,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"7ac4gdtkcc","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col2}}"},{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => SelectQuery.run(), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":42,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Row Index: {{data_table.selectedRow.rowIndex}}"},{"widgetName":"col_text_1","rightColumn":17,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":7,"bottomRow":11,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"col_text_2","rightColumn":17,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":14,"bottomRow":18,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"col_text_3","rightColumn":17,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":21,"bottomRow":25,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"col_text_4","rightColumn":17,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":28,"bottomRow":32,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"colInput1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":7,"bottomRow":11,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"p2sugbwwx3","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col1}}"}]}]}]}}],"slug":"google-sheets","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc1"},{"publishedPage":{"name":"S3","userPermissions":[],"layouts":[{"new":false,"id":"S3","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","jsonPathKeys":["60 * 24","search_input.text"],"name":"ListFiles","timeoutInMillisecond":10000,"id":"S3_ListFiles"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":1300,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Zoom_Modal2","rightColumn":0,"detachFromLayout":true,"widgetId":"kqxoe40pg6","topRow":89,"bottomRow":89,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas9Copy","rightColumn":0,"detachFromLayout":true,"widgetId":"80wzwajsst","topRow":0,"bottomRow":590,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"kqxoe40pg6","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon3Copy","rightColumn":64,"onClick":"{{closeModal('Zoom_Modal2')}}","color":"#040627","iconName":"cross","widgetId":"8kw9kfcd5y","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_WIDGET","version":1,"parentId":"80wzwajsst","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"iconSize":24},{"widgetName":"Text15Copy","rightColumn":41,"textAlign":"LEFT","widgetId":"vk710q1v3s","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"80wzwajsst","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Zoom Image"},{"widgetName":"Button13Copy","rightColumn":63,"onClick":"{{closeModal('Zoom_Modal2')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"lfiwss1u3w","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"80wzwajsst","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Close","isDisabled":false},{"image":"{{selected_files.selectedItem.base64}}","widgetName":"Image3Copy","rightColumn":64,"objectFit":"contain","widgetId":"2bewgakjx9","topRow":6,"bottomRow":51,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"80wzwajsst","isLoading":false,"maxZoomLevel":8,"parentColumnSpace":8,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png"}],"isDisabled":false}],"width":532,"height":600},{"backgroundColor":"#FFFFFF","widgetName":"Container3","rightColumn":37,"widgetId":"th4d9oxy8z","containerStyle":"card","topRow":5,"bottomRow":88,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":634,"detachFromLayout":true,"widgetId":"6tz2s7ivi5","containerStyle":"none","topRow":0,"bottomRow":840,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"th4d9oxy8z","minHeight":830,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"template":{"DownloadIcon":{"boxShadow":"NONE","widgetName":"DownloadIcon","onClick":"{{navigateTo(currentItem.signedUrl, {})}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":57,"iconName":"download","widgetId":"ljk8fj5jc1","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"CopyURLIcon":{"boxShadow":"NONE","widgetName":"CopyURLIcon","onClick":"{{copyToClipboard(currentItem.signedUrl)}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":51,"iconName":"link","widgetId":"d2z5zj56j9","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"EditIcon":{"boxShadow":"NONE","widgetName":"EditIcon","onClick":"{{showModal('Edit_Modal')}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":39,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":45,"iconName":"edit","widgetId":"x5bft8h9vd","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"Text21":{"widgetName":"Text21","rightColumn":24,"textAlign":"LEFT","displayName":"Text","iconSVG":"/static/media/icon.e6c93592.svg","widgetId":"nu44q8kd9p","topRow":4,"bottomRow":8,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"hideCard":false,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[{"key":"text"}],"leftColumn":16,"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem) => currentItem.id)}}","textStyle":"BODY","key":"xvmvdekk3s"},"Text20":{"widgetName":"Text20","rightColumn":28,"textAlign":"LEFT","displayName":"Text","iconSVG":"/static/media/icon.e6c93592.svg","widgetId":"thgbdemmiw","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"hideCard":false,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[{"key":"text"}],"leftColumn":16,"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem) => currentItem.name)}}","textStyle":"HEADING","key":"xvmvdekk3s"},"Image3":{"widgetName":"Image3","displayName":"Image","iconSVG":"/static/media/icon.52d8fb96.svg","topRow":0,"bottomRow":8.4,"type":"IMAGE_WIDGET","hideCard":false,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","dynamicBindingPathList":[{"key":"image"}],"leftColumn":0,"defaultImage":"https://assets.appsmith.com/widgets/default.png","key":"lsc53q139g","image":"{{File_List.listData.map((currentItem) => currentItem.img)}}","rightColumn":16,"objectFit":"contain","widgetId":"2rrg354q8i","isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false},"FileListItemImage":{"widgetName":"FileListItemImage","onClick":"{{showModal('Zoom_Modal')}}","dynamicPropertyPathList":[],"topRow":1,"bottomRow":13,"parentRowSpace":10,"type":"IMAGE_WIDGET","parentColumnSpace":19.0625,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png","image":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.signedUrl;\n })();\n })}}","rightColumn":20,"objectFit":"contain","widgetId":"lh1sjszc93","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"enableDownload":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"enableRotation":true,"defaultImage":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false},"FileListItemName":{"widgetName":"FileListItemName","rightColumn":63,"textAlign":"LEFT","widgetId":"qyqv89mu1c","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"parentColumnSpace":true,"leftColumn":true,"fontSize":true,"text":true},"topRow":1,"bottomRow":8,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"lcz0rhije8","isLoading":false,"parentColumnSpace":19.0625,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.fileName;\n })();\n })}}"},"DeleteIcon":{"boxShadow":"NONE","widgetName":"DeleteIcon","onClick":"{{showModal('delete_modal')}}","buttonColor":"#DD4B34","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":63,"iconName":"trash","widgetId":"f8ipd8gbls","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"}},"widgetName":"File_List","listData":"{{ListFiles.data}}","isCanvas":true,"displayName":"List","iconSVG":"/static/media/icon.9925ee17.svg","topRow":9,"bottomRow":82,"parentRowSpace":10,"type":"LIST_WIDGET","hideCard":false,"gridGap":0,"parentColumnSpace":9.67822265625,"dynamicTriggerPathList":[{"key":"template.DownloadIcon.onClick"},{"key":"template.CopyURLIcon.onClick"}],"leftColumn":1,"dynamicBindingPathList":[{"key":"listData"},{"key":"template.FileListItemImage.image"},{"key":"template.FileListItemName.text"}],"gridType":"vertical","enhancements":true,"children":[{"widgetName":"Canvas14","displayName":"Canvas","topRow":0,"bottomRow":390,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":false,"hideCard":true,"dropDisabled":true,"openParentPropertyPane":true,"minHeight":400,"noPad":true,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"Container7","borderColor":"transparent","disallowCopy":true,"isCanvas":true,"displayName":"Container","iconSVG":"/static/media/icon.1977dca3.svg","topRow":0,"bottomRow":17,"dragDisabled":true,"type":"CONTAINER_WIDGET","hideCard":false,"openParentPropertyPane":true,"isDeletable":false,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas15","detachFromLayout":true,"displayName":"Canvas","widgetId":"lcz0rhije8","containerStyle":"none","topRow":0,"bottomRow":160,"parentRowSpace":1,"isVisible":true,"type":"CANVAS_WIDGET","canExtend":false,"version":1,"hideCard":true,"parentId":"66oc53smx3","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"EditIcon","onClick":"{{showModal('Edit_Modal')}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":39,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":45,"iconName":"edit","widgetId":"x5bft8h9vd","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"CopyURLIcon","onClick":"{{copyToClipboard(currentItem.signedUrl)}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":51,"iconName":"link","widgetId":"d2z5zj56j9","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"DownloadIcon","onClick":"{{navigateTo(currentItem.signedUrl, {})}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":57,"iconName":"download","widgetId":"ljk8fj5jc1","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"DeleteIcon","onClick":"{{showModal('delete_modal')}}","buttonColor":"#DD4B34","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":63,"iconName":"trash","widgetId":"f8ipd8gbls","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"widgetName":"FileListItemName","rightColumn":63,"textAlign":"LEFT","widgetId":"kmwv6dap5n","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"parentColumnSpace":true,"leftColumn":true,"fontSize":true,"text":true},"topRow":0,"bottomRow":7,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"lcz0rhije8","isLoading":false,"parentColumnSpace":19.0625,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{currentItem.fileName}}"},{"widgetName":"FileListItemImage","onClick":"{{showModal('Zoom_Modal')}}","dynamicPropertyPathList":[],"topRow":0,"bottomRow":13,"parentRowSpace":10,"type":"IMAGE_WIDGET","parentColumnSpace":19.0625,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png","image":"{{currentItem.signedUrl}}","rightColumn":20,"objectFit":"contain","widgetId":"4laf7e6wer","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"enableDownload":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"enableRotation":true,"defaultImage":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false}],"key":"29vrztch46"}],"borderWidth":"0","key":"cw0dtdoe0g","disablePropertyPane":true,"backgroundColor":"white","rightColumn":64,"widgetId":"66oc53smx3","containerStyle":"card","isVisible":true,"version":1,"parentId":"sh1yahe7kl","renderMode":"CANVAS","isLoading":false,"borderRadius":"0"}],"key":"29vrztch46","rightColumn":232.27734375,"detachFromLayout":true,"widgetId":"sh1yahe7kl","containerStyle":"none","isVisible":true,"version":1,"parentId":"cjgg2thzom","renderMode":"CANVAS","isLoading":false}],"privateWidgets":{"DownloadIcon":true,"EditIcon":true,"CopyURLIcon":true,"FileListItemImage":true,"FileListItemName":true,"DeleteIcon":true},"key":"x51ms5k6q9","backgroundColor":"transparent","rightColumn":63,"itemBackgroundColor":"#FFFFFF","widgetId":"cjgg2thzom","isVisible":true,"parentId":"6tz2s7ivi5","renderMode":"CANVAS","isLoading":false},{"widgetName":"search_input","dynamicPropertyPathList":[{"key":"onTextChanged"}],"displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":16.4169921875,"dynamicTriggerPathList":[{"key":"onTextChanged"}],"resetOnSubmit":true,"leftColumn":1,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"Search File Prefix","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":false,"onTextChanged":"{{ListFiles.run()}}","rightColumn":40,"widgetId":"why172fko6","isVisible":true,"label":"","version":2,"parentId":"6tz2s7ivi5","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]},{"widgetName":"Text6","rightColumn":64,"backgroundColor":"","textAlign":"LEFT","widgetId":"t54ituq472","topRow":0,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#2E3D49","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Bucket"},{"widgetName":"Upload_Files_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"1fxorj7v97","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":0,"detachFromLayout":true,"widgetId":"d8io5ijwj4","topRow":0,"bottomRow":620,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"1fxorj7v97","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[],"isDisabled":false}],"width":532,"height":600},{"widgetName":"delete_modal","rightColumn":0,"detachFromLayout":true,"widgetId":"9g0cw9adf8","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas6","rightColumn":0,"detachFromLayout":true,"widgetId":"ozvpoudxz2","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"9g0cw9adf8","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon2","rightColumn":64,"onClick":"{{closeModal('delete_modal')}}","color":"#040627","iconName":"cross","widgetId":"xkyh49z71e","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_WIDGET","version":1,"parentId":"ozvpoudxz2","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"iconSize":24},{"widgetName":"Text12","rightColumn":41,"textAlign":"LEFT","widgetId":"s1y44xm547","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete File"},{"widgetName":"Button10","rightColumn":48,"onClick":"{{closeModal('delete_modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"pi0t67rnwh","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Button11","rightColumn":64,"onClick":"{{\nDeleteFile.run(() => {closeModal('delete_modal'); \nListFiles.run();\n});\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"hp22uj3dra","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text13","rightColumn":64,"textAlign":"LEFT","widgetId":"oypa9ad1tg","topRow":5,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ozvpoudxz2","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete the file?\n\n{{File_List.selectedItem.fileName}}"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Edit_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"usealgbtyj","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas10","rightColumn":0,"detachFromLayout":true,"widgetId":"6i7m9kpuky","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"usealgbtyj","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon4","rightColumn":64,"onClick":"{{closeModal('Edit_Modal')}}","color":"#040627","iconName":"cross","widgetId":"pstfdcc1e4","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_WIDGET","version":1,"parentId":"6i7m9kpuky","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"iconSize":24},{"widgetName":"Text17","rightColumn":41,"textAlign":"LEFT","widgetId":"z64z3l112n","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update File"},{"widgetName":"Button15","rightColumn":44,"onClick":"{{closeModal('Edit_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"trc4e6ylcz","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":32,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"update_button","rightColumn":64,"onClick":"{{UpdateFile.run(() => {ListFiles.run();resetWidget('update_file_picker');closeModal('Edit_Modal');})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"},{"key":"isDisabled"}],"buttonColor":"#03B365","widgetId":"8lbthc9dml","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":44,"dynamicBindingPathList":[{"key":"isDisabled"}],"buttonVariant":"PRIMARY","text":"Update","isDisabled":"{{update_file_picker.files.length == 0}}"},{"widgetName":"Text18","rightColumn":17,"textAlign":"RIGHT","widgetId":"qb26g34etr","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6i7m9kpuky","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"File Name"},{"widgetName":"update_file_picker","displayName":"FilePicker","iconSVG":"/static/media/icon.7c5ad9c3.svg","topRow":14,"bottomRow":18,"parentRowSpace":10,"allowedFileTypes":[],"type":"FILE_PICKER_WIDGET_V2","hideCard":false,"animateLoading":true,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[],"leftColumn":22,"dynamicBindingPathList":[],"isDisabled":false,"key":"h2212wpg64","isRequired":false,"rightColumn":56,"isDefaultClickDisabled":true,"widgetId":"i8g6khu01a","defaultSelectedFiles":[],"isVisible":true,"label":"Select File","maxFileSize":"10","version":1,"fileDataType":"Base64","parentId":"6i7m9kpuky","selectedFiles":[],"renderMode":"CANVAS","isLoading":false,"files":[],"maxNumFiles":1},{"widgetName":"update_file_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":true,"key":"auxyd97lu3","validation":"true","isRequired":false,"rightColumn":64,"widgetId":"uabsu3mjt3","isVisible":true,"label":"","version":2,"parentId":"6i7m9kpuky","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{File_List.selectedItem.fileName}}"}],"isDisabled":false}],"width":456,"height":240},{"backgroundColor":"#FFFFFF","widgetName":"Container6","rightColumn":64,"widgetId":"yg1iyxq9kd","containerStyle":"card","topRow":5,"bottomRow":88,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"leftColumn":37,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas13","rightColumn":634,"detachFromLayout":true,"widgetId":"xv97g6rzgq","containerStyle":"none","topRow":0,"bottomRow":820,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"yg1iyxq9kd","minHeight":830,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Button8","rightColumn":46,"onClick":"{{closeModal('Upload_Files_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"bx8wok3aut","topRow":75,"bottomRow":79,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":31,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"template":{"Canvas7":{"widgetName":"Canvas7","rightColumn":256,"detachFromLayout":true,"widgetId":"oqhzaygncs","containerStyle":"none","topRow":0,"bottomRow":400,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"dropDisabled":true,"parentId":"0n30419eso","openParentPropertyPane":true,"minHeight":340,"isLoading":false,"noPad":true,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":["u3nvgafsdo"]},"update_files_name":{"widgetName":"update_files_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.4580078125,"resetOnSubmit":true,"leftColumn":23,"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'true';\n })();\n })}}","isRequired":false,"rightColumn":43,"widgetId":"yqxzzh2oqi","logBlackList":{"widgetName":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"autoFocus":true,"type":true,"hideCard":true,"minHeight":true,"animateLoading":true,"parentColumnSpace":true,"resetOnSubmit":true,"leftColumn":true,"labelStyle":true,"inputType":true,"isDisabled":true,"key":true,"isRequired":true,"rightColumn":true,"widgetId":true,"isVisible":true,"label":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"iconAlign":true,"defaultText":true},"isVisible":true,"label":"","version":2,"parentId":"romgsruzxz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.name;\n })();\n })}}"},"Image2":{"image":"{{selected_files.listData.map((currentItem) => currentItem.base64)}}","widgetName":"Image2","rightColumn":10,"onClick":"{{showModal('Zoom_Modal2')}}","objectFit":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'contain';\n })();\n })}}","widgetId":"ql8qs2xelx","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"defaultImage":true},"topRow":0,"bottomRow":6,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"romgsruzxz","isLoading":false,"maxZoomLevel":1,"parentColumnSpace":7.3125,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":0,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png"},"Container4":{"backgroundColor":"white","widgetName":"Container4","rightColumn":64,"disallowCopy":true,"widgetId":"u3nvgafsdo","containerStyle":"card","topRow":0,"bottomRow":8,"dragDisabled":true,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"oqhzaygncs","openParentPropertyPane":true,"isDeletable":false,"isLoading":false,"leftColumn":0,"children":["romgsruzxz"],"disablePropertyPane":true},"Canvas8":{"widgetName":"Canvas8","detachFromLayout":true,"widgetId":"romgsruzxz","containerStyle":"none","topRow":0,"bottomRow":180,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"u3nvgafsdo","minHeight":80,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":["vu7fb0dbt8","7zziet357m","ql8qs2xelx"]},"Text14":{"widgetName":"Text14","rightColumn":23,"textAlign":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'LEFT';\n })();\n })}}","widgetId":"vu7fb0dbt8","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"dynamicTriggerPathList":true,"parentColumnSpace":true,"dynamicBindingPathList":true,"leftColumn":true,"fontSize":true,"text":true,"textStyle":true},"topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"romgsruzxz","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":11,"fontSize":"PARAGRAPH","text":"File Name","textStyle":"HEADING"}},"widgetName":"selected_files","listData":"{{FilePicker.files}}","dynamicPropertyPathList":[{"key":"isVisible"}],"topRow":23,"bottomRow":75,"parentRowSpace":10,"type":"LIST_WIDGET","gridGap":0,"parentColumnSpace":8,"dynamicTriggerPathList":[{"key":"template.Image2.onClick"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"listData"},{"key":"template.update_files_name.defaultText"},{"key":"template.update_files_name.validation"}],"gridType":"vertical","enhancements":true,"children":[{"widgetName":"Canvas7","rightColumn":256,"detachFromLayout":true,"widgetId":"oqhzaygncs","containerStyle":"none","topRow":0,"bottomRow":510,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"dropDisabled":true,"parentId":"0n30419eso","openParentPropertyPane":true,"minHeight":520,"isLoading":false,"noPad":true,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"backgroundColor":"white","widgetName":"Container4","rightColumn":64,"disallowCopy":true,"widgetId":"u3nvgafsdo","containerStyle":"card","topRow":0,"bottomRow":14,"dragDisabled":true,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"oqhzaygncs","openParentPropertyPane":true,"isDeletable":false,"isLoading":false,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas8","detachFromLayout":true,"widgetId":"romgsruzxz","containerStyle":"none","topRow":0,"bottomRow":120,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"u3nvgafsdo","minHeight":120,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text14","rightColumn":31,"textAlign":"LEFT","widgetId":"vu7fb0dbt8","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"dynamicTriggerPathList":true,"parentColumnSpace":true,"dynamicBindingPathList":true,"leftColumn":true,"fontSize":true,"text":true,"textStyle":true},"topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"romgsruzxz","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":19,"fontSize":"PARAGRAPH","text":"File Name","textStyle":"HEADING"},{"image":"{{currentItem.base64}}","widgetName":"Image2","rightColumn":18,"onClick":"{{showModal('Zoom_Modal2')}}","objectFit":"contain","widgetId":"ql8qs2xelx","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"defaultImage":true},"topRow":0,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"romgsruzxz","isLoading":false,"maxZoomLevel":1,"parentColumnSpace":7.3125,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":0,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png"},{"widgetName":"update_files_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.4580078125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":60,"widgetId":"yqxzzh2oqi","logBlackList":{"widgetName":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"autoFocus":true,"type":true,"hideCard":true,"minHeight":true,"animateLoading":true,"parentColumnSpace":true,"resetOnSubmit":true,"leftColumn":true,"labelStyle":true,"inputType":true,"isDisabled":true,"key":true,"isRequired":true,"rightColumn":true,"widgetId":true,"isVisible":true,"label":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"iconAlign":true,"defaultText":true},"isVisible":true,"label":"","version":2,"parentId":"romgsruzxz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{currentItem.name}}"}]}],"disablePropertyPane":true}]}],"privateWidgets":{"update_files_name":true,"Image2":true,"Text14":true},"childAutoComplete":{"currentItem":{"data":"","base64":"","name":"","raw":"","id":"","text":"","type":""}},"backgroundColor":"","rightColumn":64,"itemBackgroundColor":"#FFFFFF","widgetId":"0n30419eso","isVisible":"{{FilePicker.files.length > 0}}","parentId":"xv97g6rzgq","isLoading":false},{"widgetName":"Text9","rightColumn":14,"textAlign":"LEFT","widgetId":"jc21bnjh92","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Upload Folder"},{"widgetName":"Text7","rightColumn":52,"textAlign":"LEFT","widgetId":"364shivyaz","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Upload New Files"},{"widgetName":"upload_button","rightColumn":63,"onClick":"{{\nFilePicker.files.forEach((file, index) => {\n\tCreateFile.run((response, params) => { showAlert('File Uploaded','success'); \nif (params.isLastFile) {\n\tListFiles.run(() => {closeModal('Upload_Files_Modal'); resetWidget('folder_name', true);\t\t\t\t\tresetWidget('FilePicker', true);\nresetWidget('update_files_name', true);\n})\t\n}\n}, () => showAlert('File Upload Failed','error'), {fileIndex: index, name: selected_files.items[index].update_files_name.text, isLastFile: index == (FilePicker.files.length - 1), });\n\treturn true;\n})\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"},{"key":"isDisabled"}],"buttonColor":"#03B365","widgetId":"1uava20nxi","topRow":75,"bottomRow":79,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[{"key":"isDisabled"}],"buttonVariant":"PRIMARY","text":"Upload","isDisabled":"{{ selected_files.items.length == 0 || selected_files.items.map((file) => file.update_files_name.text).includes(\"\") }}"},{"widgetName":"Text19","rightColumn":52,"textAlign":"LEFT","dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"9wh2ereoy9","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":"{{FilePicker.files.length > 0}}","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"parentColumnSpace":8.0458984375,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[{"key":"isVisible"}],"fontSize":"HEADING3","text":"Selected Files"},{"widgetName":"FilePicker","dynamicPropertyPathList":[],"displayName":"FilePicker","iconSVG":"/static/media/icon.7c5ad9c3.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"allowedFileTypes":[],"type":"FILE_PICKER_WIDGET_V2","hideCard":false,"animateLoading":true,"parentColumnSpace":4.86865234375,"leftColumn":31,"isDisabled":false,"key":"h2212wpg64","onFilesSelected":"","isRequired":false,"rightColumn":58,"isDefaultClickDisabled":true,"widgetId":"8l6lm067zw","defaultSelectedFiles":[],"isVisible":true,"label":"Select Files","maxFileSize":5,"version":1,"fileDataType":"Base64","parentId":"xv97g6rzgq","selectedFiles":[],"renderMode":"CANVAS","isLoading":false,"files":[],"maxNumFiles":1},{"widgetName":"folder_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.8955078125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"folder/sub-folder","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"215nlsqncm","isVisible":true,"label":"","version":2,"parentId":"xv97g6rzgq","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}]}}],"slug":"s3","isHidden":false},"new":true,"unpublishedPage":{"name":"S3","userPermissions":[],"layouts":[{"new":false,"id":"S3","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["60 * 24","search_input.text"],"name":"ListFiles","timeoutInMillisecond":10000,"id":"S3_ListFiles"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":912,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":1300,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":53,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Zoom_Modal2","rightColumn":0,"detachFromLayout":true,"widgetId":"kqxoe40pg6","topRow":89,"bottomRow":89,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas9Copy","rightColumn":0,"detachFromLayout":true,"widgetId":"80wzwajsst","topRow":0,"bottomRow":590,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"kqxoe40pg6","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon3Copy","rightColumn":64,"onClick":"{{closeModal('Zoom_Modal2')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"8kw9kfcd5y","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"80wzwajsst","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text15Copy","rightColumn":41,"textAlign":"LEFT","widgetId":"vk710q1v3s","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"80wzwajsst","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Zoom Image"},{"widgetName":"Button13Copy","rightColumn":63,"onClick":"{{closeModal('Zoom_Modal2')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"lfiwss1u3w","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"80wzwajsst","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Close","isDisabled":false},{"image":"{{selected_files.selectedItem.base64}}","widgetName":"Image3Copy","rightColumn":64,"objectFit":"contain","widgetId":"2bewgakjx9","topRow":6,"bottomRow":51,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"80wzwajsst","isLoading":false,"maxZoomLevel":8,"parentColumnSpace":8,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png"}],"isDisabled":false}],"width":532,"height":600},{"backgroundColor":"#FFFFFF","widgetName":"Container3","rightColumn":37,"widgetId":"th4d9oxy8z","containerStyle":"card","topRow":5,"bottomRow":88,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":634,"detachFromLayout":true,"widgetId":"6tz2s7ivi5","containerStyle":"none","topRow":0,"bottomRow":840,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"th4d9oxy8z","minHeight":830,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"template":{"DownloadIcon":{"boxShadow":"NONE","widgetName":"DownloadIcon","onClick":"{{navigateTo(currentItem.signedUrl, {})}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":57,"iconName":"download","widgetId":"ljk8fj5jc1","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"CopyURLIcon":{"boxShadow":"NONE","widgetName":"CopyURLIcon","onClick":"{{copyToClipboard(currentItem.signedUrl)}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":51,"iconName":"link","widgetId":"d2z5zj56j9","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"EditIcon":{"boxShadow":"NONE","widgetName":"EditIcon","onClick":"{{showModal('Edit_Modal')}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":39,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":45,"iconName":"edit","widgetId":"x5bft8h9vd","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"Text21":{"widgetName":"Text21","rightColumn":24,"textAlign":"LEFT","displayName":"Text","iconSVG":"/static/media/icon.e6c93592.svg","widgetId":"nu44q8kd9p","topRow":4,"bottomRow":8,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"hideCard":false,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[{"key":"text"}],"leftColumn":16,"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem) => currentItem.id)}}","textStyle":"BODY","key":"xvmvdekk3s"},"Text20":{"widgetName":"Text20","rightColumn":28,"textAlign":"LEFT","displayName":"Text","iconSVG":"/static/media/icon.e6c93592.svg","widgetId":"thgbdemmiw","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"hideCard":false,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[{"key":"text"}],"leftColumn":16,"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem) => currentItem.name)}}","textStyle":"HEADING","key":"xvmvdekk3s"},"Image3":{"widgetName":"Image3","displayName":"Image","iconSVG":"/static/media/icon.52d8fb96.svg","topRow":0,"bottomRow":8.4,"type":"IMAGE_WIDGET","hideCard":false,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","dynamicBindingPathList":[{"key":"image"}],"leftColumn":0,"defaultImage":"https://assets.appsmith.com/widgets/default.png","key":"lsc53q139g","image":"{{File_List.listData.map((currentItem) => currentItem.img)}}","rightColumn":16,"objectFit":"contain","widgetId":"2rrg354q8i","isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false},"FileListItemImage":{"widgetName":"FileListItemImage","onClick":"{{showModal('Zoom_Modal')}}","dynamicPropertyPathList":[],"topRow":1,"bottomRow":13,"parentRowSpace":10,"type":"IMAGE_WIDGET","parentColumnSpace":19.0625,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png","image":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.signedUrl;\n })();\n })}}","rightColumn":20,"objectFit":"contain","widgetId":"lh1sjszc93","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"enableDownload":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"enableRotation":true,"defaultImage":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false},"FileListItemName":{"widgetName":"FileListItemName","rightColumn":63,"textAlign":"LEFT","widgetId":"qyqv89mu1c","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"parentColumnSpace":true,"leftColumn":true,"fontSize":true,"text":true},"topRow":1,"bottomRow":8,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"lcz0rhije8","isLoading":false,"parentColumnSpace":19.0625,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.fileName;\n })();\n })}}"},"DeleteIcon":{"boxShadow":"NONE","widgetName":"DeleteIcon","onClick":"{{showModal('delete_modal')}}","buttonColor":"#DD4B34","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":63,"iconName":"trash","widgetId":"f8ipd8gbls","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"}},"widgetName":"File_List","listData":"{{ListFiles.data}}","isCanvas":true,"displayName":"List","iconSVG":"/static/media/icon.9925ee17.svg","topRow":9,"bottomRow":82,"parentRowSpace":10,"type":"LIST_WIDGET","hideCard":false,"gridGap":0,"parentColumnSpace":9.67822265625,"dynamicTriggerPathList":[{"key":"template.DownloadIcon.onClick"},{"key":"template.CopyURLIcon.onClick"}],"leftColumn":1,"dynamicBindingPathList":[{"key":"listData"},{"key":"template.FileListItemImage.image"},{"key":"template.FileListItemName.text"}],"gridType":"vertical","enhancements":true,"children":[{"widgetName":"Canvas14","displayName":"Canvas","topRow":0,"bottomRow":390,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":false,"hideCard":true,"dropDisabled":true,"openParentPropertyPane":true,"minHeight":400,"noPad":true,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"Container7","borderColor":"transparent","disallowCopy":true,"isCanvas":true,"displayName":"Container","iconSVG":"/static/media/icon.1977dca3.svg","topRow":0,"bottomRow":17,"dragDisabled":true,"type":"CONTAINER_WIDGET","hideCard":false,"openParentPropertyPane":true,"isDeletable":false,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas15","detachFromLayout":true,"displayName":"Canvas","widgetId":"lcz0rhije8","containerStyle":"none","topRow":0,"bottomRow":160,"parentRowSpace":1,"isVisible":true,"type":"CANVAS_WIDGET","canExtend":false,"version":1,"hideCard":true,"parentId":"66oc53smx3","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"EditIcon","onClick":"{{showModal('Edit_Modal')}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":39,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":45,"iconName":"edit","widgetId":"x5bft8h9vd","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"CopyURLIcon","onClick":"{{copyToClipboard(currentItem.signedUrl)}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":51,"iconName":"link","widgetId":"d2z5zj56j9","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"DownloadIcon","onClick":"{{navigateTo(currentItem.signedUrl, {})}}","buttonColor":"#03B365","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":57,"iconName":"download","widgetId":"ljk8fj5jc1","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"DeleteIcon","onClick":"{{showModal('delete_modal')}}","buttonColor":"#DD4B34","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":63,"iconName":"trash","widgetId":"f8ipd8gbls","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"widgetName":"FileListItemName","rightColumn":63,"textAlign":"LEFT","widgetId":"kmwv6dap5n","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"parentColumnSpace":true,"leftColumn":true,"fontSize":true,"text":true},"topRow":0,"bottomRow":7,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"lcz0rhije8","isLoading":false,"parentColumnSpace":19.0625,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{currentItem.fileName}}"},{"widgetName":"FileListItemImage","onClick":"{{showModal('Zoom_Modal')}}","dynamicPropertyPathList":[],"topRow":0,"bottomRow":13,"parentRowSpace":10,"type":"IMAGE_WIDGET","parentColumnSpace":19.0625,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png","image":"{{currentItem.signedUrl}}","rightColumn":20,"objectFit":"contain","widgetId":"4laf7e6wer","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"enableDownload":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"enableRotation":true,"defaultImage":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false}],"key":"29vrztch46"}],"borderWidth":"0","key":"cw0dtdoe0g","disablePropertyPane":true,"backgroundColor":"white","rightColumn":64,"widgetId":"66oc53smx3","containerStyle":"card","isVisible":true,"version":1,"parentId":"sh1yahe7kl","renderMode":"CANVAS","isLoading":false,"borderRadius":"0"}],"key":"29vrztch46","rightColumn":232.27734375,"detachFromLayout":true,"widgetId":"sh1yahe7kl","containerStyle":"none","isVisible":true,"version":1,"parentId":"cjgg2thzom","renderMode":"CANVAS","isLoading":false}],"privateWidgets":{"DownloadIcon":true,"EditIcon":true,"CopyURLIcon":true,"FileListItemImage":true,"FileListItemName":true,"DeleteIcon":true},"key":"x51ms5k6q9","backgroundColor":"transparent","rightColumn":63,"itemBackgroundColor":"#FFFFFF","widgetId":"cjgg2thzom","isVisible":true,"parentId":"6tz2s7ivi5","renderMode":"CANVAS","isLoading":false},{"widgetName":"search_input","dynamicPropertyPathList":[{"key":"onTextChanged"}],"displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":16.4169921875,"dynamicTriggerPathList":[{"key":"onTextChanged"}],"resetOnSubmit":true,"leftColumn":1,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"Search File Prefix","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":false,"onTextChanged":"{{ListFiles.run()}}","rightColumn":40,"widgetId":"why172fko6","isVisible":true,"label":"","version":2,"parentId":"6tz2s7ivi5","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]},{"widgetName":"Text6","rightColumn":64,"backgroundColor":"","textAlign":"LEFT","widgetId":"t54ituq472","topRow":0,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#2E3D49","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Bucket"},{"widgetName":"Upload_Files_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"1fxorj7v97","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":0,"detachFromLayout":true,"widgetId":"d8io5ijwj4","topRow":0,"bottomRow":620,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"1fxorj7v97","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[],"isDisabled":false}],"width":532,"height":600},{"widgetName":"delete_modal","rightColumn":0,"detachFromLayout":true,"widgetId":"9g0cw9adf8","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas6","rightColumn":0,"detachFromLayout":true,"widgetId":"ozvpoudxz2","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"9g0cw9adf8","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon2","rightColumn":64,"onClick":"{{closeModal('delete_modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"xkyh49z71e","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"ozvpoudxz2","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text12","rightColumn":41,"textAlign":"LEFT","widgetId":"s1y44xm547","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete File"},{"widgetName":"Button10","rightColumn":48,"onClick":"{{closeModal('delete_modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"pi0t67rnwh","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Button11","rightColumn":64,"onClick":"{{\nDeleteFile.run(() => {closeModal('delete_modal'); \nListFiles.run();\n});\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"hp22uj3dra","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text13","rightColumn":64,"textAlign":"LEFT","widgetId":"oypa9ad1tg","topRow":5,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ozvpoudxz2","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete the file?\n\n{{File_List.selectedItem.fileName}}"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Edit_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"usealgbtyj","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas10","rightColumn":0,"detachFromLayout":true,"widgetId":"6i7m9kpuky","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"usealgbtyj","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon4","rightColumn":64,"onClick":"{{closeModal('Edit_Modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"pstfdcc1e4","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"6i7m9kpuky","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text17","rightColumn":41,"textAlign":"LEFT","widgetId":"z64z3l112n","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update File"},{"widgetName":"Button15","rightColumn":44,"onClick":"{{closeModal('Edit_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"trc4e6ylcz","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":32,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"update_button","rightColumn":64,"onClick":"{{UpdateFile.run(() => {ListFiles.run();resetWidget('update_file_picker');closeModal('Edit_Modal');})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"},{"key":"isDisabled"}],"buttonColor":"#03B365","widgetId":"8lbthc9dml","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":44,"dynamicBindingPathList":[{"key":"isDisabled"}],"buttonVariant":"PRIMARY","text":"Update","isDisabled":"{{update_file_picker.files.length == 0}}"},{"widgetName":"Text18","rightColumn":17,"textAlign":"RIGHT","widgetId":"qb26g34etr","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6i7m9kpuky","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"File Name"},{"widgetName":"update_file_picker","displayName":"FilePicker","iconSVG":"/static/media/icon.7c5ad9c3.svg","topRow":14,"bottomRow":18,"parentRowSpace":10,"allowedFileTypes":[],"type":"FILE_PICKER_WIDGET_V2","hideCard":false,"animateLoading":true,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[],"leftColumn":22,"dynamicBindingPathList":[],"isDisabled":false,"key":"h2212wpg64","isRequired":false,"rightColumn":56,"isDefaultClickDisabled":true,"widgetId":"i8g6khu01a","defaultSelectedFiles":[],"isVisible":true,"label":"Select File","maxFileSize":"10","version":1,"fileDataType":"Base64","parentId":"6i7m9kpuky","selectedFiles":[],"renderMode":"CANVAS","isLoading":false,"files":[],"maxNumFiles":1},{"widgetName":"update_file_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":true,"key":"auxyd97lu3","validation":"true","isRequired":false,"rightColumn":64,"widgetId":"uabsu3mjt3","isVisible":true,"label":"","version":2,"parentId":"6i7m9kpuky","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{File_List.selectedItem.fileName}}"}],"isDisabled":false}],"width":456,"height":240},{"backgroundColor":"#FFFFFF","widgetName":"Container6","rightColumn":64,"widgetId":"yg1iyxq9kd","containerStyle":"card","topRow":5,"bottomRow":88,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"leftColumn":37,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas13","rightColumn":634,"detachFromLayout":true,"widgetId":"xv97g6rzgq","containerStyle":"none","topRow":0,"bottomRow":820,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"yg1iyxq9kd","minHeight":830,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Button8","rightColumn":46,"onClick":"{{closeModal('Upload_Files_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"bx8wok3aut","topRow":75,"bottomRow":79,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":31,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"template":{"Canvas7":{"widgetName":"Canvas7","rightColumn":256,"detachFromLayout":true,"widgetId":"oqhzaygncs","containerStyle":"none","topRow":0,"bottomRow":400,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"dropDisabled":true,"parentId":"0n30419eso","openParentPropertyPane":true,"minHeight":340,"isLoading":false,"noPad":true,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":["u3nvgafsdo"]},"update_files_name":{"widgetName":"update_files_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.4580078125,"resetOnSubmit":true,"leftColumn":23,"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'true';\n })();\n })}}","isRequired":false,"rightColumn":43,"widgetId":"yqxzzh2oqi","logBlackList":{"widgetName":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"autoFocus":true,"type":true,"hideCard":true,"minHeight":true,"animateLoading":true,"parentColumnSpace":true,"resetOnSubmit":true,"leftColumn":true,"labelStyle":true,"inputType":true,"isDisabled":true,"key":true,"isRequired":true,"rightColumn":true,"widgetId":true,"isVisible":true,"label":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"iconAlign":true,"defaultText":true},"isVisible":true,"label":"","version":2,"parentId":"romgsruzxz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.name;\n })();\n })}}"},"Image2":{"image":"{{selected_files.listData.map((currentItem) => currentItem.base64)}}","widgetName":"Image2","rightColumn":10,"onClick":"{{showModal('Zoom_Modal2')}}","objectFit":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'contain';\n })();\n })}}","widgetId":"ql8qs2xelx","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"defaultImage":true},"topRow":0,"bottomRow":6,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"romgsruzxz","isLoading":false,"maxZoomLevel":1,"parentColumnSpace":7.3125,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":0,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png"},"Container4":{"backgroundColor":"white","widgetName":"Container4","rightColumn":64,"disallowCopy":true,"widgetId":"u3nvgafsdo","containerStyle":"card","topRow":0,"bottomRow":8,"dragDisabled":true,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"oqhzaygncs","openParentPropertyPane":true,"isDeletable":false,"isLoading":false,"leftColumn":0,"children":["romgsruzxz"],"disablePropertyPane":true},"Canvas8":{"widgetName":"Canvas8","detachFromLayout":true,"widgetId":"romgsruzxz","containerStyle":"none","topRow":0,"bottomRow":180,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"u3nvgafsdo","minHeight":80,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":["vu7fb0dbt8","7zziet357m","ql8qs2xelx"]},"Text14":{"widgetName":"Text14","rightColumn":23,"textAlign":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'LEFT';\n })();\n })}}","widgetId":"vu7fb0dbt8","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"dynamicTriggerPathList":true,"parentColumnSpace":true,"dynamicBindingPathList":true,"leftColumn":true,"fontSize":true,"text":true,"textStyle":true},"topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"romgsruzxz","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":11,"fontSize":"PARAGRAPH","text":"File Name","textStyle":"HEADING"}},"widgetName":"selected_files","listData":"{{FilePicker.files}}","dynamicPropertyPathList":[{"key":"isVisible"}],"topRow":23,"bottomRow":75,"parentRowSpace":10,"type":"LIST_WIDGET","gridGap":0,"parentColumnSpace":8,"dynamicTriggerPathList":[{"key":"template.Image2.onClick"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"listData"},{"key":"template.update_files_name.defaultText"},{"key":"template.update_files_name.validation"}],"gridType":"vertical","enhancements":true,"children":[{"widgetName":"Canvas7","rightColumn":256,"detachFromLayout":true,"widgetId":"oqhzaygncs","containerStyle":"none","topRow":0,"bottomRow":510,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"dropDisabled":true,"parentId":"0n30419eso","openParentPropertyPane":true,"minHeight":520,"isLoading":false,"noPad":true,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"backgroundColor":"white","widgetName":"Container4","rightColumn":64,"disallowCopy":true,"widgetId":"u3nvgafsdo","containerStyle":"card","topRow":0,"bottomRow":14,"dragDisabled":true,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"oqhzaygncs","openParentPropertyPane":true,"isDeletable":false,"isLoading":false,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas8","detachFromLayout":true,"widgetId":"romgsruzxz","containerStyle":"none","topRow":0,"bottomRow":120,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"u3nvgafsdo","minHeight":120,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text14","rightColumn":31,"textAlign":"LEFT","widgetId":"vu7fb0dbt8","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"dynamicTriggerPathList":true,"parentColumnSpace":true,"dynamicBindingPathList":true,"leftColumn":true,"fontSize":true,"text":true,"textStyle":true},"topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"romgsruzxz","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":19,"fontSize":"PARAGRAPH","text":"File Name","textStyle":"HEADING"},{"image":"{{currentItem.base64}}","widgetName":"Image2","rightColumn":18,"onClick":"{{showModal('Zoom_Modal2')}}","objectFit":"contain","widgetId":"ql8qs2xelx","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"defaultImage":true},"topRow":0,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"romgsruzxz","isLoading":false,"maxZoomLevel":1,"parentColumnSpace":7.3125,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":0,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png"},{"widgetName":"update_files_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.4580078125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":60,"widgetId":"yqxzzh2oqi","logBlackList":{"widgetName":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"autoFocus":true,"type":true,"hideCard":true,"minHeight":true,"animateLoading":true,"parentColumnSpace":true,"resetOnSubmit":true,"leftColumn":true,"labelStyle":true,"inputType":true,"isDisabled":true,"key":true,"isRequired":true,"rightColumn":true,"widgetId":true,"isVisible":true,"label":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"iconAlign":true,"defaultText":true},"isVisible":true,"label":"","version":2,"parentId":"romgsruzxz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{currentItem.name}}"}]}],"disablePropertyPane":true}]}],"privateWidgets":{"update_files_name":true,"Image2":true,"Text14":true},"childAutoComplete":{"currentItem":{"data":"","base64":"","name":"","raw":"","id":"","text":"","type":""}},"backgroundColor":"","rightColumn":64,"itemBackgroundColor":"#FFFFFF","widgetId":"0n30419eso","isVisible":"{{FilePicker.files.length > 0}}","parentId":"xv97g6rzgq","isLoading":false},{"widgetName":"Text9","rightColumn":14,"textAlign":"LEFT","widgetId":"jc21bnjh92","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Upload Folder"},{"widgetName":"Text7","rightColumn":52,"textAlign":"LEFT","widgetId":"364shivyaz","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Upload New Files"},{"widgetName":"upload_button","rightColumn":63,"onClick":"{{\nFilePicker.files.forEach((file, index) => {\n\tCreateFile.run((response, params) => { showAlert('File Uploaded','success'); \nif (params.isLastFile) {\n\tListFiles.run(() => {closeModal('Upload_Files_Modal'); resetWidget('folder_name', true);\t\t\t\t\tresetWidget('FilePicker', true);\nresetWidget('update_files_name', true);\n})\t\n}\n}, () => showAlert('File Upload Failed','error'), {fileIndex: index, name: selected_files.items[index].update_files_name.text, isLastFile: index == (FilePicker.files.length - 1), });\n\treturn true;\n})\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"},{"key":"isDisabled"}],"buttonColor":"#03B365","widgetId":"1uava20nxi","topRow":75,"bottomRow":79,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[{"key":"isDisabled"}],"buttonVariant":"PRIMARY","text":"Upload","isDisabled":"{{ selected_files.items.length == 0 || selected_files.items.map((file) => file.update_files_name.text).includes(\"\") }}"},{"widgetName":"Text19","rightColumn":52,"textAlign":"LEFT","dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"9wh2ereoy9","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":"{{FilePicker.files.length > 0}}","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"parentColumnSpace":8.0458984375,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[{"key":"isVisible"}],"fontSize":"HEADING3","text":"Selected Files"},{"widgetName":"FilePicker","dynamicPropertyPathList":[],"displayName":"FilePicker","iconSVG":"/static/media/icon.7c5ad9c3.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"allowedFileTypes":[],"type":"FILE_PICKER_WIDGET_V2","hideCard":false,"animateLoading":true,"parentColumnSpace":4.86865234375,"leftColumn":31,"isDisabled":false,"key":"h2212wpg64","onFilesSelected":"","isRequired":false,"rightColumn":58,"isDefaultClickDisabled":true,"widgetId":"8l6lm067zw","defaultSelectedFiles":[],"isVisible":true,"label":"Select Files","maxFileSize":5,"version":1,"fileDataType":"Base64","parentId":"xv97g6rzgq","selectedFiles":[],"renderMode":"CANVAS","isLoading":false,"files":[],"maxNumFiles":1},{"widgetName":"folder_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.8955078125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"folder/sub-folder","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"215nlsqncm","isVisible":true,"label":"","version":2,"parentId":"xv97g6rzgq","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}]}}],"slug":"s3","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc2"},{"publishedPage":{"name":"Admin","userPermissions":[],"layouts":[{"new":false,"id":"Admin","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"API","jsonPathKeys":[],"name":"get_exported_app","timeoutInMillisecond":10000,"id":"Admin_get_exported_app"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":910,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Form1","backgroundColor":"#2E3D49","rightColumn":45,"widgetId":"hdpwx2szs0","topRow":5,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":554.75,"detachFromLayout":true,"widgetId":"kwx6oz4fub","containerStyle":"none","topRow":0,"bottomRow":800,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"hdpwx2szs0","minHeight":810,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text1","rightColumn":53,"textAlign":"LEFT","widgetId":"7fqtlu52np","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update App Template"},{"widgetName":"Text2","rightColumn":62,"textAlign":"LEFT","widgetId":"w2l08fshj2","topRow":9,"bottomRow":61,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"shouldScroll":true,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{\"<pre>\" + JSON.stringify(get_exported_app.data, null, 2) + \"</pre>\" || \"Fetch The App\"}}"},{"widgetName":"Button1","rightColumn":21,"onClick":"{{\n get_exported_app.run(() => {\n \tconst arr = JSON.parse(datasource_arr.text);\n\t\tarr.map((row) => { get_datasource_structure.run((res, params) => {\n storeValue(params.name, res); \n },undefined, row)\n })\n })\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"2vtg0qdlqv","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":3,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Fetch App","isDisabled":false},{"widgetName":"Button2","rightColumn":63,"onClick":"{{update_template.run(() => showAlert('Template Updated','success'), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"isDisabled"}],"buttonColor":"#03B365","widgetId":"jg23u09rwk","topRow":73,"bottomRow":77,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":4,"dynamicBindingPathList":[{"key":"isDisabled"}],"buttonVariant":"PRIMARY","text":"Deploy","isDisabled":"{{get_exported_app.data.exportedApplication === undefined}}"},{"widgetName":"Text3","rightColumn":12,"textAlign":"LEFT","widgetId":"y57v1yp7vb","topRow":63,"bottomRow":67,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Branch"},{"widgetName":"Text4","rightColumn":63,"backgroundColor":"#DD4B34","textAlign":"LEFT","widgetId":"fanskapltd","topRow":69,"bottomRow":73,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Note : Please use update-crud-template branch to avoid TCs failing in release"},{"widgetName":"branch_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":63,"bottomRow":67,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.34765625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":13,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"q59sbo2ecd","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"t05x88vwee","isVisible":true,"label":"","version":2,"parentId":"kwx6oz4fub","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"update-crud-template"}]}]},{"widgetName":"datasource_arr","rightColumn":16,"textAlign":"LEFT","widgetId":"znji9afu2q","topRow":1,"bottomRow":35,"parentRowSpace":10,"isVisible":false,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"[\n{ \"name\":\"mongo-plugin\",\n\"id\": \"61d6b292053d041e6d486fbb\"\n},\n{ \"name\":\"postgres-plugin\",\n\"id\": \"61764f91ba7e887d03bc35d3\"\n}\n]"}]}}],"slug":"admin","isHidden":false},"new":true,"unpublishedPage":{"name":"Admin","userPermissions":[],"layouts":[{"new":false,"id":"Admin","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"API","confirmBeforeExecute":false,"jsonPathKeys":[],"name":"get_exported_app","timeoutInMillisecond":10000,"id":"Admin_get_exported_app"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":912,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":910,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":53,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Form1","backgroundColor":"#2E3D49","rightColumn":45,"widgetId":"hdpwx2szs0","topRow":5,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":554.75,"detachFromLayout":true,"widgetId":"kwx6oz4fub","containerStyle":"none","topRow":0,"bottomRow":800,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"hdpwx2szs0","minHeight":810,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text1","rightColumn":53,"textAlign":"LEFT","widgetId":"7fqtlu52np","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update App Template"},{"widgetName":"Text2","rightColumn":62,"textAlign":"LEFT","widgetId":"w2l08fshj2","topRow":9,"bottomRow":61,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"shouldScroll":true,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{\"<pre>\" + JSON.stringify(get_exported_app.data, null, 2) + \"</pre>\" || \"Fetch The App\"}}"},{"widgetName":"Button1","rightColumn":21,"onClick":"{{\n get_exported_app.run(() => {\n \tconst arr = JSON.parse(datasource_arr.text);\n\t\tarr.map((row) => { get_datasource_structure.run((res, params) => {\n storeValue(params.name, res); \n },undefined, row)\n })\n })\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"2vtg0qdlqv","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":3,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Fetch App","isDisabled":false},{"widgetName":"Button2","rightColumn":63,"onClick":"{{update_template.run(() => showAlert('Template Updated','success'), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"isDisabled"}],"buttonColor":"#03B365","widgetId":"jg23u09rwk","topRow":73,"bottomRow":77,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":4,"dynamicBindingPathList":[{"key":"isDisabled"}],"buttonVariant":"PRIMARY","text":"Deploy","isDisabled":"{{get_exported_app.data.exportedApplication === undefined}}"},{"widgetName":"Text3","rightColumn":12,"textAlign":"LEFT","widgetId":"y57v1yp7vb","topRow":63,"bottomRow":67,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Branch"},{"widgetName":"Text4","rightColumn":63,"backgroundColor":"#DD4B34","textAlign":"LEFT","widgetId":"fanskapltd","topRow":69,"bottomRow":73,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Note : Please use update-crud-template branch to avoid TCs failing in release"},{"widgetName":"branch_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":63,"bottomRow":67,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.34765625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":13,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"q59sbo2ecd","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"t05x88vwee","isVisible":true,"label":"","version":2,"parentId":"kwx6oz4fub","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"update-crud-template"}]}]},{"widgetName":"datasource_arr","rightColumn":16,"textAlign":"LEFT","widgetId":"znji9afu2q","topRow":1,"bottomRow":35,"parentRowSpace":10,"isVisible":false,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"[\n{ \"name\":\"mongo-plugin\",\n\"id\": \"61d6b292053d041e6d486fbb\"\n},\n{ \"name\":\"postgres-plugin\",\n\"id\": \"61764f91ba7e887d03bc35d3\"\n}\n]"}]}}],"slug":"admin","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc3"},{"publishedPage":{"name":"Page Generator","userPermissions":[],"layouts":[{"new":false,"id":"Page Generator","userPermissions":[],"layoutOnLoadActions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":850,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":860,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Tabs1","rightColumn":45,"widgetId":"jalvzswyyk","defaultTab":"SQL","topRow":11,"bottomRow":52,"shouldShowTabs":true,"parentRowSpace":10,"tabsObj":{"tab1":{"widgetId":"nyka98xqpv","index":0,"label":"SQL","id":"tab1","isVisible":true},"tab2":{"widgetId":"neexe4fljs","index":1,"label":"GSheet","id":"tab2","isVisible":true},"tab7qxuerb9p7":{"widgetId":"4yqoh4fjmv","id":"tab7qxuerb9p7","label":"Mongo","isVisible":true}},"isVisible":true,"type":"TABS_WIDGET","version":3,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":16,"dynamicBindingPathList":[],"children":[{"tabId":"tab1","tabName":"SQL","rightColumn":634,"widgetName":"Canvas2","detachFromLayout":true,"widgetId":"nyka98xqpv","topRow":0,"bottomRow":400,"parentRowSpace":1,"type":"CANVAS_WIDGET","parentId":"jalvzswyyk","isLoading":false,"renderMode":"CANVAS","minHeight":410,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text2","rightColumn":14,"textAlign":"RIGHT","widgetId":"957c72jpan","topRow":3,"bottomRow":7,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Datasource URL"},{"widgetName":"Text4","rightColumn":14,"textAlign":"RIGHT","widgetId":"nz74xi3ae3","topRow":10,"bottomRow":14,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Table Name"},{"widgetName":"Text6","rightColumn":14,"textAlign":"RIGHT","widgetId":"s1i89k31f5","topRow":17,"bottomRow":21,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Columns to Select"},{"widgetName":"Text7","rightColumn":14,"textAlign":"RIGHT","widgetId":"rbacxz6brz","topRow":25,"bottomRow":29,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Column to Search"},{"resetFormOnClick":false,"widgetName":"FormButton1","rightColumn":63,"onClick":"{{generate_sql_app.run(() => showAlert('Page Created!','success'), () => {})}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"n6220hgzzs","topRow":31,"bottomRow":35,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"nyka98xqpv","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate"},{"widgetName":"datasource_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":3,"bottomRow":7,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"fk5njkiu28","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"tableName_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"v6vho5uqct","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"select_cols_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":17,"bottomRow":21,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"e1j5kngy1t","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"search_col_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":25,"bottomRow":29,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"cqxwse0717","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]},{"tabId":"tab2","tabName":"GSheet","rightColumn":634,"widgetName":"Canvas3","detachFromLayout":true,"widgetId":"neexe4fljs","topRow":0,"bottomRow":400,"parentRowSpace":1,"type":"CANVAS_WIDGET","parentId":"jalvzswyyk","isLoading":false,"renderMode":"CANVAS","minHeight":410,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text8","rightColumn":16,"textAlign":"RIGHT","widgetId":"3ghywz6tk6","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"DataSource URL"},{"widgetName":"Text9","rightColumn":16,"textAlign":"RIGHT","widgetId":"r6o12im1qd","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"SpreadSheet URL"},{"widgetName":"Text10","rightColumn":16,"textAlign":"RIGHT","widgetId":"k0ul3uaoph","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Sheet Name"},{"widgetName":"Text11","rightColumn":16,"textAlign":"RIGHT","widgetId":"l1r1tfbx6y","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Table Header Index"},{"widgetName":"Button1","rightColumn":62,"onClick":"{{generate_gsheet_app.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"zzsh2d5rns","topRow":30,"bottomRow":34,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate","isDisabled":false},{"widgetName":"gsheet_ds_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"j61fbsst0i","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"spreadsheet_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"vm21ddffi6","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"sheet_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"5r5hxd2qs8","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"header_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"z3nz99y80l","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]},{"tabId":"tab7qxuerb9p7","widgetName":"Canvas4","tabName":"Mongo","rightColumn":574.5625,"detachFromLayout":true,"widgetId":"4yqoh4fjmv","containerStyle":"none","topRow":1,"bottomRow":400,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"jalvzswyyk","minHeight":410,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text12","rightColumn":17,"textAlign":"RIGHT","widgetId":"4l1uqhf2au","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Datasource URL"},{"widgetName":"Text13","rightColumn":17,"textAlign":"RIGHT","widgetId":"0y3rz6ufib","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Collection Name"},{"widgetName":"Text14","rightColumn":17,"textAlign":"RIGHT","widgetId":"s1fhjft9to","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Keys to Fetch"},{"widgetName":"Text15","rightColumn":17,"textAlign":"RIGHT","widgetId":"rwi67ouhe1","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Key to Search"},{"widgetName":"Button2","rightColumn":62,"onClick":"{{generate_mongo_app.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"6ui5kmqebf","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate","isDisabled":false},{"widgetName":"mongo_ds_url","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"3iwx4ppimv","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"collection_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"82uk5g7krv","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"fetch_keys_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"jx1zxum47l","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"search_keys_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":28.9375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"24223uwmke","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}]}}],"slug":"page-generator","isHidden":false},"new":true,"unpublishedPage":{"name":"Page Generator","userPermissions":[],"layouts":[{"new":false,"id":"Page Generator","userPermissions":[],"layoutOnLoadActions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":850,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":53,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Tabs1","rightColumn":45,"widgetId":"jalvzswyyk","defaultTab":"SQL","topRow":11,"bottomRow":52,"shouldShowTabs":true,"parentRowSpace":10,"tabsObj":{"tab1":{"widgetId":"nyka98xqpv","index":0,"label":"SQL","id":"tab1","isVisible":true},"tab2":{"widgetId":"neexe4fljs","index":1,"label":"GSheet","id":"tab2","isVisible":true},"tab7qxuerb9p7":{"widgetId":"4yqoh4fjmv","id":"tab7qxuerb9p7","label":"Mongo","isVisible":true}},"isVisible":true,"type":"TABS_WIDGET","version":3,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":16,"dynamicBindingPathList":[],"children":[{"tabId":"tab1","tabName":"SQL","rightColumn":634,"widgetName":"Canvas2","detachFromLayout":true,"widgetId":"nyka98xqpv","topRow":0,"bottomRow":400,"parentRowSpace":1,"type":"CANVAS_WIDGET","parentId":"jalvzswyyk","isLoading":false,"renderMode":"CANVAS","minHeight":410,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text2","rightColumn":14,"textAlign":"RIGHT","widgetId":"957c72jpan","topRow":3,"bottomRow":7,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Datasource URL"},{"widgetName":"Text4","rightColumn":14,"textAlign":"RIGHT","widgetId":"nz74xi3ae3","topRow":10,"bottomRow":14,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Table Name"},{"widgetName":"Text6","rightColumn":14,"textAlign":"RIGHT","widgetId":"s1i89k31f5","topRow":17,"bottomRow":21,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Columns to Select"},{"widgetName":"Text7","rightColumn":14,"textAlign":"RIGHT","widgetId":"rbacxz6brz","topRow":25,"bottomRow":29,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Column to Search"},{"resetFormOnClick":false,"widgetName":"FormButton1","rightColumn":63,"onClick":"{{generate_sql_app.run(() => showAlert('Page Created!','success'), () => {})}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"n6220hgzzs","topRow":31,"bottomRow":35,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"nyka98xqpv","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate"},{"widgetName":"datasource_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":3,"bottomRow":7,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"fk5njkiu28","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"tableName_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"v6vho5uqct","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"select_cols_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":17,"bottomRow":21,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"e1j5kngy1t","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"search_col_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":25,"bottomRow":29,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"cqxwse0717","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]},{"tabId":"tab2","tabName":"GSheet","rightColumn":634,"widgetName":"Canvas3","detachFromLayout":true,"widgetId":"neexe4fljs","topRow":0,"bottomRow":400,"parentRowSpace":1,"type":"CANVAS_WIDGET","parentId":"jalvzswyyk","isLoading":false,"renderMode":"CANVAS","minHeight":410,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text8","rightColumn":16,"textAlign":"RIGHT","widgetId":"3ghywz6tk6","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"DataSource URL"},{"widgetName":"Text9","rightColumn":16,"textAlign":"RIGHT","widgetId":"r6o12im1qd","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"SpreadSheet URL"},{"widgetName":"Text10","rightColumn":16,"textAlign":"RIGHT","widgetId":"k0ul3uaoph","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Sheet Name"},{"widgetName":"Text11","rightColumn":16,"textAlign":"RIGHT","widgetId":"l1r1tfbx6y","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Table Header Index"},{"widgetName":"Button1","rightColumn":62,"onClick":"{{generate_gsheet_app.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"zzsh2d5rns","topRow":30,"bottomRow":34,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate","isDisabled":false},{"widgetName":"gsheet_ds_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"j61fbsst0i","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"spreadsheet_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"vm21ddffi6","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"sheet_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"5r5hxd2qs8","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"header_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"z3nz99y80l","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]},{"tabId":"tab7qxuerb9p7","widgetName":"Canvas4","tabName":"Mongo","rightColumn":574.5625,"detachFromLayout":true,"widgetId":"4yqoh4fjmv","containerStyle":"none","topRow":1,"bottomRow":400,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"jalvzswyyk","minHeight":410,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text12","rightColumn":17,"textAlign":"RIGHT","widgetId":"4l1uqhf2au","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Datasource URL"},{"widgetName":"Text13","rightColumn":17,"textAlign":"RIGHT","widgetId":"0y3rz6ufib","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Collection Name"},{"widgetName":"Text14","rightColumn":17,"textAlign":"RIGHT","widgetId":"s1fhjft9to","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Keys to Fetch"},{"widgetName":"Text15","rightColumn":17,"textAlign":"RIGHT","widgetId":"rwi67ouhe1","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Key to Search"},{"widgetName":"Button2","rightColumn":62,"onClick":"{{generate_mongo_app.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"6ui5kmqebf","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate","isDisabled":false},{"widgetName":"mongo_ds_url","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"3iwx4ppimv","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"collection_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"82uk5g7krv","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"fetch_keys_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"jx1zxum47l","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"search_keys_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":28.9375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"24223uwmke","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}]}}],"slug":"page-generator","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc4"},{"publishedPage":{"name":"MongoDB","userPermissions":[],"layouts":[{"new":false,"id":"MongoDB","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","jsonPathKeys":["key_select.selectedOptionValue","data_table.pageSize","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"name":"FindQuery","timeoutInMillisecond":10000,"id":"MongoDB_FindQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":940,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["customColumn1","_id","col4","col2","col3","col1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{FindQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns._id.computedValue"}],"leftColumn":0,"primaryColumns":{"appsmith_mongo_escape_id":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._id))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"_id","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_id","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{FindQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{FindQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"isRequired":false,"widgetName":"key_select","isFilterable":true,"rightColumn":22,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"asmgosgxjm","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{FindQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"col1","parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":7,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n\t{\n\t\t\"label\": \"col1\",\n\t\t\"value\": \"col1\"\n\t},\n\t{\n\t\t\"label\": \"col2\",\n\t\t\"value\": \"col2\"\n\t},\n\t{\n\t\t\"label\": \"col3\",\n\t\t\"value\": \"col3\"\n\t},\n\t{\n\t\t\"label\": \"col4\",\n\t\t\"value\": \"col4\"\n\t}\n]","onOptionChange":"{{FindQuery.run()}}","isDisabled":false},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"isRequired":false,"widgetName":"order_select","isFilterable":true,"rightColumn":30,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"10v8a19m25","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{FindQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"1","parentColumnSpace":19.75,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":22,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"ASC\",\n \"value\": \"1\"\n },\n {\n \"label\": \"DESC\",\n \"value\": \"-1\"\n }\n]","onOptionChange":"{{FindQuery.run()}}","isDisabled":false},{"widgetName":"Text16","rightColumn":41,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{FindQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"nj85l57r47","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"atgojamsmw","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => FindQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => FindQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col1","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"r07mzbm43d","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col2","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"b1y8w16g8n","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col3","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"2hseu4ai1m","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col4","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"yslrtpwrzf","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{!!data_table.selectedRow._id}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => FindQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"twwgpz5wfu","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":6,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update Selected Row"},{"widgetName":"Text17","rightColumn":18,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text18","rightColumn":18,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text19","rightColumn":18,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text20","rightColumn":18,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"update_col_1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"w1v1l55z5w","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col1}}"},{"widgetName":"update_col_2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"s4pbk7f7dg","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col2}}"},{"widgetName":"update_col_3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"qpzuy0ne6u","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"regex":"","iconAlign":"left","defaultText":"{{data_table.selectedRow.col3}}"},{"widgetName":"update_col_4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":29,"bottomRow":33,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"gep4mc8qrd","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col4}}"}]}]}]}}],"slug":"mongodb","isHidden":false},"new":true,"unpublishedPage":{"name":"MongoDB","userPermissions":[],"layouts":[{"new":false,"id":"MongoDB","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["key_select.selectedOptionValue","data_table.pageSize","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"name":"FindQuery","timeoutInMillisecond":10000,"id":"MongoDB_FindQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":1940,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":53,"minHeight":1920,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["customColumn1","_id","col4","col2","col3","col1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":11,"bottomRow":87,"parentRowSpace":10,"onPageChange":"{{FindQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns._id.computedValue"}],"leftColumn":0,"primaryColumns":{"appsmith_mongo_escape_id":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._id))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"_id","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_id","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{FindQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{FindQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"widgetName":"Text16","rightColumn":41,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{FindQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"nj85l57r47","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"atgojamsmw","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"widgetName":"key_select","isFilterable":true,"dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Select","iconSVG":"/static/media/icon.bd99caba.svg","labelText":"","topRow":5,"bottomRow":9,"parentRowSpace":10,"type":"SELECT_WIDGET","serverSideFiltering":false,"hideCard":false,"defaultOptionValue":"col1","animateLoading":true,"parentColumnSpace":22.375,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":8,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n\t{\n\t\t\"label\": \"col1\",\n\t\t\"value\": \"col1\"\n\t},\n\t{\n\t\t\"label\": \"col2\",\n\t\t\"value\": \"col2\"\n\t},\n\t{\n\t\t\"label\": \"col3\",\n\t\t\"value\": \"col3\"\n\t},\n\t{\n\t\t\"label\": \"col4\",\n\t\t\"value\": \"col4\"\n\t}\n]","placeholderText":"Select option","isDisabled":false,"key":"52ieik6s6e","isRequired":false,"rightColumn":21,"widgetId":"zsfqk78u1x","isVisible":"{{FindQuery.data.length > 0}}","version":1,"parentId":"59rw5mx0bq","renderMode":"CANVAS","isLoading":false,"onOptionChange":"{{FindQuery.run()}}"},{"widgetName":"order_select","isFilterable":true,"dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Select","iconSVG":"/static/media/icon.bd99caba.svg","labelText":"","topRow":5,"bottomRow":9,"parentRowSpace":10,"type":"SELECT_WIDGET","serverSideFiltering":false,"hideCard":false,"defaultOptionValue":"{\n \"label\": \"ASC\",\n \"value\": \"1\"\n }","animateLoading":true,"parentColumnSpace":22.375,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":22,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"Ascending\",\n \"value\": \"1\"\n },\n {\n \"label\": \"Descending\",\n \"value\": \"-1\"\n }\n]","placeholderText":"Select option","isDisabled":false,"key":"52ieik6s6e","isRequired":false,"rightColumn":35,"widgetId":"ihgdtihjgn","isVisible":"{{FindQuery.data.length > 0}}","version":1,"parentId":"59rw5mx0bq","renderMode":"CANVAS","isLoading":false,"onOptionChange":"{{FindQuery.run()}}"}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => FindQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => FindQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col1","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"r07mzbm43d","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col2","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"b1y8w16g8n","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col3","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"2hseu4ai1m","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col4","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"yslrtpwrzf","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{!!data_table.selectedRow._id}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => FindQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"twwgpz5wfu","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":6,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update Selected Row"},{"widgetName":"Text17","rightColumn":18,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text18","rightColumn":18,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text19","rightColumn":18,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text20","rightColumn":18,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"update_col_1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"w1v1l55z5w","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col1}}"},{"widgetName":"update_col_2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"s4pbk7f7dg","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col2}}"},{"widgetName":"update_col_3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"qpzuy0ne6u","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"regex":"","iconAlign":"left","defaultText":"{{data_table.selectedRow.col3}}"},{"widgetName":"update_col_4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":29,"bottomRow":33,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"gep4mc8qrd","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col4}}"}]}]}]}}],"slug":"mongodb","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc5"},{"publishedPage":{"name":"Redis","userPermissions":[],"layouts":[{"new":false,"id":"Redis","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","jsonPathKeys":[],"name":"FetchKeys","timeoutInMillisecond":10000,"id":"Redis_FetchKeys"}],[{"pluginType":"DB","jsonPathKeys":["data_table.selectedRow.result"],"name":"FetchValue","timeoutInMillisecond":10000,"id":"Redis_FetchValue"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":5160,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":860,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"eer73khglm","topRow":1,"bottomRow":47,"parentRowSpace":10,"isVisible":"{{data_table.selectedRow.result}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"9nvn3gfw6q","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"eer73khglm","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateKey.run(() => FetchKeys.run(), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"3apd2wkt91","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"9nvn3gfw6q","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"hhh0296qfj","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"9nvn3gfw6q","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"uawwds1z0r","topRow":0,"bottomRow":8,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"9nvn3gfw6q","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Key: {{data_table.selectedRow.result}}"},{"widgetName":"update_value_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":1,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"l3qtdja15h","isVisible":true,"label":"","version":2,"parentId":"9nvn3gfw6q","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{FetchValue.data[0].result}}"}]}]},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"v8nfulwuy0","containerStyle":"card","topRow":1,"bottomRow":88,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"erkvdsolhu","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"v8nfulwuy0","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["result","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":5,"bottomRow":86,"parentRowSpace":10,"onPageChange":"","isSortable":true,"type":"TABLE_WIDGET","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onRowSelected"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.result.computedValue"}],"leftColumn":0,"primaryColumns":{"result":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.result))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"result","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"result","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"delimiter":",","onRowSelected":"{{FetchValue.run()}}","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"tefed053r1","isVisibleFilters":true,"tableData":"{{FetchKeys.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"erkvdsolhu","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"result":503,"task":245,"deliveryAddress":170,"step":62,"id":228,"customColumn2":174,"status":75}},{"widgetName":"new_key_button","rightColumn":64,"onClick":"{{showModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"2rlp4irwh0","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":6.8310546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"New Key","isDisabled":false},{"widgetName":"refresh_button","rightColumn":51,"onClick":"{{FetchKeys.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o9t8fslxdi","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":40,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Refresh","isDisabled":false},{"widgetName":"Text16","rightColumn":39,"textAlign":"LEFT","widgetId":"nt181ks4ci","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Redis Data"}]}]},{"widgetName":"Insert_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"c8fg4ubw52","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":0,"detachFromLayout":true,"widgetId":"re60vbuakz","topRow":0,"bottomRow":600,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"c8fg4ubw52","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon1","rightColumn":64,"onClick":"{{closeModal('Insert_Modal')}}","color":"#040627","iconName":"cross","widgetId":"3tk445loxa","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_WIDGET","version":1,"parentId":"re60vbuakz","isLoading":false,"leftColumn":56,"iconSize":24},{"widgetName":"Text21","rightColumn":41,"textAlign":"LEFT","widgetId":"fgi9qp4uwr","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"New Key"},{"widgetName":"Button1","rightColumn":47,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"xnh96plcyo","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":35,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Button2","rightColumn":64,"onClick":"{{InsertKey.run(() => FetchKeys.run(() => closeModal('Insert_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"ix2dralfal","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Insert","isDisabled":false},{"widgetName":"Text22","rightColumn":17,"textAlign":"RIGHT","widgetId":"kotk4wa6pe","topRow":9,"bottomRow":13,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Key"},{"widgetName":"Text23","rightColumn":17,"textAlign":"RIGHT","widgetId":"y2dlumuetl","topRow":16,"bottomRow":20,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Value"},{"widgetName":"insert_key_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":8.125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"ynw4ir8luz","isVisible":true,"label":"","version":2,"parentId":"re60vbuakz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_value_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":52,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":8.125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"6qn1qkr18d","isVisible":true,"label":"","version":2,"parentId":"re60vbuakz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"value_modal","rightColumn":0,"detachFromLayout":true,"widgetId":"fh14k9y353","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"children":[{"widgetName":"Canvas4","rightColumn":0,"detachFromLayout":true,"widgetId":"v8n3d5aecd","topRow":0,"bottomRow":260,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"fh14k9y353","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon2","rightColumn":64,"onClick":"{{closeModal('value_modal')}}","color":"#040627","iconName":"cross","widgetId":"jqaazpo3zy","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_WIDGET","version":1,"parentId":"v8n3d5aecd","isLoading":false,"leftColumn":56,"iconSize":24},{"widgetName":"Text24","rightColumn":41,"textAlign":"LEFT","widgetId":"hvb3xnk1u8","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"v8n3d5aecd","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Value for Key: {{data_table.selectedRow.result}}"},{"widgetName":"Button4","rightColumn":64,"onClick":"{{closeModal('value_modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"yka7b6k706","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"v8n3d5aecd","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Close","isDisabled":false},{"widgetName":"Text25","rightColumn":64,"textAlign":"LEFT","widgetId":"j9315vzr13","topRow":6,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"v8n3d5aecd","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{FetchValue.data[0].result}}"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Delete_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"0skbil3ntd","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"children":[{"widgetName":"Canvas5","rightColumn":0,"detachFromLayout":true,"widgetId":"lwsyaz55ll","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"0skbil3ntd","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon3","rightColumn":64,"onClick":"{{closeModal('Delete_Modal')}}","color":"#040627","iconName":"cross","widgetId":"dtuc8ag2of","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_WIDGET","version":1,"parentId":"lwsyaz55ll","isLoading":false,"leftColumn":56,"iconSize":24},{"widgetName":"Text26","rightColumn":41,"textAlign":"LEFT","widgetId":"d9ap4dp300","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"lwsyaz55ll","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Key"},{"widgetName":"Button6","rightColumn":64,"onClick":"{{DeleteKey.run(() => FetchKeys.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"2kg6lmim5m","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"lwsyaz55ll","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text27","rightColumn":64,"textAlign":"LEFT","widgetId":"c698jgkzjg","topRow":7,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"lwsyaz55ll","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete the key?\n\n{{data_table.selectedRow.result}}"},{"widgetName":"Button7","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"lsvqrab5v2","topRow":18,"bottomRow":22,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"lwsyaz55ll","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":32,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false}],"isDisabled":false}],"width":456,"height":240}]}}],"slug":"redis","isHidden":false},"new":true,"unpublishedPage":{"name":"Redis","userPermissions":[],"layouts":[{"new":false,"id":"Redis","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":[],"name":"FetchKeys","timeoutInMillisecond":10000,"id":"Redis_FetchKeys"}],[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow.result"],"name":"FetchValue","timeoutInMillisecond":10000,"id":"Redis_FetchValue"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":5160,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":53,"minHeight":860,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"eer73khglm","topRow":1,"bottomRow":47,"parentRowSpace":10,"isVisible":"{{data_table.selectedRow.result}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"9nvn3gfw6q","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"eer73khglm","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateKey.run(() => FetchKeys.run(), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"3apd2wkt91","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"9nvn3gfw6q","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"hhh0296qfj","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"9nvn3gfw6q","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"uawwds1z0r","topRow":0,"bottomRow":8,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"9nvn3gfw6q","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Key: {{data_table.selectedRow.result}}"},{"widgetName":"update_value_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":1,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"l3qtdja15h","isVisible":true,"label":"","version":2,"parentId":"9nvn3gfw6q","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{FetchValue.data[0].result}}"}]}]},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"v8nfulwuy0","containerStyle":"card","topRow":1,"bottomRow":88,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"erkvdsolhu","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"v8nfulwuy0","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["result","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":5,"bottomRow":86,"parentRowSpace":10,"onPageChange":"","isSortable":true,"type":"TABLE_WIDGET","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onRowSelected"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.result.computedValue"}],"leftColumn":0,"primaryColumns":{"result":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.result))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"result","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"result","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"delimiter":",","onRowSelected":"{{FetchValue.run()}}","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"tefed053r1","isVisibleFilters":true,"tableData":"{{FetchKeys.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"erkvdsolhu","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"result":503,"task":245,"deliveryAddress":170,"step":62,"id":228,"customColumn2":174,"status":75}},{"widgetName":"new_key_button","rightColumn":64,"onClick":"{{showModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"2rlp4irwh0","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":6.8310546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"New Key","isDisabled":false},{"widgetName":"refresh_button","rightColumn":51,"onClick":"{{FetchKeys.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o9t8fslxdi","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":40,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Refresh","isDisabled":false},{"widgetName":"Text16","rightColumn":39,"textAlign":"LEFT","widgetId":"nt181ks4ci","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Redis Data"}]}]},{"widgetName":"Insert_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"c8fg4ubw52","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":0,"detachFromLayout":true,"widgetId":"re60vbuakz","topRow":0,"bottomRow":600,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"c8fg4ubw52","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon1","rightColumn":64,"onClick":"{{closeModal('Insert_Modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"3tk445loxa","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"re60vbuakz","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text21","rightColumn":41,"textAlign":"LEFT","widgetId":"fgi9qp4uwr","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"New Key"},{"widgetName":"Button1","rightColumn":47,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"xnh96plcyo","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":35,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Button2","rightColumn":64,"onClick":"{{InsertKey.run(() => FetchKeys.run(() => closeModal('Insert_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"ix2dralfal","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Insert","isDisabled":false},{"widgetName":"Text22","rightColumn":17,"textAlign":"RIGHT","widgetId":"kotk4wa6pe","topRow":9,"bottomRow":13,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Key"},{"widgetName":"Text23","rightColumn":17,"textAlign":"RIGHT","widgetId":"y2dlumuetl","topRow":16,"bottomRow":20,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Value"},{"widgetName":"insert_key_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":8.125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"ynw4ir8luz","isVisible":true,"label":"","version":2,"parentId":"re60vbuakz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_value_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":52,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":8.125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"6qn1qkr18d","isVisible":true,"label":"","version":2,"parentId":"re60vbuakz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"value_modal","rightColumn":0,"detachFromLayout":true,"widgetId":"fh14k9y353","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"children":[{"widgetName":"Canvas4","rightColumn":0,"detachFromLayout":true,"widgetId":"v8n3d5aecd","topRow":0,"bottomRow":260,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"fh14k9y353","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon2","rightColumn":64,"onClick":"{{closeModal('value_modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"jqaazpo3zy","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"v8n3d5aecd","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text24","rightColumn":41,"textAlign":"LEFT","widgetId":"hvb3xnk1u8","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"v8n3d5aecd","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Value for Key: {{data_table.selectedRow.result}}"},{"widgetName":"Button4","rightColumn":64,"onClick":"{{closeModal('value_modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"yka7b6k706","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"v8n3d5aecd","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Close","isDisabled":false},{"widgetName":"Text25","rightColumn":64,"textAlign":"LEFT","widgetId":"j9315vzr13","topRow":6,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"v8n3d5aecd","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{FetchValue.data[0].result}}"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Delete_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"0skbil3ntd","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"children":[{"widgetName":"Canvas5","rightColumn":0,"detachFromLayout":true,"widgetId":"lwsyaz55ll","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"0skbil3ntd","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon3","rightColumn":64,"onClick":"{{closeModal('Delete_Modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"dtuc8ag2of","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"lwsyaz55ll","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text26","rightColumn":41,"textAlign":"LEFT","widgetId":"d9ap4dp300","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"lwsyaz55ll","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Key"},{"widgetName":"Button6","rightColumn":64,"onClick":"{{DeleteKey.run(() => FetchKeys.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"2kg6lmim5m","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"lwsyaz55ll","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text27","rightColumn":64,"textAlign":"LEFT","widgetId":"c698jgkzjg","topRow":7,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"lwsyaz55ll","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete the key?\n\n{{data_table.selectedRow.result}}"},{"widgetName":"Button7","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"lsvqrab5v2","topRow":18,"bottomRow":22,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"lwsyaz55ll","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":32,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false}],"isDisabled":false}],"width":456,"height":240}]}}],"slug":"redis","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc6"},{"publishedPage":{"name":"Firestore","userPermissions":[],"layouts":[{"new":false,"id":"Firestore","userPermissions":[],"layoutOnLoadActions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":890,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":720,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["_ref","col4","col5","col2","col3","col1","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns._ref.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col1.computedValue"}],"leftColumn":0,"primaryColumns":{"_ref":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._ref))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"_ref","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_ref","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":5,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":6,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":7,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":8,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"_ref":251,"step":62,"id":228,"status":75}},{"widgetName":"new_row_button","rightColumn":64,"onClick":"{{showModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"aiy9e38won","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":6.8310546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"New Row","isDisabled":false},{"isRequired":false,"widgetName":"key_select","isFilterable":true,"rightColumn":22,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"asmgosgxjm","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{SelectQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"col1","parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":7,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n\t{\n\t\t\"label\": \"col1\",\n\t\t\"value\": \"col1\"\n\t},\n\t{\n\t\t\"label\": \"col2\",\n\t\t\"value\": \"col2\"\n\t},\n\t{\n\t\t\"label\": \"col3\",\n\t\t\"value\": \"col3\"\n\t},\n\t{\n\t\t\"label\": \"col4\",\n\t\t\"value\": \"col4\"\n\t}\n]","onOptionChange":"{{SelectQuery.run()}}","isDisabled":false},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"isRequired":false,"widgetName":"order_select","isFilterable":true,"rightColumn":30,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"10v8a19m25","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{SelectQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"","parentColumnSpace":19.75,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":22,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"ASC\",\n \"value\": \"\"\n },\n {\n \"label\": \"DESC\",\n \"value\": \"-\"\n }\n]","onOptionChange":"{{SelectQuery.run()}}","isDisabled":false},{"widgetName":"refresh_button","rightColumn":51,"onClick":"{{SelectQuery.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"qykn04gnsw","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":40,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Refresh","isDisabled":false},{"widgetName":"Text16","rightColumn":64,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text14Copy","rightColumn":19,"textAlign":"RIGHT","widgetId":"yy4u8kzs8p","topRow":33,"bottomRow":37,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => SelectQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col1","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"9i061jtfhj","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col2","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"14nra1c4f6","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col3","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"iepat3iat7","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col4","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"whurxe4mth","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":33,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col5","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"pnp9uljvq8","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":54,"parentRowSpace":10,"isVisible":"{{data_table.selectedRow._ref}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":520,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":500,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text20Copy","rightColumn":19,"textAlign":"RIGHT","widgetId":"kv1pqyhxvs","topRow":37,"bottomRow":41,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5 :"},{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":64,"onClick":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":46,"bottomRow":50,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"twwgpz5wfu","topRow":46,"bottomRow":50,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Row ID: {{data_table.selectedRow._id}}"},{"widgetName":"Text17","rightColumn":19,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":9,"bottomRow":13,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1 :"},{"widgetName":"Text18","rightColumn":19,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":16,"bottomRow":20,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2 :"},{"widgetName":"Text19","rightColumn":19,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":23,"bottomRow":27,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3 :"},{"widgetName":"Text20","rightColumn":19,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":30,"bottomRow":34,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4 :"},{"widgetName":"update_col_1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"kwh3g1fmbz","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col1}}"},{"widgetName":"update_col_2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":16,"bottomRow":20,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"d58a3ox22l","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col2}}"},{"widgetName":"update_col_3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":23,"bottomRow":27,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"6iizmnlspv","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col3}}"},{"widgetName":"update_col_4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":30,"bottomRow":34,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"l1zlhtgwjm","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col4}}"},{"widgetName":"update_col_5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":37,"bottomRow":41,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"dx2982c128","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col5}}"}]}]}]}}],"slug":"firestore","isHidden":false},"new":true,"unpublishedPage":{"name":"Firestore","userPermissions":[],"layouts":[{"new":false,"id":"Firestore","userPermissions":[],"layoutOnLoadActions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":890,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":720,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["_ref","col4","col5","col2","col3","col1","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns._ref.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col1.computedValue"}],"leftColumn":0,"primaryColumns":{"_ref":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._ref))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"_ref","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_ref","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":5,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":6,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":7,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":8,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"_ref":251,"step":62,"id":228,"status":75}},{"widgetName":"new_row_button","rightColumn":64,"onClick":"{{showModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"aiy9e38won","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":6.8310546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"New Row","isDisabled":false},{"isRequired":false,"widgetName":"key_select","isFilterable":true,"rightColumn":22,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"asmgosgxjm","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{SelectQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"col1","parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":7,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n\t{\n\t\t\"label\": \"col1\",\n\t\t\"value\": \"col1\"\n\t},\n\t{\n\t\t\"label\": \"col2\",\n\t\t\"value\": \"col2\"\n\t},\n\t{\n\t\t\"label\": \"col3\",\n\t\t\"value\": \"col3\"\n\t},\n\t{\n\t\t\"label\": \"col4\",\n\t\t\"value\": \"col4\"\n\t}\n]","onOptionChange":"{{SelectQuery.run()}}","isDisabled":false},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"isRequired":false,"widgetName":"order_select","isFilterable":true,"rightColumn":30,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"10v8a19m25","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{SelectQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"","parentColumnSpace":19.75,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":22,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"ASC\",\n \"value\": \"\"\n },\n {\n \"label\": \"DESC\",\n \"value\": \"-\"\n }\n]","onOptionChange":"{{SelectQuery.run()}}","isDisabled":false},{"widgetName":"refresh_button","rightColumn":51,"onClick":"{{SelectQuery.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"qykn04gnsw","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":40,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Refresh","isDisabled":false},{"widgetName":"Text16","rightColumn":64,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text14Copy","rightColumn":19,"textAlign":"RIGHT","widgetId":"yy4u8kzs8p","topRow":33,"bottomRow":37,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => SelectQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col1","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"9i061jtfhj","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col2","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"14nra1c4f6","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col3","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"iepat3iat7","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col4","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"whurxe4mth","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":33,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.685546875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col5","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":58,"widgetId":"pnp9uljvq8","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":54,"parentRowSpace":10,"isVisible":"{{data_table.selectedRow._ref}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":520,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":500,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text20Copy","rightColumn":19,"textAlign":"RIGHT","widgetId":"kv1pqyhxvs","topRow":37,"bottomRow":41,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5 :"},{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":64,"onClick":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":46,"bottomRow":50,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"twwgpz5wfu","topRow":46,"bottomRow":50,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Row ID: {{data_table.selectedRow._id}}"},{"widgetName":"Text17","rightColumn":19,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":9,"bottomRow":13,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1 :"},{"widgetName":"Text18","rightColumn":19,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":16,"bottomRow":20,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2 :"},{"widgetName":"Text19","rightColumn":19,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":23,"bottomRow":27,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3 :"},{"widgetName":"Text20","rightColumn":19,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":30,"bottomRow":34,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4 :"},{"widgetName":"update_col_1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"kwh3g1fmbz","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col1}}"},{"widgetName":"update_col_2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":16,"bottomRow":20,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"d58a3ox22l","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col2}}"},{"widgetName":"update_col_3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":23,"bottomRow":27,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"6iizmnlspv","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col3}}"},{"widgetName":"update_col_4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":30,"bottomRow":34,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"l1zlhtgwjm","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col4}}"},{"widgetName":"update_col_5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":37,"bottomRow":41,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"dx2982c128","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{data_table.selectedRow.col5}}"}]}]}]}}],"slug":"firestore","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc7"},{"publishedPage":{"name":"PostgreSQL","userPermissions":[],"layouts":[{"new":false,"id":"PostgreSQL","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","col_select.selectedOptionValue","Table1.pageSize","order_select.selectedOptionValue"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"PostgreSQL_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1864,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":940,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":51,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":880,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Table1","columnOrder":["col1","col3","col4","col5","col2","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"},{"key":"primaryColumns.col2.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"isRequired":false,"widgetName":"col_select","isFilterable":true,"rightColumn":22,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"asmgosgxjm","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{SelectQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"col1","parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":7,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n\t{\n\t\t\"label\": \"col1\",\n\t\t\"value\": \"col1\"\n\t},\n\t{\n\t\t\"label\": \"col2\",\n\t\t\"value\": \"col2\"\n\t},\n\t{\n\t\t\"label\": \"col3\",\n\t\t\"value\": \"col3\"\n\t}\n]","onOptionChange":"{{SelectQuery.run()}}","isDisabled":false},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"isRequired":false,"widgetName":"order_select","isFilterable":true,"rightColumn":37,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"10v8a19m25","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{SelectQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"ASC","parentColumnSpace":19.75,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":22,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"Ascending\",\n \"value\": \"ASC\"\n },\n {\n \"label\": \"Descending\",\n \"value\": \"DESC\"\n }\n]","onOptionChange":"{{SelectQuery.run()}}","isDisabled":false},{"widgetName":"Text16","rightColumn":64,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"xp5u9a9nzq","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"nh3cu4lb1g","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":604,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":59,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => SelectQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text24","rightColumn":19,"textAlign":"RIGHT","widgetId":"9t3vdjd5xj","topRow":33,"bottomRow":37,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col1","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"udpykd6frr","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col2","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"okr4t68xnm","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col3","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"vyo3iifdlv","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col4","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"px3syo16j9","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":33,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col5","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"30aa658gdv","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":604},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{!!Table1.selectedRow.col1}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"twwgpz5wfu","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Row: {{Table1.selectedRow.col1}}"},{"widgetName":"Text17","rightColumn":18,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text18","rightColumn":18,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":13,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text19","rightColumn":18,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":20,"bottomRow":24,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text20","rightColumn":18,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":27,"bottomRow":31,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"update_col_2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"xsmln3d0zi","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"nax7kexro0","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col2.toString()}}"},{"widgetName":"update_col_3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":13,"bottomRow":17,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"xsmln3d0zi","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"q1s9k8g8a5","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col3.toString()}}"},{"widgetName":"update_col_4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":20,"bottomRow":24,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"xsmln3d0zi","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"z8t8n43i2w","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col4.toString()}}"},{"widgetName":"update_col_5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":27,"bottomRow":31,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"xsmln3d0zi","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"efeklwpf35","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col5.toString()}}"}]}]}]}}],"slug":"postgresql","isHidden":false},"new":true,"unpublishedPage":{"name":"PostgreSQL","userPermissions":[],"layouts":[{"new":false,"id":"PostgreSQL","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","col_select.selectedOptionValue","Table1.pageSize","order_select.selectedOptionValue"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"PostgreSQL_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1431,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":1120,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":53,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":880,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Table1","columnOrder":["col1","col3","col4","col5","col2","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"},{"key":"primaryColumns.col2.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"widgetName":"Text16","rightColumn":64,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"xp5u9a9nzq","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"nh3cu4lb1g","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"TERTIARY","isDisabled":false},{"widgetName":"col_select","isFilterable":true,"dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Select","iconSVG":"/static/media/icon.bd99caba.svg","labelText":"","topRow":5,"bottomRow":9,"parentRowSpace":10,"type":"SELECT_WIDGET","serverSideFiltering":false,"hideCard":false,"defaultOptionValue":"col1","animateLoading":true,"parentColumnSpace":22.171875,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":9,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n\t{\n\t\t\"label\": \"col1\",\n\t\t\"value\": \"col1\"\n\t},\n\t{\n\t\t\"label\": \"col2\",\n\t\t\"value\": \"col2\"\n\t},\n\t{\n\t\t\"label\": \"col3\",\n\t\t\"value\": \"col3\"\n\t}\n]","placeholderText":"Select option","isDisabled":false,"key":"un5y91u42x","isRequired":false,"rightColumn":22,"widgetId":"kqo2g4nu86","isVisible":"{{SelectQuery.data.length > 0}}","version":1,"parentId":"59rw5mx0bq","renderMode":"CANVAS","isLoading":false,"onOptionChange":"{{SelectQuery.run()}}"},{"widgetName":"order_select","isFilterable":true,"dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Select","iconSVG":"/static/media/icon.bd99caba.svg","labelText":"","topRow":5,"bottomRow":9,"parentRowSpace":10,"type":"SELECT_WIDGET","serverSideFiltering":false,"hideCard":false,"defaultOptionValue":"ASC","animateLoading":true,"parentColumnSpace":22.171875,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":23,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"Ascending\",\n \"value\": \"ASC\"\n },\n {\n \"label\": \"Descending\",\n \"value\": \"DESC\"\n }\n]","placeholderText":"Select option","isDisabled":false,"key":"un5y91u42x","isRequired":false,"rightColumn":36,"widgetId":"abax6hf704","isVisible":"{{SelectQuery.data.length > 0}}","version":1,"parentId":"59rw5mx0bq","renderMode":"CANVAS","isLoading":false,"onOptionChange":"{{SelectQuery.run()}}"}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":604,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":59,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => SelectQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","buttonVariant":"PRIMARY","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col1:"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text24","rightColumn":19,"textAlign":"RIGHT","widgetId":"9t3vdjd5xj","topRow":33,"bottomRow":37,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"},{"widgetName":"insert_col_input1","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col1","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"udpykd6frr","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":12,"bottomRow":16,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col2","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"okr4t68xnm","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":19,"bottomRow":23,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col3","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"vyo3iifdlv","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":26,"bottomRow":30,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col4","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":62,"widgetId":"px3syo16j9","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_col_input5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":33,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":7.8125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":20,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"col5","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":true,"rightColumn":61,"widgetId":"30aa658gdv","isVisible":true,"label":"","version":2,"parentId":"tp9pui0e6y","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}],"isDisabled":false}],"width":532,"height":604},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{!!Table1.selectedRow.col1}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"twwgpz5wfu","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Row: {{Table1.selectedRow.col1}}"},{"widgetName":"Text17","rightColumn":18,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col2:"},{"widgetName":"Text18","rightColumn":18,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":13,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col3:"},{"widgetName":"Text19","rightColumn":18,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":20,"bottomRow":24,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col4:"},{"widgetName":"Text20","rightColumn":18,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":27,"bottomRow":31,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"col5:"},{"widgetName":"update_col_2","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"xsmln3d0zi","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"nax7kexro0","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col2.toString()}}"},{"widgetName":"update_col_3","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":13,"bottomRow":17,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"xsmln3d0zi","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"q1s9k8g8a5","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col3.toString()}}"},{"widgetName":"update_col_4","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":20,"bottomRow":24,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"xsmln3d0zi","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"z8t8n43i2w","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col4.toString()}}"},{"widgetName":"update_col_5","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":27,"bottomRow":31,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"xsmln3d0zi","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"efeklwpf35","isVisible":true,"label":"","version":2,"parentId":"cicukwhp5j","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{Table1.selectedRow.col5.toString()}}"}]}]}]}}],"slug":"postgresql","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc8"}],"publishedLayoutmongoEscapedWidgets":{"MongoDB":["data_table"]},"actionCollectionList":[],"exportedApplication":{"applicationVersion":2,"new":true,"color":"#D9E7FF","name":"CRUD App Templates","appIsExample":false,"icon":"bag","isPublic":false,"unreadCommentThreads":0,"slug":"crud-app-templates","isManualUpdate":false}} \ No newline at end of file +{"editModeTheme":{"new":true,"isSystemTheme":true,"displayName":"Classic","name":"Classic"},"datasourceList":[{"isConfigured":true,"new":true,"invalids":[],"pluginId":"amazons3-plugin","isValid":true,"name":"AmazonS3 CRUD","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d704509528942","structure":{}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"Appsmith Release","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d704509528a53","structure":{}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"firestore-plugin","isValid":true,"name":"FBTemplateDB","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d70450952893f","structure":{}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"google-sheets-plugin","isValid":true,"name":"Google Sheet","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d704509528941","structure":{}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"postgres-plugin","isValid":true,"name":"Internal DB","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d70450952893c","structure":{"tables":[{"schema":"public","columns":[{"defaultValue":"nextval('aforce_roster_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"email","type":"text","isAutogenerated":false},{"name":"name","type":"text","isAutogenerated":false},{"name":"registration_date","type":"date","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"aforce_roster_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"aforce_heroes\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"aforce_heroes\" (\"email\", \"name\", \"registration_date\")\n VALUES ('', '', '2019-07-01');"},{"title":"UPDATE","body":"UPDATE public.\"aforce_heroes\" SET\n \"email\" = '',\n \"name\" = '',\n \"registration_date\" = '2019-07-01'\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"aforce_heroes\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.aforce_heroes","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('aforce_roster_id_seq1'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"date","type":"date","isAutogenerated":false},{"name":"hero_id","type":"int4","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"aforce_roster_pkey1","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"aforce_roster\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"aforce_roster\" (\"date\", \"hero_id\")\n VALUES ('2019-07-01', 1);"},{"title":"UPDATE","body":"UPDATE public.\"aforce_roster\" SET\n \"date\" = '2019-07-01',\n \"hero_id\" = 1\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"aforce_roster\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.aforce_roster","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('discord_messages_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"msg_id","type":"text","isAutogenerated":false},{"name":"created_at","type":"date","isAutogenerated":false},{"name":"author","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"discord_messages_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"discord_messages\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"discord_messages\" (\"msg_id\", \"created_at\", \"author\")\n VALUES ('', '2019-07-01', '');"},{"title":"UPDATE","body":"UPDATE public.\"discord_messages\" SET\n \"msg_id\" = '',\n \"created_at\" = '2019-07-01',\n \"author\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"discord_messages\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.discord_messages","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('email_issues_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"from","type":"text","isAutogenerated":false},{"name":"body","type":"text","isAutogenerated":false},{"name":"created_at","type":"timestamptz","isAutogenerated":false},{"name":"subject","type":"text","isAutogenerated":false},{"name":"is_tagged","type":"bool","isAutogenerated":false},{"name":"assignee","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"email_issues_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"email_issues\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"email_issues\" (\"from\", \"body\", \"created_at\", \"subject\", \"is_tagged\", \"assignee\")\n VALUES ('', '', TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET', '', '', '');"},{"title":"UPDATE","body":"UPDATE public.\"email_issues\" SET\n \"from\" = '',\n \"body\" = '',\n \"created_at\" = TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET',\n \"subject\" = '',\n \"is_tagged\" = '',\n \"assignee\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"email_issues\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.email_issues","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('github_issues_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"upvotes","type":"int4","isAutogenerated":false},{"name":"closed_date","type":"date","isAutogenerated":false},{"name":"created_date","type":"date","isAutogenerated":false},{"name":"assignee","type":"text","isAutogenerated":false},{"name":"state","type":"text","isAutogenerated":false},{"name":"issue_creator_id","type":"text","isAutogenerated":false},{"name":"title","type":"text","isAutogenerated":false},{"name":"issue_number","type":"int4","isAutogenerated":false},{"name":"label_arr","type":"_text","isAutogenerated":false},{"name":"total_reactions","type":"int4","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"github_issues_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"github_issues\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"github_issues\" (\"upvotes\", \"closed_date\", \"created_date\", \"assignee\", \"state\", \"issue_creator_id\", \"title\", \"issue_number\", \"label_arr\", \"total_reactions\")\n VALUES (1, '2019-07-01', '2019-07-01', '', '', '', '', 1, '', 1);"},{"title":"UPDATE","body":"UPDATE public.\"github_issues\" SET\n \"upvotes\" = 1,\n \"closed_date\" = '2019-07-01',\n \"created_date\" = '2019-07-01',\n \"assignee\" = '',\n \"state\" = '',\n \"issue_creator_id\" = '',\n \"title\" = '',\n \"issue_number\" = 1,\n \"label_arr\" = '',\n \"total_reactions\" = 1\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"github_issues\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.github_issues","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('issue_db_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"github_issue_id","type":"int4","isAutogenerated":false},{"name":"author","type":"text","isAutogenerated":false},{"name":"created_at","type":"timestamp","isAutogenerated":false},{"name":"title","type":"text","isAutogenerated":false},{"name":"description","type":"text","isAutogenerated":false},{"name":"labels","type":"_text","isAutogenerated":false},{"name":"type","type":"text","isAutogenerated":false},{"name":"state","type":"text","isAutogenerated":false},{"name":"answer","type":"text","isAutogenerated":false},{"name":"needs_docs","type":"bool","isAutogenerated":false},{"name":"link","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"issue_db_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"global_issues\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"global_issues\" (\"github_issue_id\", \"author\", \"created_at\", \"title\", \"description\", \"labels\", \"type\", \"state\", \"answer\", \"needs_docs\", \"link\")\n VALUES (1, '', TIMESTAMP '2019-07-01 10:00:00', '', '', '', '', '', '', '', '');"},{"title":"UPDATE","body":"UPDATE public.\"global_issues\" SET\n \"github_issue_id\" = 1,\n \"author\" = '',\n \"created_at\" = TIMESTAMP '2019-07-01 10:00:00',\n \"title\" = '',\n \"description\" = '',\n \"labels\" = '',\n \"type\" = '',\n \"state\" = '',\n \"answer\" = '',\n \"needs_docs\" = '',\n \"link\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"global_issues\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.global_issues","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('issue_upvote_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"link","type":"text","isAutogenerated":false},{"name":"comment","type":"text","isAutogenerated":false},{"name":"author","type":"text","isAutogenerated":false},{"name":"created_at","type":"timestamp","isAutogenerated":false},{"name":"issue_id","type":"int4","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"issue_upvote_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"issue_upvote\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"issue_upvote\" (\"link\", \"comment\", \"author\", \"created_at\", \"issue_id\")\n VALUES ('', '', '', TIMESTAMP '2019-07-01 10:00:00', 1);"},{"title":"UPDATE","body":"UPDATE public.\"issue_upvote\" SET\n \"link\" = '',\n \"comment\" = '',\n \"author\" = '',\n \"created_at\" = TIMESTAMP '2019-07-01 10:00:00',\n \"issue_id\" = 1\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"issue_upvote\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.issue_upvote","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('standup_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"name","type":"text","isAutogenerated":false},{"name":"yesterday","type":"text","isAutogenerated":false},{"name":"today","type":"text","isAutogenerated":false},{"name":"blocked","type":"text","isAutogenerated":false},{"name":"date","type":"date","isAutogenerated":false},{"name":"pod","type":"text","isAutogenerated":false},{"name":"dayrating","type":"int4","isAutogenerated":false},{"name":"restrating","type":"int4","isAutogenerated":false},{"name":"focusrating","type":"int4","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"standup_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"standup\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"standup\" (\"name\", \"yesterday\", \"today\", \"blocked\", \"date\", \"pod\", \"dayrating\", \"restrating\", \"focusrating\")\n VALUES ('', '', '', '', '2019-07-01', '', 1, 1, 1);"},{"title":"UPDATE","body":"UPDATE public.\"standup\" SET\n \"name\" = '',\n \"yesterday\" = '',\n \"today\" = '',\n \"blocked\" = '',\n \"date\" = '2019-07-01',\n \"pod\" = '',\n \"dayrating\" = 1,\n \"restrating\" = 1,\n \"focusrating\" = 1\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"standup\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.standup","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('support_tickets_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"description","type":"varchar","isAutogenerated":false},{"name":"created_at","type":"timestamptz","isAutogenerated":false},{"name":"author","type":"text","isAutogenerated":false},{"name":"user","type":"text","isAutogenerated":false},{"name":"comments","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"support_tickets_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"support_tickets\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"support_tickets\" (\"description\", \"created_at\", \"author\", \"user\", \"comments\")\n VALUES ('', TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET', '', '', '');"},{"title":"UPDATE","body":"UPDATE public.\"support_tickets\" SET\n \"description\" = '',\n \"created_at\" = TIMESTAMP WITH TIME ZONE '2019-07-01 06:30:00 CET',\n \"author\" = '',\n \"user\" = '',\n \"comments\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"support_tickets\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.support_tickets","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('template_table_col1_seq'::regclass)","name":"col1","type":"int4","isAutogenerated":true},{"name":"col3","type":"text","isAutogenerated":false},{"name":"col4","type":"int4","isAutogenerated":false},{"name":"col5","type":"bool","isAutogenerated":false},{"name":"col2","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["col1"],"name":"template_table_pkey","type":"primary key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"template_table\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"template_table\" (\"col3\", \"col4\", \"col5\", \"col2\")\n VALUES ('', 1, '', '');"},{"title":"UPDATE","body":"UPDATE public.\"template_table\" SET\n \"col3\" = '',\n \"col4\" = 1,\n \"col5\" = '',\n \"col2\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"template_table\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.template_table","type":"TABLE"},{"schema":"public","columns":[{"defaultValue":"nextval('ticket_tags_id_seq'::regclass)","name":"id","type":"int4","isAutogenerated":true},{"name":"ticket_id","type":"int4","isAutogenerated":false},{"name":"github_tag_id","type":"text","isAutogenerated":false}],"keys":[{"columnNames":["id"],"name":"ticket_tags_pkey","type":"primary key"},{"fromColumns":["ticket_id"],"name":"ticket_id_fk","toColumns":["support_tickets.id"],"type":"foreign key"}],"templates":[{"title":"SELECT","body":"SELECT * FROM public.\"ticket_tags\" LIMIT 10;"},{"title":"INSERT","body":"INSERT INTO public.\"ticket_tags\" (\"ticket_id\", \"github_tag_id\")\n VALUES (1, '');"},{"title":"UPDATE","body":"UPDATE public.\"ticket_tags\" SET\n \"ticket_id\" = 1,\n \"github_tag_id\" = ''\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may update every row in the table!"},{"title":"DELETE","body":"DELETE FROM public.\"ticket_tags\"\n WHERE 1 = 0; -- Specify a valid condition here. Removing the condition may delete everything in the table!"}],"name":"public.ticket_tags","type":"TABLE"}]}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"mongo-plugin","isValid":true,"name":"Mock_Mongo","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"5f7add8687af934ed846dd6a_61c43332e89bc475f3cae797","structure":{"tables":[{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"col1","type":"String","isAutogenerated":false},{"name":"col2","type":"String","isAutogenerated":false},{"name":"col3","type":"String","isAutogenerated":false},{"name":"col4","type":"String","isAutogenerated":false}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"col1\": \"test\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"template_table","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"template_table\",\n \"filter\": {\n \"col1\": \"test\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"template_table","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"template_table\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"col1\": \"new value\",\n \"col2\": \"new value\",\n \"col3\": \"new value\",\n \"col4\": \"new value\",\n}]"},"collection":"template_table","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"template_table\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"col1\": \"new value\",\n \"col2\": \"new value\",\n \"col3\": \"new value\",\n \"col4\": \"new value\",\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"col1\": \"new value\" } }"},"collection":"template_table","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"template_table\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"col1\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"template_table","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"template_table\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"template_table","type":"COLLECTION"},{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"createdAt","type":"Date","isAutogenerated":false},{"name":"email","type":"String","isAutogenerated":false},{"name":"name","type":"String","isAutogenerated":false},{"name":"role","type":"String","isAutogenerated":false},{"name":"status","type":"Object","isAutogenerated":false}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"email\": \"[email protected]\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"users","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"users\",\n \"filter\": {\n \"email\": \"[email protected]\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"users","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"users\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"email\": \"new value\",\n \"name\": \"new value\",\n \"role\": \"new value\",\n \"status\": {},\n}]"},"collection":"users","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"users\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"email\": \"new value\",\n \"name\": \"new value\",\n \"role\": \"new value\",\n \"status\": {},\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"email\": \"new value\" } }"},"collection":"users","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"users\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"email\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"users","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"users\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"users","type":"COLLECTION"},{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"createdAt","type":"Date","isAutogenerated":false},{"name":"currentLimit","type":"Integer","isAutogenerated":false},{"name":"featureName","type":"String","isAutogenerated":false},{"name":"key","type":"Integer","isAutogenerated":false},{"name":"limit","type":"Integer","isAutogenerated":false},{"name":"subscriptionId","type":"ObjectId","isAutogenerated":true}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"featureName\": \"Okuneva Inc\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"orgs","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"orgs\",\n \"filter\": {\n \"featureName\": \"Okuneva Inc\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"orgs","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"orgs\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"currentLimit\": 1,\n \"featureName\": \"new value\",\n \"key\": 1,\n \"limit\": 1,\n \"subscriptionId\": ObjectId(\"a_valid_object_id_hex\"),\n}]"},"collection":"orgs","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"orgs\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"currentLimit\": 1,\n \"featureName\": \"new value\",\n \"key\": 1,\n \"limit\": 1,\n \"subscriptionId\": ObjectId(\"a_valid_object_id_hex\"),\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"featureName\": \"new value\" } }"},"collection":"orgs","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"orgs\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"featureName\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"orgs","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"orgs\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"orgs","type":"COLLECTION"},{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"createdAt","type":"Date","isAutogenerated":false},{"name":"createdBy","type":"ObjectId","isAutogenerated":true},{"name":"domain","type":"String","isAutogenerated":false},{"name":"name","type":"String","isAutogenerated":false},{"name":"numUsers","type":"Integer","isAutogenerated":false},{"name":"orgId","type":"ObjectId","isAutogenerated":true}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"domain\": \"adolph.biz\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"apps","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"apps\",\n \"filter\": {\n \"domain\": \"adolph.biz\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"apps","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"apps\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"createdBy\": ObjectId(\"a_valid_object_id_hex\"),\n \"domain\": \"new value\",\n \"name\": \"new value\",\n \"numUsers\": 1,\n \"orgId\": ObjectId(\"a_valid_object_id_hex\"),\n}]"},"collection":"apps","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"apps\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"createdBy\": ObjectId(\"a_valid_object_id_hex\"),\n \"domain\": \"new value\",\n \"name\": \"new value\",\n \"numUsers\": 1,\n \"orgId\": ObjectId(\"a_valid_object_id_hex\"),\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"domain\": \"new value\" } }"},"collection":"apps","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"apps\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"domain\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"apps","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"apps\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"apps","type":"COLLECTION"},{"columns":[{"name":"_id","type":"ObjectId","isAutogenerated":true},{"name":"createdAt","type":"Date","isAutogenerated":false},{"name":"currency","type":"String","isAutogenerated":false},{"name":"mrr","type":"String","isAutogenerated":false},{"name":"name","type":"String","isAutogenerated":false},{"name":"renewalDate","type":"Date","isAutogenerated":false},{"name":"status","type":"String","isAutogenerated":false},{"name":"statusOfApp","type":"Object","isAutogenerated":false}],"keys":[],"templates":[{"configuration":{"find":{"query":"{ \"currency\": \"RUB\"}","limit":"10","sort":"{\"_id\": 1}"},"collection":"subscriptions","command":"FIND","smartSubstitution":true},"title":"Find","body":"{\n \"find\": \"subscriptions\",\n \"filter\": {\n \"currency\": \"RUB\"\n },\n \"sort\": {\n \"_id\": 1\n },\n \"limit\": 10\n}\n"},{"configuration":{"find":{"query":"{\"_id\": ObjectId(\"id_to_query_with\")}"},"collection":"subscriptions","command":"FIND","smartSubstitution":true},"title":"Find by ID","body":"{\n \"find\": \"subscriptions\",\n \"filter\": {\n \"_id\": ObjectId(\"id_to_query_with\")\n }\n}\n"},{"configuration":{"insert":{"documents":"[{ \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"currency\": \"new value\",\n \"mrr\": \"new value\",\n \"name\": \"new value\",\n \"renewalDate\": new Date(\"2019-07-01\"),\n \"status\": \"new value\",\n \"statusOfApp\": {},\n}]"},"collection":"subscriptions","command":"INSERT","smartSubstitution":true},"title":"Insert","body":"{\n \"insert\": \"subscriptions\",\n \"documents\": [\n {\n \"_id\": ObjectId(\"a_valid_object_id_hex\"),\n \"createdAt\": new Date(\"2019-07-01\"),\n \"currency\": \"new value\",\n \"mrr\": \"new value\",\n \"name\": \"new value\",\n \"renewalDate\": new Date(\"2019-07-01\"),\n \"status\": \"new value\",\n \"statusOfApp\": {},\n }\n ]\n}\n"},{"configuration":{"updateMany":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_update\") }","limit":"ALL","update":"{ \"$set\": { \"currency\": \"new value\" } }"},"collection":"subscriptions","command":"UPDATE","smartSubstitution":true},"title":"Update","body":"{\n \"update\": \"subscriptions\",\n \"updates\": [\n {\n \"q\": {\n \"_id\": ObjectId(\"id_of_document_to_update\")\n },\n \"u\": { \"$set\": { \"currency\": \"new value\" } }\n }\n ]\n}\n"},{"configuration":{"collection":"subscriptions","delete":{"query":"{ \"_id\": ObjectId(\"id_of_document_to_delete\") }","limit":"SINGLE"},"command":"DELETE","smartSubstitution":true},"title":"Delete","body":"{\n \"delete\": \"subscriptions\",\n \"deletes\": [\n {\n \"q\": {\n \"_id\": \"id_of_document_to_delete\"\n },\n \"limit\": 1\n }\n ]\n}\n"}],"name":"subscriptions","type":"COLLECTION"}]}},{"isConfigured":true,"new":true,"invalids":[],"pluginId":"redis-plugin","isValid":true,"name":"RedisTemplateApps","messages":[],"userPermissions":["execute:datasources","manage:datasources","read:datasources"],"gitSyncId":"6171a062b7de236aa183ee0e_61bb76c8cd5d704509528943","structure":{}}],"actionList":[{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"SELECT * FROM public.template_table\nWHERE col2 like '%{{Table1.searchText || \"\"}}%'\nORDER BY {{Table1.sortOrder.column || 'col1'}} {{Table1.sortOrder.order || \"ASC\"}}\nLIMIT {{Table1.pageSize}}\nOFFSET {{(Table1.pageNo - 1) * Table1.pageSize}};","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.sortOrder.order || \"ASC\"","(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","Table1.pageSize","Table1.sortOrder.column || 'col1'"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"pluginId":"postgres-plugin","id":"SQL_SelectQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"SELECT * FROM public.template_table\nWHERE col2 like '%{{Table1.searchText || \"\"}}%'\nORDER BY {{Table1.sortOrder.column || 'col1'}} {{Table1.sortOrder.order || \"ASC\"}}\nLIMIT {{Table1.pageSize}}\nOFFSET {{(Table1.pageNo - 1) * Table1.pageSize}};","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.sortOrder.order || \"ASC\"","(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","Table1.pageSize","Table1.sortOrder.column || 'col1'"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531ef8"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"INSERT INTO public.template_table (\n\t\"{{Object.keys(insert_form.sourceData).join('\",\"')}}\"\n)\nVALUES (\n\t'{{Object.values(insert_form.formData).join(\"','\")}}'\n);","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Object.values(insert_form.formData).join(\"','\")","Object.keys(insert_form.sourceData).join('\",\"')"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"postgres-plugin","id":"SQL_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"INSERT INTO public.template_table (\n\t\"{{Object.keys(insert_form.sourceData).join('\",\"')}}\"\n)\nVALUES (\n\t'{{Object.values(insert_form.formData).join(\"','\")}}'\n);","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Object.values(insert_form.formData).join(\"','\")","Object.keys(insert_form.sourceData).join('\",\"')"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531ef9"},{"new":false,"pluginType":"SAAS","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"UPDATE","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"","key":"rowOffset"},{"value":"{{update_form.formData}}","key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[9].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_form.formData"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"google-sheets-plugin","id":"Google Sheets_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"UPDATE","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"","key":"rowOffset"},{"value":"{{update_form.formData}}","key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[9].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_form.formData"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efa"},{"new":false,"pluginType":"SAAS","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"APPEND","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"","key":"rowOffset"},{"value":"{{insert_form.formData}}","key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[9].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_form.formData"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"google-sheets-plugin","id":"Google Sheets_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"APPEND","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"","key":"rowOffset"},{"value":"{{insert_form.formData}}","key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[9].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_form.formData"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efb"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":100000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name}}","viewType":"component","componentData":"{{(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name}}"},"create":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"},"expiry":{"data":"5","viewType":"component","componentData":"5"}},"body":{"data":"{{FilePicker.files[this.params.fileIndex]}}","viewType":"component","componentData":"{{FilePicker.files[this.params.fileIndex]}}"},"command":{"data":"UPLOAD_FILE_FROM_BODY","viewType":"component","componentData":"UPLOAD_FILE_FROM_BODY"}}},"userPermissions":[],"pageId":"S3","invalids":["'Query timeout' field must be an integer between 0 and 60000"],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name","FilePicker.files[this.params.fileIndex]"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"CreateFile","name":"CreateFile","messages":[]},"pluginId":"amazons3-plugin","id":"S3_CreateFile","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":100000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name}}","viewType":"component","componentData":"{{(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name}}"},"create":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"},"expiry":{"data":"5","viewType":"component","componentData":"5"}},"body":{"data":"{{FilePicker.files[this.params.fileIndex]}}","viewType":"component","componentData":"{{FilePicker.files[this.params.fileIndex]}}"},"command":{"data":"UPLOAD_FILE_FROM_BODY","viewType":"component","componentData":"UPLOAD_FILE_FROM_BODY"}}},"userPermissions":[],"pageId":"S3","invalids":["'Query timeout' field must be an integer between 0 and 60000"],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["(!!folder_name.text ? folder_name.text + \"/\" : \"\") + this.params.name","FilePicker.files[this.params.fileIndex]"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"CreateFile","name":"CreateFile","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efc"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"path":"","paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"body":{"data":"{\n\t\"data\": \"\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"\"\n}"},"list":{"prefix":{"data":"{{search_input.text}}","viewType":"component","componentData":"{{search_input.text}}"},"where":{"data":{"condition":"AND","children":[{"condition":"EQ"}]},"viewType":"component","componentData":{"condition":"AND","children":[{"condition":"EQ"}]}},"expiry":{"data":"{{ 60 * 24 }}","viewType":"component","componentData":"{{ 60 * 24 }}"},"signedUrl":{"data":"YES","viewType":"component","componentData":"YES"},"unSignedUrl":{"data":"YES","viewType":"component","componentData":"YES"}},"command":{"data":"LIST","viewType":"component","componentData":"LIST"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.list.prefix.data"},{"key":"formData.list.expiry.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["60 * 24","search_input.text"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"ListFiles","name":"ListFiles","messages":[]},"pluginId":"amazons3-plugin","id":"S3_ListFiles","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"path":"","paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"body":{"data":"{\n\t\"data\": \"\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"\"\n}"},"list":{"prefix":{"data":"{{search_input.text}}","viewType":"component","componentData":"{{search_input.text}}"},"where":{"data":{"condition":"AND","children":[{"condition":"EQ"}]},"viewType":"component","componentData":{"condition":"AND","children":[{"condition":"EQ"}]}},"expiry":{"data":"{{ 60 * 24 }}","viewType":"component","componentData":"{{ 60 * 24 }}"},"signedUrl":{"data":"YES","viewType":"component","componentData":"YES"},"unSignedUrl":{"data":"YES","viewType":"component","componentData":"YES"}},"command":{"data":"LIST","viewType":"component","componentData":"LIST"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.list.prefix.data"},{"key":"formData.list.expiry.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["60 * 24","search_input.text"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"ListFiles","name":"ListFiles","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efd"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/uepsj7o6a0hmiodonjr7xrcqj9pixe0s","headers":[{"value":"application/json","key":"content-type"}],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n\t\"app\": {{ {...get_exported_app.data, decryptedFields: undefined, datasourceList: get_exported_app.data.datasourceList.map((source) => { return {...source, structure: appsmith.store[source.pluginId] == undefined ? {}: appsmith.store[source.pluginId].data} } ) } }},\n\t\"branch\": \"{{branch_input.text}}\"\n} ","httpMethod":"POST","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":true,"jsonPathKeys":["{...get_exported_app.data, decryptedFields: undefined, datasourceList: get_exported_app.data.datasourceList.map((source) => { return {...source, structure: appsmith.store[source.pluginId] == undefined ? {}: appsmith.store[source.pluginId].data} } ) }","branch_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://hook.integromat.com"}},"validName":"update_template","name":"update_template","messages":[]},"pluginId":"restapi-plugin","id":"Admin_update_template","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/uepsj7o6a0hmiodonjr7xrcqj9pixe0s","headers":[{"value":"application/json","key":"content-type"}],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n\t\"app\": {{ {...get_exported_app.data, decryptedFields: undefined, datasourceList: get_exported_app.data.datasourceList.map((source) => { return {...source, structure: appsmith.store[source.pluginId] == undefined ? {}: appsmith.store[source.pluginId].data} } ) } }},\n\t\"branch\": \"{{branch_input.text}}\"\n} ","httpMethod":"POST","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":true,"jsonPathKeys":["{...get_exported_app.data, decryptedFields: undefined, datasourceList: get_exported_app.data.datasourceList.map((source) => { return {...source, structure: appsmith.store[source.pluginId] == undefined ? {}: appsmith.store[source.pluginId].data} } ) }","branch_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://hook.integromat.com"}},"validName":"update_template","name":"update_template","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531efe"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"path":"/api/v1/applications/export/61764fbeba7e887d03bc3631","headers":[],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"httpMethod":"GET","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_exported_app","name":"get_exported_app","messages":[]},"pluginId":"restapi-plugin","id":"Admin_get_exported_app","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"path":"/api/v1/applications/export/61764fbeba7e887d03bc3631","headers":[],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"httpMethod":"GET","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_exported_app","name":"get_exported_app","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531eff"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/datasources/{{this.params.id}}/structure","headers":[],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["this.params.id"],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_datasource_structure","name":"get_datasource_structure","messages":[]},"pluginId":"restapi-plugin","id":"Admin_get_datasource_structure","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/datasources/{{this.params.id}}/structure","headers":[],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[{"key":"path"}],"confirmBeforeExecute":false,"jsonPathKeys":["this.params.id"],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_datasource_structure","name":"get_datasource_structure","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f00"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"DELETE FROM public.template_table\n WHERE col1 = {{Table1.triggeredRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.triggeredRow.col1"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"postgres-plugin","id":"SQL_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"DELETE FROM public.template_table\n WHERE col1 = {{Table1.triggeredRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.triggeredRow.col1"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f01"},{"new":false,"pluginType":"SAAS","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"GET","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"{{data_table.pageSize}}","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"{{(data_table.pageNo - 1) * data_table.pageSize}}","key":"rowOffset"},{"key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"},{"value":[{}],"key":"where"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","(data_table.pageNo - 1) * data_table.pageSize"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"pluginId":"google-sheets-plugin","id":"Google Sheets_SelectQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"GET","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"{{data_table.pageSize}}","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"{{(data_table.pageNo - 1) * data_table.pageSize}}","key":"rowOffset"},{"key":"rowObject"},{"key":"rowObjects"},{"value":"","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"},{"value":[{}],"key":"where"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","(data_table.pageNo - 1) * data_table.pageSize"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f02"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"UPDATE public.template_table SET\n\t\tcol2 = '{{update_form.formData.col2}}',\n col3 = '{{update_form.formData.col3}}',\n col4 = '{{update_form.formData.col4}}',\n col5 = '{{update_form.formData.col5}}'\n WHERE col1 = {{Table1.selectedRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_form.formData.col2","Table1.selectedRow.col1","update_form.formData.col3","update_form.formData.col4","update_form.formData.col5"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"postgres-plugin","id":"SQL_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"UPDATE public.template_table SET\n\t\tcol2 = '{{update_form.formData.col2}}',\n col3 = '{{update_form.formData.col3}}',\n col4 = '{{update_form.formData.col4}}',\n col5 = '{{update_form.formData.col5}}'\n WHERE col1 = {{Table1.selectedRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"SQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_form.formData.col2","Table1.selectedRow.col1","update_form.formData.col3","update_form.formData.col4","update_form.formData.col5"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f03"},{"new":false,"pluginType":"SAAS","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"DELETE_ROW","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"{{data_table.pageSize}}","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"{{(data_table.pageNo - 1) * data_table.pageSize}}","key":"rowOffset"},{"key":"rowObject"},{"key":"rowObjects"},{"value":"{{data_table.triggeredRow.rowIndex}}","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[6].value"},{"key":"pluginSpecifiedTemplates[8].value"},{"key":"pluginSpecifiedTemplates[11].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","data_table.triggeredRow.rowIndex","(data_table.pageNo - 1) * data_table.pageSize"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"google-sheets-plugin","id":"Google Sheets_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"pluginSpecifiedTemplates":[{"value":"DELETE_ROW","key":"method"},{"value":"https://docs.google.com/spreadsheets/d/1P6or_F8UZ9sJX3JRAsX_kQDMRRnXqrnRgRIiml8Gjl0/edit#gid=0","key":"sheetUrl"},{"value":"","key":"range"},{"value":"","key":"spreadsheetName"},{"value":"1","key":"tableHeaderIndex"},{"value":"ROWS","key":"queryFormat"},{"value":"{{data_table.pageSize}}","key":"rowLimit"},{"value":"template_table","key":"sheetName"},{"value":"{{(data_table.pageNo - 1) * data_table.pageSize}}","key":"rowOffset"},{"key":"rowObject"},{"key":"rowObjects"},{"value":"{{data_table.triggeredRow.rowIndex}}","key":"rowIndex"},{"value":"SHEET","key":"deleteFormat"},{"value":false,"key":"smartSubstitution"}]},"userPermissions":[],"pageId":"Google Sheets","invalids":[],"dynamicBindingPathList":[{"key":"pluginSpecifiedTemplates[6].value"},{"key":"pluginSpecifiedTemplates[8].value"},{"key":"pluginSpecifiedTemplates[11].value"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","data_table.triggeredRow.rowIndex","(data_table.pageNo - 1) * data_table.pageSize"],"datasource":{"new":false,"pluginId":"google-sheets-plugin","isValid":true,"messages":[],"id":"Google Sheet","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f04"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{tableName_input.text}}\",\n \"datasourceId\": \"{{datasource_input.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]}}\",\n \"applicationId\" : \"{{datasource_input.text.split(\"applications/\")[1].split(\"/\")[0]}}\",\n\t\t\"searchColumn\": \"{{search_col_input.text}}\",\n\t\t\"columns\": \"{{select_cols_input.text}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["select_cols_input.text","datasource_input.text.split(\"applications/\")[1].split(\"/\")[0]","datasource_input.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]","search_col_input.text","tableName_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_sql_app","name":"generate_sql_app","messages":[]},"pluginId":"restapi-plugin","id":"Page Generator_generate_sql_app","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{tableName_input.text}}\",\n \"datasourceId\": \"{{datasource_input.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]}}\",\n \"applicationId\" : \"{{datasource_input.text.split(\"applications/\")[1].split(\"/\")[0]}}\",\n\t\t\"searchColumn\": \"{{search_col_input.text}}\",\n\t\t\"columns\": \"{{select_cols_input.text}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["select_cols_input.text","datasource_input.text.split(\"applications/\")[1].split(\"/\")[0]","datasource_input.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]","search_col_input.text","tableName_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_sql_app","name":"generate_sql_app","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f05"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"find":{"query":{"data":"{ col2: /{{data_table.searchText||\"\"}}/i }","viewType":"component","componentData":"{ col2: /{{data_table.searchText||\"\"}}/i }"},"limit":{"data":"{{data_table.pageSize}}","viewType":"component","componentData":"{{data_table.pageSize}}"},"skip":{"data":"{{(data_table.pageNo - 1) * data_table.pageSize}}","viewType":"component","componentData":"{{(data_table.pageNo - 1) * data_table.pageSize}}"},"sort":{"data":"{ \n{{data_table.sortOrder.column || 'col1'}}: {{data_table.sortOrder.order == \"desc\" ? -1 : 1}} \n}","viewType":"component","componentData":"{ \n{{key_select.selectedOptionValue}}: {{order_select.selectedOptionValue}} \n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"FIND","viewType":"component","componentData":"FIND"},"smartSubstitution":{"data":false,"viewType":"component","componentData":false},"misc":{"formToNativeQuery":{"data":"{\n \"find\": \"template_table\",\n \"filter\": { col2: /{{data_table.searchText||\"\"}}/i },\n \"sort\": { \n{{data_table.sortOrder.column || 'col1'}}: {{data_table.sortOrder.order == \"desc\" ? -1 : 1}} \n},\n \"skip\": {{(data_table.pageNo - 1) * data_table.pageSize}},\n \"limit\": {{data_table.pageSize}},\n \"batchSize\": {{data_table.pageSize}}\n}\n","status":"SUCCESS"}}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[{"key":"formData.find.sort.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.sortOrder.column || 'col1'","key_select.selectedOptionValue","data_table.pageSize","data_table.sortOrder.order == \"desc\" ? -1 : 1","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"FindQuery","name":"FindQuery","messages":[]},"pluginId":"mongo-plugin","id":"MongoDB_FindQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"find":{"query":{"data":"{ col2: /{{data_table.searchText||\"\"}}/i }","viewType":"component","componentData":"{ col2: /{{data_table.searchText||\"\"}}/i }"},"limit":{"data":"{{data_table.pageSize}}","viewType":"component","componentData":"{{data_table.pageSize}}"},"skip":{"data":"{{(data_table.pageNo - 1) * data_table.pageSize}}","viewType":"component","componentData":"{{(data_table.pageNo - 1) * data_table.pageSize}}"},"sort":{"data":"{ \n{{data_table.sortOrder.column || 'col1'}}: {{data_table.sortOrder.order == \"desc\" ? -1 : 1}} \n}","viewType":"component","componentData":"{ \n{{key_select.selectedOptionValue}}: {{order_select.selectedOptionValue}} \n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"FIND","viewType":"component","componentData":"FIND"},"smartSubstitution":{"data":false,"viewType":"component","componentData":false},"misc":{"formToNativeQuery":{"data":"{\n \"find\": \"template_table\",\n \"filter\": { col2: /{{data_table.searchText||\"\"}}/i },\n \"sort\": { \n{{data_table.sortOrder.column || 'col1'}}: {{data_table.sortOrder.order == \"desc\" ? -1 : 1}} \n},\n \"skip\": {{(data_table.pageNo - 1) * data_table.pageSize}},\n \"limit\": {{data_table.pageSize}},\n \"batchSize\": {{data_table.pageSize}}\n}\n","status":"SUCCESS"}}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[{"key":"formData.find.sort.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.sortOrder.column || 'col1'","key_select.selectedOptionValue","data_table.pageSize","data_table.sortOrder.order == \"desc\" ? -1 : 1","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"FindQuery","name":"FindQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f06"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"template_table/{{data_table.selectedRow._ref}}","paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"delete":{"query":{"data":"{ _id: ObjectId('{{data_table.triggeredRow._id}}') }","viewType":"component","componentData":"{ _id: ObjectId('{{data_table.triggeredRow._id}}') }"},"limit":{"data":"SINGLE","viewType":"component","componentData":"SINGLE"}},"command":{"data":"DELETE","viewType":"component","componentData":"DELETE"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow._ref","data_table.triggeredRow._id"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"mongo-plugin","id":"MongoDB_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"template_table/{{data_table.selectedRow._ref}}","paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"delete":{"query":{"data":"{ _id: ObjectId('{{data_table.triggeredRow._id}}') }","viewType":"component","componentData":"{ _id: ObjectId('{{data_table.triggeredRow._id}}') }"},"limit":{"data":"SINGLE","viewType":"component","componentData":"SINGLE"}},"command":{"data":"DELETE","viewType":"component","componentData":"DELETE"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow._ref","data_table.triggeredRow._id"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f07"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"updateMany":{"query":{"data":"{ _id: ObjectId('{{data_table.selectedRow._id}}') }","viewType":"component","componentData":"{ _id: ObjectId('{{data_table.selectedRow._id}}') }"},"limit":{"data":"SINGLE","viewType":"component","componentData":"SINGLE"},"update":{"data":"{{update_form.formData}}","viewType":"component","componentData":"{\n \"col1\" : {{update_col_1.text}},\n\t\"col2\" : {{update_col_2.text}},\n \"col3\" : {{update_col_3.text}},\n \"col4\" : {{update_col_4.text}}\n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"UPDATE","viewType":"component","componentData":"UPDATE"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true},"misc":{"formToNativeQuery":{"data":"{\n \"update\": \"template_table\",\n \"updates\": [{\n \"q\": { _id: ObjectId('{{data_table.selectedRow._id}}') },\n \"u\": {{update_form.formData}},\n \"multi\": false,\n }]\n}\n","status":"SUCCESS"}}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[{"key":"formData.updateMany.update.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","update_col_2.text","update_form.formData","data_table.selectedRow._id","update_col_1.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"mongo-plugin","id":"MongoDB_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"updateMany":{"query":{"data":"{ _id: ObjectId('{{data_table.selectedRow._id}}') }","viewType":"component","componentData":"{ _id: ObjectId('{{data_table.selectedRow._id}}') }"},"limit":{"data":"SINGLE","viewType":"component","componentData":"SINGLE"},"update":{"data":"{{update_form.formData}}","viewType":"component","componentData":"{\n \"col1\" : {{update_col_1.text}},\n\t\"col2\" : {{update_col_2.text}},\n \"col3\" : {{update_col_3.text}},\n \"col4\" : {{update_col_4.text}}\n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"UPDATE","viewType":"component","componentData":"UPDATE"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true},"misc":{"formToNativeQuery":{"data":"{\n \"update\": \"template_table\",\n \"updates\": [{\n \"q\": { _id: ObjectId('{{data_table.selectedRow._id}}') },\n \"u\": {{update_form.formData}},\n \"multi\": false,\n }]\n}\n","status":"SUCCESS"}}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[{"key":"formData.updateMany.update.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","update_col_2.text","update_form.formData","data_table.selectedRow._id","update_col_1.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f08"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"insert":{"documents":{"data":"{{insert_form.formData}}","viewType":"component","componentData":"{\n \"col1\": {{insert_col_input1.text}}, \n \"col2\": {{insert_col_input2.text}}, \n \"col3\": {{insert_col_input3.text}}, \n \"col4\": {{insert_col_input4.text}}\n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"INSERT","viewType":"component","componentData":"INSERT"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true},"misc":{"formToNativeQuery":{"data":"{\n \"insert\": \"template_table\",\n \"documents\": {{insert_form.formData}}\n}\n","status":"SUCCESS"}}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[{"key":"formData.insert.documents.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input4.text","insert_col_input3.text","insert_form.formData","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"mongo-plugin","id":"MongoDB_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"insert":{"documents":{"data":"{{insert_form.formData}}","viewType":"component","componentData":"{\n \"col1\": {{insert_col_input1.text}}, \n \"col2\": {{insert_col_input2.text}}, \n \"col3\": {{insert_col_input3.text}}, \n \"col4\": {{insert_col_input4.text}}\n}"}},"collection":{"data":"template_table","viewType":"component","componentData":"template_table"},"command":{"data":"INSERT","viewType":"component","componentData":"INSERT"},"smartSubstitution":{"data":true,"viewType":"component","componentData":true},"misc":{"formToNativeQuery":{"data":"{\n \"insert\": \"template_table\",\n \"documents\": {{insert_form.formData}}\n}\n","status":"SUCCESS"}}}},"userPermissions":[],"pageId":"MongoDB","invalids":[],"dynamicBindingPathList":[{"key":"formData.insert.documents.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input4.text","insert_col_input3.text","insert_form.formData","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"mongo-plugin","isValid":true,"messages":[],"id":"Mock_Mongo","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f09"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{collection_input.text}}\",\n \"datasourceId\": \"{{mongo_ds_url.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]}}\",\n \"applicationId\" : \"untitled-application-1\",\n\t\t\"searchColumn\" : \"{{search_keys_input.text}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["mongo_ds_url.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]","collection_input.text","search_keys_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_mongo_app","name":"generate_mongo_app","messages":[]},"pluginId":"restapi-plugin","id":"Page Generator_generate_mongo_app","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{collection_input.text}}\",\n \"datasourceId\": \"{{mongo_ds_url.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]}}\",\n \"applicationId\" : \"untitled-application-1\",\n\t\t\"searchColumn\" : \"{{search_keys_input.text}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["mongo_ds_url.text.split(\"datasource/\")[1].split(\"?\" || \"/\")[0]","collection_input.text","search_keys_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_mongo_app","name":"generate_mongo_app","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0a"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{collection_input.text}}\",\n \"datasourceId\": \"{{gsheet_ds_input.text.split(\"datasources/\")[1].split(\"/\" || \"?\")[0]}}\",\n \"applicationId\" : \"{{gsheet_ds_input.text.split(\"applications/\")[1].split(\"/\")[0]}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["gsheet_ds_input.text.split(\"datasources/\")[1].split(\"/\" || \"?\")[0]","gsheet_ds_input.text.split(\"applications/\")[1].split(\"/\")[0]","collection_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_gsheet_app","name":"generate_gsheet_app","messages":[]},"pluginId":"restapi-plugin","id":"Page Generator_generate_gsheet_app","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/pages/crud-page","headers":[{"value":"application/json","key":"Content-Type"},{"value":"SESSION=691d7061-6eb8-4483-af91-b6e5de0692cc","key":"Cookie"}],"paginationType":"PAGE_NO","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"{\n \"tableName\": \"{{collection_input.text}}\",\n \"datasourceId\": \"{{gsheet_ds_input.text.split(\"datasources/\")[1].split(\"/\" || \"?\")[0]}}\",\n \"applicationId\" : \"{{gsheet_ds_input.text.split(\"applications/\")[1].split(\"/\")[0]}}\"\n}","httpMethod":"POST"},"userPermissions":[],"pageId":"Page Generator","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["gsheet_ds_input.text.split(\"datasources/\")[1].split(\"/\" || \"?\")[0]","gsheet_ds_input.text.split(\"applications/\")[1].split(\"/\")[0]","collection_input.text"],"datasource":{"new":true,"invalids":[],"pluginId":"restapi-plugin","isValid":true,"name":"DEFAULT_REST_DATASOURCE","messages":[],"userPermissions":[],"datasourceConfiguration":{"url":"https://release.app.appsmith.com"}},"validName":"generate_gsheet_app","name":"generate_gsheet_app","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0b"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{File_List.selectedItem.fileName}}","viewType":"component","componentData":"{{File_List.selectedItem.fileName}}"},"body":{"data":"{\n\t\"data\": \"null\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"null\"\n}"},"command":{"data":"DELETE_FILE","viewType":"component","componentData":"DELETE_FILE"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["File_List.selectedItem.fileName"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"DeleteFile","name":"DeleteFile","messages":[]},"pluginId":"amazons3-plugin","id":"S3_DeleteFile","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{File_List.selectedItem.fileName}}","viewType":"component","componentData":"{{File_List.selectedItem.fileName}}"},"body":{"data":"{\n\t\"data\": \"null\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"null\"\n}"},"command":{"data":"DELETE_FILE","viewType":"component","componentData":"DELETE_FILE"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["File_List.selectedItem.fileName"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"DeleteFile","name":"DeleteFile","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0c"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{File_List.selectedItem.fileName}}","viewType":"component","componentData":"{{File_List.selectedItem.fileName}}"},"read":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"}},"body":{"data":"{\n\t\"data\": \"\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"\"\n}"},"command":{"data":"READ_FILE","viewType":"component","componentData":"READ_FILE"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["File_List.selectedItem.fileName"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"ReadFile","name":"ReadFile","messages":[]},"pluginId":"amazons3-plugin","id":"S3_ReadFile","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{File_List.selectedItem.fileName}}","viewType":"component","componentData":"{{File_List.selectedItem.fileName}}"},"read":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"}},"body":{"data":"{\n\t\"data\": \"\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"\"\n}"},"command":{"data":"READ_FILE","viewType":"component","componentData":"READ_FILE"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["File_List.selectedItem.fileName"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"ReadFile","name":"ReadFile","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0d"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{update_file_name.text}}","viewType":"component","componentData":"{{update_file_name.text}}"},"create":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"},"expiry":{"data":"5","viewType":"component","componentData":"5"}},"body":{"data":"{\n\t\"data\": \"{{update_file_picker.files.length ? update_file_picker.files[0].data : \"\" }}\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"{{update_file_picker.files.length ? update_file_picker.files[0].data : \"\" }}\"\n}"},"command":{"data":"UPLOAD_FILE_FROM_BODY","viewType":"component","componentData":"UPLOAD_FILE_FROM_BODY"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_file_picker.files.length ? update_file_picker.files[0].data : \"\"","update_file_name.text"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"UpdateFile","name":"UpdateFile","messages":[]},"pluginId":"amazons3-plugin","id":"S3_UpdateFile","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"bucket":{"data":"assets-test.appsmith.com","viewType":"component","componentData":"assets-test.appsmith.com"},"path":{"data":"{{update_file_name.text}}","viewType":"component","componentData":"{{update_file_name.text}}"},"create":{"dataType":{"data":"YES","viewType":"component","componentData":"YES"},"expiry":{"data":"5","viewType":"component","componentData":"5"}},"body":{"data":"{\n\t\"data\": \"{{update_file_picker.files.length ? update_file_picker.files[0].data : \"\" }}\"\n}","viewType":"component","componentData":"{\n\t\"data\": \"{{update_file_picker.files.length ? update_file_picker.files[0].data : \"\" }}\"\n}"},"command":{"data":"UPLOAD_FILE_FROM_BODY","viewType":"component","componentData":"UPLOAD_FILE_FROM_BODY"}}},"userPermissions":[],"pageId":"S3","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_file_picker.files.length ? update_file_picker.files[0].data : \"\"","update_file_name.text"],"datasource":{"new":false,"pluginId":"amazons3-plugin","isValid":true,"messages":[],"id":"AmazonS3 CRUD","userPermissions":[]},"validName":"UpdateFile","name":"UpdateFile","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0e"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"{{data_table.selectedRow._ref.path}}","viewType":"component","componentData":"{{data_table.selectedRow._ref.path}}"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"UPDATE","viewType":"component","componentData":"UPDATE"},"body":{"data":"{{update_form.formData}}","viewType":"component","componentData":"{\n\t\"col1\": \"{{update_col_1.text}}\",\n\t\"col2\": \"{{update_col_2.text}}\",\n\t\"col3\": \"{{update_col_3.text}}\",\n\t\"col4\": \"{{update_col_4.text}}\",\n\t\"col5\": \"{{update_col_5.text}}\"\n}"},"command":{"data":"UPDATE_DOCUMENT","viewType":"component","componentData":"UPDATE_DOCUMENT"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","update_col_2.text","data_table.selectedRow._ref.path","update_form.formData","update_col_1.text","update_col_5.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"firestore-plugin","id":"Firestore_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"{{data_table.selectedRow._ref.path}}","viewType":"component","componentData":"{{data_table.selectedRow._ref.path}}"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"UPDATE","viewType":"component","componentData":"UPDATE"},"body":{"data":"{{update_form.formData}}","viewType":"component","componentData":"{\n\t\"col1\": \"{{update_col_1.text}}\",\n\t\"col2\": \"{{update_col_2.text}}\",\n\t\"col3\": \"{{update_col_3.text}}\",\n\t\"col4\": \"{{update_col_4.text}}\",\n\t\"col5\": \"{{update_col_5.text}}\"\n}"},"command":{"data":"UPDATE_DOCUMENT","viewType":"component","componentData":"UPDATE_DOCUMENT"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"},{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_col_3.text","update_col_2.text","data_table.selectedRow._ref.path","update_form.formData","update_col_1.text","update_col_5.text","update_col_4.text"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f0f"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"{{data_table.triggeredRow._ref.path}}","viewType":"component","componentData":"{{data_table.triggeredRow._ref.path}}"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"DELETE","viewType":"component","componentData":"DELETE"},"command":{"data":"DELETE_DOCUMENT","viewType":"component","componentData":"DELETE_DOCUMENT"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.triggeredRow._ref.path","data_table.selectedRow._id"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"firestore-plugin","id":"Firestore_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"{{data_table.triggeredRow._ref.path}}","viewType":"component","componentData":"{{data_table.triggeredRow._ref.path}}"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"DELETE","viewType":"component","componentData":"DELETE"},"command":{"data":"DELETE_DOCUMENT","viewType":"component","componentData":"DELETE_DOCUMENT"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.path.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.triggeredRow._ref.path","data_table.selectedRow._id"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f10"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"template_table","viewType":"component","componentData":"template_table"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"INSERT","viewType":"component","componentData":"INSERT"},"body":{"data":"{{insert_form.formData}}","viewType":"component","componentData":"{\n\t\"col1\": \"{{insert_col_input1.text}}\",\n\t\"col2\": \"{{insert_col_input2.text}}\",\n\t\"col3\": \"{{insert_col_input3.text}}\",\n\t\"col4\": \"{{insert_col_input4.text}}\",\n\t\"col5\": \"{{insert_col_input5.text}}\"\n}"},"command":{"data":"ADD_TO_COLLECTION","viewType":"component","componentData":"ADD_TO_COLLECTION"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_form.formData","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"firestore-plugin","id":"Firestore_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{}","viewType":"component","componentData":"{}"},"path":{"data":"template_table","viewType":"component","componentData":"template_table"},"prev":{"data":"{}","viewType":"component","componentData":"{}"},"orderBy":{"data":"FORM","viewType":"component","componentData":"FORM"},"limitDocuments":{"data":"INSERT","viewType":"component","componentData":"INSERT"},"body":{"data":"{{insert_form.formData}}","viewType":"component","componentData":"{\n\t\"col1\": \"{{insert_col_input1.text}}\",\n\t\"col2\": \"{{insert_col_input2.text}}\",\n\t\"col3\": \"{{insert_col_input3.text}}\",\n\t\"col4\": \"{{insert_col_input4.text}}\",\n\t\"col5\": \"{{insert_col_input5.text}}\"\n}"},"command":{"data":"ADD_TO_COLLECTION","viewType":"component","componentData":"ADD_TO_COLLECTION"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.body.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_col_input1.text","insert_col_input5.text","insert_col_input4.text","insert_col_input3.text","insert_form.formData","insert_col_input2.text"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f11"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{{data_table.tableData[data_table.tableData.length - 1]}}","viewType":"component","componentData":"{{SelectQuery.data[SelectQuery.data.length - 1]}}"},"timestampValuePath":{"data":"","viewType":"component","componentData":""},"path":{"data":"template_table","viewType":"component","componentData":"template_table"},"startAfter":{"data":"{{SelectQuery.data[SelectQuery.data.length - 1]}}","viewType":"component","componentData":"{{SelectQuery.data[SelectQuery.data.length - 1]}}"},"endBefore":{"data":"{{SelectQuery.data[0]}}","viewType":"component","componentData":"{{SelectQuery.data[0]}}"},"deleteKeyPath":{"data":"","viewType":"component","componentData":""},"prev":{"data":"{{data_table.tableData[0]}}","viewType":"component","componentData":"{{SelectQuery.data[0]}}"},"orderBy":{"data":"[\"{{(data_table.sortOrder.order === \"desc\" ? \"-\" : \"\") + (data_table.sortOrder.column || 'col1')}}\"]","viewType":"component","componentData":"[\"{{order_select.selectedOptionValue + key_select.selectedOptionValue}}\"]"},"where":{"data":{"children":[{"condition":"EQ"}]},"viewType":"component"},"limitDocuments":{"data":"{{data_table.pageSize}}","viewType":"component","componentData":"1"},"command":{"data":"GET_COLLECTION","viewType":"component","componentData":"GET_COLLECTION"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.startAfter.data"},{"key":"formData.endBefore.data"},{"key":"formData.orderBy.data"},{"key":"formData.next.data"},{"key":"formData.prev.data"},{"key":"formData.limitDocuments.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["SelectQuery.data[SelectQuery.data.length - 1]","data_table.tableData[data_table.tableData.length - 1]","data_table.pageSize","data_table.tableData[0]","(data_table.sortOrder.order === \"desc\" ? \"-\" : \"\") + (data_table.sortOrder.column || 'col1')","order_select.selectedOptionValue + key_select.selectedOptionValue","SelectQuery.data[0]"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"pluginId":"firestore-plugin","id":"Firestore_SelectQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"formData":{"next":{"data":"{{data_table.tableData[data_table.tableData.length - 1]}}","viewType":"component","componentData":"{{SelectQuery.data[SelectQuery.data.length - 1]}}"},"timestampValuePath":{"data":"","viewType":"component","componentData":""},"path":{"data":"template_table","viewType":"component","componentData":"template_table"},"startAfter":{"data":"{{SelectQuery.data[SelectQuery.data.length - 1]}}","viewType":"component","componentData":"{{SelectQuery.data[SelectQuery.data.length - 1]}}"},"endBefore":{"data":"{{SelectQuery.data[0]}}","viewType":"component","componentData":"{{SelectQuery.data[0]}}"},"deleteKeyPath":{"data":"","viewType":"component","componentData":""},"prev":{"data":"{{data_table.tableData[0]}}","viewType":"component","componentData":"{{SelectQuery.data[0]}}"},"orderBy":{"data":"[\"{{(data_table.sortOrder.order === \"desc\" ? \"-\" : \"\") + (data_table.sortOrder.column || 'col1')}}\"]","viewType":"component","componentData":"[\"{{order_select.selectedOptionValue + key_select.selectedOptionValue}}\"]"},"where":{"data":{"children":[{"condition":"EQ"}]},"viewType":"component"},"limitDocuments":{"data":"{{data_table.pageSize}}","viewType":"component","componentData":"1"},"command":{"data":"GET_COLLECTION","viewType":"component","componentData":"GET_COLLECTION"},"smartSubstitution":"false"}},"userPermissions":[],"pageId":"Firestore","invalids":[],"dynamicBindingPathList":[{"key":"formData.startAfter.data"},{"key":"formData.endBefore.data"},{"key":"formData.orderBy.data"},{"key":"formData.next.data"},{"key":"formData.prev.data"},{"key":"formData.limitDocuments.data"}],"confirmBeforeExecute":false,"jsonPathKeys":["SelectQuery.data[SelectQuery.data.length - 1]","data_table.tableData[data_table.tableData.length - 1]","data_table.pageSize","data_table.tableData[0]","(data_table.sortOrder.order === \"desc\" ? \"-\" : \"\") + (data_table.sortOrder.column || 'col1')","order_select.selectedOptionValue + key_select.selectedOptionValue","SelectQuery.data[0]"],"datasource":{"new":false,"pluginId":"firestore-plugin","isValid":true,"messages":[],"id":"FBTemplateDB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f12"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"keys *"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"FetchKeys","name":"FetchKeys","messages":[]},"pluginId":"redis-plugin","id":"Redis_FetchKeys","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"keys *"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"FetchKeys","name":"FetchKeys","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f13"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"set {{insert_key_input.text}} \"{{insert_value_input.text}}\""},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_key_input.text","insert_value_input.text"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"InsertKey","name":"InsertKey","messages":[]},"pluginId":"redis-plugin","id":"Redis_InsertKey","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"set {{insert_key_input.text}} \"{{insert_value_input.text}}\""},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["insert_key_input.text","insert_value_input.text"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"InsertKey","name":"InsertKey","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f14"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"set {{data_table.selectedRow.result}} \"{{update_value_input.text}}\""},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_value_input.text","data_table.selectedRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"UpdateKey","name":"UpdateKey","messages":[]},"pluginId":"redis-plugin","id":"Redis_UpdateKey","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"set {{data_table.selectedRow.result}} \"{{update_value_input.text}}\""},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_value_input.text","data_table.selectedRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"UpdateKey","name":"UpdateKey","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f15"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"del {{data_table.triggeredRow.result}}"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.triggeredRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"DeleteKey","name":"DeleteKey","messages":[]},"pluginId":"redis-plugin","id":"Redis_DeleteKey","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"del {{data_table.triggeredRow.result}}"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.triggeredRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"DeleteKey","name":"DeleteKey","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f16"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"GET {{data_table.selectedRow.result}}"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"FetchValue","name":"FetchValue","messages":[]},"pluginId":"redis-plugin","id":"Redis_FetchValue","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"GET {{data_table.selectedRow.result}}"},"userPermissions":[],"pageId":"Redis","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow.result"],"datasource":{"new":false,"pluginId":"redis-plugin","isValid":true,"messages":[],"id":"RedisTemplateApps","userPermissions":[]},"validName":"FetchValue","name":"FetchValue","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f17"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"DELETE FROM public.template_table\n WHERE \"col1\" = {{Table1.triggeredRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.triggeredRow.col1"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"pluginId":"postgres-plugin","id":"PostgreSQL_DeleteQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"DELETE FROM public.template_table\n WHERE \"col1\" = {{Table1.triggeredRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Table1.triggeredRow.col1"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"DeleteQuery","name":"DeleteQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f18"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"UPDATE public.template_table SET\n\t\t\"col2\" = '{{update_form.formData.col2}}',\n \"col3\" = '{{update_form.formData.col3}}',\n \"col4\" = '{{update_form.formData.col4}}',\n \"col5\" = '{{update_form.formData.col5}}'\n WHERE \"col1\" = {{Table1.selectedRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_form.formData.col2","Table1.selectedRow.col1","update_form.formData.col3","update_form.formData.col4","update_form.formData.col5"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"pluginId":"postgres-plugin","id":"PostgreSQL_UpdateQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"UPDATE public.template_table SET\n\t\t\"col2\" = '{{update_form.formData.col2}}',\n \"col3\" = '{{update_form.formData.col3}}',\n \"col4\" = '{{update_form.formData.col4}}',\n \"col5\" = '{{update_form.formData.col5}}'\n WHERE \"col1\" = {{Table1.selectedRow.col1}};","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["update_form.formData.col2","Table1.selectedRow.col1","update_form.formData.col3","update_form.formData.col4","update_form.formData.col5"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"UpdateQuery","name":"UpdateQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f19"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"SELECT * FROM public.template_table\nWHERE \"col2\" ilike '%{{Table1.searchText || \"\"}}%'\nORDER BY \"{{Table1.sortOrder.column || 'col1'}}\" {{Table1.sortOrder.order || 'ASC'}}\nLIMIT {{Table1.pageSize}}\nOFFSET {{(Table1.pageNo - 1) * Table1.pageSize}};","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","Table1.pageSize","Table1.sortOrder.order || 'ASC'","Table1.sortOrder.column || 'col1'"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"pluginId":"postgres-plugin","id":"PostgreSQL_SelectQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":true,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"SELECT * FROM public.template_table\nWHERE \"col2\" ilike '%{{Table1.searchText || \"\"}}%'\nORDER BY \"{{Table1.sortOrder.column || 'col1'}}\" {{Table1.sortOrder.order || 'ASC'}}\nLIMIT {{Table1.pageSize}}\nOFFSET {{(Table1.pageNo - 1) * Table1.pageSize}};","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","Table1.pageSize","Table1.sortOrder.order || 'ASC'","Table1.sortOrder.column || 'col1'"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"SelectQuery","name":"SelectQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f1a"},{"new":false,"pluginType":"DB","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"INSERT INTO public.template_table (\n\t\"{{Object.keys(insert_form.sourceData).join('\",\"')}}\"\n)\nVALUES (\n\t'{{Object.values(insert_form.formData).join(\"','\")}}'\n);","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Object.values(insert_form.formData).join(\"','\")","Object.keys(insert_form.sourceData).join('\",\"')"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"pluginId":"postgres-plugin","id":"PostgreSQL_InsertQuery","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"paginationType":"NONE","timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"INSERT INTO public.template_table (\n\t\"{{Object.keys(insert_form.sourceData).join('\",\"')}}\"\n)\nVALUES (\n\t'{{Object.values(insert_form.formData).join(\"','\")}}'\n);","pluginSpecifiedTemplates":[{"value":false}]},"userPermissions":[],"pageId":"PostgreSQL","invalids":[],"dynamicBindingPathList":[{"key":"body"}],"confirmBeforeExecute":false,"jsonPathKeys":["Object.values(insert_form.formData).join(\"','\")","Object.keys(insert_form.sourceData).join('\",\"')"],"datasource":{"new":false,"pluginId":"postgres-plugin","isValid":true,"messages":[],"id":"Internal DB","userPermissions":[]},"validName":"InsertQuery","name":"InsertQuery","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb7738cd5d704509531f1b"},{"new":false,"pluginType":"API","unpublishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/users/me","headers":[{"value":"_hjid=41cedd95-19f9-438a-8b6e-f2c4d7fb086b; SL_C_23361dd035530_KEY=c370af0df0edf38360adbefbdc47d2b42ea137c9; SL_C_23361dd035530_VID=P3kBR7eMjg; ajs_anonymous_id=e6ef9c9b-3407-4374-81ab-6bafef26a4d1; [email protected]; intercom-id-y10e7138=50e190b7-b24e-4bef-b320-3c47a3c91006; amplitude_id_fef1e872c952688acd962d30aa545b9eappsmith.com=eyJkZXZpY2VJZCI6IjIxNWJlMWRkLTNjMGQtNDY5NS05YzRmLTFjYTM4MjNhNzM5NlIiLCJ1c2VySWQiOm51bGwsIm9wdE91dCI6ZmFsc2UsInNlc3Npb25JZCI6MTYzNjI1ODEwMjkyNCwibGFzdEV2ZW50VGltZSI6MTYzNjI1ODEwMzE3MywiZXZlbnRJZCI6NSwiaWRlbnRpZnlJZCI6MSwic2VxdWVuY2VOdW1iZXIiOjZ9; _ga=GA1.2.526957763.1633412376; _gid=GA1.2.1610516593.1636258104; _ga_0JZ9C3M56S=GS1.1.1636258103.3.1.1636258646.0; SESSION=09ae7c78-ca84-4a38-916a-f282893efb40; mp_70b8ea94d623dd857fb555a76d11f944_mixpanel=%7B%22distinct_id%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24device_id%22%3A%20%2217c91e75170277-051d4ff86c77bb-1d3b6650-168000-17c91e75171dc2%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22mp_lib%22%3A%20%22Segment%3A%20web%22%2C%22%24user_id%22%3A%20%22nidhi%40appsmith.com%22%2C%22mp_name_tag%22%3A%20%22nidhi%40appsmith.com%22%2C%22userId%22%3A%20%22nidhi%40appsmith.com%22%2C%22source%22%3A%20%22cloud%22%2C%22id%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24email%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24first_name%22%3A%20%22Nidhi%22%2C%22%24last_name%22%3A%20%22Nair%22%2C%22%24name%22%3A%20%22Nidhi%20Nair%22%7D; SL_C_23361dd035530_SID=3VIjO5jKCt; intercom-session-y10e7138=WnhwMVl4VmVIUDFPVkgxUDVidm8wOXUzNjZ2elJ0OWx2a21Qc3NCYk1zenNEa0dzMkswWFlpanM4YXNxY2pQYi0taFpkWkR6K0xLUFJyUVFRSkMwZ3pUUT09--376a7fef0d7774b3284b94fb4c1ea1c8e2305afe; _hjAbsoluteSessionInProgress=1","key":"Cookie"}],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_user","name":"get_user","messages":[]},"pluginId":"restapi-plugin","id":"Admin_get_user","userPermissions":["read:actions","execute:actions","manage:actions"],"publishedAction":{"executeOnLoad":false,"isValid":true,"actionConfiguration":{"path":"/api/v1/users/me","headers":[{"value":"_hjid=41cedd95-19f9-438a-8b6e-f2c4d7fb086b; SL_C_23361dd035530_KEY=c370af0df0edf38360adbefbdc47d2b42ea137c9; SL_C_23361dd035530_VID=P3kBR7eMjg; ajs_anonymous_id=e6ef9c9b-3407-4374-81ab-6bafef26a4d1; [email protected]; intercom-id-y10e7138=50e190b7-b24e-4bef-b320-3c47a3c91006; amplitude_id_fef1e872c952688acd962d30aa545b9eappsmith.com=eyJkZXZpY2VJZCI6IjIxNWJlMWRkLTNjMGQtNDY5NS05YzRmLTFjYTM4MjNhNzM5NlIiLCJ1c2VySWQiOm51bGwsIm9wdE91dCI6ZmFsc2UsInNlc3Npb25JZCI6MTYzNjI1ODEwMjkyNCwibGFzdEV2ZW50VGltZSI6MTYzNjI1ODEwMzE3MywiZXZlbnRJZCI6NSwiaWRlbnRpZnlJZCI6MSwic2VxdWVuY2VOdW1iZXIiOjZ9; _ga=GA1.2.526957763.1633412376; _gid=GA1.2.1610516593.1636258104; _ga_0JZ9C3M56S=GS1.1.1636258103.3.1.1636258646.0; SESSION=09ae7c78-ca84-4a38-916a-f282893efb40; mp_70b8ea94d623dd857fb555a76d11f944_mixpanel=%7B%22distinct_id%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24device_id%22%3A%20%2217c91e75170277-051d4ff86c77bb-1d3b6650-168000-17c91e75171dc2%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22mp_lib%22%3A%20%22Segment%3A%20web%22%2C%22%24user_id%22%3A%20%22nidhi%40appsmith.com%22%2C%22mp_name_tag%22%3A%20%22nidhi%40appsmith.com%22%2C%22userId%22%3A%20%22nidhi%40appsmith.com%22%2C%22source%22%3A%20%22cloud%22%2C%22id%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24email%22%3A%20%22nidhi%40appsmith.com%22%2C%22%24first_name%22%3A%20%22Nidhi%22%2C%22%24last_name%22%3A%20%22Nair%22%2C%22%24name%22%3A%20%22Nidhi%20Nair%22%7D; SL_C_23361dd035530_SID=3VIjO5jKCt; intercom-session-y10e7138=WnhwMVl4VmVIUDFPVkgxUDVidm8wOXUzNjZ2elJ0OWx2a21Qc3NCYk1zenNEa0dzMkswWFlpanM4YXNxY2pQYi0taFpkWkR6K0xLUFJyUVFRSkMwZ3pUUT09--376a7fef0d7774b3284b94fb4c1ea1c8e2305afe; _hjAbsoluteSessionInProgress=1","key":"Cookie"}],"paginationType":"NONE","queryParameters":[],"timeoutInMillisecond":10000,"encodeParamsToggle":true,"body":"","httpMethod":"GET","pluginSpecifiedTemplates":[{"value":true}]},"userPermissions":[],"pageId":"Admin","invalids":[],"dynamicBindingPathList":[],"confirmBeforeExecute":false,"jsonPathKeys":[],"datasource":{"new":false,"pluginId":"restapi-plugin","isValid":true,"messages":[],"id":"Appsmith Release","userPermissions":[]},"validName":"get_user","name":"get_user","messages":[]},"gitSyncId":"61764fbeba7e887d03bc3631_61bb773acd5d7045095322ff"}],"clientSchemaVersion":1,"publishedDefaultPageName":"PostgreSQL","unpublishedDefaultPageName":"PostgreSQL","publishedTheme":{"new":true,"isSystemTheme":true,"displayName":"Classic","name":"Classic"},"invisibleActionFields":{"Admin_get_exported_app":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Admin_get_datasource_structure":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_UpdateFile":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"PostgreSQL_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"SQL_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_UpdateKey":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_FetchValue":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"PostgreSQL_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Page Generator_generate_mongo_app":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_DeleteKey":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Admin_get_user":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Firestore_SelectQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"SQL_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"MongoDB_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_ListFiles":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Firestore_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Google Sheets_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"MongoDB_FindQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"SQL_SelectQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"MongoDB_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"PostgreSQL_SelectQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Page Generator_generate_sql_app":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Google Sheets_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Page Generator_generate_gsheet_app":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"MongoDB_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Firestore_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Google Sheets_DeleteQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_DeleteFile":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_CreateFile":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_FetchKeys":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"PostgreSQL_UpdateQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Admin_update_template":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Google Sheets_SelectQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Firestore_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"S3_ReadFile":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"Redis_InsertKey":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false},"SQL_InsertQuery":{"unpublishedUserSetOnLoad":false,"publishedUserSetOnLoad":false}},"serverSchemaVersion":3,"unpublishedLayoutmongoEscapedWidgets":{"MongoDB":["data_table"]},"pageList":[{"publishedPage":{"name":"PostgreSQL","userPermissions":[],"layouts":[{"new":false,"id":"PostgreSQL","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","Table1.pageSize","Table1.sortOrder.order || 'ASC'","Table1.sortOrder.column || 'col1'"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"PostgreSQL_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":880,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":39,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"borderRadius":"5","dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":860,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Table1","onSort":"{{SelectQuery.run()}}","columnOrder":["col1","col2","col3","col4","col5","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":5,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onSort"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"},{"key":"primaryColumns.col2.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text16","rightColumn":54,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"xp5u9a9nzq","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"nh3cu4lb1g","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":1120,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":604,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(JSONForm1Copy.sourceData, JSONForm1Copy.formData, JSONForm1Copy.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"customColumn1":{"identifier":"customColumn1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.customColumn1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"customColumn1","isVisible":true,"label":"Custom Column 1","originalIdentifier":"customColumn1","children":{},"isSpellCheck":false,"iconAlign":"left","position":5,"isDisabled":false,"sourceData":"","fieldType":"Text Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":3,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"},"__originalIndex__":{"identifier":"__originalIndex__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.__originalIndex__))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"__originalIndex__","isVisible":true,"label":"Original Index","originalIdentifier":"__originalIndex__","children":{},"isSpellCheck":false,"iconAlign":"left","position":6,"isDisabled":false,"sourceData":0,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"customColumn1":"","col5":true,"col2":"col2","col3":"coll3","col1":1,"__originalIndex__":0},"fieldType":"Object"}},"widgetName":"JSONForm1Copy","submitButtonStyles":{"buttonColor":"#03B365","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","topRow":59,"bottomRow":110,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.customColumn1.defaultValue"},{"key":"schema.__root_schema__.children.__originalIndex__.defaultValue"}],"sourceData":"{{Table1.selectedRow}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"tkgd4xlukf","resetButtonStyles":{"buttonColor":"#03B365","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true},{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":3,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"col5":true,"col2":"col2","col3":"coll3","col1":1},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => SelectQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":59,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":8.125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"sourceData":"{{Table1.tableData[0]}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"o8oiq6vwkk","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true}],"isDisabled":false}],"width":532,"height":604},{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":4,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":false,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"col5":true,"col2":"col2","col3":"coll3","col1":1},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","topRow":0,"bottomRow":86,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":39,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(Table1.selectedRow, \"customColumn1\", \"__originalIndex__\", \"__primaryKey__\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#FFFFFF","rightColumn":64,"autoGenerateForm":true,"widgetId":"y5cjzuxnb3","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"}]}}],"slug":"postgresql","isHidden":false},"new":true,"unpublishedPage":{"name":"PostgreSQL","userPermissions":[],"layouts":[{"new":false,"id":"PostgreSQL","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","Table1.pageSize","Table1.sortOrder.order || 'ASC'","Table1.sortOrder.column || 'col1'"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"PostgreSQL_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":880,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":39,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"borderRadius":"5","dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":860,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Table1","onSort":"{{SelectQuery.run()}}","columnOrder":["col1","col2","col3","col4","col5","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":5,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onSort"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"},{"key":"primaryColumns.col2.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text16","rightColumn":54,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"xp5u9a9nzq","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"nh3cu4lb1g","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":1120,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":604,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(JSONForm1Copy.sourceData, JSONForm1Copy.formData, JSONForm1Copy.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"customColumn1":{"identifier":"customColumn1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.customColumn1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"customColumn1","isVisible":true,"label":"Custom Column 1","originalIdentifier":"customColumn1","children":{},"isSpellCheck":false,"iconAlign":"left","position":5,"isDisabled":false,"sourceData":"","fieldType":"Text Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":3,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"},"__originalIndex__":{"identifier":"__originalIndex__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.__originalIndex__))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"__originalIndex__","isVisible":true,"label":"Original Index","originalIdentifier":"__originalIndex__","children":{},"isSpellCheck":false,"iconAlign":"left","position":6,"isDisabled":false,"sourceData":0,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"customColumn1":"","col5":true,"col2":"col2","col3":"coll3","col1":1,"__originalIndex__":0},"fieldType":"Object"}},"widgetName":"JSONForm1Copy","submitButtonStyles":{"buttonColor":"#03B365","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","topRow":59,"bottomRow":110,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.customColumn1.defaultValue"},{"key":"schema.__root_schema__.children.__originalIndex__.defaultValue"}],"sourceData":"{{Table1.selectedRow}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"tkgd4xlukf","resetButtonStyles":{"buttonColor":"#03B365","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true},{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":3,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"col5":true,"col2":"col2","col3":"coll3","col1":1},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => SelectQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":59,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":8.125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"sourceData":"{{Table1.tableData[0]}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"o8oiq6vwkk","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true}],"isDisabled":false}],"width":532,"height":604},{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":4,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":false,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"col5":true,"col2":"col2","col3":"coll3","col1":1},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","topRow":0,"bottomRow":86,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":39,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(Table1.selectedRow, \"customColumn1\", \"__originalIndex__\", \"__primaryKey__\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#FFFFFF","rightColumn":64,"autoGenerateForm":true,"widgetId":"y5cjzuxnb3","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"}]}}],"slug":"postgresql","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc8"},{"publishedPage":{"name":"Admin","userPermissions":[],"layouts":[{"new":false,"id":"Admin","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"API","confirmBeforeExecute":false,"jsonPathKeys":[],"name":"get_exported_app","timeoutInMillisecond":10000,"id":"Admin_get_exported_app"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1174,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":910,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Form1","backgroundColor":"#2E3D49","rightColumn":45,"widgetId":"hdpwx2szs0","topRow":5,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":554.75,"detachFromLayout":true,"widgetId":"kwx6oz4fub","containerStyle":"none","topRow":0,"bottomRow":800,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"hdpwx2szs0","minHeight":810,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text1","rightColumn":53,"textAlign":"LEFT","widgetId":"7fqtlu52np","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":2,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update App Template"},{"widgetName":"Text2","rightColumn":62,"textAlign":"LEFT","widgetId":"w2l08fshj2","topRow":9,"bottomRow":61,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"SCROLL","leftColumn":3,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{\"<pre>\" + JSON.stringify(get_exported_app.data, null, 2) + \"</pre>\" || \"Fetch The App\"}}"},{"widgetName":"Button1","rightColumn":21,"onClick":"{{\n get_exported_app.run(() => {\n \tconst arr = JSON.parse(datasource_arr.text);\n\t\tarr.map((row) => { get_datasource_structure.run((res, params) => {\n storeValue(params.name, res); \n },undefined, row)\n })\n })\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"2vtg0qdlqv","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":3,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Fetch App","isDisabled":false},{"widgetName":"Button2","rightColumn":63,"onClick":"{{update_template.run(() => showAlert('Template Updated','success'), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"isDisabled"}],"buttonColor":"#03B365","widgetId":"jg23u09rwk","topRow":73,"bottomRow":77,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":4,"dynamicBindingPathList":[{"key":"isDisabled"}],"buttonVariant":"PRIMARY","text":"Deploy","isDisabled":"{{get_exported_app.data.exportedApplication === undefined}}"},{"widgetName":"Text3","rightColumn":12,"textAlign":"LEFT","widgetId":"y57v1yp7vb","topRow":63,"bottomRow":67,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":3,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Branch"},{"widgetName":"Text4","rightColumn":63,"backgroundColor":"#DD4B34","textAlign":"LEFT","widgetId":"fanskapltd","topRow":69,"bottomRow":73,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Note : Please use update-crud-template branch to avoid TCs failing in release"},{"widgetName":"branch_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":63,"bottomRow":67,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.34765625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":13,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"q59sbo2ecd","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"t05x88vwee","isVisible":true,"label":"","version":2,"parentId":"kwx6oz4fub","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"update-crud-template"}]}]},{"widgetName":"datasource_arr","rightColumn":16,"textAlign":"LEFT","widgetId":"znji9afu2q","topRow":1,"bottomRow":35,"parentRowSpace":10,"isVisible":false,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"[\n{ \"name\":\"mongo-plugin\",\n\"id\": \"61d6b292053d041e6d486fbb\"\n},\n{ \"name\":\"postgres-plugin\",\n\"id\": \"61764f91ba7e887d03bc35d3\"\n}\n]"}]}}],"slug":"admin","isHidden":false},"new":true,"unpublishedPage":{"name":"Admin","userPermissions":[],"layouts":[{"new":false,"id":"Admin","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"API","confirmBeforeExecute":false,"jsonPathKeys":[],"name":"get_exported_app","timeoutInMillisecond":10000,"id":"Admin_get_exported_app"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1174,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":910,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Form1","backgroundColor":"#2E3D49","rightColumn":45,"widgetId":"hdpwx2szs0","topRow":5,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"FORM_WIDGET","parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":554.75,"detachFromLayout":true,"widgetId":"kwx6oz4fub","containerStyle":"none","topRow":0,"bottomRow":800,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"hdpwx2szs0","minHeight":810,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text1","rightColumn":53,"textAlign":"LEFT","widgetId":"7fqtlu52np","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":2,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update App Template"},{"widgetName":"Text2","rightColumn":62,"textAlign":"LEFT","widgetId":"w2l08fshj2","topRow":9,"bottomRow":61,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"SCROLL","leftColumn":3,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{\"<pre>\" + JSON.stringify(get_exported_app.data, null, 2) + \"</pre>\" || \"Fetch The App\"}}"},{"widgetName":"Button1","rightColumn":21,"onClick":"{{\n get_exported_app.run(() => {\n \tconst arr = JSON.parse(datasource_arr.text);\n\t\tarr.map((row) => { get_datasource_structure.run((res, params) => {\n storeValue(params.name, res); \n },undefined, row)\n })\n })\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"2vtg0qdlqv","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":3,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Fetch App","isDisabled":false},{"widgetName":"Button2","rightColumn":63,"onClick":"{{update_template.run(() => showAlert('Template Updated','success'), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"isDisabled"}],"buttonColor":"#03B365","widgetId":"jg23u09rwk","topRow":73,"bottomRow":77,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":4,"dynamicBindingPathList":[{"key":"isDisabled"}],"buttonVariant":"PRIMARY","text":"Deploy","isDisabled":"{{get_exported_app.data.exportedApplication === undefined}}"},{"widgetName":"Text3","rightColumn":12,"textAlign":"LEFT","widgetId":"y57v1yp7vb","topRow":63,"bottomRow":67,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":3,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Branch"},{"widgetName":"Text4","rightColumn":63,"backgroundColor":"#DD4B34","textAlign":"LEFT","widgetId":"fanskapltd","topRow":69,"bottomRow":73,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#FFFFFF","version":1,"parentId":"kwx6oz4fub","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Note : Please use update-crud-template branch to avoid TCs failing in release"},{"widgetName":"branch_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":63,"bottomRow":67,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.34765625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":13,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"q59sbo2ecd","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"t05x88vwee","isVisible":true,"label":"","version":2,"parentId":"kwx6oz4fub","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"update-crud-template"}]}]},{"widgetName":"datasource_arr","rightColumn":16,"textAlign":"LEFT","widgetId":"znji9afu2q","topRow":1,"bottomRow":35,"parentRowSpace":10,"isVisible":false,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"[\n{ \"name\":\"mongo-plugin\",\n\"id\": \"61d6b292053d041e6d486fbb\"\n},\n{ \"name\":\"postgres-plugin\",\n\"id\": \"61764f91ba7e887d03bc35d3\"\n}\n]"}]}}],"slug":"admin","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc3"},{"publishedPage":{"name":"Page Generator","userPermissions":[],"layouts":[{"new":false,"id":"Page Generator","userPermissions":[],"layoutOnLoadActions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":850,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Tabs1","rightColumn":45,"widgetId":"jalvzswyyk","defaultTab":"SQL","topRow":11,"bottomRow":52,"shouldShowTabs":true,"parentRowSpace":10,"tabsObj":{"tab1":{"widgetId":"nyka98xqpv","index":0,"label":"SQL","id":"tab1","isVisible":true},"tab2":{"widgetId":"neexe4fljs","index":1,"label":"GSheet","id":"tab2","isVisible":true},"tab7qxuerb9p7":{"widgetId":"4yqoh4fjmv","id":"tab7qxuerb9p7","label":"Mongo","isVisible":true}},"isVisible":true,"type":"TABS_WIDGET","version":3,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":16,"dynamicBindingPathList":[],"children":[{"tabId":"tab1","tabName":"SQL","rightColumn":634,"widgetName":"Canvas2","detachFromLayout":true,"widgetId":"nyka98xqpv","topRow":0,"bottomRow":400,"parentRowSpace":1,"type":"CANVAS_WIDGET","parentId":"jalvzswyyk","isLoading":false,"renderMode":"CANVAS","minHeight":410,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text2","rightColumn":14,"textAlign":"RIGHT","widgetId":"957c72jpan","topRow":3,"bottomRow":7,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Datasource URL"},{"widgetName":"Text4","rightColumn":14,"textAlign":"RIGHT","widgetId":"nz74xi3ae3","topRow":10,"bottomRow":14,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Table Name"},{"widgetName":"Text6","rightColumn":14,"textAlign":"RIGHT","widgetId":"s1i89k31f5","topRow":17,"bottomRow":21,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Columns to Select"},{"widgetName":"Text7","rightColumn":14,"textAlign":"RIGHT","widgetId":"rbacxz6brz","topRow":25,"bottomRow":29,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Column to Search"},{"resetFormOnClick":false,"widgetName":"FormButton1","rightColumn":63,"onClick":"{{generate_sql_app.run(() => showAlert('Page Created!','success'), () => {})}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"n6220hgzzs","topRow":31,"bottomRow":35,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"nyka98xqpv","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate"},{"widgetName":"datasource_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":3,"bottomRow":7,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"fk5njkiu28","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"tableName_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"v6vho5uqct","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"select_cols_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":17,"bottomRow":21,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"e1j5kngy1t","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"search_col_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":25,"bottomRow":29,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"cqxwse0717","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]},{"tabId":"tab2","tabName":"GSheet","rightColumn":634,"widgetName":"Canvas3","detachFromLayout":true,"widgetId":"neexe4fljs","topRow":0,"bottomRow":400,"parentRowSpace":1,"type":"CANVAS_WIDGET","parentId":"jalvzswyyk","isLoading":false,"renderMode":"CANVAS","minHeight":410,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text8","rightColumn":16,"textAlign":"RIGHT","widgetId":"3ghywz6tk6","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"DataSource URL"},{"widgetName":"Text9","rightColumn":16,"textAlign":"RIGHT","widgetId":"r6o12im1qd","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"SpreadSheet URL"},{"widgetName":"Text10","rightColumn":16,"textAlign":"RIGHT","widgetId":"k0ul3uaoph","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Sheet Name"},{"widgetName":"Text11","rightColumn":16,"textAlign":"RIGHT","widgetId":"l1r1tfbx6y","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Table Header Index"},{"widgetName":"Button1","rightColumn":62,"onClick":"{{generate_gsheet_app.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"zzsh2d5rns","topRow":30,"bottomRow":34,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate","isDisabled":false},{"widgetName":"gsheet_ds_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"j61fbsst0i","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"spreadsheet_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"vm21ddffi6","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"sheet_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"5r5hxd2qs8","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"header_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"z3nz99y80l","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]},{"tabId":"tab7qxuerb9p7","widgetName":"Canvas4","tabName":"Mongo","rightColumn":574.5625,"detachFromLayout":true,"widgetId":"4yqoh4fjmv","containerStyle":"none","topRow":1,"bottomRow":400,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"jalvzswyyk","minHeight":410,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text12","rightColumn":17,"textAlign":"RIGHT","widgetId":"4l1uqhf2au","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Datasource URL"},{"widgetName":"Text13","rightColumn":17,"textAlign":"RIGHT","widgetId":"0y3rz6ufib","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Collection Name"},{"widgetName":"Text14","rightColumn":17,"textAlign":"RIGHT","widgetId":"s1fhjft9to","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Keys to Fetch"},{"widgetName":"Text15","rightColumn":17,"textAlign":"RIGHT","widgetId":"rwi67ouhe1","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Key to Search"},{"widgetName":"Button2","rightColumn":62,"onClick":"{{generate_mongo_app.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"6ui5kmqebf","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate","isDisabled":false},{"widgetName":"mongo_ds_url","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"3iwx4ppimv","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"collection_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"82uk5g7krv","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"fetch_keys_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"jx1zxum47l","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"search_keys_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":28.9375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"24223uwmke","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}]}}],"slug":"page-generator","isHidden":false},"new":true,"unpublishedPage":{"name":"Page Generator","userPermissions":[],"layouts":[{"new":false,"id":"Page Generator","userPermissions":[],"layoutOnLoadActions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":850,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":1130,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Tabs1","rightColumn":45,"widgetId":"jalvzswyyk","defaultTab":"SQL","topRow":11,"bottomRow":52,"shouldShowTabs":true,"parentRowSpace":10,"tabsObj":{"tab1":{"widgetId":"nyka98xqpv","index":0,"label":"SQL","id":"tab1","isVisible":true},"tab2":{"widgetId":"neexe4fljs","index":1,"label":"GSheet","id":"tab2","isVisible":true},"tab7qxuerb9p7":{"widgetId":"4yqoh4fjmv","id":"tab7qxuerb9p7","label":"Mongo","isVisible":true}},"isVisible":true,"type":"TABS_WIDGET","version":3,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":16,"dynamicBindingPathList":[],"children":[{"tabId":"tab1","tabName":"SQL","rightColumn":634,"widgetName":"Canvas2","detachFromLayout":true,"widgetId":"nyka98xqpv","topRow":0,"bottomRow":400,"parentRowSpace":1,"type":"CANVAS_WIDGET","parentId":"jalvzswyyk","isLoading":false,"renderMode":"CANVAS","minHeight":410,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text2","rightColumn":14,"textAlign":"RIGHT","widgetId":"957c72jpan","topRow":3,"bottomRow":7,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Datasource URL"},{"widgetName":"Text4","rightColumn":14,"textAlign":"RIGHT","widgetId":"nz74xi3ae3","topRow":10,"bottomRow":14,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Table Name"},{"widgetName":"Text6","rightColumn":14,"textAlign":"RIGHT","widgetId":"s1i89k31f5","topRow":17,"bottomRow":21,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Columns to Select"},{"widgetName":"Text7","rightColumn":14,"textAlign":"RIGHT","widgetId":"rbacxz6brz","topRow":25,"bottomRow":29,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"nyka98xqpv","isLoading":false,"parentColumnSpace":8.35546875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Column to Search"},{"resetFormOnClick":false,"widgetName":"FormButton1","rightColumn":63,"onClick":"{{generate_sql_app.run(() => showAlert('Page Created!','success'), () => {})}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"n6220hgzzs","topRow":31,"bottomRow":35,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"nyka98xqpv","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate"},{"widgetName":"datasource_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":3,"bottomRow":7,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"fk5njkiu28","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"tableName_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"v6vho5uqct","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"select_cols_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":17,"bottomRow":21,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"e1j5kngy1t","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"search_col_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":25,"bottomRow":29,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":15,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"cqxwse0717","isVisible":true,"label":"","version":2,"parentId":"nyka98xqpv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]},{"tabId":"tab2","tabName":"GSheet","rightColumn":634,"widgetName":"Canvas3","detachFromLayout":true,"widgetId":"neexe4fljs","topRow":0,"bottomRow":400,"parentRowSpace":1,"type":"CANVAS_WIDGET","parentId":"jalvzswyyk","isLoading":false,"renderMode":"CANVAS","minHeight":410,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text8","rightColumn":16,"textAlign":"RIGHT","widgetId":"3ghywz6tk6","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"DataSource URL"},{"widgetName":"Text9","rightColumn":16,"textAlign":"RIGHT","widgetId":"r6o12im1qd","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"SpreadSheet URL"},{"widgetName":"Text10","rightColumn":16,"textAlign":"RIGHT","widgetId":"k0ul3uaoph","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Sheet Name"},{"widgetName":"Text11","rightColumn":16,"textAlign":"RIGHT","widgetId":"l1r1tfbx6y","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Table Header Index"},{"widgetName":"Button1","rightColumn":62,"onClick":"{{generate_gsheet_app.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"zzsh2d5rns","topRow":30,"bottomRow":34,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"neexe4fljs","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate","isDisabled":false},{"widgetName":"gsheet_ds_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"j61fbsst0i","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"spreadsheet_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"vm21ddffi6","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"sheet_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"5r5hxd2qs8","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"header_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":17,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"z3nz99y80l","isVisible":true,"label":"","version":2,"parentId":"neexe4fljs","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]},{"tabId":"tab7qxuerb9p7","widgetName":"Canvas4","tabName":"Mongo","rightColumn":574.5625,"detachFromLayout":true,"widgetId":"4yqoh4fjmv","containerStyle":"none","topRow":1,"bottomRow":400,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"jalvzswyyk","minHeight":410,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text12","rightColumn":17,"textAlign":"RIGHT","widgetId":"4l1uqhf2au","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Datasource URL"},{"widgetName":"Text13","rightColumn":17,"textAlign":"RIGHT","widgetId":"0y3rz6ufib","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Collection Name"},{"widgetName":"Text14","rightColumn":17,"textAlign":"RIGHT","widgetId":"s1fhjft9to","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Keys to Fetch"},{"widgetName":"Text15","rightColumn":17,"textAlign":"RIGHT","widgetId":"rwi67ouhe1","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Key to Search"},{"widgetName":"Button2","rightColumn":62,"onClick":"{{generate_mongo_app.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"6ui5kmqebf","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"4yqoh4fjmv","isLoading":false,"parentColumnSpace":8.6650390625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Generate","isDisabled":false},{"widgetName":"mongo_ds_url","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":1,"bottomRow":5,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"3iwx4ppimv","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"collection_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"82uk5g7krv","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"fetch_keys_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":19,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":12.7998046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"jx1zxum47l","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"search_keys_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":22,"bottomRow":26,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":28.9375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"0equv9lg65","validation":"true","isRequired":false,"rightColumn":61,"widgetId":"24223uwmke","isVisible":true,"label":"","version":2,"parentId":"4yqoh4fjmv","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}]}]}}],"slug":"page-generator","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc4"},{"publishedPage":{"name":"MongoDB","userPermissions":[],"layouts":[{"new":false,"id":"MongoDB","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["data_table.sortOrder.column || 'col1'","key_select.selectedOptionValue","data_table.pageSize","data_table.sortOrder.order == \"desc\" ? -1 : 1","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"name":"FindQuery","timeoutInMillisecond":10000,"id":"MongoDB_FindQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":880,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"Col4","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"Col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"Col3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"Col1","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"Col4","col2":"Col2","col3":"Col3","col1":"Col1"},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => FindQuery.run(), () => showAlert('Error while updating resource!','error'))}}","topRow":0,"bottomRow":86,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Document","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":39,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(data_table.selectedRow, \"customColumn1\", \"__originalIndex__\", \"__primaryKey__\", \"_id\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"0511vwn3zi","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":39,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"borderRadius":"5","dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":860,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","onSort":"{{FindQuery.run()}}","columnOrder":["_id","col1","col2","col3","col4","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":5,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{FindQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onSort"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns._id.computedValue"}],"leftColumn":0,"primaryColumns":{"appsmith_mongo_escape_id":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._id))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"_id","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_id","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{FindQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{FindQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text16","rightColumn":41,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{FindQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"nj85l57r47","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"atgojamsmw","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":45,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":33,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => FindQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this document?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"Col4","fieldType":"Text Input"},"_id":{"identifier":"_id","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData._id))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"_id","isVisible":true,"label":"Id","originalIdentifier":"_id","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"60ec151bb6f96663f386ba86","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"Col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"Col3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"Col1","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"Col4","_id":"60ec151bb6f96663f386ba86","col2":"Col2","col3":"Col3","col1":"Col1"},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => FindQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":59,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Document","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children._id.defaultValue"}],"borderWidth":"","sourceData":"{{_.omit(data_table.tableData[0], \"customColumn1\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"ktpocp4ka2","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true,"borderRadius":"5"}],"isDisabled":false}],"width":532,"height":600}]}}],"slug":"mongodb","isHidden":false},"new":true,"unpublishedPage":{"name":"MongoDB","userPermissions":[],"layouts":[{"new":false,"id":"MongoDB","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["data_table.sortOrder.column || 'col1'","key_select.selectedOptionValue","data_table.pageSize","data_table.sortOrder.order == \"desc\" ? -1 : 1","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"name":"FindQuery","timeoutInMillisecond":10000,"id":"MongoDB_FindQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":880,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"Col4","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"Col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"Col3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"Col1","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"Col4","col2":"Col2","col3":"Col3","col1":"Col1"},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => FindQuery.run(), () => showAlert('Error while updating resource!','error'))}}","topRow":0,"bottomRow":86,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Document","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":39,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(data_table.selectedRow, \"customColumn1\", \"__originalIndex__\", \"__primaryKey__\", \"_id\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"0511vwn3zi","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":39,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"borderRadius":"5","dynamicBindingPathList":[],"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":860,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","onSort":"{{FindQuery.run()}}","columnOrder":["_id","col1","col2","col3","col4","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":5,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{FindQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onSort"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns._id.computedValue"}],"leftColumn":0,"primaryColumns":{"appsmith_mongo_escape_id":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._id))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"_id","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_id","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{FindQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{FindQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text16","rightColumn":41,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{FindQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"nj85l57r47","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"atgojamsmw","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":45,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":33,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => FindQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this document?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"Col4","fieldType":"Text Input"},"_id":{"identifier":"_id","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData._id))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"_id","isVisible":true,"label":"Id","originalIdentifier":"_id","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"60ec151bb6f96663f386ba86","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"Col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"Col3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"Col1","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"Col4","_id":"60ec151bb6f96663f386ba86","col2":"Col2","col3":"Col3","col1":"Col1"},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => FindQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":59,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Document","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children._id.defaultValue"}],"borderWidth":"","sourceData":"{{_.omit(data_table.tableData[0], \"customColumn1\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"ktpocp4ka2","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true,"borderRadius":"5"}],"isDisabled":false}],"width":532,"height":600}]}}],"slug":"mongodb","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc5"},{"publishedPage":{"name":"SQL","userPermissions":[],"layouts":[{"new":false,"id":"SQL","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["Table1.sortOrder.order || \"ASC\"","(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","Table1.pageSize","Table1.sortOrder.column || 'col1'"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"SQL_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":910,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":4,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":false,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"col5":true,"col2":"col2","col3":"coll3","col1":1},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","topRow":0,"bottomRow":89,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":39,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(Table1.selectedRow, \"customColumn1\", \"__originalIndex__\", \"__primaryKey__\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"6g4ewsx2v0","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":39,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":89,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Table1","onSort":"{{SelectQuery.run()}}","columnOrder":["col1","col2","col3","col4","col5","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":5,"bottomRow":87,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onSort"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","fontStyle":"","textColor":"","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text16","rightColumn":55,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"2jj0197tff","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"kby34l9nbb","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":600,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":4,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"col5":true,"col2":"col2","col3":"coll3","col1":1},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => SelectQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":58,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"borderWidth":"","sourceData":"{{_.omit(Table1.tableData[0], \"customColumn1\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"w10l8merz2","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true,"borderRadius":"5"}],"isDisabled":false}],"width":532,"height":600}]}}],"slug":"sql","isHidden":false},"new":true,"unpublishedPage":{"name":"SQL","userPermissions":[],"layouts":[{"new":false,"id":"SQL","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["Table1.sortOrder.order || \"ASC\"","(Table1.pageNo - 1) * Table1.pageSize","Table1.searchText || \"\"","Table1.pageSize","Table1.sortOrder.column || 'col1'"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"SQL_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":910,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":4,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":false,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"col5":true,"col2":"col2","col3":"coll3","col1":1},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating resource!','error'))}}","topRow":0,"bottomRow":89,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":39,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(Table1.selectedRow, \"customColumn1\", \"__originalIndex__\", \"__primaryKey__\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"6g4ewsx2v0","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":39,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":89,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Table1","onSort":"{{SelectQuery.run()}}","columnOrder":["col1","col2","col3","col4","col5","customColumn1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":5,"bottomRow":87,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onSort"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","fontStyle":"","textColor":"","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{Table1.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"widgetName":"Text16","rightColumn":55,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"2jj0197tff","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"kby34l9nbb","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":600,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":1001,"fieldType":"Number Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"boolean","accessor":"col5","isVisible":true,"label":"Col 5","alignWidget":"LEFT","originalIdentifier":"col5","children":{},"position":4,"isDisabled":false,"sourceData":true,"fieldType":"Switch"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"col2","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"coll3","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"number","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":1,"fieldType":"Number Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":1001,"col5":true,"col2":"col2","col3":"coll3","col1":1},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => SelectQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":58,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"}],"borderWidth":"","sourceData":"{{_.omit(Table1.tableData[0], \"customColumn1\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"w10l8merz2","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true,"borderRadius":"5"}],"isDisabled":false}],"width":532,"height":600}]}}],"slug":"sql","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc0"},{"publishedPage":{"name":"Google Sheets","userPermissions":[],"layouts":[{"new":false,"id":"Google Sheets","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"SAAS","confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","(data_table.pageNo - 1) * data_table.pageSize"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"Google Sheets_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":880,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"Hello","fieldType":"Text Input"},"rowIndex":{"identifier":"rowIndex","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rowIndex))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"rowIndex","isVisible":false,"label":"Row Index","originalIdentifier":"rowIndex","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"0","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"28","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"11","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"testing","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"Hello","rowIndex":"0","col2":"28","col3":"11","col1":"testing"},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating row!','error'))}}","topRow":0,"bottomRow":86,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":40,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.rowIndex.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(data_table.selectedRow, \"customColumn1\", \"__originalIndex__\", \"__primaryKey__\", \"_id\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"tn9ri7ylp2","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":860,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["col1","col2","col3","col4","rowIndex","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":5,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"}],"dynamicBindingPathList":[{"key":"tableData"},{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"primaryColumns.rowIndex.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col1.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"rowIndex":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex))}}","textSize":"PARAGRAPH","index":4,"isVisible":false,"label":"rowIndex","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"rowIndex","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{deleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"step":62,"status":75,"col1":140}},{"widgetName":"Text16","rightColumn":39,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"typ9jslblf","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"8b67sbqskr","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":18.8828125,"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text11","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":48,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"delete_button","rightColumn":64,"onClick":"{{(function () {\nDeleteQuery.run(() =>{ showAlert('Row successfully deleted!','success');\tSelectQuery.run();\n}, () => showAlert('Something went wrong! Please check debugger for more info.','error'));\ncloseModal('Delete_Modal');\n})()}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#DD4B34","widgetId":"qq02lh7ust","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"Hello","fieldType":"Text Input"},"rowIndex":{"identifier":"rowIndex","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rowIndex))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"rowIndex","isVisible":false,"label":"Row Index","originalIdentifier":"rowIndex","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"0","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"28","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"11","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"testing","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"Hello","rowIndex":"0","col2":"28","col3":"11","col1":"testing"},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => SelectQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":59,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.rowIndex.defaultValue"}],"borderWidth":"0","sourceData":"{{_.omit(data_table.tableData[0], \"customColumn1\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"4amgm2y5ph","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true,"borderRadius":"0"}],"isDisabled":false}],"width":532,"height":600}]}}],"slug":"google-sheets","isHidden":false},"new":true,"unpublishedPage":{"name":"Google Sheets","userPermissions":[],"layouts":[{"new":false,"id":"Google Sheets","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"SAAS","confirmBeforeExecute":false,"jsonPathKeys":["data_table.pageSize","(data_table.pageNo - 1) * data_table.pageSize"],"name":"SelectQuery","timeoutInMillisecond":10000,"id":"Google Sheets_SelectQuery"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":880,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"Hello","fieldType":"Text Input"},"rowIndex":{"identifier":"rowIndex","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rowIndex))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"rowIndex","isVisible":false,"label":"Row Index","originalIdentifier":"rowIndex","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"0","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"28","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"11","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"testing","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"Hello","rowIndex":"0","col2":"28","col3":"11","col1":"testing"},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating row!','error'))}}","topRow":0,"bottomRow":86,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":40,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.rowIndex.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(data_table.selectedRow, \"customColumn1\", \"__originalIndex__\", \"__primaryKey__\", \"_id\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"tn9ri7ylp2","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":860,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["col1","col2","col3","col4","rowIndex","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":5,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"}],"dynamicBindingPathList":[{"key":"tableData"},{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"primaryColumns.rowIndex.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col1.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"rowIndex":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex))}}","textSize":"PARAGRAPH","index":4,"isVisible":false,"label":"rowIndex","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"rowIndex","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{deleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"step":62,"status":75,"col1":140}},{"widgetName":"Text16","rightColumn":39,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"typ9jslblf","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"8b67sbqskr","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":18.8828125,"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text11","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":48,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"delete_button","rightColumn":64,"onClick":"{{(function () {\nDeleteQuery.run(() =>{ showAlert('Row successfully deleted!','success');\tSelectQuery.run();\n}, () => showAlert('Something went wrong! Please check debugger for more info.','error'));\ncloseModal('Delete_Modal');\n})()}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#DD4B34","widgetId":"qq02lh7ust","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"Hello","fieldType":"Text Input"},"rowIndex":{"identifier":"rowIndex","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rowIndex))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"rowIndex","isVisible":false,"label":"Row Index","originalIdentifier":"rowIndex","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"0","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"28","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"11","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"testing","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"Hello","rowIndex":"0","col2":"28","col3":"11","col1":"testing"},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => SelectQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":59,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.rowIndex.defaultValue"}],"borderWidth":"0","sourceData":"{{_.omit(data_table.tableData[0], \"customColumn1\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"4amgm2y5ph","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true,"borderRadius":"0"}],"isDisabled":false}],"width":532,"height":600}]}}],"slug":"google-sheets","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc1"},{"publishedPage":{"name":"Firestore","userPermissions":[],"layouts":[{"new":false,"id":"Firestore","userPermissions":[],"layoutOnLoadActions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":880,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"4","fieldType":"Text Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col5","isVisible":true,"label":"Col 5","originalIdentifier":"col5","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"5","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"new","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"neighbour","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"Hello","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"4","col5":"5","col2":"new","col3":"neighbour","col1":"Hello"},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.children.key2.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating row!','error'))}}","topRow":0,"bottomRow":86,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":40,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(data_table.selectedRow, \"customColumn1\", \"__originalIndex__\", \"_ref\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"pfyg9tlwj1","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":860,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"lqa75t4x8s","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"rc610d47lm","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"widgetName":"data_table","columnOrder":["_ref","col4","col5","col2","col3","col1","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":5,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns._ref.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col1.computedValue"}],"leftColumn":0,"primaryColumns":{"_ref":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._ref.id))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"_ref","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_ref","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":5,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":6,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":7,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":8,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"_ref":251,"step":62,"id":228,"status":75}},{"widgetName":"Text16","rightColumn":53,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"4","fieldType":"Text Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"col5","isVisible":true,"label":"Col 5","originalIdentifier":"col5","children":{},"isSpellCheck":false,"iconAlign":"left","position":5,"isDisabled":false,"sourceData":"5","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"new","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"neighbour","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"Hello","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"4","col5":"5","col2":"new","col3":"neighbour","col1":"Hello"},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => SelectQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":59,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"borderWidth":"0","sourceData":"{{_.omit(data_table.tableData[0], \"customColumn1\", \"_ref\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"qljqxmx394","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true,"borderRadius":"0"}],"isDisabled":false}],"width":532,"height":600}]}}],"slug":"firestore","isHidden":false},"new":true,"unpublishedPage":{"name":"Firestore","userPermissions":[],"layouts":[{"new":false,"id":"Firestore","userPermissions":[],"layoutOnLoadActions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":880,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"4","fieldType":"Text Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col5","isVisible":true,"label":"Col 5","originalIdentifier":"col5","children":{},"isSpellCheck":false,"iconAlign":"left","position":4,"isDisabled":false,"sourceData":"5","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"new","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"neighbour","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"Hello","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"4","col5":"5","col2":"new","col3":"neighbour","col1":"Hello"},"fieldType":"Object"}},"widgetName":"update_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"#2E3D4955","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.children.key2.defaultValue"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{UpdateQuery.run(() => SelectQuery.run(), () => showAlert('Error while updating row!','error'))}}","topRow":0,"bottomRow":86,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Update Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":40,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"borderWidth":"1","sourceData":"{{_.omit(data_table.selectedRow, \"customColumn1\", \"__originalIndex__\", \"_ref\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"pfyg9tlwj1","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"0","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Update","disabledWhenInvalid":true,"borderRadius":"5"},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"borderColor":"#2E3D4955","widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":86,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":860,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":59,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#2E3D49","widgetId":"lqa75t4x8s","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":55,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{SelectQuery.run()}}","iconName":"refresh","buttonColor":"#2E3D49","widgetId":"rc610d47lm","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"ROUNDED","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","isDisabled":false},{"widgetName":"data_table","columnOrder":["_ref","col4","col5","col2","col3","col1","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":5,"bottomRow":84,"parentRowSpace":10,"onPageChange":"{{SelectQuery.run()}}","isSortable":true,"type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns._ref.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns.col5.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col1.computedValue"}],"leftColumn":0,"primaryColumns":{"_ref":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._ref.id))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"_ref","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_ref","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":4,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"col5":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col5))}}","textSize":"PARAGRAPH","index":5,"isVisible":true,"label":"col5","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col5","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":6,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":7,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":8,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{SelectQuery.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{SelectQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"_ref":251,"step":62,"id":228,"status":75}},{"widgetName":"Text16","rightColumn":53,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":1,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Data"}]}],"borderWidth":"1"},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#2E3D49","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":true,"fontStyle":"","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING3","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"schema":{"__root_schema__":{"identifier":"__root_schema__","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"object","accessor":"__root_schema__","isVisible":true,"label":"","originalIdentifier":"__root_schema__","children":{"col4":{"identifier":"col4","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col4))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col4","isVisible":true,"label":"Col 4","originalIdentifier":"col4","children":{},"isSpellCheck":false,"iconAlign":"left","position":3,"isDisabled":false,"sourceData":"4","fieldType":"Text Input"},"col5":{"identifier":"col5","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col5))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}","dataType":"string","accessor":"col5","isVisible":true,"label":"Col 5","originalIdentifier":"col5","children":{},"isSpellCheck":false,"iconAlign":"left","position":5,"isDisabled":false,"sourceData":"5","fieldType":"Text Input"},"col2":{"identifier":"col2","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col2))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col2","isVisible":true,"label":"Col 2","originalIdentifier":"col2","children":{},"isSpellCheck":false,"iconAlign":"left","position":1,"isDisabled":false,"sourceData":"new","fieldType":"Text Input"},"col3":{"identifier":"col3","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col3))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col3","isVisible":true,"label":"Col 3","originalIdentifier":"col3","children":{},"isSpellCheck":false,"iconAlign":"left","position":2,"isDisabled":false,"sourceData":"neighbour","fieldType":"Text Input"},"col1":{"identifier":"col1","isRequired":false,"isCustomField":false,"defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.col1))(update_form.sourceData, update_form.formData, update_form.fieldState)}}","dataType":"string","accessor":"col1","isVisible":true,"label":"Col 1","originalIdentifier":"col1","children":{},"isSpellCheck":false,"iconAlign":"left","position":0,"isDisabled":false,"sourceData":"Hello","fieldType":"Text Input"}},"position":-1,"isDisabled":false,"sourceData":{"col4":"4","col5":"5","col2":"new","col3":"neighbour","col1":"Hello"},"fieldType":"Object"}},"widgetName":"insert_form","submitButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"PRIMARY"},"borderColor":"","dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.date_of_birth.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"},{"key":"onSubmit"}],"displayName":"JSON Form","iconSVG":"/static/media/icon.6bacf7df.svg","onSubmit":"{{InsertQuery.run(() => SelectQuery.run(() => resetWidget('Insert_Modal')), () => {})}}","topRow":0,"bottomRow":59,"fieldLimitExceeded":false,"parentRowSpace":10,"title":"Insert Row","type":"JSON_FORM_WIDGET","hideCard":false,"animateLoading":true,"parentColumnSpace":16.3125,"dynamicTriggerPathList":[{"key":"onSubmit"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.defaultValue"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.col1.defaultValue"},{"key":"schema.__root_schema__.children.col3.defaultValue"},{"key":"schema.__root_schema__.children.col4.defaultValue"},{"key":"schema.__root_schema__.children.col2.defaultValue"},{"key":"schema.__root_schema__.children.col5.defaultValue"}],"borderWidth":"0","sourceData":"{{_.omit(data_table.tableData[0], \"customColumn1\", \"_ref\")}}","showReset":true,"resetButtonLabel":"Reset","key":"h9l9ozr8op","backgroundColor":"#fff","rightColumn":64,"autoGenerateForm":true,"widgetId":"qljqxmx394","resetButtonStyles":{"borderRadius":"ROUNDED","buttonColor":"#2E3D49","buttonVariant":"SECONDARY"},"isVisible":true,"version":1,"parentId":"9rhv3ioohq","renderMode":"CANVAS","isLoading":false,"scrollContents":true,"fixedFooter":true,"submitButtonLabel":"Submit","disabledWhenInvalid":true,"borderRadius":"0"}],"isDisabled":false}],"width":532,"height":600}]}}],"slug":"firestore","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc7"},{"publishedPage":{"name":"S3","userPermissions":[],"layouts":[{"new":false,"id":"S3","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["60 * 24","search_input.text"],"name":"ListFiles","timeoutInMillisecond":10000,"id":"S3_ListFiles"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":910,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Zoom_Modal2","rightColumn":0,"detachFromLayout":true,"widgetId":"kqxoe40pg6","topRow":89,"bottomRow":89,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas9Copy","rightColumn":0,"detachFromLayout":true,"widgetId":"80wzwajsst","topRow":0,"bottomRow":590,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"kqxoe40pg6","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon3Copy","rightColumn":64,"onClick":"{{closeModal('Zoom_Modal2')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"8kw9kfcd5y","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"80wzwajsst","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text15Copy","rightColumn":41,"textAlign":"LEFT","widgetId":"vk710q1v3s","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"80wzwajsst","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Zoom Image"},{"widgetName":"Button13Copy","rightColumn":63,"onClick":"{{closeModal('Zoom_Modal2')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"lfiwss1u3w","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"80wzwajsst","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Close","isDisabled":false},{"image":"{{selected_files.selectedItem.base64}}","widgetName":"Image3Copy","rightColumn":64,"objectFit":"contain","widgetId":"2bewgakjx9","topRow":6,"bottomRow":51,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"80wzwajsst","isLoading":false,"maxZoomLevel":8,"parentColumnSpace":8,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png"}],"isDisabled":false}],"width":532,"height":600},{"backgroundColor":"#FFFFFF","widgetName":"Container3","rightColumn":37,"borderColor":"#2E3D4955","widgetId":"th4d9oxy8z","containerStyle":"card","topRow":0,"bottomRow":85,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas4","rightColumn":634,"detachFromLayout":true,"widgetId":"6tz2s7ivi5","containerStyle":"none","topRow":0,"bottomRow":850,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"th4d9oxy8z","minHeight":830,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"template":{"DownloadIcon":{"boxShadow":"NONE","widgetName":"DownloadIcon","onClick":"{{navigateTo(currentItem.signedUrl, {})}}","buttonColor":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D49';\n })();\n })}}","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":57,"iconName":"download","widgetId":"ljk8fj5jc1","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"CopyURLIcon":{"boxShadow":"NONE","widgetName":"CopyURLIcon","onClick":"{{copyToClipboard(currentItem.signedUrl)}}","buttonColor":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D49';\n })();\n })}}","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":51,"iconName":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'duplicate';\n })();\n })}}","widgetId":"d2z5zj56j9","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"EditIcon":{"boxShadow":"NONE","widgetName":"EditIcon","onClick":"{{showModal('Edit_Modal')}}","buttonColor":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D49';\n })();\n })}}","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":39,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":45,"iconName":"edit","widgetId":"x5bft8h9vd","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"Text21":{"widgetName":"Text21","rightColumn":24,"textAlign":"LEFT","displayName":"Text","iconSVG":"/static/media/icon.e6c93592.svg","widgetId":"nu44q8kd9p","topRow":4,"bottomRow":8,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"hideCard":false,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[{"key":"text"}],"leftColumn":16,"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem) => currentItem.id)}}","textStyle":"BODY","key":"xvmvdekk3s"},"Text20":{"widgetName":"Text20","rightColumn":28,"textAlign":"LEFT","displayName":"Text","iconSVG":"/static/media/icon.e6c93592.svg","widgetId":"thgbdemmiw","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"hideCard":false,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[{"key":"text"}],"leftColumn":16,"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem) => currentItem.name)}}","textStyle":"HEADING","key":"xvmvdekk3s"},"Image3":{"widgetName":"Image3","displayName":"Image","iconSVG":"/static/media/icon.52d8fb96.svg","topRow":0,"bottomRow":8.4,"type":"IMAGE_WIDGET","hideCard":false,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","dynamicBindingPathList":[{"key":"image"}],"leftColumn":0,"defaultImage":"https://assets.appsmith.com/widgets/default.png","key":"lsc53q139g","image":"{{File_List.listData.map((currentItem) => currentItem.img)}}","rightColumn":16,"objectFit":"contain","widgetId":"2rrg354q8i","isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false},"FileListItemImage":{"widgetName":"FileListItemImage","onClick":"{{showModal('Zoom_Modal')}}","dynamicPropertyPathList":[],"topRow":1,"bottomRow":13,"parentRowSpace":10,"type":"IMAGE_WIDGET","parentColumnSpace":19.0625,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png","image":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.signedUrl;\n })();\n })}}","rightColumn":20,"objectFit":"contain","widgetId":"lh1sjszc93","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"enableDownload":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"enableRotation":true,"defaultImage":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false},"Container7":{"borderColor":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D4955';\n })();\n })}}","borderRadius":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '5';\n })();\n })}}","borderWidth":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '1';\n })();\n })}}"},"FileListItemName":{"widgetName":"FileListItemName","rightColumn":63,"textAlign":"LEFT","widgetId":"qyqv89mu1c","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"parentColumnSpace":true,"leftColumn":true,"fontSize":true,"text":true},"topRow":1,"bottomRow":8,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"lcz0rhije8","isLoading":false,"parentColumnSpace":19.0625,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.fileName;\n })();\n })}}"},"DeleteIcon":{"boxShadow":"NONE","widgetName":"DeleteIcon","onClick":"{{showModal('delete_modal')}}","buttonColor":"#DD4B34","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":63,"iconName":"trash","widgetId":"f8ipd8gbls","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"}},"widgetName":"File_List","listData":"{{ListFiles.data}}","isCanvas":true,"displayName":"List","iconSVG":"/static/media/icon.9925ee17.svg","topRow":10,"bottomRow":83,"parentRowSpace":10,"type":"LIST_WIDGET","hideCard":false,"gridGap":0,"parentColumnSpace":9.67822265625,"dynamicTriggerPathList":[{"key":"template.DownloadIcon.onClick"},{"key":"template.CopyURLIcon.onClick"}],"leftColumn":1,"dynamicBindingPathList":[{"key":"listData"},{"key":"template.FileListItemImage.image"},{"key":"template.FileListItemName.text"},{"key":"template.EditIcon.buttonColor"},{"key":"template.CopyURLIcon.buttonColor"},{"key":"template.DownloadIcon.buttonColor"},{"key":"template.Container7.borderColor"},{"key":"template.Container7.borderWidth"},{"key":"template.Container7.borderRadius"},{"key":"template.CopyURLIcon.iconName"}],"gridType":"vertical","enhancements":true,"children":[{"widgetName":"Canvas14","displayName":"Canvas","topRow":0,"bottomRow":390,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":false,"hideCard":true,"dropDisabled":true,"openParentPropertyPane":true,"minHeight":400,"noPad":true,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"Container7","borderColor":"#2E3D4955","disallowCopy":true,"isCanvas":true,"displayName":"Container","iconSVG":"/static/media/icon.1977dca3.svg","topRow":0,"bottomRow":17,"dragDisabled":true,"type":"CONTAINER_WIDGET","hideCard":false,"openParentPropertyPane":true,"isDeletable":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas15","detachFromLayout":true,"displayName":"Canvas","widgetId":"lcz0rhije8","containerStyle":"none","topRow":0,"bottomRow":160,"parentRowSpace":1,"isVisible":true,"type":"CANVAS_WIDGET","canExtend":false,"version":1,"hideCard":true,"parentId":"66oc53smx3","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"EditIcon","onClick":"{{showModal('Edit_Modal')}}","buttonColor":"#2E3D49","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":39,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":45,"iconName":"edit","widgetId":"x5bft8h9vd","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"CopyURLIcon","onClick":"{{copyToClipboard(currentItem.signedUrl)}}","buttonColor":"#2E3D49","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":51,"iconName":"duplicate","widgetId":"d2z5zj56j9","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"DownloadIcon","onClick":"{{navigateTo(currentItem.signedUrl, {})}}","buttonColor":"#2E3D49","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":57,"iconName":"download","widgetId":"ljk8fj5jc1","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"DeleteIcon","onClick":"{{showModal('delete_modal')}}","buttonColor":"#DD4B34","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":63,"iconName":"trash","widgetId":"f8ipd8gbls","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"widgetName":"FileListItemName","rightColumn":64,"textAlign":"LEFT","widgetId":"kmwv6dap5n","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"parentColumnSpace":true,"leftColumn":true,"fontSize":true,"text":true},"topRow":0,"bottomRow":7,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"lcz0rhije8","isLoading":false,"parentColumnSpace":19.0625,"dynamicTriggerPathList":[],"overflow":"SCROLL","leftColumn":21,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{currentItem.fileName}}"},{"widgetName":"FileListItemImage","onClick":"{{showModal('Zoom_Modal')}}","dynamicPropertyPathList":[],"topRow":0,"bottomRow":13,"parentRowSpace":10,"type":"IMAGE_WIDGET","parentColumnSpace":19.0625,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png","image":"{{currentItem.signedUrl}}","rightColumn":20,"objectFit":"contain","widgetId":"4laf7e6wer","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"enableDownload":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"enableRotation":true,"defaultImage":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false}],"key":"29vrztch46"}],"borderWidth":"1","key":"cw0dtdoe0g","disablePropertyPane":true,"backgroundColor":"white","rightColumn":64,"widgetId":"66oc53smx3","containerStyle":"card","isVisible":true,"version":1,"parentId":"sh1yahe7kl","renderMode":"CANVAS","isLoading":false,"borderRadius":"5"}],"key":"29vrztch46","rightColumn":232.27734375,"detachFromLayout":true,"widgetId":"sh1yahe7kl","containerStyle":"none","isVisible":true,"version":1,"parentId":"cjgg2thzom","renderMode":"CANVAS","isLoading":false}],"privateWidgets":{"DownloadIcon":true,"EditIcon":true,"CopyURLIcon":true,"FileListItemImage":true,"FileListItemName":true,"DeleteIcon":true},"key":"x51ms5k6q9","backgroundColor":"transparent","rightColumn":63,"itemBackgroundColor":"#F6F7F8","widgetId":"cjgg2thzom","isVisible":true,"parentId":"6tz2s7ivi5","renderMode":"CANVAS","isLoading":false},{"widgetName":"search_input","dynamicPropertyPathList":[{"key":"onTextChanged"}],"displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":16.4169921875,"dynamicTriggerPathList":[{"key":"onTextChanged"}],"resetOnSubmit":true,"leftColumn":1,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"Search File Prefix","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":false,"onTextChanged":"{{ListFiles.run()}}","rightColumn":40,"widgetId":"why172fko6","isVisible":true,"label":"","version":2,"parentId":"6tz2s7ivi5","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"Text6","rightColumn":63,"backgroundColor":"","textAlign":"LEFT","widgetId":"t54ituq472","topRow":0,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6tz2s7ivi5","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Bucket"}]}],"borderWidth":"1"},{"widgetName":"delete_modal","rightColumn":0,"detachFromLayout":true,"widgetId":"9g0cw9adf8","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas6","rightColumn":0,"detachFromLayout":true,"widgetId":"ozvpoudxz2","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"9g0cw9adf8","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon2","rightColumn":64,"onClick":"{{closeModal('delete_modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"xkyh49z71e","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"ozvpoudxz2","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text12","rightColumn":41,"textAlign":"LEFT","widgetId":"s1y44xm547","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete File"},{"widgetName":"Button10","rightColumn":48,"onClick":"{{closeModal('delete_modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"pi0t67rnwh","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Button11","rightColumn":64,"onClick":"{{\nDeleteFile.run(() => {closeModal('delete_modal'); \nListFiles.run();\n});\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"hp22uj3dra","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text13","rightColumn":64,"textAlign":"LEFT","widgetId":"oypa9ad1tg","topRow":5,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ozvpoudxz2","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete the file?\n\n{{File_List.selectedItem.fileName}}"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Edit_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"usealgbtyj","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas10","rightColumn":0,"detachFromLayout":true,"widgetId":"6i7m9kpuky","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"usealgbtyj","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text17","rightColumn":41,"textAlign":"LEFT","widgetId":"z64z3l112n","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update File"},{"widgetName":"Button15","rightColumn":44,"onClick":"{{closeModal('Edit_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#2E3D49","widgetId":"trc4e6ylcz","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":32,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"update_button","rightColumn":64,"onClick":"{{UpdateFile.run(() => {ListFiles.run();resetWidget('update_file_picker');closeModal('Edit_Modal');})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"},{"key":"isDisabled"}],"buttonColor":"#2E3D49","widgetId":"8lbthc9dml","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":44,"dynamicBindingPathList":[{"key":"isDisabled"}],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Update","isDisabled":"{{update_file_picker.files.length == 0}}"},{"widgetName":"Text18","rightColumn":17,"textAlign":"RIGHT","widgetId":"qb26g34etr","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6i7m9kpuky","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"File Name"},{"widgetName":"update_file_picker","displayName":"FilePicker","iconSVG":"/static/media/icon.7c5ad9c3.svg","topRow":11,"bottomRow":15,"parentRowSpace":10,"allowedFileTypes":[],"type":"FILE_PICKER_WIDGET_V2","hideCard":false,"animateLoading":true,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[],"leftColumn":18,"dynamicBindingPathList":[],"isDisabled":false,"key":"h2212wpg64","isRequired":false,"rightColumn":64,"isDefaultClickDisabled":true,"widgetId":"i8g6khu01a","defaultSelectedFiles":[],"isVisible":true,"label":"Select File","maxFileSize":"10","version":1,"fileDataType":"Base64","parentId":"6i7m9kpuky","selectedFiles":[],"renderMode":"CANVAS","isLoading":false,"files":[],"maxNumFiles":1},{"widgetName":"update_file_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":true,"key":"auxyd97lu3","validation":"true","isRequired":false,"rightColumn":64,"widgetId":"uabsu3mjt3","isVisible":true,"label":"","version":2,"parentId":"6i7m9kpuky","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{File_List.selectedItem.fileName}}"}],"isDisabled":false}],"width":456,"height":240},{"backgroundColor":"#FFFFFF","widgetName":"Container6","rightColumn":64,"borderColor":"#2E3D4955","widgetId":"yg1iyxq9kd","containerStyle":"card","topRow":0,"bottomRow":85,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":37,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas13","rightColumn":634,"detachFromLayout":true,"widgetId":"xv97g6rzgq","containerStyle":"none","topRow":0,"bottomRow":820,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"yg1iyxq9kd","minHeight":830,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"template":{"Canvas7":{"widgetName":"Canvas7","rightColumn":256,"detachFromLayout":true,"widgetId":"oqhzaygncs","containerStyle":"none","topRow":0,"bottomRow":400,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"dropDisabled":true,"parentId":"0n30419eso","openParentPropertyPane":true,"minHeight":340,"isLoading":false,"noPad":true,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":["u3nvgafsdo"]},"update_files_name":{"widgetName":"update_files_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.4580078125,"resetOnSubmit":true,"leftColumn":23,"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'true';\n })();\n })}}","isRequired":false,"rightColumn":43,"widgetId":"yqxzzh2oqi","logBlackList":{"widgetName":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"autoFocus":true,"type":true,"hideCard":true,"minHeight":true,"animateLoading":true,"parentColumnSpace":true,"resetOnSubmit":true,"leftColumn":true,"labelStyle":true,"inputType":true,"isDisabled":true,"key":true,"isRequired":true,"rightColumn":true,"widgetId":true,"isVisible":true,"label":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"iconAlign":true,"defaultText":true},"isVisible":true,"label":"","version":2,"parentId":"romgsruzxz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.name;\n })();\n })}}"},"Image2":{"image":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.data;\n })();\n })}}","widgetName":"Image2","rightColumn":10,"onClick":"{{showModal('Zoom_Modal2')}}","objectFit":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'contain';\n })();\n })}}","widgetId":"ql8qs2xelx","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"defaultImage":true},"topRow":0,"bottomRow":6,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"romgsruzxz","isLoading":false,"maxZoomLevel":1,"parentColumnSpace":7.3125,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":0,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png"},"Container4":{"backgroundColor":"white","widgetName":"Container4","rightColumn":64,"borderColor":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D4955';\n })();\n })}}","disallowCopy":true,"widgetId":"u3nvgafsdo","containerStyle":"card","topRow":0,"bottomRow":8,"dragDisabled":true,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"oqhzaygncs","openParentPropertyPane":true,"isDeletable":false,"isLoading":false,"leftColumn":0,"borderRadius":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '5';\n })();\n })}}","children":["romgsruzxz"],"borderWidth":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '1';\n })();\n })}}","disablePropertyPane":true},"Canvas8":{"widgetName":"Canvas8","detachFromLayout":true,"widgetId":"romgsruzxz","containerStyle":"none","topRow":0,"bottomRow":180,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"u3nvgafsdo","minHeight":80,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":["vu7fb0dbt8","7zziet357m","ql8qs2xelx"]},"Text14":{"widgetName":"Text14","rightColumn":23,"textAlign":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'LEFT';\n })();\n })}}","widgetId":"vu7fb0dbt8","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"dynamicTriggerPathList":true,"parentColumnSpace":true,"dynamicBindingPathList":true,"leftColumn":true,"fontSize":true,"text":true,"textStyle":true},"topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"romgsruzxz","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":11,"fontSize":"PARAGRAPH","text":"File Name","textStyle":"HEADING"}},"widgetName":"selected_files","listData":"{{FilePicker.files}}","dynamicPropertyPathList":[{"key":"isVisible"}],"topRow":23,"bottomRow":75,"parentRowSpace":10,"type":"LIST_WIDGET","gridGap":0,"parentColumnSpace":8,"dynamicTriggerPathList":[{"key":"template.Image2.onClick"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"listData"},{"key":"template.update_files_name.defaultText"},{"key":"template.update_files_name.validation"},{"key":"template.Container4.borderWidth"},{"key":"template.Container4.borderRadius"},{"key":"template.Container4.borderColor"},{"key":"template.Image2.image"}],"gridType":"vertical","enhancements":true,"children":[{"widgetName":"Canvas7","rightColumn":256,"detachFromLayout":true,"widgetId":"oqhzaygncs","containerStyle":"none","topRow":0,"bottomRow":510,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"dropDisabled":true,"parentId":"0n30419eso","openParentPropertyPane":true,"minHeight":520,"isLoading":false,"noPad":true,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Container4","borderColor":"#2E3D4955","backgroundColor":"white","rightColumn":64,"disallowCopy":true,"widgetId":"u3nvgafsdo","topRow":0,"bottomRow":12,"containerStyle":"card","dragDisabled":true,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"oqhzaygncs","openParentPropertyPane":true,"isDeletable":false,"isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas8","detachFromLayout":true,"widgetId":"romgsruzxz","containerStyle":"none","topRow":0,"bottomRow":110,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"u3nvgafsdo","minHeight":120,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text14","rightColumn":60,"textAlign":"LEFT","widgetId":"vu7fb0dbt8","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"dynamicTriggerPathList":true,"parentColumnSpace":true,"dynamicBindingPathList":true,"leftColumn":true,"fontSize":true,"text":true,"textStyle":true},"topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"romgsruzxz","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","dynamicBindingPathList":[],"leftColumn":19,"fontSize":"PARAGRAPH","text":"File Name","textStyle":"HEADING"},{"image":"{{currentItem.data}}","widgetName":"Image2","rightColumn":19,"onClick":"{{showModal('Zoom_Modal2')}}","objectFit":"contain","widgetId":"ql8qs2xelx","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"defaultImage":true},"topRow":0,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"romgsruzxz","isLoading":false,"maxZoomLevel":1,"parentColumnSpace":7.3125,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":0,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png"},{"widgetName":"update_files_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.4580078125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"yqxzzh2oqi","logBlackList":{"widgetName":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"autoFocus":true,"type":true,"hideCard":true,"minHeight":true,"animateLoading":true,"parentColumnSpace":true,"resetOnSubmit":true,"leftColumn":true,"labelStyle":true,"inputType":true,"isDisabled":true,"key":true,"isRequired":true,"rightColumn":true,"widgetId":true,"isVisible":true,"label":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"iconAlign":true,"defaultText":true},"isVisible":true,"label":"","version":2,"parentId":"romgsruzxz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{currentItem.name}}"}]}],"borderWidth":"1","disablePropertyPane":true}]}],"privateWidgets":{"update_files_name":true,"Image2":true,"Text14":true},"childAutoComplete":{"currentItem":{"data":"","base64":"","name":"","raw":"","id":"","text":"","type":""}},"backgroundColor":"","rightColumn":64,"itemBackgroundColor":"#F6F7F8","widgetId":"0n30419eso","isVisible":"{{FilePicker.files.length > 0}}","parentId":"xv97g6rzgq","isLoading":false},{"widgetName":"Text9","rightColumn":16,"textAlign":"LEFT","widgetId":"jc21bnjh92","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Upload Folder"},{"widgetName":"Text7","rightColumn":64,"textAlign":"LEFT","widgetId":"364shivyaz","topRow":0,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Upload New Files"},{"widgetName":"upload_button","rightColumn":64,"onClick":"{{\nFilePicker.files.forEach((file, index) => {\n\tCreateFile.run((response, params) => { showAlert('File Uploaded','success'); \nif (params.isLastFile) {\n\tListFiles.run(() => {closeModal('Upload_Files_Modal'); resetWidget('folder_name', true);\t\t\t\t\tresetWidget('FilePicker', true);\nresetWidget('update_files_name', true);\n})\t\n}\n}, () => showAlert('File Upload Failed','error'), {fileIndex: index, name: selected_files.items[index].update_files_name.text, isLastFile: index == (FilePicker.files.length - 1), });\n\treturn true;\n})\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"},{"key":"isDisabled"}],"buttonColor":"#2E3D49","widgetId":"1uava20nxi","topRow":75,"bottomRow":79,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[{"key":"isDisabled"}],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Upload","isDisabled":"{{ selected_files.items.length == 0 || selected_files.items.map((file) => file.update_files_name.text).includes(\"\") }}"},{"widgetName":"Text19","rightColumn":52,"textAlign":"LEFT","dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"9wh2ereoy9","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":"{{FilePicker.files.length > 0}}","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"parentColumnSpace":8.0458984375,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[{"key":"isVisible"}],"fontSize":"HEADING3","text":"Selected files to upload"},{"widgetName":"FilePicker","dynamicPropertyPathList":[],"displayName":"FilePicker","iconSVG":"/static/media/icon.7c5ad9c3.svg","topRow":13,"bottomRow":17,"parentRowSpace":10,"allowedFileTypes":[],"type":"FILE_PICKER_WIDGET_V2","hideCard":false,"animateLoading":true,"parentColumnSpace":4.86865234375,"dynamicTriggerPathList":[],"leftColumn":16,"dynamicBindingPathList":[],"isDisabled":false,"key":"h2212wpg64","onFilesSelected":"","isRequired":false,"rightColumn":63,"isDefaultClickDisabled":true,"widgetId":"8l6lm067zw","defaultSelectedFiles":[],"isVisible":true,"label":"Select Files","maxFileSize":5,"version":1,"fileDataType":"Base64","parentId":"xv97g6rzgq","selectedFiles":[],"renderMode":"CANVAS","isLoading":false,"files":[],"maxNumFiles":"3"},{"widgetName":"folder_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.8955078125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":16,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"folder/sub-folder","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"215nlsqncm","isVisible":true,"label":"","version":2,"parentId":"xv97g6rzgq","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}],"borderWidth":"1"}]}}],"slug":"s3","isHidden":false},"new":true,"unpublishedPage":{"name":"S3","userPermissions":[],"layouts":[{"new":false,"id":"S3","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["60 * 24","search_input.text"],"name":"ListFiles","timeoutInMillisecond":10000,"id":"S3_ListFiles"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":910,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Zoom_Modal2","rightColumn":0,"detachFromLayout":true,"widgetId":"kqxoe40pg6","topRow":89,"bottomRow":89,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas9Copy","rightColumn":0,"detachFromLayout":true,"widgetId":"80wzwajsst","topRow":0,"bottomRow":590,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"kqxoe40pg6","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon3Copy","rightColumn":64,"onClick":"{{closeModal('Zoom_Modal2')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"8kw9kfcd5y","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"80wzwajsst","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text15Copy","rightColumn":41,"textAlign":"LEFT","widgetId":"vk710q1v3s","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"80wzwajsst","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Zoom Image"},{"widgetName":"Button13Copy","rightColumn":63,"onClick":"{{closeModal('Zoom_Modal2')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"lfiwss1u3w","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"80wzwajsst","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Close","isDisabled":false},{"image":"{{selected_files.selectedItem.base64}}","widgetName":"Image3Copy","rightColumn":64,"objectFit":"contain","widgetId":"2bewgakjx9","topRow":6,"bottomRow":51,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"80wzwajsst","isLoading":false,"maxZoomLevel":8,"parentColumnSpace":8,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png"}],"isDisabled":false}],"width":532,"height":600},{"backgroundColor":"#FFFFFF","widgetName":"Container3","rightColumn":37,"borderColor":"#2E3D4955","widgetId":"th4d9oxy8z","containerStyle":"card","topRow":0,"bottomRow":85,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas4","rightColumn":634,"detachFromLayout":true,"widgetId":"6tz2s7ivi5","containerStyle":"none","topRow":0,"bottomRow":850,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"th4d9oxy8z","minHeight":830,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"template":{"DownloadIcon":{"boxShadow":"NONE","widgetName":"DownloadIcon","onClick":"{{navigateTo(currentItem.signedUrl, {})}}","buttonColor":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D49';\n })();\n })}}","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":57,"iconName":"download","widgetId":"ljk8fj5jc1","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"CopyURLIcon":{"boxShadow":"NONE","widgetName":"CopyURLIcon","onClick":"{{copyToClipboard(currentItem.signedUrl)}}","buttonColor":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D49';\n })();\n })}}","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":51,"iconName":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'duplicate';\n })();\n })}}","widgetId":"d2z5zj56j9","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"EditIcon":{"boxShadow":"NONE","widgetName":"EditIcon","onClick":"{{showModal('Edit_Modal')}}","buttonColor":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D49';\n })();\n })}}","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":39,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":45,"iconName":"edit","widgetId":"x5bft8h9vd","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},"Text21":{"widgetName":"Text21","rightColumn":24,"textAlign":"LEFT","displayName":"Text","iconSVG":"/static/media/icon.e6c93592.svg","widgetId":"nu44q8kd9p","topRow":4,"bottomRow":8,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"hideCard":false,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[{"key":"text"}],"leftColumn":16,"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem) => currentItem.id)}}","textStyle":"BODY","key":"xvmvdekk3s"},"Text20":{"widgetName":"Text20","rightColumn":28,"textAlign":"LEFT","displayName":"Text","iconSVG":"/static/media/icon.e6c93592.svg","widgetId":"thgbdemmiw","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"hideCard":false,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[{"key":"text"}],"leftColumn":16,"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem) => currentItem.name)}}","textStyle":"HEADING","key":"xvmvdekk3s"},"Image3":{"widgetName":"Image3","displayName":"Image","iconSVG":"/static/media/icon.52d8fb96.svg","topRow":0,"bottomRow":8.4,"type":"IMAGE_WIDGET","hideCard":false,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","dynamicBindingPathList":[{"key":"image"}],"leftColumn":0,"defaultImage":"https://assets.appsmith.com/widgets/default.png","key":"lsc53q139g","image":"{{File_List.listData.map((currentItem) => currentItem.img)}}","rightColumn":16,"objectFit":"contain","widgetId":"2rrg354q8i","isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false},"FileListItemImage":{"widgetName":"FileListItemImage","onClick":"{{showModal('Zoom_Modal')}}","dynamicPropertyPathList":[],"topRow":1,"bottomRow":13,"parentRowSpace":10,"type":"IMAGE_WIDGET","parentColumnSpace":19.0625,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png","image":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.signedUrl;\n })();\n })}}","rightColumn":20,"objectFit":"contain","widgetId":"lh1sjszc93","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"enableDownload":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"enableRotation":true,"defaultImage":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false},"Container7":{"borderColor":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D4955';\n })();\n })}}","borderRadius":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '5';\n })();\n })}}","borderWidth":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '1';\n })();\n })}}"},"FileListItemName":{"widgetName":"FileListItemName","rightColumn":63,"textAlign":"LEFT","widgetId":"qyqv89mu1c","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"parentColumnSpace":true,"leftColumn":true,"fontSize":true,"text":true},"topRow":1,"bottomRow":8,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":true,"parentId":"lcz0rhije8","isLoading":false,"parentColumnSpace":19.0625,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{File_List.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.fileName;\n })();\n })}}"},"DeleteIcon":{"boxShadow":"NONE","widgetName":"DeleteIcon","onClick":"{{showModal('delete_modal')}}","buttonColor":"#DD4B34","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":63,"iconName":"trash","widgetId":"f8ipd8gbls","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"}},"widgetName":"File_List","listData":"{{ListFiles.data}}","isCanvas":true,"displayName":"List","iconSVG":"/static/media/icon.9925ee17.svg","topRow":10,"bottomRow":83,"parentRowSpace":10,"type":"LIST_WIDGET","hideCard":false,"gridGap":0,"parentColumnSpace":9.67822265625,"dynamicTriggerPathList":[{"key":"template.DownloadIcon.onClick"},{"key":"template.CopyURLIcon.onClick"}],"leftColumn":1,"dynamicBindingPathList":[{"key":"listData"},{"key":"template.FileListItemImage.image"},{"key":"template.FileListItemName.text"},{"key":"template.EditIcon.buttonColor"},{"key":"template.CopyURLIcon.buttonColor"},{"key":"template.DownloadIcon.buttonColor"},{"key":"template.Container7.borderColor"},{"key":"template.Container7.borderWidth"},{"key":"template.Container7.borderRadius"},{"key":"template.CopyURLIcon.iconName"}],"gridType":"vertical","enhancements":true,"children":[{"widgetName":"Canvas14","displayName":"Canvas","topRow":0,"bottomRow":390,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":false,"hideCard":true,"dropDisabled":true,"openParentPropertyPane":true,"minHeight":400,"noPad":true,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"Container7","borderColor":"#2E3D4955","disallowCopy":true,"isCanvas":true,"displayName":"Container","iconSVG":"/static/media/icon.1977dca3.svg","topRow":0,"bottomRow":17,"dragDisabled":true,"type":"CONTAINER_WIDGET","hideCard":false,"openParentPropertyPane":true,"isDeletable":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas15","detachFromLayout":true,"displayName":"Canvas","widgetId":"lcz0rhije8","containerStyle":"none","topRow":0,"bottomRow":160,"parentRowSpace":1,"isVisible":true,"type":"CANVAS_WIDGET","canExtend":false,"version":1,"hideCard":true,"parentId":"66oc53smx3","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"boxShadow":"NONE","widgetName":"EditIcon","onClick":"{{showModal('Edit_Modal')}}","buttonColor":"#2E3D49","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":39,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":45,"iconName":"edit","widgetId":"x5bft8h9vd","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"CopyURLIcon","onClick":"{{copyToClipboard(currentItem.signedUrl)}}","buttonColor":"#2E3D49","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":45,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":51,"iconName":"duplicate","widgetId":"d2z5zj56j9","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"DownloadIcon","onClick":"{{navigateTo(currentItem.signedUrl, {})}}","buttonColor":"#2E3D49","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":57,"iconName":"download","widgetId":"ljk8fj5jc1","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"boxShadow":"NONE","widgetName":"DeleteIcon","onClick":"{{showModal('delete_modal')}}","buttonColor":"#DD4B34","dynamicPropertyPathList":[{"key":"onClick"}],"displayName":"Icon Button","iconSVG":"/static/media/icon.bff4eac0.svg","topRow":10,"bottomRow":14,"parentRowSpace":10,"type":"ICON_BUTTON_WIDGET","hideCard":false,"parentColumnSpace":9.4658203125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57,"dynamicBindingPathList":[],"isDisabled":false,"key":"8akz850h7z","rightColumn":63,"iconName":"trash","widgetId":"f8ipd8gbls","logBlackList":{"boxShadow":true,"widgetName":true,"buttonColor":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"type":true,"hideCard":true,"minHeight":true,"parentColumnSpace":true,"leftColumn":true,"isDisabled":true,"key":true,"rightColumn":true,"iconName":true,"widgetId":true,"isVisible":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"borderRadius":true,"buttonVariant":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","renderMode":"CANVAS","isLoading":false,"borderRadius":"CIRCLE","buttonVariant":"TERTIARY"},{"widgetName":"FileListItemName","rightColumn":64,"textAlign":"LEFT","widgetId":"kmwv6dap5n","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"parentColumnSpace":true,"leftColumn":true,"fontSize":true,"text":true},"topRow":0,"bottomRow":7,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"lcz0rhije8","isLoading":false,"parentColumnSpace":19.0625,"dynamicTriggerPathList":[],"overflow":"SCROLL","leftColumn":21,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{currentItem.fileName}}"},{"widgetName":"FileListItemImage","onClick":"{{showModal('Zoom_Modal')}}","dynamicPropertyPathList":[],"topRow":0,"bottomRow":13,"parentRowSpace":10,"type":"IMAGE_WIDGET","parentColumnSpace":19.0625,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":1,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://cdn3.iconfinder.com/data/icons/brands-applications/512/File-512.png","image":"{{currentItem.signedUrl}}","rightColumn":20,"objectFit":"contain","widgetId":"4laf7e6wer","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"enableDownload":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"enableRotation":true,"defaultImage":true},"isVisible":true,"version":1,"parentId":"lcz0rhije8","isLoading":false,"maxZoomLevel":1,"enableDownload":false,"enableRotation":false}],"key":"29vrztch46"}],"borderWidth":"1","key":"cw0dtdoe0g","disablePropertyPane":true,"backgroundColor":"white","rightColumn":64,"widgetId":"66oc53smx3","containerStyle":"card","isVisible":true,"version":1,"parentId":"sh1yahe7kl","renderMode":"CANVAS","isLoading":false,"borderRadius":"5"}],"key":"29vrztch46","rightColumn":232.27734375,"detachFromLayout":true,"widgetId":"sh1yahe7kl","containerStyle":"none","isVisible":true,"version":1,"parentId":"cjgg2thzom","renderMode":"CANVAS","isLoading":false}],"privateWidgets":{"DownloadIcon":true,"EditIcon":true,"CopyURLIcon":true,"FileListItemImage":true,"FileListItemName":true,"DeleteIcon":true},"key":"x51ms5k6q9","backgroundColor":"transparent","rightColumn":63,"itemBackgroundColor":"#F6F7F8","widgetId":"cjgg2thzom","isVisible":true,"parentId":"6tz2s7ivi5","renderMode":"CANVAS","isLoading":false},{"widgetName":"search_input","dynamicPropertyPathList":[{"key":"onTextChanged"}],"displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":16.4169921875,"dynamicTriggerPathList":[{"key":"onTextChanged"}],"resetOnSubmit":true,"leftColumn":1,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"Search File Prefix","isDisabled":false,"key":"auxyd97lu3","validation":"true","isRequired":false,"onTextChanged":"{{ListFiles.run()}}","rightColumn":40,"widgetId":"why172fko6","isVisible":true,"label":"","version":2,"parentId":"6tz2s7ivi5","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"Text6","rightColumn":63,"backgroundColor":"","textAlign":"LEFT","widgetId":"t54ituq472","topRow":0,"bottomRow":5,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6tz2s7ivi5","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"template_table Bucket"}]}],"borderWidth":"1"},{"widgetName":"delete_modal","rightColumn":0,"detachFromLayout":true,"widgetId":"9g0cw9adf8","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas6","rightColumn":0,"detachFromLayout":true,"widgetId":"ozvpoudxz2","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"9g0cw9adf8","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon2","rightColumn":64,"onClick":"{{closeModal('delete_modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"xkyh49z71e","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"ozvpoudxz2","isLoading":false,"leftColumn":56,"dynamicBindingPathList":[],"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text12","rightColumn":41,"textAlign":"LEFT","widgetId":"s1y44xm547","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete File"},{"widgetName":"Button10","rightColumn":48,"onClick":"{{closeModal('delete_modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"pi0t67rnwh","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Button11","rightColumn":64,"onClick":"{{\nDeleteFile.run(() => {closeModal('delete_modal'); \nListFiles.run();\n});\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"hp22uj3dra","topRow":17,"bottomRow":21,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"ozvpoudxz2","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text13","rightColumn":64,"textAlign":"LEFT","widgetId":"oypa9ad1tg","topRow":5,"bottomRow":16,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"ozvpoudxz2","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete the file?\n\n{{File_List.selectedItem.fileName}}"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Edit_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"usealgbtyj","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas10","rightColumn":0,"detachFromLayout":true,"widgetId":"6i7m9kpuky","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"usealgbtyj","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text17","rightColumn":41,"textAlign":"LEFT","widgetId":"z64z3l112n","topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update File"},{"widgetName":"Button15","rightColumn":44,"onClick":"{{closeModal('Edit_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#2E3D49","widgetId":"trc4e6ylcz","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":32,"dynamicBindingPathList":[],"borderRadius":"ROUNDED","buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"update_button","rightColumn":64,"onClick":"{{UpdateFile.run(() => {ListFiles.run();resetWidget('update_file_picker');closeModal('Edit_Modal');})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"},{"key":"isDisabled"}],"buttonColor":"#2E3D49","widgetId":"8lbthc9dml","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"6i7m9kpuky","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":44,"dynamicBindingPathList":[{"key":"isDisabled"}],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Update","isDisabled":"{{update_file_picker.files.length == 0}}"},{"widgetName":"Text18","rightColumn":17,"textAlign":"RIGHT","widgetId":"qb26g34etr","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"6i7m9kpuky","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"File Name"},{"widgetName":"update_file_picker","displayName":"FilePicker","iconSVG":"/static/media/icon.7c5ad9c3.svg","topRow":11,"bottomRow":15,"parentRowSpace":10,"allowedFileTypes":[],"type":"FILE_PICKER_WIDGET_V2","hideCard":false,"animateLoading":true,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[],"leftColumn":18,"dynamicBindingPathList":[],"isDisabled":false,"key":"h2212wpg64","isRequired":false,"rightColumn":64,"isDefaultClickDisabled":true,"widgetId":"i8g6khu01a","defaultSelectedFiles":[],"isVisible":true,"label":"Select File","maxFileSize":"10","version":1,"fileDataType":"Base64","parentId":"6i7m9kpuky","selectedFiles":[],"renderMode":"CANVAS","isLoading":false,"files":[],"maxNumFiles":1},{"widgetName":"update_file_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":18,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":true,"key":"auxyd97lu3","validation":"true","isRequired":false,"rightColumn":64,"widgetId":"uabsu3mjt3","isVisible":true,"label":"","version":2,"parentId":"6i7m9kpuky","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{File_List.selectedItem.fileName}}"}],"isDisabled":false}],"width":456,"height":240},{"backgroundColor":"#FFFFFF","widgetName":"Container6","rightColumn":64,"borderColor":"#2E3D4955","widgetId":"yg1iyxq9kd","containerStyle":"card","topRow":0,"bottomRow":85,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.8125,"dynamicTriggerPathList":[],"leftColumn":37,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas13","rightColumn":634,"detachFromLayout":true,"widgetId":"xv97g6rzgq","containerStyle":"none","topRow":0,"bottomRow":820,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"yg1iyxq9kd","minHeight":830,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"template":{"Canvas7":{"widgetName":"Canvas7","rightColumn":256,"detachFromLayout":true,"widgetId":"oqhzaygncs","containerStyle":"none","topRow":0,"bottomRow":400,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"dropDisabled":true,"parentId":"0n30419eso","openParentPropertyPane":true,"minHeight":340,"isLoading":false,"noPad":true,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":["u3nvgafsdo"]},"update_files_name":{"widgetName":"update_files_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":8,"bottomRow":12,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.4580078125,"resetOnSubmit":true,"leftColumn":23,"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'true';\n })();\n })}}","isRequired":false,"rightColumn":43,"widgetId":"yqxzzh2oqi","logBlackList":{"widgetName":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"autoFocus":true,"type":true,"hideCard":true,"minHeight":true,"animateLoading":true,"parentColumnSpace":true,"resetOnSubmit":true,"leftColumn":true,"labelStyle":true,"inputType":true,"isDisabled":true,"key":true,"isRequired":true,"rightColumn":true,"widgetId":true,"isVisible":true,"label":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"iconAlign":true,"defaultText":true},"isVisible":true,"label":"","version":2,"parentId":"romgsruzxz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.name;\n })();\n })}}"},"Image2":{"image":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.data;\n })();\n })}}","widgetName":"Image2","rightColumn":10,"onClick":"{{showModal('Zoom_Modal2')}}","objectFit":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'contain';\n })();\n })}}","widgetId":"ql8qs2xelx","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"defaultImage":true},"topRow":0,"bottomRow":6,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"romgsruzxz","isLoading":false,"maxZoomLevel":1,"parentColumnSpace":7.3125,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":0,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png"},"Container4":{"backgroundColor":"white","widgetName":"Container4","rightColumn":64,"borderColor":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '#2E3D4955';\n })();\n })}}","disallowCopy":true,"widgetId":"u3nvgafsdo","containerStyle":"card","topRow":0,"bottomRow":8,"dragDisabled":true,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"oqhzaygncs","openParentPropertyPane":true,"isDeletable":false,"isLoading":false,"leftColumn":0,"borderRadius":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '5';\n })();\n })}}","children":["romgsruzxz"],"borderWidth":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return '1';\n })();\n })}}","disablePropertyPane":true},"Canvas8":{"widgetName":"Canvas8","detachFromLayout":true,"widgetId":"romgsruzxz","containerStyle":"none","topRow":0,"bottomRow":180,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"u3nvgafsdo","minHeight":80,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":["vu7fb0dbt8","7zziet357m","ql8qs2xelx"]},"Text14":{"widgetName":"Text14","rightColumn":23,"textAlign":"{{selected_files.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'LEFT';\n })();\n })}}","widgetId":"vu7fb0dbt8","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"dynamicTriggerPathList":true,"parentColumnSpace":true,"dynamicBindingPathList":true,"leftColumn":true,"fontSize":true,"text":true,"textStyle":true},"topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"romgsruzxz","isLoading":false,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":11,"fontSize":"PARAGRAPH","text":"File Name","textStyle":"HEADING"}},"widgetName":"selected_files","listData":"{{FilePicker.files}}","dynamicPropertyPathList":[{"key":"isVisible"}],"topRow":23,"bottomRow":75,"parentRowSpace":10,"type":"LIST_WIDGET","gridGap":0,"parentColumnSpace":8,"dynamicTriggerPathList":[{"key":"template.Image2.onClick"}],"leftColumn":0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"listData"},{"key":"template.update_files_name.defaultText"},{"key":"template.update_files_name.validation"},{"key":"template.Container4.borderWidth"},{"key":"template.Container4.borderRadius"},{"key":"template.Container4.borderColor"},{"key":"template.Image2.image"}],"gridType":"vertical","enhancements":true,"children":[{"widgetName":"Canvas7","rightColumn":256,"detachFromLayout":true,"widgetId":"oqhzaygncs","containerStyle":"none","topRow":0,"bottomRow":510,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"dropDisabled":true,"parentId":"0n30419eso","openParentPropertyPane":true,"minHeight":520,"isLoading":false,"noPad":true,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Container4","borderColor":"#2E3D4955","backgroundColor":"white","rightColumn":64,"disallowCopy":true,"widgetId":"u3nvgafsdo","topRow":0,"bottomRow":12,"containerStyle":"card","dragDisabled":true,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"oqhzaygncs","openParentPropertyPane":true,"isDeletable":false,"isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"borderRadius":"5","children":[{"widgetName":"Canvas8","detachFromLayout":true,"widgetId":"romgsruzxz","containerStyle":"none","topRow":0,"bottomRow":110,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"u3nvgafsdo","minHeight":120,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Text14","rightColumn":60,"textAlign":"LEFT","widgetId":"vu7fb0dbt8","logBlackList":{"widgetName":true,"rightColumn":true,"textAlign":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"fontStyle":true,"type":true,"textColor":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"dynamicTriggerPathList":true,"parentColumnSpace":true,"dynamicBindingPathList":true,"leftColumn":true,"fontSize":true,"text":true,"textStyle":true},"topRow":0,"bottomRow":4,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"romgsruzxz","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","dynamicBindingPathList":[],"leftColumn":19,"fontSize":"PARAGRAPH","text":"File Name","textStyle":"HEADING"},{"image":"{{currentItem.data}}","widgetName":"Image2","rightColumn":19,"onClick":"{{showModal('Zoom_Modal2')}}","objectFit":"contain","widgetId":"ql8qs2xelx","logBlackList":{"image":true,"widgetName":true,"rightColumn":true,"objectFit":true,"widgetId":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"isVisible":true,"type":true,"version":true,"parentId":true,"minHeight":true,"isLoading":true,"maxZoomLevel":true,"parentColumnSpace":true,"imageShape":true,"leftColumn":true,"defaultImage":true},"topRow":0,"bottomRow":9,"parentRowSpace":10,"isVisible":true,"type":"IMAGE_WIDGET","version":1,"parentId":"romgsruzxz","isLoading":false,"maxZoomLevel":1,"parentColumnSpace":7.3125,"dynamicTriggerPathList":[{"key":"onClick"}],"imageShape":"RECTANGLE","leftColumn":0,"dynamicBindingPathList":[{"key":"image"}],"defaultImage":"https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png"},{"widgetName":"update_files_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":5,"bottomRow":9,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.4580078125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"yqxzzh2oqi","logBlackList":{"widgetName":true,"isCanvas":true,"displayName":true,"iconSVG":true,"topRow":true,"bottomRow":true,"parentRowSpace":true,"autoFocus":true,"type":true,"hideCard":true,"minHeight":true,"animateLoading":true,"parentColumnSpace":true,"resetOnSubmit":true,"leftColumn":true,"labelStyle":true,"inputType":true,"isDisabled":true,"key":true,"isRequired":true,"rightColumn":true,"widgetId":true,"isVisible":true,"label":true,"version":true,"parentId":true,"renderMode":true,"isLoading":true,"iconAlign":true,"defaultText":true},"isVisible":true,"label":"","version":2,"parentId":"romgsruzxz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{currentItem.name}}"}]}],"borderWidth":"1","disablePropertyPane":true}]}],"privateWidgets":{"update_files_name":true,"Image2":true,"Text14":true},"childAutoComplete":{"currentItem":{"data":"","base64":"","name":"","raw":"","id":"","text":"","type":""}},"backgroundColor":"","rightColumn":64,"itemBackgroundColor":"#F6F7F8","widgetId":"0n30419eso","isVisible":"{{FilePicker.files.length > 0}}","parentId":"xv97g6rzgq","isLoading":false},{"widgetName":"Text9","rightColumn":16,"textAlign":"LEFT","widgetId":"jc21bnjh92","topRow":6,"bottomRow":10,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Upload Folder"},{"widgetName":"Text7","rightColumn":64,"textAlign":"LEFT","widgetId":"364shivyaz","topRow":0,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Upload New Files"},{"widgetName":"upload_button","rightColumn":64,"onClick":"{{\nFilePicker.files.forEach((file, index) => {\n\tCreateFile.run((response, params) => { showAlert('File Uploaded','success'); \nif (params.isLastFile) {\n\tListFiles.run(() => {closeModal('Upload_Files_Modal'); resetWidget('folder_name', true);\t\t\t\t\tresetWidget('FilePicker', true);\nresetWidget('update_files_name', true);\n})\t\n}\n}, () => showAlert('File Upload Failed','error'), {fileIndex: index, name: selected_files.items[index].update_files_name.text, isLastFile: index == (FilePicker.files.length - 1), });\n\treturn true;\n})\n}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"},{"key":"isDisabled"}],"buttonColor":"#2E3D49","widgetId":"1uava20nxi","topRow":75,"bottomRow":79,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"xv97g6rzgq","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":36,"dynamicBindingPathList":[{"key":"isDisabled"}],"borderRadius":"ROUNDED","buttonVariant":"PRIMARY","text":"Upload","isDisabled":"{{ selected_files.items.length == 0 || selected_files.items.map((file) => file.update_files_name.text).includes(\"\") }}"},{"widgetName":"Text19","rightColumn":52,"textAlign":"LEFT","dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"9wh2ereoy9","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":"{{FilePicker.files.length > 0}}","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"xv97g6rzgq","isLoading":false,"parentColumnSpace":8.0458984375,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[{"key":"isVisible"}],"fontSize":"HEADING3","text":"Selected files to upload"},{"widgetName":"FilePicker","dynamicPropertyPathList":[],"displayName":"FilePicker","iconSVG":"/static/media/icon.7c5ad9c3.svg","topRow":13,"bottomRow":17,"parentRowSpace":10,"allowedFileTypes":[],"type":"FILE_PICKER_WIDGET_V2","hideCard":false,"animateLoading":true,"parentColumnSpace":4.86865234375,"dynamicTriggerPathList":[],"leftColumn":16,"dynamicBindingPathList":[],"isDisabled":false,"key":"h2212wpg64","onFilesSelected":"","isRequired":false,"rightColumn":63,"isDefaultClickDisabled":true,"widgetId":"8l6lm067zw","defaultSelectedFiles":[],"isVisible":true,"label":"Select Files","maxFileSize":5,"version":1,"fileDataType":"Base64","parentId":"xv97g6rzgq","selectedFiles":[],"renderMode":"CANVAS","isLoading":false,"files":[],"maxNumFiles":"3"},{"widgetName":"folder_name","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":6,"bottomRow":10,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":11.8955078125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":16,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","placeholderText":"folder/sub-folder","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":63,"widgetId":"215nlsqncm","isVisible":true,"label":"","version":2,"parentId":"xv97g6rzgq","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}]}],"borderWidth":"1"}]}}],"slug":"s3","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc2"},{"publishedPage":{"name":"Redis","userPermissions":[],"layouts":[{"new":false,"id":"Redis","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":[],"name":"FetchKeys","timeoutInMillisecond":10000,"id":"Redis_FetchKeys"}],[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow.result"],"name":"FetchValue","timeoutInMillisecond":10000,"id":"Redis_FetchValue"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":5160,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"eer73khglm","topRow":1,"bottomRow":47,"parentRowSpace":10,"isVisible":"{{data_table.selectedRow.result}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"9nvn3gfw6q","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"eer73khglm","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateKey.run(() => FetchKeys.run(), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"3apd2wkt91","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"9nvn3gfw6q","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"hhh0296qfj","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"9nvn3gfw6q","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"uawwds1z0r","topRow":0,"bottomRow":8,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"9nvn3gfw6q","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Key: {{data_table.selectedRow.result}}"},{"widgetName":"update_value_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":1,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"l3qtdja15h","isVisible":true,"label":"","version":2,"parentId":"9nvn3gfw6q","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{FetchValue.data[0].result}}"}]}]},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"v8nfulwuy0","containerStyle":"card","topRow":1,"bottomRow":88,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"erkvdsolhu","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"v8nfulwuy0","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["result","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":5,"bottomRow":86,"parentRowSpace":10,"onPageChange":"","isSortable":true,"type":"TABLE_WIDGET","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onRowSelected"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.result.computedValue"}],"leftColumn":0,"primaryColumns":{"result":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.result))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"result","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"result","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"delimiter":",","onRowSelected":"{{FetchValue.run()}}","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"tefed053r1","isVisibleFilters":true,"tableData":"{{FetchKeys.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"erkvdsolhu","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"result":503,"task":245,"deliveryAddress":170,"step":62,"id":228,"customColumn2":174,"status":75}},{"widgetName":"new_key_button","rightColumn":64,"onClick":"{{showModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"2rlp4irwh0","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":6.8310546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"New Key","isDisabled":false},{"widgetName":"refresh_button","rightColumn":51,"onClick":"{{FetchKeys.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o9t8fslxdi","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":40,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Refresh","isDisabled":false},{"widgetName":"Text16","rightColumn":39,"textAlign":"LEFT","widgetId":"nt181ks4ci","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Redis Data"}]}]},{"widgetName":"Insert_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"c8fg4ubw52","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":0,"detachFromLayout":true,"widgetId":"re60vbuakz","topRow":0,"bottomRow":600,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"c8fg4ubw52","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon1","rightColumn":64,"onClick":"{{closeModal('Insert_Modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"3tk445loxa","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"re60vbuakz","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text21","rightColumn":41,"textAlign":"LEFT","widgetId":"fgi9qp4uwr","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"New Key"},{"widgetName":"Button1","rightColumn":47,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"xnh96plcyo","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":35,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Button2","rightColumn":64,"onClick":"{{InsertKey.run(() => FetchKeys.run(() => closeModal('Insert_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"ix2dralfal","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Insert","isDisabled":false},{"widgetName":"Text22","rightColumn":17,"textAlign":"RIGHT","widgetId":"kotk4wa6pe","topRow":9,"bottomRow":13,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Key"},{"widgetName":"Text23","rightColumn":17,"textAlign":"RIGHT","widgetId":"y2dlumuetl","topRow":16,"bottomRow":20,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Value"},{"widgetName":"insert_key_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":8.125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"ynw4ir8luz","isVisible":true,"label":"","version":2,"parentId":"re60vbuakz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_value_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":52,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":8.125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"6qn1qkr18d","isVisible":true,"label":"","version":2,"parentId":"re60vbuakz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"value_modal","rightColumn":0,"detachFromLayout":true,"widgetId":"fh14k9y353","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"children":[{"widgetName":"Canvas4","rightColumn":0,"detachFromLayout":true,"widgetId":"v8n3d5aecd","topRow":0,"bottomRow":260,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"fh14k9y353","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon2","rightColumn":64,"onClick":"{{closeModal('value_modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"jqaazpo3zy","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"v8n3d5aecd","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text24","rightColumn":41,"textAlign":"LEFT","widgetId":"hvb3xnk1u8","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"v8n3d5aecd","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Value for Key: {{data_table.selectedRow.result}}"},{"widgetName":"Button4","rightColumn":64,"onClick":"{{closeModal('value_modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"yka7b6k706","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"v8n3d5aecd","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Close","isDisabled":false},{"widgetName":"Text25","rightColumn":64,"textAlign":"LEFT","widgetId":"j9315vzr13","topRow":6,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"v8n3d5aecd","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"SCROLL","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{FetchValue.data[0].result}}"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Delete_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"0skbil3ntd","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"children":[{"widgetName":"Canvas5","rightColumn":0,"detachFromLayout":true,"widgetId":"lwsyaz55ll","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"0skbil3ntd","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon3","rightColumn":64,"onClick":"{{closeModal('Delete_Modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"dtuc8ag2of","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"lwsyaz55ll","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text26","rightColumn":41,"textAlign":"LEFT","widgetId":"d9ap4dp300","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"lwsyaz55ll","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Key"},{"widgetName":"Button6","rightColumn":64,"onClick":"{{DeleteKey.run(() => FetchKeys.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"2kg6lmim5m","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"lwsyaz55ll","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text27","rightColumn":64,"textAlign":"LEFT","widgetId":"c698jgkzjg","topRow":7,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"lwsyaz55ll","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"SCROLL","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete the key?\n\n{{data_table.selectedRow.result}}"},{"widgetName":"Button7","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"lsvqrab5v2","topRow":18,"bottomRow":22,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"lwsyaz55ll","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":32,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false}],"isDisabled":false}],"width":456,"height":240}]}}],"slug":"redis","isHidden":false},"new":true,"unpublishedPage":{"name":"Redis","userPermissions":[],"layouts":[{"new":false,"id":"Redis","userPermissions":[],"layoutOnLoadActions":[[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":[],"name":"FetchKeys","timeoutInMillisecond":10000,"id":"Redis_FetchKeys"}],[{"pluginType":"DB","confirmBeforeExecute":false,"jsonPathKeys":["data_table.selectedRow.result"],"name":"FetchValue","timeoutInMillisecond":10000,"id":"Redis_FetchValue"}]],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1056,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":5160,"containerStyle":"none","snapRows":129,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":54,"minHeight":890,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"eer73khglm","topRow":1,"bottomRow":47,"parentRowSpace":10,"isVisible":"{{data_table.selectedRow.result}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"9nvn3gfw6q","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"eer73khglm","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateKey.run(() => FetchKeys.run(), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"3apd2wkt91","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"9nvn3gfw6q","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"hhh0296qfj","topRow":39,"bottomRow":43,"isVisible":true,"type":"FORM_BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"9nvn3gfw6q","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Reset"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"uawwds1z0r","topRow":0,"bottomRow":8,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"9nvn3gfw6q","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Update Key: {{data_table.selectedRow.result}}"},{"widgetName":"update_value_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":37,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":10.5390625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":1,"dynamicBindingPathList":[{"key":"defaultText"}],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":true,"rightColumn":63,"widgetId":"l3qtdja15h","isVisible":true,"label":"","version":2,"parentId":"9nvn3gfw6q","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":"{{FetchValue.data[0].result}}"}]}]},{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"v8nfulwuy0","containerStyle":"card","topRow":1,"bottomRow":88,"parentRowSpace":10,"isVisible":true,"type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"erkvdsolhu","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":true,"canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"v8nfulwuy0","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["result","customColumn1"],"dynamicPropertyPathList":[],"isVisibleDownload":true,"topRow":5,"bottomRow":86,"parentRowSpace":10,"onPageChange":"","isSortable":true,"type":"TABLE_WIDGET","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"},{"key":"onRowSelected"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.result.computedValue"}],"leftColumn":0,"primaryColumns":{"result":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.result))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"result","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"result","verticalAlignment":"CENTER"},"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"delimiter":",","onRowSelected":"{{FetchValue.run()}}","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"tefed053r1","isVisibleFilters":true,"tableData":"{{FetchKeys.data}}","isVisible":true,"label":"Data","searchKey":"","version":3,"parentId":"erkvdsolhu","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"result":503,"task":245,"deliveryAddress":170,"step":62,"id":228,"customColumn2":174,"status":75}},{"widgetName":"new_key_button","rightColumn":64,"onClick":"{{showModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"2rlp4irwh0","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":6.8310546875,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"New Key","isDisabled":false},{"widgetName":"refresh_button","rightColumn":51,"onClick":"{{FetchKeys.run()}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o9t8fslxdi","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":40,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Refresh","isDisabled":false},{"widgetName":"Text16","rightColumn":39,"textAlign":"LEFT","widgetId":"nt181ks4ci","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"erkvdsolhu","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Redis Data"}]}]},{"widgetName":"Insert_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"c8fg4ubw52","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":0,"detachFromLayout":true,"widgetId":"re60vbuakz","topRow":0,"bottomRow":600,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"c8fg4ubw52","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon1","rightColumn":64,"onClick":"{{closeModal('Insert_Modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"3tk445loxa","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"re60vbuakz","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text21","rightColumn":41,"textAlign":"LEFT","widgetId":"fgi9qp4uwr","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"New Key"},{"widgetName":"Button1","rightColumn":47,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"xnh96plcyo","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":35,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false},{"widgetName":"Button2","rightColumn":64,"onClick":"{{InsertKey.run(() => FetchKeys.run(() => closeModal('Insert_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"ix2dralfal","topRow":53,"bottomRow":57,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"re60vbuakz","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Insert","isDisabled":false},{"widgetName":"Text22","rightColumn":17,"textAlign":"RIGHT","widgetId":"kotk4wa6pe","topRow":9,"bottomRow":13,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Key"},{"widgetName":"Text23","rightColumn":17,"textAlign":"RIGHT","widgetId":"y2dlumuetl","topRow":16,"bottomRow":20,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"re60vbuakz","isLoading":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Value"},{"widgetName":"insert_key_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":9,"bottomRow":13,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":8.125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"ynw4ir8luz","isVisible":true,"label":"","version":2,"parentId":"re60vbuakz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""},{"widgetName":"insert_value_input","displayName":"Input","iconSVG":"/static/media/icon.9f505595.svg","topRow":15,"bottomRow":52,"parentRowSpace":10,"autoFocus":false,"type":"INPUT_WIDGET_V2","hideCard":false,"animateLoading":false,"parentColumnSpace":8.125,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"labelStyle":"","inputType":"TEXT","isDisabled":false,"key":"om9y3ljmtt","validation":"true","isRequired":false,"rightColumn":62,"widgetId":"6qn1qkr18d","isVisible":true,"label":"","version":2,"parentId":"re60vbuakz","renderMode":"CANVAS","isLoading":false,"iconAlign":"left","defaultText":""}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"value_modal","rightColumn":0,"detachFromLayout":true,"widgetId":"fh14k9y353","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"children":[{"widgetName":"Canvas4","rightColumn":0,"detachFromLayout":true,"widgetId":"v8n3d5aecd","topRow":0,"bottomRow":260,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"fh14k9y353","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon2","rightColumn":64,"onClick":"{{closeModal('value_modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"jqaazpo3zy","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"v8n3d5aecd","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text24","rightColumn":41,"textAlign":"LEFT","widgetId":"hvb3xnk1u8","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"v8n3d5aecd","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"HEADING1","text":"Value for Key: {{data_table.selectedRow.result}}"},{"widgetName":"Button4","rightColumn":64,"onClick":"{{closeModal('value_modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"yka7b6k706","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"v8n3d5aecd","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Close","isDisabled":false},{"widgetName":"Text25","rightColumn":64,"textAlign":"LEFT","widgetId":"j9315vzr13","topRow":6,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"v8n3d5aecd","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"SCROLL","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"{{FetchValue.data[0].result}}"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Delete_Modal","rightColumn":0,"detachFromLayout":true,"widgetId":"0skbil3ntd","topRow":0,"bottomRow":0,"parentRowSpace":1,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":true,"isLoading":false,"parentColumnSpace":1,"leftColumn":0,"children":[{"widgetName":"Canvas5","rightColumn":0,"detachFromLayout":true,"widgetId":"lwsyaz55ll","topRow":0,"bottomRow":240,"parentRowSpace":1,"isVisible":true,"canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"0skbil3ntd","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Icon3","rightColumn":64,"onClick":"{{closeModal('Delete_Modal')}}","iconName":"cross","buttonColor":"#2E3D49","widgetId":"dtuc8ag2of","topRow":1,"bottomRow":5,"isVisible":true,"type":"ICON_BUTTON_WIDGET","version":1,"parentId":"lwsyaz55ll","isLoading":false,"leftColumn":56,"borderRadius":"SHARP","buttonVariant":"TERTIARY","iconSize":24},{"widgetName":"Text26","rightColumn":41,"textAlign":"LEFT","widgetId":"d9ap4dp300","topRow":1,"bottomRow":5,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"lwsyaz55ll","isLoading":false,"dynamicTriggerPathList":[],"overflow":"NONE","leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Key"},{"widgetName":"Button6","rightColumn":64,"onClick":"{{DeleteKey.run(() => FetchKeys.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"2kg6lmim5m","topRow":18,"bottomRow":22,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"lwsyaz55ll","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":46,"dynamicBindingPathList":[],"buttonVariant":"PRIMARY","text":"Confirm","isDisabled":false},{"widgetName":"Text27","rightColumn":64,"textAlign":"LEFT","widgetId":"c698jgkzjg","topRow":7,"bottomRow":17,"parentRowSpace":10,"isVisible":true,"fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"lwsyaz55ll","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[],"overflow":"SCROLL","leftColumn":1,"dynamicBindingPathList":[{"key":"text"}],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete the key?\n\n{{data_table.selectedRow.result}}"},{"widgetName":"Button7","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"lsvqrab5v2","topRow":18,"bottomRow":22,"parentRowSpace":10,"isVisible":true,"type":"BUTTON_WIDGET","version":1,"recaptchaType":"V3","parentId":"lwsyaz55ll","isLoading":false,"parentColumnSpace":6.8125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":32,"dynamicBindingPathList":[],"buttonVariant":"SECONDARY","text":"Cancel","isDisabled":false}],"isDisabled":false}],"width":456,"height":240}]}}],"slug":"redis","isHidden":false},"userPermissions":["read:pages","manage:pages"],"gitSyncId":"61764fbeba7e887d03bc3631_61bb770ecd5d70450952ccc6"}],"publishedLayoutmongoEscapedWidgets":{"MongoDB":["data_table"]},"actionCollectionList":[],"exportedApplication":{"applicationVersion":2,"appLayout":{"type":"FLUID"},"new":true,"color":"#D9E7FF","name":"CRUD App Templates","appIsExample":false,"icon":"bag","isPublic":false,"unreadCommentThreads":0,"slug":"crud-app-templates","isManualUpdate":false}} \ No newline at end of file
e7730394678cdd3ce065178467df9d65be1a3961
2024-09-04 15:49:53
Manish Kumar
fix: Embedded datasource persistence changes for git. (#36109)
false
Embedded datasource persistence changes for git. (#36109)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java index e2b41d1c8076..e067733a8094 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java @@ -54,7 +54,7 @@ public class Datasource extends GitSyncedDomain { String templateName; // This is only kept public for embedded datasource - @JsonView({Views.Public.class, FromRequest.class}) + @JsonView({Views.Public.class, FromRequest.class, Git.class}) DatasourceConfiguration datasourceConfiguration; @Transient diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceConfiguration.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceConfiguration.java index ee6c0097cf42..5a81b66b730c 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceConfiguration.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceConfiguration.java @@ -1,6 +1,7 @@ package com.appsmith.external.models; import com.appsmith.external.views.FromRequest; +import com.appsmith.external.views.Git; import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonView; import lombok.AllArgsConstructor; @@ -37,17 +38,17 @@ public class DatasourceConfiguration implements AppsmithDomain { Boolean sshProxyEnabled; - @JsonView({Views.Public.class, FromRequest.class}) + @JsonView({Views.Public.class, FromRequest.class, Git.class}) List<Property> properties; // For REST API. - @JsonView({Views.Public.class, FromRequest.class}) + @JsonView({Views.Public.class, FromRequest.class, Git.class}) String url; - @JsonView({Views.Public.class, FromRequest.class}) + @JsonView({Views.Public.class, FromRequest.class, Git.class}) List<Property> headers; - @JsonView({Views.Public.class, FromRequest.class}) + @JsonView({Views.Public.class, FromRequest.class, Git.class}) List<Property> queryParameters; public boolean isSshProxyEnabled() {